facebook facebook facebook facebook facebook


As you can’t change the type of variable straight when working inside a Django template and you can only do it to the variables going TO the template, I found a stupid work around it.

Say you have variable a = ‘2′ and b = 2 and you want to compare them. The way I did it was adding the same value to both variables, thus changing the string variable into an integer by adding a filter. Might not be the best solution in the world but it worked.

Not working:
{% ifequal a b %}
HTML stuff 'round here
{% endifequal%}

Working:
{% ifequal a|add:"0" b|add:"0" %}
HTML stuff 'round here
{% endifequal %}

It does look a little bit silly but it might do the trick if you’re too lazy to change your views/models.


2 Comments to Comparing string with integer in Django’s template

 Subscribe in a reader Or, subscribe via email:
Enter your email address: 



  1. Abe's Gravatar Abe
    May 6, 2010 at 7:53 pm | Permalink

    Thanks for the tip. Thankfully it appears this won’t be necessary in Django 1.2 thanks to support for the “==” operator.

    For now I think this hack can be made slightly nicer and more readable by using |add:”0″ instead of a random number like 2.


Leave a Reply