Determine empty template variable in Django Determine empty template variable in Django django django

Determine empty template variable in Django


Pipe through length and do your test against that value.

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


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..


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 %}