Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django logs out when dev server restarts

Tags:

python

django

While developing a Django 1.8 project, I am logged out each time the dev server restarts. That means each time the python code is changed (and the dev server restarts) I have to log back in. It's driving me slightly crazy.

I am using the default SESSION_ENGINE i.e. django.contrib.sessions.backends.db and can see the django_session table has values.

I have DEBUG=True on.

Can anyone suggest other things to check? Thanks.

like image 648
Zemogle Avatar asked Oct 28 '25 08:10

Zemogle


1 Answers

As a security measure (so as to not save sensitive information in public version control) I was autogenerating the SECRET_KEY in settings.py e.g.

chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
SECRET_KEY = get_random_string(50, chars)

When the runserver reboots, this gets regenerated but because this is the session token, the one in the database doesn't match the one in settings and I have log in. Not a problem for deployed version but the cause of the pain in dev version.

To get around this I leave this line in settings.py and hard code a SECRET_KEY in local_settings.py which does not get committed to version control.

Update 20 Oct 2022

I now use an environment variable e.g.

import os
SECRET_KEY = os.environ['SECRET_KEY']

and would not recommend this solution. As mentioned by @abdul-aziz-barkat in the comments, when you have multiple processes serving a website you can get a condition where you users are constantly logged out.

like image 179
Zemogle Avatar answered Oct 29 '25 21:10

Zemogle