What is equivalent to "none" in django templates?

I want to see if there is a field / variable in a Django template. What is the correct syntax for this?

This is what I 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"?

+49
python django django-forms django-templates django-views
Aug 14 '12 at 3:17
source share
7 answers

None, False and True all available in template tags and filters. None, False , empty string ( '', "", """""" ) and empty lists / tuples are evaluated to False when evaluating if , so you can easily do

 {% if profile.user.first_name == None %} {% if not profile.user.first_name %} 

Hint: @fabiocerqueira is right, keep the logic for the models, limit the templates to a single level of presentation, and figure things out like in your model. Example:

 # someapp/models.py class UserProfile(models.Model): user = models.OneToOneField('auth.User') # other fields def get_full_name(self): if not self.user.first_name: return return ' '.join([self.user.first_name, self.user.last_name]) # template {{ user.get_profile.get_full_name }} 

Hope this helps :)

+75
Aug 14 2018-12-12T00:
source share

You can also use another default_if_none built-in template default_if_none

 {{ profile.user.first_name|default_if_none:"--" }} 
+25
Mar 05 '15 at 14:46
source share

See yesno helper

For example:

 {{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }} 
+4
Nov 27 '13 at 10:52
source share

{% if profile.user.first_name %} works (assuming you also don't want to accept '' ).

if in Python generally treats None , False , '' , [] , {} , ... everything is false.

+3
Aug 14 '12 at 3:19
source share

You do not need to do this β€œif”, use: {{ profile.user.get_full_name }}

+2
Aug 14 '12 at 3:24
source share

You can also use the default built-in template filter:

If the value is False (for example, None, empty string, 0, False); the default is "-".

 {{ profile.user.first_name|default:"--" }} 

Documentation: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#default

+1
23 Oct '14 at 21:10
source share

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 %} 
+1
Aug 27 '16 at 3:47 on
source share



All Articles