Question

Let's say I created a Middleware which should redirect user after login to a view with "next" parameter taken from LOGIN_REDIRECT_URL. But it should do it only once directly after logging, not with every request to LOGIN_REDIRECT_URL. At the moment I check User.last_login and compare it with datetime.datetime.now(), but it seems not to be a reasonable solution. Any better ideas?

Was it helpful?

Solution 2

I managed to solve this issue. I created signal for user_logged_in action, thats add a variable redirect_me=True. Thats that i had still the same request in middleware, I could check it and make and redirct. Thats a sample code here:
signals.py: from django.contrib.auth.signals import user_logged_in

def do_stuff(sender, user, request, **kwargs):
    if getattr(request, 'user', None) and not request.user.is_superuser:
        request.do_stuff = True

models.py (you also can place it in init.py, or other file that is run initially on 'runserver'):

from django.contrib.auth.signals import user_logged_in
user_logged_in.connect(do_stuff)

middleware.py:

class PrimordialAdvertMiddleware(object):

def process_response(self, request, response):
        if getattr(request, 'do_stuff', None):
            return do_some_other_stuff()
        return response

You make a process_request action as well. I hope that it will help someone in future.

OTHER TIPS

Maybe you should try to use user_logged_in signal instead of middleware?

Also you can check user object from request for is_anonymous, maybe it can helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top