What is the equivalent of “none” in django templates?

后端 未结 7 1066
孤街浪徒
孤街浪徒 2020-12-12 21:40

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         


        
7条回答
  •  我在风中等你
    2020-12-12 22:09

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

    Hope this helps :)

提交回复
热议问题