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:
JavaScript
x
6
1
{% if profile.user.first_name is null %}
2
<p> -- </p>
3
{% elif %}
4
{{ profile.user.first_name }} {{ profile.user.last_name }}
5
{% endif%}
6
In the example above, what would I use to replace “null”?
Advertisement
Answer
None, False and True
all are available within template tags and filters. None, False
, the empty string ('', "", """"""
) and empty lists/tuples all evaluate to False
when evaluated by if
, so you can easily do
JavaScript
1
3
1
{% if profile.user.first_name == None %}
2
{% if not profile.user.first_name %}
3
A hint: @fabiocerqueira is right, leave logic to models, limit templates to be the only presentation layer and calculate stuff like that in you model. An example:
JavaScript
1
13
13
1
# someapp/models.py
2
class UserProfile(models.Model):
3
user = models.OneToOneField('auth.User')
4
# other fields
5
6
def get_full_name(self):
7
if not self.user.first_name:
8
return
9
return ' '.join([self.user.first_name, self.user.last_name])
10
11
# template
12
{{ user.get_profile.get_full_name }}
13