Sign up ×

Im getting strangest error in django so far:

'if' statement improperly formatted

Template that raises the error is this:

{% if diff >= 0 %}
<span class="pos">+{{ diff }}
{% else %}
<span class="neg">-{{ diff }}
{% endif %}
<span>{{ a }}</span>

view that has a and diff in context is this:

def add(request, kaart_id):
    if request.is_ajax() and request.method == 'POST':
    	x = Kaart.objects.get(id=kaart_id)
    	x.pos += 1
    	x = Kaart.objects.get(id=kaart_id)		
    	from django.utils import simplejson
    	diff = x.pos - x.neg
    	a = "(+1)"
    	context = { 'diff':diff, 'a':a }
    	return render_to_response('sum.html', context, context_instance=RequestContext(request))

It does not matter what equation i use in if, >, >=, ==.. they all raise the same error.

and as far as i can tell its all by the book:


share|improve this question

4 Answers 4

up vote 7 down vote accepted

Until Django 1.2 lands you are looking for "Smart If", a Django Template Tag.

A smarter {% if %} tag for django templates.

While retaining current Django functionality, it also handles equality, greater than and less than operators. Some common case examples::

    {% if articles|length >= 5 %}...{% endif %}
    {% if "ifnotequal tag" != "beautiful" %}...{% endif %}

Arguments and operators must have a space between them, so {% if 1>2 %} is not a valid smart if tag.

All supported operators are: or, and, in, = (or ==), !=, >, >=, < and <=.

share|improve this answer
Thanks! Ill think of something else then and wait for 1.2! –  Odif Yltsaeb Dec 20 '09 at 20:36
Just use the tag. Its really easy to load them (its in the docs) and then when 1.2 is released your code is already compatible and you can remove the tag code. –  Mark Stahler Dec 21 '09 at 2:55

As mentioned, you can't use operators in the {% if %} tag. It accepts only Boolean values (which you can AND, OR and NOT together.)

For simple equality, you can use the {% ifequal val1 val2 %} tag.

The reason is to push the "logic" out of the template and into the model layer. I.e. you should have a method on your model like so:

def positive_diff(self):
   return self.diff >= 0

Then call that in your template:

{% if x.positive_diff %} ... {% endif %}

Or, you can set an extra variable in your view:

positive_diff = diff >= 0
share|improve this answer

You need to close each if statement with an endif

{% if var1 %}

{{ var1|safe }}

{% else %}

{% if var2 %}

{{ var2|safe }}

{% else %}

{% if var3 %}

{{ var3|safe }}


share|improve this answer

The "smart if" tag was just added in the development version (that will eventually become 1.2).

If you're using a stable release (1.1.x or earlier) you won't be able to use those comparison operators in the "if" template tag.

Edit: look just above the == operator

share|improve this answer

Your Answer


