Suppress "?next=blah" behavior in django's login_required decorator
django, django-authentication
Solution
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 a very intuitive way, if a later developer inherits your codebase along with a mandate to allow the redirect, it might be a bit flummoxing.
Problem
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?