Search code examples
pythondjangofor-loopdjango-templatesdate-conversion

Convert str to int in django template


I need to convert the a date day to int to compare with other value in the template.

Something like this:

views.py

def userEdit(request):
    userdata = user.objects.get(id=request.session['user_id'])
    dic.update({'userdata':userdata, 'dayrange': range(1,32)})
    return render(request, 'my_app/userEdit.html', dic)

my_app/userEdit.html

<select name="day">
  {% for i in dayrange %}
    {% if i == userdata.birth_date|date:"d" %}
      <option value="{{ i }}" selected>{{ i }}</option>
    {% else %}
      <option value="{{ i }}">{{ i }}</option>
    {% endif %}
  {% endfor %}
</select>

I need to convert userdata.birth_date|date:"d" to int and then compare with the "i" variable in the for loop. Please help


Solution

  • you can use the add filter with an argument of 0 to coerce it to an integer e.g.

    {% if i == userdata.birth_date|date:"d"|add:0 %}