如何在 django 模板中引用选择列表?
我的 django 模型中有以下内容:
PRIORITY = (
(1, 'Low'),
(2, 'Normal'),
(3, 'High'),
)
显然,与此相关的条目正在存储整数。然而,在我的模板中,我想以人类可读的格式显示优先级。我究竟如何实现这一目标?
我的模板:
{% for x in items %}
{{ x }} (added on {{ x.create_date }})<br>
{% endfor %}
{{ x.id }}
将是优先级 ID。
提前致谢。
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 format. 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设您已正确设置 选项< /a> 选项定义模型时,Django 会自动创建辅助函数来为您显示名称。请参阅有关额外实例方法的文档细节。
如果您的模型实例是
x
并且存储优先级的属性是priority
,那么在您的模板中您将使用: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 ispriority
, then in your template you would use:实际上,带有名称和 ID 的“优先级”是您自行发明的一种对象。如果您只是将其设为优先级模型并如此对待它,那么一切都会按其应有的方式工作。这是因为您试图避免使用您遇到麻烦的系统。
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.