Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of "none" in django templates?

People also ask

What does {{ name }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What are Django template tags?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.

How do you solve template does not exist in Django?

Django TemplateDoesNotExist error means simply that the framework can't find the template file. To use the template-loading API, you'll need to tell the framework where you store your templates. The place to do this is in your settings file ( settings.py ) by TEMPLATE_DIRS setting.


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 :)


You can also use another built-in template default_if_none

{{ profile.user.first_name|default_if_none:"--" }}

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


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

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}