简体   繁体   English

DEBUG = FALSE 时 Whitenoise 不工作 - Django - 托管 Static 文件

[英]Whitenoise Not Working when DEBUG = FALSE - Django - Hosting Static Files

I am running a Django website and it's about to go into production.我正在运行一个 Django 网站,它即将 go 投入生产。 I am now at the point where I need to set DEBUG = False in my settings.py file.我现在需要在我的 settings.py 文件中设置 DEBUG = False。 I am getting the typical 500 errors because I have static files that are being hosted locally.我收到典型的 500 错误,因为我有 static 个文件在本地托管。 I am working on getting Whitenoise to work to host my static files so I can move on with DEBUG = False.我正在努力让 Whitenoise 能够托管我的 static 文件,这样我就可以继续使用 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.当 DEBUG = False 时,我的生产页面上仍然出现 500 个错误,其中包含 static 个文件。 Also when I inspect any static files on the page when DEBUG = True the URL has not changed at all.此外,当我在 DEBUG = True 时检查页面上的任何 static 文件时,URL 根本没有改变。 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".我在下面发布了我的所有配置,希望我犯了一个简单的错误,我一直被跳过但是 Whitenoise 似乎没有工作,而且似乎与以前的方式没有什么不同,因为 Whitenoise是“实施”。

  • I have run python manage.py collect static我已经运行 python manage.py collect static

  • I have run pip install whitenoise我已经运行 pip 安装 whitenoise

  • I am new to white noise so I am just basing my knowledge on the tutorials and documentation I have found.我是白噪声的新手,所以我只是根据我找到的教程和文档来了解我的知识。

settings.py设置.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在 HTML 文件中加载 static 的示例在生产中不断出现 500 错误

{{ load static from staticfiles }}

Thanks in advance!!提前致谢!!

UPDATE:更新:

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 = ['localhost', '127.0.0.1']



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


TINYMCE_DEFAULT_CONFIG = {
    'selector': 'textarea',
    'theme': 'modern',
    'plugins': 'link image imagetools preview codesample contextmenu table code lists print save autosave fullscreen spellchecker textcolor',
    'toolbar1': 'fontselect fontsizeselect formatselect | bold italic underline | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent | table | link image | preview',
    'contextmenu': 'formats | link image',
    'menubar': True,
    'inline': False,
    'statusbar': True,
    'width': 740,
    'height': 990,
}
#TINYMCE_SPELLCHECKER = True

QUILL_CONFIGS = {
    'default': {
        'theme': 'snow',
        'modules': {
            #'syntax': True,
            #'imageResize': True,
            'toolbar': [
                [
                    {'font': []},
                    {'header': []},
                    {'align': []},
                    'bold', 'italic', 'underline', 'strike', 'blockquote',
                    {'color': []},
                    {'size': []},
                    {'background': []},
                ],
                ['code-block', 'link'],
                ['clean'],
                ['link', 'image'],
            ],
        }
    }
}

CKEDITOR_THUMBNAIL_SIZE = (500, 500)

CKEDITOR_CONFIGS = {
    'default': {
        'height': '1010',
        'width': '747',
        'skin': 'moono',
        'toolbar_Basic': [
            ['Source', '-', 'Bold', 'Italic']
        ],
        'toolbar_YourCustomToolbarConfig': [
            {'name': 'document', 'items': ['Save', 'Print', '-', 'Templates']},
            {'name': 'clipboard', 'items': ['Cut', 'Copy', '-', 'Undo', 'Redo']},
            {'name': 'editing', 'items': ['Find', 'Replace']},
            '/',
            {'name': 'basicstyles',
             'items': ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript']},
            {'name': 'paragraph',
             'items': ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-',
                       'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl']},
            {'name': 'insert',
             'items': ['Image', 'Table', 'SpecialChar']},
            '/',
            {'name': 'styles', 'items': ['Styles', 'Format', 'Font', 'FontSize']},
            {'name': 'colors', 'items': ['TextColor', 'BGColor', 'ShowBlocks']},
            #{'name': 'about', 'items': ['About']},
            '/',  # put this to force next toolbar on new line
            {'name': 'yourcustomtools', 'items': [
                # put the name of your editor.ui.addButton here

            ]},
        ],
        'toolbar': 'YourCustomToolbarConfig',  # put selected toolbar config here
        # 'toolbarGroups': [{ 'name': 'document', 'groups': [ 'mode', 'document', 'doctools' ] }],
        # 'height': 291,
        # 'width': '100%',
        # 'filebrowserWindowHeight': 725,
        # 'filebrowserWindowWidth': 940,
        # 'toolbarCanCollapse': True,
        # 'mathJaxLib': '//cdn.mathjax.org/mathjax/2.2-latest/MathJax.js?config=TeX-AMS_HTML',
        'tabSpaces': 4,
        'extraPlugins': ','.join([
            'uploadimage', # the upload image feature
            # your extra plugins here
            'div',
            'autolink',
            'autoembed',
            'embedsemantic',
            # 'devtools',
            'widget',
            'lineutils',
            'clipboard',
            'dialog',
            'dialogui',
            'elementspath'
        ]),
    }
}

CKEDITOR_UPLOAD_PATH = "uploads/"

# 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_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'


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











# 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())

Also, all static files now are just {{ load static }}此外,所有 static 文件现在只是 {{ load static }}

Try this:尝试这个:

#in Template #in 模板

{%load static%}

#in settings.py #在设置.py

if your static files directory name is not 'static', then just replace 'static' in the below code with your static-files directory name.如果您的 static 文件目录名称不是“静态”,则只需将以下代码中的'static'替换为您的静态文件目录名称。

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.注意:注释STATICFILES_DIRS并在运行collectstatic命令时使用STATIC_ROOT

Always begin your.html template file with {% load static %} if you call {% static 'your_file' %} in the same file.如果您在同一文件中调用{% static 'your_file' %} ,请始终以{% load static %}开头 your.html 模板文件。

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.使用Debug = True没关系,但如果您将其设置为False ,那么您必须提供至少一个有效的允许主机。

...
ALLOWED_HOSTS = ['your_url_comes_here.com']
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM