[Django]-How to check if django template variable is defined?

73👍

You need to switch your {% block %} and your {% if %}

{% block messages %}
    {% if message %}<div class='imp_message'>{{ message }}</div>{% endif %}
{% endblock %}

45👍

To check, in an if statement, you need to compare the value to None, like this:

{% if some_missing_var is None %}
   // code here if some_missing_var exists
{% else %}
   // code here if some_missing_var does not exist
{% endif %}

In other cases (from the docs):

Generally, if a variable doesn’t exist, the template system inserts the value of the engine’s string_if_invalid configuration option, which is set to '' (the empty string) by default.

I tried some of the other answers, and they didn’t work until I read the docs on how invalid variables are handled and the above was made clear.

5👍

If you don’t want to litter your logs with KeyError when there is no variable in the template context I recommend to use templatetags filters.

In myapp/templatetags/filters.py I add:

@register.simple_tag(takes_context=True)
def var_exists(context, name):
    dicts = context.dicts  # array of dicts
    if dicts:
        for d in dicts:
            if name in d:
                return True
    return False

In html template:

{% load filters %}
...
{% var_exists 'project' as project_exists %}
{% if project_exists %}
  ...
{% endif}

Leave a comment