Related
I am developing a django project using nginx on the production. But when I start running my nginx server, the django_session table on the mysql starts growing. In each resfresh, I see more rows in the table. Why is that happening? Any way to stop this?
Here is my django settings.
import os
import platform
from pathlib import Path
from mydjangoapp import utilities as util
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'my secret key' #deidentified
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'example.com']
CSRF_TRUSTED_ORIGINS = ['http://localhost', 'http://example.com', 'https://example.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'mydjangoapp',
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'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 = 'mydjangoproj.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'mydjangoapp/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 = 'mydjangoproj.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {},
'db_magicnote': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydb_test',
'USER': '',
'PASSWORD': '',
'HOST': '',
'PORT': '3306',
'OPTIONS': {
'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
},
}
}
DATABASE_ROUTERS = ['mydjangoapp.dbRouter.MyDbRouter']
CURRENT_DATABASE = 'db_mydjangoapp'
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = '/static/'
#STATICFILES_DIRS = [
# BASE_DIR / "static",
#]
STATIC_ROOT = os.path.join(BASE_DIR,'static/')
# MEDIA
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
LOGIN_REDIRECT_URL = '/'
### SESSION SETTINGS ###
CSRF_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
And here is my nginx conf settings:
# configuration of the server
server {
# the port your site will be served on
listen 80;
# the domain name it will serve for
server_name example.com;
charset utf-8;
# max upload size
client_max_body_size 75M; # adjust to taste
# Django media
location /media {
alias C:/Users/Administrator/Documents/mydjangoproj/media; # your Django project's media files - amend as required
}
location /static {
alias C:/Users/Administrator/Documents/mydjangoproj/static; # your Django project's static files - amend as required
}
# Finally, send all non-media requests to the Django server.
location / {
proxy_pass http://localhost:8080;
}
}
Okay, I've finally figured it out. This has nothing to do with the nginx web server. The health check of my AWS application load balancer was sending request every 5 seconds to my website.
I applied two steps:
1-) I increased the interval value to 300 seconds and timeout value to 120 seconds on the health check configuration (these are their maximum values). This way they don't make frequent request to the server that would increase the size of the django_sessions table significantly.
2-) I've started clearing expired sessions in the django_sessions table. There are a couple of ways to handle that:
a-) On MySQL, you can manually run the following sql:
DELETE FROM mydatabase.django_session where expire_date<now()
b-) Under the Django's main project directory, you can manually run the following command on your terminal:
python manage.py clearsessions
c-) One of these commands can be put in a shell script and scheduled to be run periodically (let's say once every day).
I prefer the python command (item 2) for now. As my userbase grows and the project gets larger, I can think of automating this manual process (the last item).
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/'
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.
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '...db name',
'USER': "postgres",
'PASSWORD': '...db password',
'HOST': 'localhost',
'PORT': '5432',
} }
I have a small protein database. You can see the codes here. Say a user searches for their proteins of interest from the database. They can add the sequences to the cart. Also, they can upload their custom data to the database using session. If the user clear the session their custom data will be removed. The purpose is to do additional analysis in the database (say pairwise alignments). The problem is when a user wants to clear session. After clearing the session still the html page shows the data. After ~60 seconds the session clears. I use anonymous sessions in the script.
The database works perfectly well locally. I couldn't figure out where the problem is. I tried both SQLite3 as well as PostgreSQL for the database. Still the problem persists.
"""
Django settings for database project.
Generated by 'django-admin startproject' using Django 2.2.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os, socket
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*******************************************'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'database',
'captcha',
'crispy_forms',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'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 = 'database.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join('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 = 'database.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"
CRISPY_TEMPLATE_PACK = 'bootstrap4'
PROJECT_DIR = os.path.dirname(__file__)
on_production_server = True if socket.gethostname() == '*****' else False
DEBUG = True if not on_production_server else False
TEMPLATE_DEBUG = DEBUG
The following versions are used installed
attrs==19.1.0
biopython==1.73
captcha==0.3
certifi==2019.9.11
chardet==3.0.4
colorclass==2.2.0
dj-database-url==0.5.0
Django==2.1
django-crispy-forms==1.7.2
django-tables2==2.1.0
docopt==0.6.2
ete3==3.1.1
numpy==1.16.4
packaging==19.1
Pillow==6.1.0
pip-upgrader==1.4.15
psycopg2==2.7.6.1
psycopg2-binary==2.7.6.1
pyparsing==2.4.2
PyQt5==5.13.0
PyQt5-sip==4.19.18
pytz==2019.2
requests==2.22.0
six==1.12.0
sqlparse==0.3.0
terminaltables==3.1.0
urllib3==1.25.3
uWSGI==2.0.17.1
whitenoise==4.1.3
I use NGINX and uWSGI for deployment in the Red Hat Enterprise Linux Server release 7.6 (Maipo). The data in the database is very small (700 protein sequences). There are no system admins in our department. Hence I am looking for the answer online. I am new to web development framework (Django) as well as deploying. How to identify and troubleshoot the problem? Can you point me where the problem could be?
The problem is not with Django. It's with nginx configuration file. Added the below line
location / {
add_header 'Cache-Control' 'no-store, no-cache,
must-revalidate, proxy-revalidate, max-age=0'; expires off; }
Referred: https://ryanclouser.com/2015/07/16/nginx-Disable-Caching/
After upgrading an old Django 1.8 to 2.1, when I try to login on my admin site, I get a 404 with message:
Using the URLconf defined in <mysite>.urls, Django tried these URL patterns, in this order:
[...]
The current path, login/, didn't match any of these.
Which I guess is true because it should be on __admin/login as in my urls.py I have:
urlpatterns = [
...
path(r'__admin/', admin.site.urls),
...
]
But:
The GET request /__admin/login returns the login page as expected
The problem happens only in production (with passenger WSGI on a VPS), not on localhost
Logging in the user manually via manage.py shell and django.contrib.auth.authenticate() works correctly
Unfortunately the upgrade happened at the same time as a migration in VPS machine so there may also be a problem with the database.
Python version (on VPS): 3.6.7
Django version (on VPS): 2.1.3 (also tried with 2.1.4)
EDIT 1
I've commented out all other urls, so that now the only URL available is __admin. Now, when I login I get this error:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
1. __admin/
The current path, login/, didn't match any of these.
It looks like django is looking for login/ rather than __admin/login. Is that possible and what could be causing this?
EDIT 2
Added settings file.
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
from django.contrib import messages
PROJ_SHORTNAME = '<removed>'
PROJ_NAME = '<removed>'
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = <removed>
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'bootstrap3',
'mysite',
'blog',
'envelope', # required for contact page
'crispy_forms', # required for contact page
'honeypot', # required for contact page
'braces', # required for contact page
'disqus',
'markdownx',
)
MIDDLEWARE = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = '<removed>.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'mysite.context_preprocessors.proj_name',
],
},
},
]
WSGI_APPLICATION = '<removed>.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': PROJ_SHORTNAME,
'HOST': 'localhost',
'USER': '<removed>',
'PASSWORD': '<removed>',
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-gb'
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
## Markdown
MARKDOWN_EXTENSIONS = ['extra', 'codehilite']
MESSAGE_TAGS = {
messages.DEBUG: 'debug',
messages.INFO: 'info',
messages.SUCCESS: 'success',
messages.WARNING: 'warning',
messages.ERROR: 'danger' # 'error' by default
}
## contact (envelope)
HONEYPOT_FIELD_NAME = 'email2'
CRISPY_TEMPLATE_PACK = 'bootstrap3'
ENVELOPE_USE_HTML_EMAIL = False
ENVELOPE_SUBJECT_INTRO = "[<removed>] "
ENVELOPE_EMAIL_RECIPIENTS = ['<removed>']
## disqus
DISQUS_API_KEY = '<removed>'
DISQUS_WEBSITE_SHORTNAME = '<removed>'
## django sites
SITE_ID = 1
BOOTSTRAP3 = {
# The URL to the jQuery JavaScript file
'jquery_url': STATIC_URL+'mysite/js/jquery.min.js',
# The Bootstrap base URL
'base_url': STATIC_URL+'mysite/',
# The complete URL to the Bootstrap CSS file (None means derive it from base_url)
"css_url": {
"url": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css",
"integrity": "sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u",
"crossorigin": "anonymous",
},
# The complete URL to the Bootstrap CSS file (None means no theme)
'theme_url': None,
# The complete URL to the Bootstrap JavaScript file (None means derive it from base_url)
"javascript_url": {
"url": "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js",
"integrity": "sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa",
"crossorigin": "anonymous",
},
# Put JavaScript in the HEAD section of the HTML document (only relevant if you use bootstrap3.html)
'javascript_in_head': False,
# Include jQuery with Bootstrap JavaScript (affects django-bootstrap3 template tags)
'include_jquery': False,
# Label class to use in horizontal forms
'horizontal_label_class': 'col-md-3',
# Field class to use in horizontal forms
'horizontal_field_class': 'col-md-9',
# Set HTML required attribute on required fields
'set_required': True,
# Set HTML disabled attribute on disabled fields
'set_disabled': False,
# Set placeholder attributes to label if no placeholder is provided
'set_placeholder': True,
# Class to indicate required (better to set this in your Django form)
'required_css_class': '',
# Class to indicate error (better to set this in your Django form)
'error_css_class': 'has-error',
# Class to indicate success, meaning the field has valid input (better to set this in your Django form)
'success_css_class': 'has-success',
# Renderers (only set these if you have studied the source and understand the inner workings)
'formset_renderers':{
'default': 'bootstrap3.renderers.FormsetRenderer',
},
'form_renderers': {
'default': 'bootstrap3.renderers.FormRenderer',
},
'field_renderers': {
'default': 'bootstrap3.renderers.FieldRenderer',
'inline': 'bootstrap3.renderers.InlineFieldRenderer',
},
}
try:
from <removed>.local_settings import *
except ImportError:
pass
And the local_settings.py:
import os
DEBUG = False
STATIC_ROOT = '/home/<removed>/public_html/<removed>/static/'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': '<removed>',
'HOST': 'localhost',
'USER': '<removed>',
'PASSWORD': '<removed>',
}
}
FROM_EMAIL = '<removed>'
BOOTSTRAP3 = {
# The URL to the jQuery JavaScript file
'jquery_url': '//code.jquery.com/jquery.min.js',
}
ALLOWED_HOSTS = [
'<removed>', # Allow domain and subdomains
'.<removed>.', # Also allow FQDN and subdomains
'<removed>', # Also allow FQDN and subdomains
]
LOGIN_URL="/__admin/login/"
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': os.path.expanduser('~/logs/django/debug.log'),
},
},
'loggers': {
'django': {
'handlers': ['file'],
'level': 'DEBUG',
'propagate': True,
},
},
}
TEST
I tried to reproduce your error creating an empty Django 2.1 project and then I modified projects file as you reported:
urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [path(r'__admin/', admin.site.urls)]
local_settings.py
DEBUG = False
ALLOWED_HOSTS = ['*']
LOGIN_URL = "/__admin/login/"
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SECRET_KEY = 'secret-key'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
)
MIDDLEWARE = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'so.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'so.wsgi.application'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = '/media/'
SITE_ID = 1
try:
from so.local_settings import * # noqa
except ImportError:
pass
I was not able to reproduce your error and I think your code is ok.
Suggestion
I think the main motivations for your error on the VPS is on the VPS.
Do you have any stale .pyc or .pyo files on your VPS ?
If so, try deleting them and then restarting the VPS.
If you solve your error, in order to prevent this issue in future, you should remove .pyc or .pyo files before starting your VPS.
It appears that this issue has to do with settings.py. I was facing the same issue and made changes to my settings.py
MIDDLEWARE_CLASSES renamed to MIDDLEWARE
commented reference to 'django.contrib.auth.middleware.SessionAuthenticationMiddleware'
and the problem disappeared
Try setting LOGIN_URL in your settings.py
LOGIN_URL = '__admin/login'
https://docs.djangoproject.com/en/2.1/ref/settings/#login-url
Default: '/accounts/login/'
The URL where requests are redirected for login, especially when using the login_required() decorator.
I just had to do an incremental upgrade too, from Django 1.8 to 2.2.
I did as previously suggested by bir singh (however was too long to post as a comment). I hope this helps someone.
I found the Django settings file
commented out the MIDDLEWARE_CLASSES for reference
added a MIDDLEWARE default section
# Django upgrade 1.11 to 2.x
# MIDDLEWARE_CLASSES = (
# 'django.contrib.sessions.middleware.SessionMiddleware',
# 'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
# 'django.contrib.auth.middleware.AuthenticationMiddleware',
# 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
# 'django.contrib.messages.middleware.MessageMiddleware',
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
# 'django.middleware.security.SecurityMiddleware',
# )
MIDDLEWARE = [
# The following is the list of default middleware in new Django projects.
'django.middleware.security.SecurityMiddleware',
'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',
]
started the runserver and checked the website functionality (all good)
previously I would be getting this error after the upgrade:
django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues:
ERRORS:
?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application.
?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application.
I'm using python 3.8v and django 2.2.
I had also this problem.
using this
url(r'^$admin/', admin.site.urls) on settings.py i could not access to the login form.
However, trying this path('admin/', admin.site.urls) i was able to access and fixed it.
I'd like to add simple cache functionality to my site. I have enabled cache for anonymous users, but it does not work as expected. I'm using memcached.
settings.py
########################### caching #################################
CACHE_PORT = '11211'
CACHE_MIDDLEWARE_SECONDS = 60
CACHE_MIDDLEWARE_KEY_PREFIX = "default"
CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True
# Production Environment
if ON_OPENSHIFT:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '%s:%s' % (os.environ['OPENSHIFT_INTERNAL_IP'], CACHE_PORT),
}
}
CACHE_VIEW_LENGTH = datetime.now() + timedelta(30) # 30 day cache expiration
# Development Environment
else:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:%s' % CACHE_PORT,
}
}
CACHE_VIEW_LENGTH = datetime.now() + timedelta(1) # Set to 0 for development
MIDDLEWARE_CLASSES = (
#cache - must be first in middleware_classes
'django.middleware.cache.UpdateCacheMiddleware',
#cache end
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
'django.middleware.clickjacking.XFrameOptionsMiddleware',
#cache - must be last in middleware_classes
'django.middleware.cache.FetchFromCacheMiddleware',
#cache end
)
Since I have set CACHE_MIDDLEWARE_ANONYMOUS_ONLY = True, I would except that if I load page as logged in user, I would not get cached version.
I loaded index page where is list of my objects. There are 10 objects. I added new object through form. When I checked on my index page again, I see only 10 objects.
So my question is simple: Why is django ignoring my setting for anonymous only and caches pages for logged in users?
CACHE_MIDDLEWARE_ANONYMOUS_ONLY option was removed in Django 1.8. Here is the ticket about that: https://code.djangoproject.com/ticket/15201
When CACHE_MIDDLEWARE_ANONYMOUS_ONLY was working, it was only about writing to cache. When CACHE_MIDDLEWARE_ANONYMOUS_ONLY is True, non-anonymous request never writes to cache, but reads from cache.