Skip to content
Advertisement

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

I am pretty new to django, but have many years experience coding in the java world, so I feel ridiculous asking this question – I am sure the answer is obvious and I am just missing it. I can’t seem to find the right way to query this in google or something… I have searched through the django docs and it either isn’t there or I am just not seeing it. All I want to do is in a template test if the var is not null OR an empty string OR just a bunch of spaces. I have an issue where spaces are getting introduced into my field – another issue I have to, and will, work out… but, I want my logic to work regardless. Right now, because my string contains just spaces simply doing this: {% if lesson.assignment %} always passes even though I don’t want it to. I have looked for a trim type functionality that would work between {% %}, but I can’t seem to find anything. I have tried strip, but it doesn’t work between {% %}. Can someone please point me in the direction of the answer… some docs I might have missed… something?

Thanks a ton in advance!

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement