Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle database exceptions in Django

Tags:

python

django

I want to known the best way to handle database exceptions and display messages back to the user. I have been looking at messages.add_message in my views using a try.

For example:

The following error (1062, "Duplicate entry '123321' for key 'PRIMARY'"). Display back to the user friendly message: "Error uploading CSV Duplicate entries"

  1. Is the the recommended way?

  2. Are there any good tutorials on error handling (i.e. blog posts) that you would recommend as a good approach?

like image 446
Prometheus Avatar asked Jan 07 '13 12:01

Prometheus


People also ask

How does Django handle db exception?

Database Exceptions are documented, check this answer to see an example of how to use them. If you are encountering this error while processing a form you should probably handle the exception when validating your form. So in case an exception is raised you redisplay the form with the appropriate error message.

What is an exception in database?

An exception is an error condition during a program execution. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are two types of exceptions − System-defined exceptions.

How do I get Donotexist in Django?

Try either using ObjectDoesNotExist instead of DoesNotExist or possibly self. DoesNotExist . If all else fails, just try and catch a vanilla Exception and evaluate it to see it's type().


1 Answers

Database Exceptions are documented, check this answer to see an example of how to use them.

If you are encountering this error while processing a form you should probably handle the exception when validating your form. So in case an exception is raised you redisplay the form with the appropriate error message.

like image 129
arie Avatar answered Oct 23 '22 07:10

arie