[Fixed]-Creating custom Exceptions that Django reacts to


For the forbidden (403) error, you could raise a PermissionDenied exception (from django.core.exceptions).

For the redirecting behaviour, there’s no built-in way to deal with it the way you describe in your question. You could write a custom middleware that will catch your exception and redirect in process_exception.


I’ve made a little middleware that return whatever your Exception class’s render method returns. Now you can throw custom exception’s (with render methods) in any of your views.

class ProductNotFound(Exception):
    def render(self, request):
        return HttpResponse("You could ofcourse use render_to_response or any response object")

pip install -e git+http://github.com/jonasgeiregat/django-excepted.git#egg=django_excepted

And add django_excepted.middleware.ExceptionHandlingMiddleware to your MIDDLEWARE_CLASSES.


Django annoying has a solution for this:

from annoying.exceptions import Redirect

    raise Redirect('/')  # or a url name, etc


You want to use decorators for this. Look up login_required for an example. Basically the decorator will allow you check check the safety and then return HttpResponseRedirect() if its not safe.

Your code will end up looking something like this:

def some_view(request):
    #Do Stuff

Leave a comment