'How check empty variable in template? Exception Value: Could not parse the remainder

{% extends 'pygiustizia/base.html' %}
{% block body %}
<div class="wrapper">
    <h2>Login</h2>
    <p>Prego, inserisci le tue credenziali di login.</p>

    <div class={% if len(tmplVar.loginErr) > 0  %} "alert alert-danger" {% endifequal %}> {% if tmplVar.loginErr is not None %} {{tmplVar.loginErr}} {% endif %}</div>
    <form action="{% url 'login' %}" method="post">
        <div class="form-group">
            <label>Username</label>
            <input type="text" name="username" class="form-control {% if tmplVar.usernameErr is not None %} is-invalid {% endif %}" value="{{tmplVar.username}}">
            <span class="invalid-feedback">{% if tmplVar.usernameErr is not None %} {{tmplVar.usernameErr}} {% endif %}</span>
        </div>
        <div class="form-group">
            <label>Password</label>
            <input type="password" name="password" class="form-control {% if tmplVar.passwordErr is not None %} is-invalid {% endif %}" value="{{tmplVar.password}}">
            <span class="invalid-feedback">{% if tmplVar.passwordErr is not None %} {{tmplVar.passwordErr}} {% endif %}</span>
        </div>
        <div class="form-group">
            <input type="submit" class="btn btn-primary" value="Login">
        </div>
    </form>
</div> 
{% endblock %}

Exception Value: Could not parse the remainder: '(tmplVar.loginErr)' from 'len(tmplVar.loginErr)'

What I miss? How can I check if variable is empty or lenght 0?



Solution 1:[1]

You can not use len(…): function calls are deliberately restricted in Django's template language. You can make use of the |length template filter [Django-doc]. But here checking the truthiness is enough:

<div {% if tmplVar.loginErr %}class="alert alert-danger"{% endif %}>

this will check if the length is greater than zero, since collections (lists, tuples, strings, etc.) have truthiness False if these are empty.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Willem Van Onsem