1

CODE:

<form>
    <div class="form-group">
    <label for="sel1">Select list (select one):</label>
    <select class="form-control" id="sel1" style="width: 96px">
        {% for i in 150 %} <!-- here is what I ask for -->
            <option>{{ i + 1989 }}</option>
        {% endfor %}
    </select>
    </div>
</form>

I want to make year select form which is from 1900 to 2050.

How can I use i variable in django template tag?

touchingtwist
  • 1,930
  • 4
  • 23
  • 38
  • 1
    Create list of range and return from view, not directly within template. – Anup Yadav Mar 16 '18 at 08:41
  • @AnupYadav Is it impossible to make it on template tags? – touchingtwist Mar 16 '18 at 08:44
  • 1
    Template tags is also good option but to have clean code for business logic I would suggest use in View. Do you need it for Addition? like `{{ i + 1989 }}` – Anup Yadav Mar 16 '18 at 08:45
  • 1
    Business logic means all data and further manipulation like *selection while edit* is useful if you keep that in VIEW file. Nothing much, this way you can avoid creating duplicate code. – Anup Yadav Mar 16 '18 at 08:48

2 Answers2

1

You can use Template range loop from django

syntax

{% range start:step:end as i %}
     {{ i }}
{% endrange %}

Example

{% range 1900:1:2050 as i %}
     {{ i }}
{% endrange %}
Astik Anand
  • 12,757
  • 9
  • 41
  • 51
0

Here's a much easier solution using django template language filter.

views.py

def my_view(request)
    return render(request, 'my_template.html', {'my_range':range(150)})

my_template.html

{% for i in my_range %}
  {{ i|add:1990 }}
{% endfor %}
BKO
  • 43
  • 1
  • 8