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

后端 未结 7 937
孤街浪徒
孤街浪徒 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 21:57

    Look at the yesno helper

    Eg:

    {{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}
    
    0 讨论(0)
  • 2020-12-12 22:03

    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

    0 讨论(0)
  • 2020-12-12 22:04

    You can also use another built-in template default_if_none

    {{ profile.user.first_name|default_if_none:"--" }}
    
    0 讨论(0)
  • 2020-12-12 22:05

    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 %}
    
    0 讨论(0)
  • 2020-12-12 22:08

    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.

    0 讨论(0)
  • 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 :)

    0 讨论(0)
提交回复
热议问题