[Fixed]-Determine empty template variable in Django

44👍

Pipe through length and do your test against that value.

{% if narratives.narrative_text|length > 0 %}
    {{ narratives.narrative_text }}
{% else %}
    None
{% endif %}

7👍

Just use {% if narratives.narrative_text %}, I think. It will use Python’s implicit false, which applies for empty strings, empty arrays, empty dicts, None, False, 0 etc..

4👍

Just confirmed via my own code using django 2.1.3 and python 3.5 and 3.7 that the following works:

{% if narratives.narrative_text %}
    # do something
    {{ narratives.narrative_text }}
{% else %}
    # do something else
    None  # displays "None" 
{% endif %}

4👍

I think that the best and obvious solution would be, in Django Template language:

{% if objects is not None %}
    {% for obj in objects %}
        {{obj}}   // Do your stuff here
    {% empty %}
        No results.    // No results case
    {% endfor %}
{% endif %}

In case the variable objects is not set, nothing will be printed out.

I had similar difficulties.
Hope it helps.

2👍

You can write Custom template filter, is_empty to check. Return false if variable is empty and true if value exists.

{% if narratives.narrative_text|is_empty %}
    # dosomthing 
{% else %}
    # dosomthing 
{% endif %}
👤Ahsan

0👍

I’ve used jijnja which is a lot similar and simpler and I think it would work if you do

{% if not narratives.narrative_text %}
  // do something 
{% else %}
 // do something else  with or without {{ narratives.narrative_text }}
{% endif %}

It uses python implicit True/False,None, etc to do the job.
In simplest terms use python variables inside {{ }} and conditionals,etc inside {% %}

Leave a comment