Home > other >  Whitenoise Not Working when DEBUG = FALSE - Django - Hosting Static Files
Whitenoise Not Working when DEBUG = FALSE - Django - Hosting Static Files

Time:01-18

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.

settings.py

import django_heroku
from pathlib import Path
import os
from django_quill import quill
from inspect_list.security import *

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
ROOT_DIR = os.path.dirname(BASE_DIR)
TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates')
#MEDIA_ROOT = os.path.join(BAS_DIR, 'media')
TIME_INPUT_FORMATS = ['%I:%M %p',]

#Media_URL = '/signup/front_page/sheets/'


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

# SECURITY WARNING: keep the secret key used in production secret!
#SECRET_KEY = 'HERE BUT SECURED IN A DIFFERENT FILE'


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

ALLOWED_HOSTS = []


#ADMIN_USERNAME = 'lhy'
#ADMIN_PASSWORD = 'pbkdf2_sha256$180000$nMNyyIvw0TgW$BWgVFXrb25VY7 QVURr4/QawrSTbHIksIYzoC3rWyRc='
#AUTHENTICATION_BACKENDS = [
 #   'django.contrib.auth.backends.ModelBackend',
 #   'config.backends.SettingsBackend',
#]


EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'my_app',
    'django_quill',
    'tinymce',
    'ckeditor',

    #'django_extensions',

    'storages',
    #'django-storages',

    'django_filters',
]

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 = 'inspect_list.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_DIR,],
        'DIRS': [os.path.join(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 = 'inspect_list.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.1/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/3.1/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',
    },
]

#AWS_ACCESS_KEY_ID = 'HERE BUT SECURED IN A DIFFERENT FILE'
#AWS_SECRET_ACCESS_KEY = 'HERE BUT SECURED IN A DIFFERENT FILE'
#AWS_STORAGE_BUCKET_NAME = 'HERE BUT SECURED IN A DIFFERENT FILE'










DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None


STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')












# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'America/Cancun'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

MEDIA_URL = '/mediafiles/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles')
AUTH_USER_MODEL = 'my_app.CustomUser'

LOGIN_REDIRECT_URL = 'front_page'
LOGOUT_REDIRECT_URL = 'login'

django_heroku.settings(locals())

example load static in HTML file that keeps getting 500 error in production

{{ load static from staticfiles }}

Thanks in advance!!

CodePudding user response:

Try this:

#in Template

{%load static%}

#in settings.py

if your static files directory name is not 'static', then just replace 'static' in the below code with your static-files directory name.

if DEBUG:
        STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static')]
else:
        STATIC_ROOT = os.path.join(BASE_DIR, 'static')

NOTE: Comment STATICFILES_DIRS and use STATIC_ROOT when you run collectstatic command.

CodePudding user response:

Always begin your .html template file with {% load static %} if you call {% static 'your_file' %} in the same file.

Also...

With Debug = True it does not matter, but if you set it to False, then you have to provide at least one valid allowed host.

...
ALLOWED_HOSTS = ['your_url_comes_here.com']
...
  •  Tags:  
  • Related