I want to see if a field/variable is none within a Django template. What is the correct syntax for that?
This is what I currently have:
{% if profile.user.first_name is null %}
<p> -- </p>
{% elif %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif%}
In the example above, what would I use to replace "null"?
This question is related to
python
django
django-forms
django-templates
django-views
{% if profile.user.first_name %}
works (assuming you also don't want to accept ''
).
if
in Python in general treats None
, False
, ''
, []
, {}
, ... all as false.
You can also use the built-in template filter default
:
If value evaluates to False (e.g. None, an empty string, 0, False); the default "--" is displayed.
{{ profile.user.first_name|default:"--" }}
Documentation: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default
is
operator : New in Django 1.10
{% if somevar is None %}
This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
You can also use another built-in template default_if_none
{{ profile.user.first_name|default_if_none:"--" }}
You could try this:
{% if not profile.user.first_name.value %}
<p> -- </p>
{% else %}
{{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}
This way, you're essentially checking to see if the form field first_name
has any value associated with it. See {{ field.value }}
in Looping over the form's fields in Django Documentation.
I'm using Django 3.0.
Source: Stackoverflow.com