Django keeps logging me out from dev server when changing my codebase

In my Django app I have a lot of if request.user.is_authenticated logic and once I change some code other than in templates (like forms, models, views, etc.) I get logged out from the development server which makes it quite annoying to always have to re-login in the frontend to test my prior code changes again.

Is there any way to stay logged in (a superuser) when in Debug = True (or other) mode?

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv("DEBUG", "False") == "True"

# Add here to keep me logged in?

The problem is:

SECRET_KEY = os.getenv("DJANGO_SECRET_KEY", get_random_secret_key())

You are generating a new secret key every time the server is restarted. The authentication details are stored in django_sessions table, and the session details are hashed with the SECRET_KEY. So, every time the SECRET_KEY value is changed, the current session details are invalidated and you need to freshly login again.

For the solution: Generate a random secret key manually once and store it as an environment variable in every environment (be it staging, production, or development).

Hope you find this useful.

Back to Top