I’m currently developing an app with django, and every time I have an error when rendering a view or a template, my session gets logged out. This ends up being pretty annoying. How do I disable this ‘feature’? Note that I don’t get logged out if there’s an error when the code is loaded/parsed (e.g. if a decorator on a view fails), only if there’s an error within a view.
EDIT: I just tested and yes, raise Exception in a view does cause this.
All my views are wrapped with a decorator, which, among other things, does:
def needs_base_index_dict(func):
def wrapper(request, *args, **kwargs):
request.session.set_expiry(30*60)
#...
If I comment out the set_expiry line, then I don’t get this behavior. When I fix errors, I am still logged in. If that line is not commented out, then any error in a view – including raise Exception() – logs the session out.
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).