Reputation: 103
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! :)
Upvotes: 9
Views: 15820
Reputation: 353
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'
Upvotes: 23
Reputation: 122326
You can simply unpack the tuple when iterating over it:
{% for n, month in month_choices %}
{{ n }}, {{ month }}<br />
{% endfor %}
Upvotes: 9
Reputation: 599470
{% for month in month_choices %}
{{ month.1 }}<br />
{% endfor %}
Although semantically you should probably use <ul>
and <li>
rather than <br>
.
Upvotes: 3