Django DecimalField returns "None" instead of an empty value

Is there a way to get django to display nothing instead of “None” for a decimal field that is left blank?

In my template, I show a list of all the values ​​for a specific field. Each value is a hyperlink to a page that displays the results of a query filtered by that value. But since there are some null-value entries, my list includes the actual DecimalField and "None" entries for all empty ones. When the user clicks No, django throws a validation error because you cannot query DecimalField with a string.

I could write if the operators check all instances of decimal fields for Nones and skip them, but this is far from an elegant solution. Any tips?

This is one part of the code, although there are other patterns that display the None value in several different ways:

{% for item in choices %}
    <a href={% url app_views.field_choice item %}>{{ item }}</a><br>
{% endfor %}
+3
source share
2 answers

If you do not want to filter the list of values, you can use the built-in defaultor default_if_nonefilter filters to control the displayed ones, but with the above example you will get empty links.

{{ item|default_if_none:"" }}

Given the need for a hyperlink and query for each value and view that will show an error if a number is not specified, I would filter the list when you pass it to the template context:

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

Ok, so let's say that Django returns an empty string instead of od None for empty values.

So what happens with this code:

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

:

  • (<a href="/field_choice/"></a>)
  • URL ( ).

, , (!) :

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

, : .

0

Source: https://habr.com/ru/post/1738691/


All Articles