如何让heroku为我的django项目提供静态文件?
在push到heroku时,我得到了与staticfiles相关的消息:
$ python manage.py collectstatic --noinput
remote: 130 static files copied to '/tmp/build_48c64d55/staticfiles', 410 post-processed.
但是当我进入我的网站时,清除静态文件不被识别并且网络选项卡显示我:
GET https://pure-everglades-09529.herokuapp.com/static/style.css 404 Not Found
这是我的html的内容引用css我找不到:
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="{% static 'style.css' %}">
<title>{% block title %}My amazing site{% endblock %}</title>
</head>
这是我的settings.py的底部,它的配置和其他地方一样,它应该是这样的:
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
STATIC_URL = '/static/'
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Activate Django-Heroku.
django_heroku.settings(locals())
在我的设置中,我已经按照建议在所有地方添加了白噪声依赖:
INSTALLED_APPS = [
'myapp.apps.MyappConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
# Disable Django's own staticfiles handling in favour of WhiteNoise, for
# greater consistency between gunicorn and `./manage.py runserver`. See:
# http://whitenoise.evans.io/en/stable/django.html#using-whitenoise-in-development
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
最后,这里是我的url,我添加了静态url,但只针对我的本地环境:
urlpatterns = [
path('', include('myapp.urls')),
path('admin/', admin.site.urls),
]
if 'Owner' in settings.BASE_DIR:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=setting
我做错了什么?是因为我在设置中有DEBUG=True吗?我将其设置为False作为检查,但得到一个500错误
显然
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(PROJECT_ROOT, 'static'),
]
必须是
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
staticfiles仍然创建在正确的位置,可能是因为变量被
覆盖django_heroku.settings(locals())