[Fixed]-Type object 'X' has no attribute 'DoesNotExist' with django

20👍

Import the exception,

from django.core.exceptions import ObjectDoesNotExist

And catch it

try:
    Report.objects.get(account_profile=current_profile)
except ObjectDoesNotExist:
    print("report doesn't exist")
    current_report=None

Because ObjectDoesNotExist is a Django specific exception and you have to import it in order to catch it.

Also it is not a property of the model to do Model.ObjectDoesNotExist

8👍

I was also facing this kind of behavior, the problem was having the same View name and Model name.You only need to change the View name.

You can handle exception in both way using

  1. Model specific exception.
  2. django.core.exceptions.ObjectDoesNotExist

try:
     Report.objects.get(account_profile=current_profile)
except Report.DoesNotExist:
     print("report doesn't exist")
     current_report=None

or

try:
     Report.objects.get(account_profile=current_profile)
except ObjectDoesNotExist:
     print("report doesn't exist")
     current_report=None

DoesNotExist

exception Model.DoesNotExist

This exception is raised by the ORM in a couple places, for example by QuerySet.get()
when an object is not found for the given query parameters.
Django provides a DoesNotExist exception as an attribute of each model class to identify the class of object that could not be found
and to allow you to catch a particular model class with try/except.
The exception is a subclass of
django.core.exceptions.ObjectDoesNotExist.

0👍

This happens when we create the function or class with the same name as the model.

👤Vimal

Leave a comment