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?

4
  • 1
    Create list of range and return from view, not directly within template. Commented Mar 16, 2018 at 8:41
  • @AnupYadav Is it impossible to make it on template tags? Commented Mar 16, 2018 at 8: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 }} Commented Mar 16, 2018 at 8: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. Commented Mar 16, 2018 at 8:48

2 Answers 2

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 %}
Sign up to request clarification or add additional context in comments.

Comments

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 %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.