Rajat Saxena Rajat Saxena - 1 year ago 117
Python Question

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

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.

Joe Joe
Answer Source

Just use try and catch.

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

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


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