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

Time:03-31

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

<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>

CodePudding user response:

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>
  • Related