0

What I want to do is simple: I want to display a HTML select tag which includes option tags with value 1971 ~ 2020.

The following is code snippet:

Year<select name="selected_year">
{% for i in "x"|rjust:"50" %}
    <option value="{{ forloop.counter }}">{{ forloop.counter }}</option>
{% endfor %}
</select>

the {{forloop.counter}} will display 1 ~ 50.
my question is: how to display 1971 ~ 2020 instead?
any suggestion?

BTW, the for loop code is referenced from another question: Numeric for loop in Django templates

Community
  • 1
  • 1
firestoke
  • 1,051
  • 11
  • 23

1 Answers1

2

You could use the |add filter to modify each value:

<option value="{{ forloop.counter|add:1970 }}">{{ forloop.counter|add:1970 }}</option>

But don't do this. Use range(1971, 2021) in the view and pass that to the template.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895