Rajat Saxena Rajat Saxena - 2 months ago 21
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

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.

Comments