Search code examples
djangodjango-formsdjango-templates

django InlineFormsets errors reporting with formset error list being empty


I have a strange error on creation using Django inline formsets.

Django is reporting formset errors, so it doesn't finish the creation.

Also I tested is_valid and it returns true. What is wrong ?

but if I check them there is nothing in the dictionary of errors:

1.

 {{formset.errors}}
[{}, {}, {}, {}, {}]

2.

{%  if formset.errors %}
        {% for error  in formset.errors %}
            error {{ error }}
        {% endfor %}
{%  endif %} 

{}

I think I understand the issue:

{%  if formset.errors %} even if I have [{}, {}, {}, {}, {}] will pass.

If I use {% if not formset.errors %}, will block also when I have real errors.

Checking if a list is empty is not working, because is not really empty, it has empty dictionaries.

I can use a loop inside the form list to check the dictionaries, but going this for each field or form/formset I don't see it as a good option.


Solution

  • Firstly, check that the formset is bound.

    formset.is_bound
    

    If you haven't bound the formset to any data, then it won't have any errors but it will never be valid.

    Secondly, make sure you are calling the is_valid method

    formset.is_valid()
    

    Finally, note that formset.errors returns a list of dictionaries containing the errors for each form. There is also formset.non_form_errors(), whic returns errors that do not belong to a particular form.