[英]Deploying my Django website to Heroku with DEBUG=False doesn't work
當使用 DEBUG=False 將 django 部署到 localhost 或 heroku 時,它會拋出一個錯誤說
C:\Users\krish\Envs\PRREMIA\lib\site-packages\whitenoise\base.py:105: UserWarning: No directory at: c:\Users\krish\Documents\python\PRREMIA\staticfiles\
warnings.warn(u'No directory at: {}'.format(root))
[28/Jul/2019 16:05:43] "GET / HTTP/1.1" 500 27
當 DEBUG=True 時,它工作正常。
靜態設置
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
為什么? 我該如何停止並解決這個問題?
注意:從MIDDLEWARE
刪除 whitenose 中間件並更改STATICFILES_STORAGE
# STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage'
刪除了 500 錯誤,但仍然找不到靜態文件。
非常感謝 Whitenoise 開發人員首先讓這一切成為可能!
在你的 settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'staticfiles')],
'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',
],
},
},
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'build/static'), os.path.join(BASE_DIR, 'build')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
在 views.py 中創建 index.html 的模板視圖
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache
# Serve Single Page Application
index = never_cache(TemplateView.as_view(template_name='index.html'))
在 urls.py 中添加新視圖的路徑
from django.urls import path, include, re_path
from .views import index
urlpatterns += [
re_path('.*', index)
]
在推送到 heroku 之前運行npm run build
然后python manage.py collectstatic
。 這會將您的應用程序構建到構建文件夾中,然后將這些靜態構建文件收集到項目根目錄中的 staticfiles 文件夾中。
如果python manage.py collectstatic
失敗,請先在項目根目錄中創建一個名為 staticfiles 的空目錄。
index re_path 視圖的重點是在像“/login”這樣的路徑重新加載頁面時,始終將您的應用程序指向 index.html。
git add .
git commit -m "blah"
git push heroku master
這對我有用,希望它在將來對人們有所幫助。
如果這不起作用,我的建議是通過在本地運行python manage.py runserver
並弄亂構建文件夾、staticfiles 文件夾和 settings.py 來進行調查,以找出發生了什么。 我還建議記錄以查找錯誤,盡管我自己沒有這樣做。
您的 STATICFILES_DIRS 設置不正確:
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
這是指在你的項目根目錄下有一個叫做static
的目錄,但是沒有這樣的目錄。
看起來您的靜態文件在business
應用程序中,在這種情況下,它們將被自動拾取,因此您可以完全刪除STATICFILES_DIRS
設置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.