2

I wanted to list an object(club) detail on a page by extracting its id from url and giving it to django models api. It is working when that id exist in the database. But when I try giving id in url which does not exist then the model api gives this error:

club = Club.objects.get(id=8) Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py", line 131, in get return self.get_query_set().get(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py", line 366, in get % self.model._meta.object_name) DoesNotExist: Club matching query does not exist.

So I added an exception handler for this error in my view. Here is the code:

def club_detail(request, offset):
    try:
        club_id = int(offset)
        club = Club.objects.get(id=club_id)
    except (ValueError, DoesNotExist):
        raise HTTP404()
    return render_to_response('home/club_detail.html', {'club': club }, context_instance = RequestContext(request))

But it is not catching DoesNotExist error and instead giving a NameError in browser:

NameError at /club/8/
  global name 'DoesNotExist' is not defined
  Request Method:   GET
  Request URL:  http://127.0.0.1:8000/club/8/
  Django Version:   1.4.1
  Exception Type:   NameError
  Exception Value:  
  global name 'DoesNotExist' is not defined

How can I make it working? Thanks in advance

3 Answers 3

8

DoesNotExist is implemented as an attribute of the model itself. Change your line to:

    except (ValueError, Club.DoesNotExist):

Alternatively, since all DoesNotExist errors inherit the ObjectDoesNotExist class, you can do:

from django.core.exceptions import ObjectDoesNotExist

...

    except (ValueError, ObjectDoesNotExist):

as described here.

Sign up to request clarification or add additional context in comments.

Comments

1

You cannot use DoesNotExist directly - it shoul'd be Club.DoesNotExist so your code would look like:

def club_detail(request, offset):
    try:
        club_id = int(offset)
        club = Club.objects.get(id=club_id)
    except (ValueError, Club.DoesNotExist):
        raise HTTP404()
    return render_to_response('home/club_detail.html', {'club': club }, context_instance = RequestContext(request))

Comments

0

You need to import DoesNotExist:

from django.core.exceptions import DoesNotExist

2 Comments

I tried this but it is giving ImportError. And I also opened exceptions.py file, but there is no DoesNotExist class. (I'm running django 1.4)
cannot import name DoesNotExist

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.