Home > Mobile >  I have an error in django template for loop
I have an error in django template for loop

Time:01-21

I have an error in django template for loop.
My code:

<div >
<label>Year</label>
<select name="year" id="year" name="year">
    {% for y in range(1980, (datetime.datetime.now().year   1)) %}
          <option value="{{ y }}">{{ y }}</option>
    {% endfor %}
</select>
</div>
    

My error:

'for' statements should use the format 'for x in y': for x in y range(1980, (datetime.datetime.now().year 1))

CodePudding user response:

You cannot use standard Python logic in templates.

Read DOCS about that topic.

The easiest way seems to create custom template tag filter:

import datetime
from django import template

register = template.Library()

@register.filter
def get_year_range(starting_year):
    return range(int(starting_year), (datetime.datetime.now().year   1))

And use it in template:

{% load custom_tags %}

...
{% for y in "1980"|get_year_range %}
    <option value="{{ y }}">{{ y }}</option>
{% endfor %}

MORE ABOUT TEMPLATE TAGS

CodePudding user response:

I solve my issue using following code:
 import datetime

 today = datetime.date.today()
        year = today.year
        year_dropdown = []
        for y in range(year,1899,-1):
            year_dropdown.append(y)

Pass key in render

return render(request, "add-ad.html",
                      {'year_dropdown': year_dropdown })

My html form django template code:
  <div >
                                    <label>Year</label>
                                    <select name="year" id="year" name="year" >
                                        <option value="">Choose...</option>
                                        {% for y in year_dropdown %}
                                      
                                        <option value="{{ y }}">{{ y }}</option>
                                        {% endfor %}
                                    </select>
                                </div>
                                
  • Related