[英]How do I iterate over Django CHOICES in a template - without using a form or model instance
I currently use choices to define a list of months and a list of days of the week. 我目前使用选项来定义月份列表和一周中的天数列表。
I want to display these lists of choices in my templates without necessarily relating to a specific instance or form. 我想在模板中显示这些选项列表,而不必与特定实例或表单相关。
For instance... 例如...
In my models: 在我的模特中:
MONTH_CHOICES = (
('01', 'January'),
('02', 'February'),
('03', 'March'),
etc
DAY_CHOICES = (
('01', 'Monday'),
('02', 'Tuesday'),
('03', 'Wednesday'),
etc
class Item(models.Model):
month = models.CharField(choices=MONTH_CHOICES)
day = models.CharField(choices=DAY_CHOICES)
In my view: 在我看来:
month_choices = MONTH_CHOICES
In my template: 在我的模板中:
{% for month in month_choices %}
{{ month }}<br />
{% endfor %}
The above code outputs: 以上代码输出:
('01', 'January')
('02', 'February')
('03', 'March')
How do I output just the name (or value) of each choice? 如何仅输出每个选项的名称(或值)?
Alternatively, is there a better way of recording a month and day of the week for a model - and later grouping/presenting instances using a month and a day? 或者,是否有更好的方法来记录模型的一个月和一周 - 以及稍后使用一个月和一天分组/呈现实例?
THANKS! 谢谢! :)
:)
There's a better way to do this. 有一个更好的方法来做到这一点。
{% for value, text in form.[field_name].field.choices %}
{{ value }}: {{ text }}
{% endfor %}
form is the form variable you pass to the template. form是传递给模板的表单变量。 [field_name] is the field name you defined in your model.
[field_name]是您在模型中定义的字段名称。 In this case 'month'
在这种情况下'月'
You can simply unpack the tuple when iterating over it: 您可以在迭代时简单地解压缩元组:
{% for n, month in month_choices %}
{{ n }}, {{ month }}<br />
{% endfor %}
{% for month in month_choices %}
{{ month.1 }}<br />
{% endfor %}
Although semantically you should probably use <ul>
and <li>
rather than <br>
. 虽然在语义上你应该使用
<ul>
和<li>
而不是<br>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.