如何在模板中迭代Django CHOICES,而不使用表单或模型实例 [英] How do I iterate over Django CHOICES in a template - without using a form or model instance
问题描述
我目前使用选项来定义一个月份列表和一周中的几天。
我想在我的模板中显示这些选择列表,而不一定关于特定的实例或表单。
例如...
在我的模型中:
MONTH_CHOICES =(
('01','1月'),
('02',' )
('03','March'),
etc
DAY_CHOICES =(
('01','Monday'),
('02','星期二'),
('03','星期三'),
等
类项目(models.Model):
月= models.CharField(choices = MONTH_CHOICES)
day = models.CharField(choices = DAY_CHOICES)
在我看来:
month_choices = MONTH_CHOICES
在我的模板中:
{%for month in month_choices%}
{{month}}< br />
{%endfor%}
上述代码输出:
<$ p $
('02','二月')
('03','三月')
如何输出每个选择的名称(或值)?
或者,是否有更好的方式为一个模型录制一个月和一个星期的日子 - 稍后分组/呈现一个月和一天的实例?
谢谢! :
有一个更好的方式来做到这一点。
{%for value,text in form。[field_name] .field.choices%}
{{value}}:{{text}}
{%endfor% }
form是您传递给模板的表单变量。
[field_name]是您在模型中定义的字段名称。在这种情况下,'月'
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. [field_name] is the field name you defined in your model. In this case 'month'
这篇关于如何在模板中迭代Django CHOICES,而不使用表单或模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!