198👍
✅
I have found the solution to this issue using ObjectDoesNotExist on this way
from django.core.exceptions import ObjectDoesNotExist
......
try:
# try something
except ObjectDoesNotExist:
# do something
After this, my code works as I need
Thanks any way, your post help me to solve my issue
175👍
This line
except Vehicle.vehicledevice.device.DoesNotExist
means look for device instance for DoesNotExist exception, but there’s none, because it’s on class level, you want something like
except Device.DoesNotExist
- [Django]-Warning: Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'
- [Django]-What is choice_set in this Django app tutorial?
- [Django]-Django: Record with max element
26👍
The solution that i believe is best and optimized is:
try: #your code except "ModelName".DoesNotExist: #your code
- [Django]-Django – how to unit test a post request using request.FILES
- [Django]-Django select only rows with duplicate field values
- [Django]-In Django, how does one filter a QuerySet with dynamic field lookups?
9👍
First way:
try:
# Your code goes here
except Model.DoesNotExist:
# Handle error here
Another way to handle not found in Django. It raises Http404 instead of the model’s DoesNotExist exception.
https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#get-object-or-404
from django.shortcuts import get_object_or_404
def get_data(request):
obj = get_object_or_404(Model, pk=1)
- [Django]-How to go from django image field to PIL image and back?
- [Django]-Adding django admin permissions in a migration: Permission matching query does not exist
- [Django]-How to change a django QueryDict to Python Dict?
Source:stackexchange.com