Last active
March 24, 2020 00:55
-
-
Save cansadadeserfeliz/3b62a13bdce7fe4178ac to your computer and use it in GitHub Desktop.
Django (extreme case): How to raise form invalid inside form_valid method of a FormView (CreateView/UpdateView) and add an error message to not field errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.forms.util import ErrorList | |
from django import forms | |
class ContractUpdateView(UpdateView): | |
model = Contract | |
template_name = 'contract/contract_form.html' | |
form_class = ContractForm | |
def form_valid(self, form): | |
if self.request.POST.get('finish'): | |
if ( | |
not form.cleaned_data['number'] or | |
not self.object.images.count() | |
): | |
form._errors[forms.forms.NON_FIELD_ERRORS] = ErrorList([ | |
u'You have to add images and a contract number' | |
]) | |
return self.form_invalid(form) | |
self.object.is_submitted = True | |
self.object = form.save() | |
return HttpResponseRedirect(self.get_success_url()) |
Thank you!!! I spent a lot of time to figure out how to raise an error from form_valid... Why it's not in django docs...
@GSNGamesAlexr It's not in the django docs because you really shouldn't do this in form_valid at all. form_valid() is not what it's for. The right place to do this is validate using clean() or other validation method in form such as clean_[] etc...
add_error() is now the best way to do this. https://docs.djangoproject.com/en/2.0/ref/forms/api/#django.forms.Form.add_error
Massively helpful, thank you! Couldn't get the validation to work in the ModelForm clean() method but this did the trick.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks!