[Django]-Python Django Templates and testing if a variable is null or empty string

64๐Ÿ‘

โœ…

{% if lesson.assignment and lesson.assignment.strip %}

The .strip calls str.strip() so you can handle whitespace-only strings as empty, while the preceding check makes sure we weed out None first (which would not have the .strip() method)

Proof that it works (in ./manage.py shell):

>>> import django
>>> from django.template import Template, Context
>>> t = Template("{% if x and x.strip %}OK{% else %}Empty{% endif %}")
>>> t.render(Context({"x": "ola"}))
u'OK'
>>> t.render(Context({"x": "   "}))
u'Empty'
>>> t.render(Context({"x": ""}))
u'Empty'
>>> t.render(Context({"x": None}))
u'Empty'
๐Ÿ‘คShawn Chin

6๐Ÿ‘

This may not have been available when the question was posted but one option could be using the built in template filter default_if_none (Django Documentation Link).

For example:
{{ lesson.assignment|default_if_none:"Empty" }}

๐Ÿ‘คPeter H

5๐Ÿ‘

If lesson.assignment is a model field, you could define a helper function in your model and use it:

class Lesson(models.Model):
    assignment = models.CharField(..., null=True, ...)
    # ...

    @property
    def has_assignment(self):
        return self.assignment is not None and self.assignment.strip() != ""

Then use {% if lesson.has_assignment %} in your template.

๐Ÿ‘คMike DeSimone

1๐Ÿ‘

You can simulate it by using the cut filter to remove all spaces. But you should probably find out why it contains all spaces in the first place.

1๐Ÿ‘

You can call any built-in methods anywhere in a Django template variable. For example, you can call the Python string method strip. So this will work:

{% if lesson.assignment.strip %}
๐Ÿ‘คDaniel Roseman

1๐Ÿ‘

Here is a simple way to do this, from Django version 3.2

{{ lesson.assignment|default:"nothing" }}

This works for both cases (empty string and None object).

ref link: https://docs.djangoproject.com/en/3.2/ref/templates/builtins/#std:templatefilter-default

Leave a comment