37

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!

6 Answers 6

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'
Sign up to request clarification or add additional context in comments.

1 Comment

@PaulP1975: You might have missed it because using and in an if is a recent addition to Django.
6

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.

1 Comment

This is an interesting option... I very much like how it cleans up the logic in the template. I am very new to python and django, so I am still learning the ropes. Thank you for this suggestion!
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" }}

Comments

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 Comment

Yes, I intend to fix that fact that it has all the spaces. However, I wanted it to work either way and couldn't get the strip function to work (Shawn's code above worked).
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 %}

4 Comments

Problem: his CharField allows NULLs, so a NULL field will cause an exception since None doesn't have a strip method.
I do not know why, but the first time I tried to do this it failed... I might have hit the exceptional condition (null)... I can't remember.
Try {% if lesson.assignment and lesson.assignment.strip %}
For a foreign key you can use {% if lesson.foreign_key_field is Null %}
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.