0

I'm creating a "Field.choice" in django that define the priority statuses available for items. When I try to display an item, I'm stuck with the constants (in CAP) when I'd like to display/ use the human-readable name.

For instance, an Item with the priority (MAITRISE, u'Maitrisé') with be displayed as MAI (value of the constant MAITRISE) instead of 'Maitrisé'.

How do I change that? How can I choose which element of the tuplue (MAITRISE, u'Maitrisé') I want to use?

Here is my field choice (I add or change a priority status to an item)

priority = models.CharField(max_length = 50,choices=PRIORITY_CHOICE,default=PRIORITAIRE)

MAITRISE = 'MAI'
IMPORTANT = 'IMP'
PRIORITAIRE = 'PRIO'

PRIORITY_CHOICE = (
    (MAITRISE, u'Maitrisé'),
    (IMPORTANT, u'Important'),
    (PRIORITAIRE, u'Prioritaire'),
     )

The view

def display(request):

    priority_scale = MemoryItem.PRIORITY_CHOICE
    # Mixed list
    mem_list = list(MemoryItem.objects.all().order_by('?'))
    item = mem_list[0]

    return render(request, 'memory/display.html',{
        'item':item,
        'priority_scale':priority_scale,
        })

The template

<div class="row">

    <!-- x,y tuple is like MAITRISE, u"maitrisé" avec MAITRISE = MAI -->
    {% for x,y in priority_scale %}
        <!-- if the priority status of the item match the current loop in priority scale list => button should be red -->
        {% if y == item.priority  %}
            <div class="col-xs-2">
                <a href=""><button class="btn btn-danger">{{y}}</button></a>
            </div>
        {% else %}
            <div class="col-xs-2">
                 <a href=" {% url 'memory:change_priority' mem_id=item.id new_priority=x %}">
                    <button class="btn btn-primary">{{y}}</button></a>
            </div>
            {% endif %}
    {% endfor %}
</div><br>

Sure it's basic skills but the documentation is a bit short on this

4

1 回答 1

0

对于具有 的字段choices,调用会instance.fieldname返回该字段的实际值。如果您希望获得选择元组中字段的详细值,则需要调用instance.get_FOO_display(). 对于你的情况,它会是item.get_priority_display(). 但请记住,您不能在 Django 模板中调用这样的函数。所以调用item.get_priority_display会给你显示值。

于 2014-03-28T10:34:34.827 回答