开发者

How do I reference a choice list in django template?

I have the following in my django model:

PRIORITY = (
    (1, 'Low'),
    (2, 'Normal'),
    (3, 'High'),
)

Obviously the entry associated with this is storing the integer. In my template however I would like to show the priority in human-readable for开发者_如何学编程mat. How exactly do I accomplish this?

My template:

{% for x in items %}
{{ x }} (added on {{ x.create_date }})<br>
{% endfor %}

{{ x.id }} would be the priority ID.

Thanks in advance.


Assuming you have correctly set the choices option when defining your model, Django automatically creates helper functions to display the names for you. See the documentation on extra instance methods for details.

If your model instance is x and your attribute that stores the priority is priority, then in your template you would use:

{{ x.get_priority_display }}


Really, the "priority" with name and ID is a self-invented kind of object that you've thought up. If you just make this a Priority model and treat it as such it will all work the way it should. It's because you're trying to avoid using the system that you're having trouble.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜