简体   繁体   中英

Model Field Choice and Unicode

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

For fields that have choices , calling instance.fieldname returns the actual value of the field. If you rather want the verbose value of the field from the choices tuple, you need to call instance.get_FOO_display() . For your case, it'd be item.get_priority_display() . But remember you cannot call functions like that in Django templates. So calling item.get_priority_display will get you the display value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM