How do I get the total number of errors count in a Django form ?

How do I get the total number of errors count ?

{% load widget_tweaks %}
{% csrf_token %}
{% if form.errors %}<div style="border:1px solid red">Errors : {{ form.errors.count }}</div>{% endif %}

Since you can’t do math within a Django template, I don’t think you can do it from within a template. I think you might need to do it from within the view.

The Form.errors attribute shows that you get a dict of lists, with each list possibly having multiple errors. If you have a formset, that at least provides a total_error_count method.

I think this is one of the the reasons why PHP is more popular - you can insert code anywhere you want.

This has nothing to do with Python vs PHP.

This is a conscious decision by the authors of Django to limit what can be done in a template - a decision that I whole-heartedly agree with.

For more on this opinion see: Alternative to Django Template Engine? - #3 by KenWhitesell

If you find this design decision to be too limiting for you, you always have the options of either using a different template engine, extending the current engine, or adding your own custom tags to do stuff like this on your own.

1 Like