[Django]-Django: don't log out when there is an error in view with `request.session.set_exipry`

4👍

Django basically writes your session to the database everytime there is a change to it. Since you are updating your session state in the view decorator, this means that there should be a session write to the DB.

However, if you are on a database with transaction management then when your view fails your database write gets rolled back. However your session cookie expire time has been updated on your browser. This means that your browser session and the session stored on the server no longer match. This inconsistency leads to the session being dropped and you being logged out.

This also explains why it works alright when you comment out that line.

If you use django dev server then you should be able to see your queries in the console. See if the session update query is running successfully when an error occurs. If not, you’ll know why you are getting logged out 🙂

This is desired behavior but if you want to disable it in your debug environment, then just add a check for DEBUG above the relevant line in your decorator. Alternatively, you could disable transaction management (not recommended).

3👍

Not an answer to why, but a workaround perhaps:

def needs_base_index_dict(func):
    def wrapper(request, *args, **kwargs):
        #... do the work
        func(*args, **kwargs)
        #... then set the expiry
        request.session.set_expiry(30*60)
👤Thomas

0👍

You say in the comments that you get the set-cookie header in the error pages as well.
Does the session object look like it’s ok? In the sessions documentation it says that you can just access a db-based session like any other database object.

from django.contrib.sessions.models import Session
s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')

If that session is for an anonymous user then I’m willing to call this a very interesting feature. If it’s a perfectly valid session but somehow it appears to you that you are no longer logged in, there is a bug in handling the session cookie.

👤Jyrsa

Leave a comment