Search code examples
djangoherokuheroku-postgresdjango-settingsdjango-sessions

Django session working normally locally but once deployed to Heroku they are refreshed upon every view change


The sessions work perfectly while changing views when working locally, but when deployed to Heroku it is as if the session was refreshed and all the information it contains is deleted upon every view change. I am using Heroku's Postgres Database.

I have already taken a look at: Django Session Not Working on Heroku but the problem still persists. Other people are having the same problem but there is no clear answer.

Here is my current settings file. Any help would be appreciated

import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent


SECRET_KEY = 'e488a0185303170daa47fe1de243823fbb3db60f045e6eae'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1', 'here goes the heroku host']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    '....',
    '....',

]
ASGI_APPLICATION = 'System.asgi.application'
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'System.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'System.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
 }
import dj_database_url

db_from_env = dj_database_url.config()
DATABASES['default'].update(db_from_env)

SESSION_ENGINE= 'django.contrib.sessions.backends.cached_db'


AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'OPTIONS': {'min_length': 8}
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'authentication.validators.NumericValidator',
    },
    {
        'NAME': 'authentication.validators.UppercaseValidator',
    },
    {
        'NAME': 'authentication.validators.LowercaseValidator',
    },

]
LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/New_York'

USE_I18N = True

USE_L10N = True

USE_TZ = False

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

MEDIA_ROOT = os.path.join(BASE_DIR, 'authentication/media/')
MEDIA_URL = '/authentication/media/'

Solution

  • You are saving sessions to your database, which is a reasonable choice on Heroku, but you are using SQLite as your database.

    Heroku's ephemeral filesystem makes SQLite a poor choice of database. Data will not be shared among dynos and will be lost whenever your dyno restarts. This happens frequently (at least once per day).

    No matter how you choose to handle sessions, you should migrate from SQLite to a client-server database like PostgreSQL if you want to continue using Heroku. Simply doing that is likely to solve your session issue as a side effect.