2

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.

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

is_valid is called and returns true, but it is in form. I'm doing this check in the templates to show the errors. How can I check is bound in the template ?
If you are definitely calling is_valid() then the form is bound - you use formset.is_valid in your question so that wasn't clear. It would help if you included some more information (e.g. formset class, view, full template) that reproduces the problem.
Thanks for this! I was stuck for hours trying to figure out why my formset was not valid when formset.errors returned an empty list. Turns out the cause lies in formset.non_form_errors()
0

To avoid that you need to follow the "Post Redirect Get" pattern for form submissions. It seems that django expects that you follow that pattern. If you do, the formset.errors will have real errors if they are instead of just empty dict objects.

When the you submit the form with POST call formset.is_valid, if is valid you do the redirect to a GET view, if not you return the template and read the errors.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.