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'
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" }}
- [Django]-How to test custom template tags in Django?
- [Django]-How do you change the collation type for a MySQL column?
- [Django]-How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip
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.
- [Django]-How can I get the full/absolute URL (with domain) in Django?
- [Django]-How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi?
- [Django]-How do I unit test django urls?
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.
- [Django]-Django equivalent of SQL not in
- [Django]-Django admin, hide a model
- [Django]-How do I force Django to ignore any caches and reload data?
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 %}
- [Django]-How to set environment variables in PyCharm?
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
- [Django]-Django: Fat models and skinny controllers?
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
- [Django]-413 Request Entity Too Large nginx django
- [Django]-How to get the current language in Django?
- [Django]-What is the difference render() and redirect() in Django?