[Fixed]-Creating custom Exceptions that Django reacts to

11👍

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.

5👍

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.

2👍

Django annoying has a solution for this:

from annoying.exceptions import Redirect

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

1👍

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:

@safety_check:
def some_view(request):
    #Do Stuff
👤Zach

Leave a comment