Django logs out when dev server restarts

Question:

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.

Asked By: Zemogle

||

Answers:

That means each time the python code is changed (and the dev server restarts) I have to log back in.

Django automatically incorporates changes to python code without the need to manually restart the server. The server will need to be restarted if any new files have been added.

Are you migrating your changes in with python manage.py migrate?
Ensure that you are not using the --noreload option with python manage.py runserver.

See the django-admin runserver docs. Hope this helps. (and apologies for not having the ability to comment.)

Answered By: Hackworth

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.

Answered By: Zemogle
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.