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.
Call full_clean(), this should initialize
form._errors. This step is critical, if you don’t do it, it won’t work.Make the error list, it takes a list of messages, instanciate it as such:
error_list = form.error_class(['your error messages'])Assign the error list to NON_FIELD_ERRORS, you have to import
NON_FIELD_ERRORSfromdjango.forms.forms, then assign as such:form._errors[NON_FIELD_ERRORS] = error_listHere is a demonstration from a shell: