django template display item value or empty string

PythonDjangoDjango Templates

Python Problem Overview


My code in template is like this:

{% for item in items %}
    {{ item.somefield }}
{% endfor %}

I want to display the item value if the item.somefield is not None, or display an empty string. I don't want to use the {% if item.somefield %} statement, I want something like {{ item.somefield or '' }}(I tried this but it doesn't work)

Python Solutions


Solution 1 - Python

You want the default_if_none template filter, (doc).

default_if_none will display the given string if the variable is 'None'.

default will display the string if the variable evaluates to False, ie empty strings, empty lists etc

{{ item.somefield|default_if_none:"" }}
{{ item.somefield|default:"" }}

Solution 2 - Python

{{ item.somefield|default_if_none:"" }}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoger LiuView Question on Stackoverflow
Solution 1 - PythonrockingskierView Answer on Stackoverflow
Solution 2 - PythonmatinoView Answer on Stackoverflow