How to raise Http403 exception.

2,871 views
Skip to first unread message

shabda

unread,
Mar 13, 2008, 2:45:07 AM3/13/08
to Django users
I have a site where each page is accesible to a different set of
viewers. In my view function, call a function which raises Http404, if
the current user does not have permissions. I want to change this to
returning Http403, when the permissions does not exist. So how can I
raise Http403 exception. I cant find any such class in Django.Http
(Changing the method to return HttpResponseForbidden is too painful,
as the value returned from this method is not returned by the view
function.)

Malcolm Tredinnick

unread,
Mar 13, 2008, 3:02:27 AM3/13/08
to django...@googlegroups.com

You don't do it this way -- as in, don't look for an exception that
corresponds precisely to a particular HTTP status code and except Django
to handle it automatically for you. Http404 is a very special case in
Django of an exception that corresponds to an HTTP response. You should
be raising more semantic exceptions in your code that will, at output
time, be mapped to the appropriate HttpResponse with status code set
(something like HttpResponseForbidde).

In this case, it sounds like you want to be raising something like
django.core.exceptions.PermissionDenied in your code and then catching
that in your view(s).

Hoewver, it's not all hard work. In this particular case (only) --
raising PermissionDenied -- if your code does nothing, the
request/response handling code in Django will convert it to a very
simple HttpResponseForbidden response for you. That's an odd case,
though. Normally, if you raise an exception, you'll have to handle it
yourself and convert it to the appropriate HTTP status code, since only
you really know what the right status code is for your exception paths.

Regards,
Malcolm

--
How many of you believe in telekinesis? Raise my hand...
http://www.pointy-stick.com/blog/

Reply all
Reply to author
Forward
0 new messages