How to append error message to form.non_field_errors in django?

Django

I have a form with several fields. I have separate validation checks for each field, done via the forms validation. I however also need to check if few fields are filled in before redirecting the user to a different view. I was hoping I could somehow append the error to forms.non_field_errors as it is not for a particular field , but I am not sure what the right syntax for this would be. I have checked online and found..

form.errors['\_\_all\_\_'] = form.error_class(["error msg"])

This displays the error message, but it seems to mess up the other pages as well and displyas the error message if I click on anything else.

I tried

form._errors[NON_FIELD_ERRORS] = form.error_class()

This causes a 'NoneType' object has no attribute 'setdefault' error for me.

I have tried

form.non_field_errors().append("Please complete your profile in order to access the content.")

This doesn't seem to do anything and I cant see the error message on the view.

What would be the best way to do this? Ideally I dont' want to do it in the form's clean method. I feel like I should be able to append an error to the form in the view.

Answer link : https://codehunter.cc/a/django/how-to-append-error-message-to-form-non-field-errors-in-django

Posted May 3, 2022, 4:04 PM UTC

10
Loading comments…