Alex Rivera | Logout

Suppress "?next=blah" behavior in django's login_required decorator

Asked 2012-06-08T14:06:30.920
20

I love django's @login_required decorator, but there's one thing I can't figure out how to make it do.

If an unauthenticated user tries visits a @login_required page (e.g. "/private-stuff/"), I want to kick them back to the home page (e.g. "/home/"). But I don't want to append a "?next=" argument to the url. In other words, I just want to redirect to "/home/", not "/home/?next=/private-stuff/".

How can I do that? Is there a better way than just writing my own decorator?

Edit
Report

1 Answer

9

Well, there's two ways that I can think of. First, would be the "correct" way, in the sense that you're not breaking any functionality, only adding new functionality: create your own login_required decorator. The problem though is that Django has really tucked the redirect after login functionality away, and it requires a lot of parts. The login_required decorator is really just a wrapper around the user_passes_test decorator, which in turn calls the redirect_to_login view, and it's that view that adds the next param to the querystring. In your custom decorator, you can roll all or some of this functionality straight into the decorator, but you'll need to reference all three for the necessary code.

The other, and far simpler option, is to create some middleware to remove the querystring if it's set:

from django.conf import settings
from django.http import HttpResponseRedirect

class RemoveNextMiddleware(object):
    def process_request(self, request):
        if request.path == settings.LOGIN_URL and request.GET.has_key('next'):
            return HttpResponseRedirect(settings.LOGIN_URL)

And, then add the import path to that middleware to MIDDLEWARE_CLASSES. Remember that in the request phase, middleware is processed first to last or top-down, in other words. This should come relatively early in the request phase, but you may need to play around a bit with it to see what can and can't come before it.

The only real problem with this method is that it "breaks" the next redirect functionality, and not in

answered 2012-06-08T14:50:25.180

Your Answer