118

I am having issues on trying to figure "DoesNotExist Errors", I have tried to find the right way for manage the no answer results, however I continue having issues on "DoesNotExist" or "Object hast not Attribute DoestNotExists"

from django.http import HttpResponse
from django.contrib.sites.models import Site
from django.utils import simplejson

from vehicles.models import *
from gpstracking.models import *


def request_statuses(request):

    data = []
    vehicles = Vehicle.objects.filter()
    Vehicle.vehicledevice_
    for vehicle in vehicles:
        try:
            vehicledevice = vehicle.vehicledevice_set.get(is_joined__exact = True)
            imei = vehicledevice.device.imei
            try:
                lastposition = vehicledevice.device.devicetrack_set.latest('date_time_process')
                altitude = lastposition.altitude
                latitude = lastposition.latitude
                longitude =  lastposition.longitude
                date_time_process = lastposition.date_time_process.strftime("%Y-%m-%d %H:%M:%S"),
                date_time_created = lastposition.created.strftime("%Y-%m-%d %H:%M:%S")
            except Vehicle.vehicledevice.device.DoesNotExist:
                lastposition = None
                altitude = None
                latitude = None
                longitude = None
                date_time_process = None
                date_time_created = None
        except Vehicle.DoesNotExist:
            vehicledevice = None
            imei = ''

        item = [
                vehicle.vehicle_type.name,
                imei,
                altitude,
                "Lat %s Lng %s" % (latitude, longitude),
                date_time_process,
                date_time_created,
                '', 
                ''
                ]
        data.append(item)
    statuses = {
                "sEcho": 1,
                "iTotalRecords": vehicles.count(),
                "iTotalDisplayRecords": vehicles.count(),
                "aaData": data
                } 
    json = simplejson.dumps(statuses)
    return HttpResponse(json, mimetype='application/json')
Carlos
  • 4,299
  • 5
  • 22
  • 34

4 Answers4

191

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

Carlos
  • 4,299
  • 5
  • 22
  • 34
  • 36
    That'll work, but it's not really the best way. You should figure what class of object is represented by `vehicledevice.device.devicetrack_set`, and then catch `.DoesNotExist`. – mipadi Apr 29 '13 at 23:00
  • I was trying to find that, also I was trying to guess, cause I couldn't find the solution, after reading some doc I found this way Could you try to edit the code please – Carlos Apr 29 '13 at 23:11
  • 1
    Look in the class that represents `vehicledevice.device`, and find out what the related model for the `devicetrack` attribute is. – mipadi Apr 29 '13 at 23:12
  • (It's not possible for me to determine that without your model definitions.) – mipadi Apr 29 '13 at 23:12
  • It would be helpful if you actually included the exact output of the exception that is occurring – storm_m2138 Mar 13 '18 at 21:24
  • @mipadi would be nice to know WHY it is so important to use the `ActualClass.DoesNotExist` exception? – benzkji Jan 05 '19 at 14:26
  • 1
    I'm assuming it's important so that you're not inadvertently catching a `DoesNotExist` for something else...the whole "explicit is better than implicit" zen stuff – Will Gordon Jun 01 '19 at 01:37
173

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
Dmitry Shevchenko
  • 31,814
  • 10
  • 56
  • 62
  • I have tried to do that but the debug on firefox gives me: DoesNotExist at /tracking/request/statuses VehicleDevice matching query does not exist. Lookup parameters were {'is_joined__exact': True} – Carlos Apr 24 '13 at 00:29
  • This is expected and only means that you request an object that does not indeed exist. You should look at your data, or the logic behind it – Dmitry Shevchenko Apr 24 '13 at 00:49
  • 1
    Thanks for you help I have found my answer on a exception management using ObjectDoesNotExist Thanks a lot for your time – Carlos Apr 29 '13 at 21:33
  • I meant to upvote this answer, but by accident downvoted. As I discovered too late I am unable to change my vote from down to up, sorry... – LMB Sep 22 '20 at 09:49
26

The solution that i believe is best and optimized is:

try:
   #your code
except "ModelName".DoesNotExist:
   #your code
Syed_Shahiq
  • 566
  • 6
  • 13
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)
Hasan Khan
  • 633
  • 1
  • 8
  • 15