Skip to content

Instantly share code, notes, and snippets.

@cansadadeserfeliz
Last active March 24, 2020 00:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save cansadadeserfeliz/3b62a13bdce7fe4178ac to your computer and use it in GitHub Desktop.
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
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())
@nicolasmendoza
Copy link

thanks!

@GSNGamesAlexr
Copy link

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...

@SLiNv
Copy link

SLiNv commented Aug 8, 2017

@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...

@epicfaace
Copy link

@bpinkert
Copy link

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