Hi, On Thu, Sep 20, 2007 at 08:47:57AM -0700, shabda wrote: > I have a number of pages which can potentially raise the > self.model.DoesNotExist exception. Whenever this exception is raised, > it maps to a HTTP 404 for me. (That object does not exist in the > database, so I cant show this, so I want to return a 404 exception). > So apart from manually adding try-except to all my views, how can I > return a 404 response on the self.model.DoesNotExist.
You probably don't want to do this in your model. How about:
from django.core.exceptions import ObjectDoesNotExist
from django.core.http import Http404
def 404_on_dne(wrapped):
def wrapper(*args, **kwargs):
try:
return wrapped(*args, **kwargs)
except ObjectDoesNotExist:
raise Http404
return wrapper
Then you can wrap your views:
@404_on_dne
def my_view(request, arg1, arg2):
obj = Model.objects.get(...)
# do something
I'm not entirely sure that you shouldn't just explicitly handle these exceptions
in your views (you can end up masking some DNE exceptions that are really bugs),
but that's a way to do what you want.
Disclaimer: I haven't tried any of this code. Might have bugs.
-Forest
--
Forest Bond
http://www.alittletooquiet.net
signature.asc
Description: Digital signature

