簡體   English   中英

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

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

我正在運行一個 Django 網站,它即將 go 投入生產。 我現在需要在我的 settings.py 文件中設置 DEBUG = False。 我收到典型的 500 錯誤,因為我有 static 個文件在本地托管。 我正在努力讓 Whitenoise 能夠托管我的 static 文件,這樣我就可以繼續使用 DEBUG = False。 我遵循了很多文檔和教程,並認為我的所有配置都已設置,但我仍然遇到相同的錯誤。 當 DEBUG = False 時,我的生產頁面上仍然出現 500 個錯誤,其中包含 static 個文件。 此外,當我在 DEBUG = True 時檢查頁面上的任何 static 文件時,URL 根本沒有改變。 我在下面發布了我的所有配置,希望我犯了一個簡單的錯誤,我一直被跳過但是 Whitenoise 似乎沒有工作,而且似乎與以前的方式沒有什么不同,因為 Whitenoise是“實施”。

  • 我已經運行 python manage.py collect static

  • 我已經運行 pip 安裝 whitenoise

  • 我是白噪聲的新手,所以我只是根據我找到的教程和文檔來了解我的知識。

設置.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())

在 HTML 文件中加載 static 的示例在生產中不斷出現 500 錯誤

{{ load static from staticfiles }}

提前致謝!!

更新:

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

此外,所有 static 文件現在只是 {{ load static }}

嘗試這個:

#in 模板

{%load static%}

#在設置.py

如果您的 static 文件目錄名稱不是“靜態”,則只需將以下代碼中的'static'替換為您的靜態文件目錄名稱。

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

注意:注釋STATICFILES_DIRS並在運行collectstatic命令時使用STATIC_ROOT

如果您在同一文件中調用{% static 'your_file' %} ,請始終以{% load static %}開頭 your.html 模板文件。

還...

使用Debug = True沒關系,但如果您將其設置為False ,那么您必須提供至少一個有效的允許主機。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM