Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching DoesNotExist exception in a custom manager in Django

I have a custom manager for a Django model. I don't seem to be able to catch DoesNotExist exception here. I know how to do it inside the model but it didn't work here:

class TaskManager(models.Manager):     def task_depend_tree(self, *args, **kwargs):         if "id" in kwargs:             try:                 task = self.get(id=kwargs["id"])             except DoesNotExist:                 raise Http404 

Get_object_or_404 doesn't work either. What is wrong here?

like image 986
Seperman Avatar asked Jan 10 '13 09:01

Seperman


People also ask

How do I handle exceptions in Django?

Custom exception handlingThe exception handler function should either return a Response object, or return None if the exception cannot be handled. If the handler returns None then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response.

What is the exception for the query which generates multiple results when you expect just one for user model class?

MultipleObjectsReturned. When we expect a query to return a single response/ object but it returns more than one object, then Django raises this exception. The MultipleObjectsReturned is also an attribute of models. It is necessary for some models to return multiple objects but for others, it cannot be more than one.

What is the name of the Django exception raised when trying to insert a record with a wrong date format?

The NoReverseMatch exception is raised by django.

What is Django error?

Server errorsWhen DEBUG is False , Django will email the users listed in the ADMINS setting whenever your code raises an unhandled exception and results in an internal server error (strictly speaking, for any response with an HTTP status code of 500 or greater).


1 Answers

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().

from django.core.exceptions import ObjectDoesNotExist

like image 87
Jeff Triplett Avatar answered Sep 16 '22 15:09

Jeff Triplett