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
- Model specific exception.
- 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.
- Django runserver custom database
- Django: specifying a base template by directory
- Django Admin without Authentication
- Django – Overriding get_form to customize admin forms based on request
- Is it possible to have validators with parameters?
- Django redirect to another view with context
- Getting Type error while opening an uploaded CSV File
- How to convert request.user into a proxy auth.User class?
- How to use full_clean() for data validation before saving in Django 1.5 gracefully?
- Writable nested serializer in django-rest-framework?