Sergio Mendez
Sergio Mendez

Reputation: 1519

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

Upvotes: 2

Views: 6174

Answers (2)

David Lam
David Lam

Reputation: 4948

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

Upvotes: 7

Stefan Collier
Stefan Collier

Reputation: 4682

Have you tried:

{% if i == userdata.birth_date.day %}
  <option value="{{ i }}" selected>{{ i }}</option>

Upvotes: 0

Related Questions