Opened 7 months ago

Last modified 7 months ago

#35290 closed Bug

500 Server error. Whitenoise Not Working when DEBUG = FALSE - Django - Hosting Static Files — at Initial Version

Reported by: Shihab Khan Owned by: nobody
Component: contrib.staticfiles Version: 4.2
Severity: Normal Keywords: 500 Server error, Whitenoise, DEBUG = FALSE
Cc: Shihab Khan Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

I am running a Django website and it's about to go into production. I am now at the point where I need to set DEBUG = False in my settings.py file. I am getting the typical 500 errors because I have static files that are being hosted locally. I am working on getting Whitenoise to work to host my static files so I can move on with DEBUG = False. I have followed a lot of documentation and a lot of tutorials and think all of my configurations are all set but I am still getting the same error. When DEBUG = False I am still getting 500 errors on my production pages that have static files. Also when I inspect any static files on the page when DEBUG = True the URL has not changed at all. I am posting all of my configuration below in hopes that there is a simple mistake I made that I have been continuously skipped over but Whitenoise doesn't seem to be working and there seems to be no different from the way it was before now as Whitenoise is "implemented".

I have run python manage.py collect static

I have run pip install whitenoise

I am new to white noise so I am just basing my knowledge on the tutorials and documentation I have found.

setting.py
from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(file).resolve().parent.parent

def load_env():

env_file = os.path.join(BASE_DIR, '.env')
if os.path.exists(env_file):

with open(env_file, 'r') as file:

for line in file:

line = line.strip()
if line and not line.startswith("#"):

key, value = line.split('=')
os.environ[key] = value

# Load environment variables from the .env file
load_env()

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-x=qe5@3%@t1fk)pk@uyv&r!z#9==*-&aiqfau3@9x@+j%nm'

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

ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS').split(',')

# Application definition

INSTALLED_APPS = [

'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'accounts',
'home',
'about',
'pricing',
'blog',
'contact',
'service',
'project',
'settings',
'legal',
'menus',
'adminapp',
'marketing',
'custompage',
'ckeditor',

]

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',

]

if os.getenv('DEMO_MODE') == 'True':

MIDDLEWARE.append('core.middleware.middleware.DemoModeMiddleware')

if os.getenv("WHITENOISE_CONFIG") == "True":

MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware')



ROOT_URLCONF = 'core.urls'

TEMPLATES = [

{

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, os.getenv('TEMPLATES_DIRS'))],
'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',
'core.context_processors.website_settings_context',
'core.context_processors.seo_settings_context',
'core.context_processors.header_footer_context',
'core.context_processors.menu_data',
'core.context_processors.user_profile_context',
'core.context_processors.service_context',
'core.context_processors.project_context',
'core.context_processors.demo_mode_enabled',

],

},

},

]

WSGI_APPLICATION = 'core.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

# First install my sql client using - pip install mysqlclient
if os.getenv('MYSQL_DB') == 'True':

DATABASES = {

'default': {

'ENGINE': 'django.db.backends.mysql',
'NAME': os.getenv('DB_NAME'),
'USER': os.getenv('DB_USER'),
'PASSWORD': os.getenv('DB_PASSWORD'),
'HOST': os.getenv('DB_HOST'),
'PORT': os.getenv('DB_PORT'),

}

}

else:

DATABASES = {
'default': {

'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',

}

}

# Email Setup
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = os.getenv('EMAIL_HOST')
EMAIL_PORT = os.getenv('EMAIL_PORT')
EMAIL_USE_TLS = os.getenv('EMAIL_USE_TLS')
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')

# Password validation
# https://docs.djangoproject.com/en/4.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/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = os.getenv('TIME_ZONE')

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = os.getenv('STATIC_URL')
STATICFILES_DIRS = [os.path.join(BASE_DIR, str(os.getenv('STATICFILES_DIRS')))]
STATIC_ROOT = os.path.join(BASE_DIR, str(os.getenv('STATIC_ROOT')))
MEDIA_URL = str(os.getenv('MEDIA_URL'))
MEDIA_ROOT = os.path.join(BASE_DIR, str(os.getenv('MEDIA_ROOT')))

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

AUTH_USER_MODEL = 'accounts.User'

# white noise settings
if os.getenv('WHITENOISE_CONFIG') == 'True':

STORAGES = {

"default": {

"BACKEND": "django.core.files.storage.FileSystemStorage",

},

"staticfiles": {

"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",

},

}

urls.py

from django.contrib import admin
from django.urls import path ,include
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from core.sitemaps import generate_sitemap
from django.urls import re_path
from django.views.static import serve

urlpatterns = [

path('oldadmin/', admin.site.urls),
path('admin/' , RedirectView.as_view(pattern_name="adminHome"), name='adminRedirect'),
path('dashboard/' , RedirectView.as_view(pattern_name="adminHome"), name='adminRedirect2'),
path(, include('adminapp.urls')),
path(
, include('accounts.urls')),
path(, include('home.urls')),
path(
, include('about.urls')),
path(, include('pricing.urls')),
path(
, include('blog.urls')),
path(, include('contact.urls')),
path(
, include('service.urls')),
path(, include('project.urls')),
path(
, include('legal.urls')),
path(, include('marketing.urls')),
path(
, include('custompage.urls')),
path('sitemap.xml', generate_sitemap, name='generate_sitemap'),

]

handler404 = 'accounts.views.error_404'
handler404 = 'adminapp.views.error_404'
handler404 = 'home.views.error_404'
handler404 = 'service.views.error_404'
handler404 = 'project.views.error_404'
handler404 = 'contact.views.error_404'
handler404 = 'about.views.error_404'
handler404 = 'blog.views.error_404'
handler404 = 'settings.views.error_404'
handler404 = 'legal.views.error_404'

handler500 = 'adminapp.views.error_500'

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top