What is the equivalent of none in django templates

0 votes

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

Jul 3, 2020 in Python by kartik
• 37,510 points
8,141 views

1 answer to this question.

0 votes

Hello @kartik,

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

Limit templates to be the only presentation layer and calculate 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 }}

Hope this helps!

Thank you!!

answered Jul 3, 2020 by Niroj
• 82,880 points

Related Questions In Python

+2 votes
3 answers

what is the practical use of polymorphism in Python?

Polymorphism is the ability to present the ...READ MORE

answered Mar 31, 2018 in Python by anto.trigg4
• 3,440 points
4,287 views
0 votes
1 answer

What is the use of raw_input function in Python?

raw_input fuction is no longer available in ...READ MORE

answered May 2, 2018 in Python by aayushi
• 750 points
920 views
0 votes
1 answer

What is the meaning of “int(a[::-1])” in Python?

Assumming a is a string. The Slice ...READ MORE

answered Aug 27, 2018 in Python by Priyaj
• 58,090 points
6,130 views
0 votes
1 answer

How to temporarily disable a foreign key constraint in MySQL?

Hello @kartik, To turn off foreign key constraint ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
2,080 views
0 votes
1 answer

How do I use Django templates without the rest of Django?

Hello @kartik, Let's say you have this important ...READ MORE

answered Jun 23, 2020 in Python by Niroj
• 82,880 points
1,227 views
0 votes
1 answer

Error: port is already in use of Django Server

Hii @kartik, Just type sudo fuser -k 8000/tcp. This ...READ MORE

answered May 6, 2020 in Python by Niroj
• 82,880 points
13,496 views
0 votes
1 answer

What is the best way to remove accents in a Python unicode string?

Hello @kartik, Some languages have combining diacritics as ...READ MORE

answered May 11, 2020 in Python by Niroj
• 82,880 points
6,835 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP