Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to show a certain value instead of None in Django?

I am new to Django and I am passing on object players
to my HTML template. I am iterating over this object and showing player.lastName but this value sometimes return None. How can I show a value of my choice if the player.lastName was None.

I want to write something like:

 {% for player in players %}
<td>{{player.lastName 'OR' - }}

Current Behavior would show

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<td> LastName 1 </td>
<td> None </td>
<td> LastName 3 </td>

But What I want to show

 <td> LastName 1 </td>
<td> - </td> // folowing the OR ( since Value was none show "-"
<td> LastName 3 </td>

>Solution :

You can work with the |default_if_none template filter [Django-doc]:

<td>{{player.lastName|default_if_none:"-" }}</td>

or use the |default template filter [Django-doc] if you want to print the alternative if the item evaluates to False (so False, None, '' empty string, 0, etc.):

<td>{{player.lastName|default:"-" }}</td>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading