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

{% 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'

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)