3

As the question says, I'd like to set some variable to user session when the user get logged and remove this variable on logout or browser close.

Initially I thought to write my custom login view to achieve this, but probably a middleware is a better solution.

realnot
  • 721
  • 1
  • 11
  • 31
  • http://stackoverflow.com/questions/14465993/how-can-i-set-and-get-session-variable-in-django – akhil viswam Jul 20 '16 at 14:27
  • that answer is about set a variable to session, my question is related to Middleware. @AK thanks for the down vote on a useful question – realnot Jul 20 '16 at 14:29
  • django have default session middleware. So why you need to use another? – akhil viswam Jul 20 '16 at 14:31
  • So the solution for you is inherit/rewrite the django auth login view to just add this variable, and doing the same with the logout to remove it instead of creating a middleware that do some business logic based on user? – realnot Jul 20 '16 at 14:36
  • If you simply want to use session use django session middleware.Else if you need to do some custome tasks also use your own custom middleware – akhil viswam Jul 20 '16 at 14:42
  • Yes, this is what I asked. – realnot Jul 20 '16 at 14:44

2 Answers2

2

The middleware wasn't the right way to achieve the solution. I discovered the signals and I implemented my solution in this way:

@receiver(user_logged_in)
def sig_user_logged_in(sender, user, request, **kwargs):
    moderator = get_or_none(CompanyModerator, moderator__user=request.user)
    if moderator:
        if 'company_id' not in request.session:
            request.session['company_id'] = moderator.company.id

The difference is that a middleware is triggered on each django request, when the needs was just do something when the user get logged-in/out. Each time that an user get logged-in/out we add some data/object-models etc.. to the session to track the user all around the website.

What do you think?

realnot
  • 721
  • 1
  • 11
  • 31
1

After going through all the comments to your question, I would also say the same as @akhil viswam in his last comment.

But now that you specified that you do want to do some custom tasks, then you can write your own custom middleware like this -> https://github.com/ankushrgv/notification/blob/master/apps/accounts/middlewares.py

and then include it in your settings.py like this -> https://github.com/ankushrgv/notification/blob/master/config/settings.py

Basically I was writing the user_id : session_id key value pairs in Redis and then reading them in my views to show real time notifications but only to the logged-in users.

I hope this will give you a fair idea about how to write your own custom middleware.

Ankush Raghuvanshi
  • 1,392
  • 11
  • 17