uncle Lem
uncle Lem

Reputation: 5024

Incorrect work of if-else statement in Django template

I have this code:

{% if username_is_ok == True %}
    <input type="text" name="inputName" placeholder="Name" required>
{% else %}
    <div class="control-group error">
        <input type="text" name="inputName" placeholder="Name" value="{{ username }}"
               class="text-error" required>
        <span class="help-block text-error">User already exists</span>
    </div>
{% endif %}

And debugger says that username_is_ok == True equals {bool} True. But it goes to the else branch and when page loads I see the error message. I can't see no mistakes and I feel frustrated about that. Can you help me? Thanks.

Upvotes: 0

Views: 832

Answers (1)

jsvk
jsvk

Reputation: 1729

The Django templating language is not Python but rather its own custom "templating language" with minimal logic (this is by design: it's encouraged that you keep "controller" logic away from templates). Therefore, you'll find that some valid Python may not be valid template syntax

In your example, the templating language tries to evaluate "True" as a literal. Since you probably didn't define a key named "True" in the context, a VariableDoesNotExist exception is raised, and the template treats the value as the python None type.

The debugger evaluates the conditional as Python, not Django templating language, and so the value is tested against the Python True and evaluates to True

In order for the logic to work, you might want to try adding True to your template context. Something like: {"True": True}

related: https://stackoverflow.com/a/5672415/927229

Upvotes: 4

Related Questions