Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if django template variable is defined?

People also ask

How do you define a variable in a template?

In the template, you use the hash symbol, # , to declare a template variable.

How do I change the value of a variable in a Django template?

We can set the value of a variable in the Django template using with tag. This will output the below content. One downside of this approach is that we have to write the lines where we are accessing the variable inside with and endwith block. Using with is useful when using a costly variable multiple times.

What does {{ name }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.


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

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

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.

link to docs that describe handling invalid variables


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}