【问题标题】:Model Field Choice and Unicode模型字段选择和 Unicode
【发布时间】:2014-03-28 10:13:11
【问题描述】:

我正在 django 中创建一个“Field.choice”,用于定义项目可用的优先级状态。当我尝试显示一个项目时,当我想显示/使用人类可读的名称时,我会遇到常量(在 CAP 中)。

例如,具有优先级 (MAITRISE, u'Maitrisé') 的项目将显示为 MAI(常量 MAITRISE 的值)而不是“Maitrisé”。

我该如何改变呢?如何选择要使用的元组 (MAITRISE, u'Maitrisé') 中的哪个元素?

这是我的字段选择(我添加或更改项目的优先状态)

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'),
     )

景色

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,
        })

模板

<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>

当然是基本技能,但是文档有点短

【问题讨论】:

标签: python django unicode django-models choicefield


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-08-17
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 2021-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多