karambir
karambir

Reputation: 385

Getting NameError for an exception handling

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

Upvotes: 2

Views: 3054

Answers (3)

David Robinson
David Robinson

Reputation: 78610

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.

Upvotes: 8

DimmuR
DimmuR

Reputation: 291

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))

Upvotes: 1

nneonneo
nneonneo

Reputation: 179452

You need to import DoesNotExist:

from django.core.exceptions import DoesNotExist

Upvotes: 0

Related Questions