Django: Catching Integrity Error and showing a customized message using template


Question

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?

1
66
8/11/2017 1:24:05 PM

Accepted Answer

Just use try and catch.

from django.db import IntegrityError
from django.shortcuts import render_to_response

try:
    # code that produces error
except IntegrityError as e:
    return render_to_response("template.html", {"message": e.message})

If you want you can use the message in your template.

EDIT

Thanks for Jill-Jênn Vie, you should use e.__cause__, as described here.

142
5/23/2017 11:47:02 AM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon