Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

django

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?

like image 844
Rajat Saxena Avatar asked Jul 02 '12 12:07

Rajat Saxena


3 Answers

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.

like image 67
Joe Avatar answered Oct 18 '22 15:10

Joe


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.

like image 14
Chirael Avatar answered Oct 18 '22 15:10

Chirael


Simplest solution: write a middleware implementing process_exception that only catches IntegrityError and returns an HttpResponse with your rendered template, and make sure this middleware is after the default error handling middleware so it is called before (cf https://docs.djangoproject.com/en/dev/topics/http/middleware/#process-exception for more).

Now if I was you, I wouldn't assume such a thing as "there is only one obvious case where "IntegrityError" can arise", so I strongly recommand you do log the exception (and send email alerts) in your middleware.

like image 3
bruno desthuilliers Avatar answered Oct 18 '22 17:10

bruno desthuilliers