Search code examples
djangosessionauthenticationsession-variablesmiddleware

How to create a middleware that set a session variable on login in Django?


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.


Solution

  • 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?