142

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"?

goelv
  • 2,774
  • 11
  • 32
  • 40

9 Answers9

175

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

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

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:

# 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 }}
starball
  • 20,030
  • 7
  • 43
  • 238
Gerard
  • 9,088
  • 8
  • 37
  • 52
  • I just tried to pass None as a parameter to the {% cache %} tag and learned that it's not available. Busy working around this. – tobych Sep 19 '13 at 18:07
  • 7
    `{% if profile.user.first_name is None %}` causes syntax error in Django template. – Rockallite Sep 24 '13 at 04:23
  • 1
    Your hint mixes presentation and logic by putting HTML in your model, doing exactly the opposite of what you are trying to teach. How about returning None if there is no name (logical behaviour for a data model) and then using the `default_if_none` filter in the template? – jbg Nov 17 '13 at 23:46
  • @JasperBryant-Greene you are right! just updated. Good catch man! Thx! – Gerard Nov 19 '13 at 00:26
100

You can also use another built-in template default_if_none

{{ profile.user.first_name|default_if_none:"--" }}
Babacar Gningue
  • 1,304
  • 1
  • 9
  • 10
  • 1
    Any idea how to use this with other filters such as date? For example, is it possible to display "N/A" if a date is none but otherwise format it? Like: {{ post.pub_date|default_if_none:"N/A"|date:"Y-m-d" }}? – Andreas Bergström Jan 07 '18 at 16:57
  • @AndreasBergström In your case you apply `date` first. If any error occurs it will return None. Then you apply `default_if_none`. – defance Jan 16 '19 at 14:30
  • What version of Django was this brought in? – User Feb 21 '20 at 21:08
17

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

Louis
  • 644
  • 5
  • 18
16

isoperator : 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 %}
user6763622
  • 169
  • 1
  • 2
6

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}
mwjackson
  • 5,403
  • 10
  • 53
  • 58
4

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

Danica
  • 28,423
  • 6
  • 90
  • 122
3

In cases where we need to validate for a field with null value, we may check so and process as under:

{% for field in form.visible_fields %}
    {% if field.name == 'some_field' %}
        {% if field.value is Null %}
            {{ 'No data found' }}
        {% else %}
            {{ field }}
        {% endif %}
    {% endif %}
{% endfor %}
carla
  • 141
  • 9
1

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.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
claypooj
  • 333
  • 2
  • 6
1

Just a note about previous answers: Everything is correct if we want to display a string, but pay attention if you want to display numbers.

In particular when you have a 0 value bool(0) evaluates to False and so it will not display and probably is not what you want.

In this case better use

{% if profile.user.credit != None %}
piertoni
  • 1,933
  • 1
  • 18
  • 30