Reputation: 3345
I want to create a year dropdown in django template. The dropdown would contain start year as 2011, and end year should be 5 years from current year.
For ex: If today i see the dropdwon it will show me years ranging from 2011, 2012, 2013,...2017.
It can be done by sending a list from views.py and looping it in the template or defining inside forms.py.
But i don't want to use any form here. I just have to show it in a template.
How can i do it in Django template.
Upvotes: 2
Views: 11702
Reputation: 6346
In your models.py
...
import datetime
year_dropdown = []
for y in range(2011, (datetime.datetime.now().year + 5)):
year_dropdown.append((y, y))
So, your field can now use year_dropdown
:
year = models.IntegerField(_('year'), max_length=4, choices=year_dropdown, default=datetime.datetime.now().year)
Which sets the current year as the default value.
If all you want is the values in the template, then do something like the following...
<select id="year">
{% for y in range(2011, (datetime.datetime.now().year + 5)) %}
<option value="{{ y }}">{{ y }}</option>
{% endfor %}
</select>
For more details, read the Django template language documentation.
Upvotes: 8
Reputation: 2598
I would suggest to use Javascript or jQuery at client side to populate the dropdown according to the current year.
Upvotes: 0
Reputation: 113948
<select name="select_year">
<option>2011</option>
<option>2012</option>
<option>2013</option>
<option>2014</option>
<option>2015</option>
<option>2016</option>
<option>2017</option>
</select>
put that in your template file ... if you want to do a dynamic range of years you will need to make your own template tag
this thread has several answers for implementing range type functionality as a template tag
Numeric for loop in Django templates
using a javascript solution would probably be the easiest way to dynamically set the range.
Upvotes: 0
Reputation: 474
This is how I like to do it.
models.py:
YEAR_CHOICES = []
for r in range(2011, (datetime.datetime.now().year+5)):
YEAR_CHOICES.append((r,r))
year = models.IntegerField(('year'), max_length=4, choices=YEAR_CHOICES, default=datetime.datetime.now().year)
Upvotes: 0
Reputation: 9458
If all you want is a simply a drop down of years itself, you can do what @Nick or @Ian suggested. In case you want some calendar type functionality (Date picker) you can have a look at JQuery UI DatePicker
Upvotes: 1