[Django]-Django DecimalField returns "None" instead of empty value

15👍

If you don’t want to filter the list of values, you could use the built-in default or default_if_none template filters to control what’s displayed, but with the example given above, you’d end up with empty links.

{{ item|default_if_none:"" }}

Given your need to hyperlink and query on each value and a view which is going to show an error if not given a number, I’d filter the list when you’re passing it to the template context:

{"choices": [choice in choices where choice is not None]}

0👍

Ok, so lets say you get Django to return an empty string instead od None for empty values.

So now what happens with this code:

{% for item in choices %}
<a href={% url app_views.field_choice item %}>{{ item }}</a><br>
{% endfor %}

You will either:

  • Get a bunch of empty links (<a href="/field_choice/"></a>)
  • Or an exception form the url reverse mechanism (because the positional argument is required).

The method you don’t want to use is much (!) more elegant:

{% for item in choices %}
    {% if item %}
        <a href={% url app_views.field_choice item %}>{{ item }}</a><br>
    {% endif %}
{% endfor %}

Of course you are also free to build a list without empty items beforehand: in the view, or even using a custom manager.

Leave a comment