TAGS :Viewed: 40 - Published at: a few seconds ago

[ Django if statement doesn't work as expected ]

I have the following in my html file:

{% trans "Result: "%} {{result}} 

Which will print out the word SUCCESS on the browser (because thats what the string contains)

But If I do the following:

{% if result == 'SUCCESS' %}
   do something
{% else %} 
   do something else
{% endif %}

I find that the if statement does not work as expected.

Why is this??

Answer 1


The if statement works fine. Your problem must be regarding the string. Maybe it's not a string at all.

Try the ifequal templatetag:

{% ifequal result 'SUCCESS' %}
   do something
{% else %} 
   do something else
{% endifequal %}

You can try different things. If you're assigning result in a view, you can validate it's a string in that very same view:

def my_view(request):
    # ... processing ...
    result = something()

    # Let's make sure it's a string containing 'SUCCESS'
    assert type(result) == str
    assert result == 'SUCCESS'

You can apply the same logic if it's a context processor. https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#ifequal