Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 965
PaulP1975 Avatar asked Jul 09 '11 20:07

PaulP1975


People also ask

How check variable is empty or not in Django?

You can Use bool() to check if a variable is empty in Python. Or you can also use if not statement to check it.

What does {% include %} do in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

What is Django template language?

A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. A template is rendered with a context.


1 Answers

{% 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' 
like image 75
Shawn Chin Avatar answered Oct 02 '22 15:10

Shawn Chin