Creating year dropdown in Django template

10,651

Solution 1

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.

Solution 2

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

Share:
10,651
sandeep
Author by

sandeep

I am a software developer working at Mindfire Solutions.

Updated on June 16, 2022

Comments

  • sandeep
    sandeep almost 2 years

    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.