[英]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.