In my django powered app there is only one obvious case where \"IntegrityError\" can arise.
So, how can I catch that error and display a message using templates?
If you're using class-based views with the CreateView
mixin, you'll want to try
the call to the superclass's form_valid
, for example:
from django.db import IntegrityError
...
class KumquatCreateView(CreateView):
model = Kumquat
form_class = forms.KumquatForm
...
def form_valid(self, form):
...
try:
return super(KumquatCreateView, self).form_valid(form)
except IntegrityError:
return HttpResponse("ERROR: Kumquat already exists!")
You can use a template, render_to_response
etc. to make the output nicer, of course.