Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating custom Exceptions that Django reacts to

Tags:

django

For my site I created an abstract Model which implements model-level read permissions. That part of the system is completed and works correctly. One of the methods the permissioned model exposes is is_safe(user) which can manually test if a user is allowed to view that model or not.

What I would like to do is add a method to the effect of continue_if_safe which can be called on any model instance, and instead of returning a boolean value like is_safe it would first test if the model can be viewed or not, then in the case of False, it would redirect the user, either to the login page if they aren't already logged in or return a 403 error if they are logged in.

Ideal usage:

model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
# ... remainder of code to be run if it's safe down here ...

I peeked at how the get_object_or_404 works, and it throws an Http404 error which seems to make sense. However, the problem is that there don't seem to be equivalent redirect or 403 errors. What's the best way to go about this?

(non-working) continue_if_safe method:

def continue_if_safe(self, user):

    if not self.is_safe(user):
        if user.is_authenticated():
            raise HttpResponseForbidden()
        else:
            raise HttpResponseRedirect('/account/')

    return

Edit -- The Solution

The code for the final solution, in case other "stackers" need some help with this:

In the Abstract Model:

def continue_if_safe(self, user):
    if not self.is_safe(user):
        raise PermissionDenied()
    return

Views are caught by the middleware:

class PermissionDeniedToLoginMiddleware(object):
    def process_exception(self, request, exception):
        if type(exception) == PermissionDenied:
            if not request.user.is_authenticated():
                return HttpResponseRedirect('/account/?next=' + request.path)
        return None

Usage in the view (very short and sweet):

model = get_object_or_404(Model, slug=slug)
model.continue_if_safe(request.user)
like image 748
T. Stone Avatar asked Feb 19 '10 19:02

T. Stone


People also ask

What are Django exceptions and how do you handle it?

An exception is an abnormal event that leads to program failure. To deal with this situation, Django uses its own exception classes and supports all core Python exceptions as well. Django core exceptions classes are defined in django. core.

What are the scenarios we may have to choose create custom exception?

You should only implement a custom exception if it provides a benefit compared to Java's standard exceptions. The class name of your exception should end with Exception. If an API method specifies an exception, the exception class becomes part of the API, and you need to document it.

How do I create a runtime exception?

We can create the custom unchecked exception by extending the RuntimeException in Java. Unchecked exceptions inherit from the Error class or the RuntimeException class.


2 Answers

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.

like image 119
Clément Avatar answered Nov 15 '22 15:11

Clément


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.

like image 23
Jonas Geiregat Avatar answered Nov 15 '22 14:11

Jonas Geiregat