I want my ModelForm error handler to show validation errors from the save()
method just like they do in the clean()
method – i.e. as a warning on the admin form, instead of generating a 500 page.
The code flow is as follows, in admin.py
:
class XForm(ModelForm):
def save(self, **kwargs):
super().save(**kwargs)
try:
self.instance.update_more_stuff_based_on_extra_fields_in_the_form()
except IntegrityError:
raise ValidationError(_("Earth to Monty Python."))
return self.instance
class XAdmin(admin.ModelAdmin):
form = XForm
admin.site.register(X, XAdmin)
This results in a debugger’s 500 page when the validation error is triggered, not the preferred admin warning.
Note: The following question addresses the similar problem of raising a validation error within the model’s save method. Here we want to raise the error in the model form’s save method.