【发布时间】:2021-01-06 01:36:22
【问题描述】:
问题
我正在构建一个 django 网络应用程序。当我在本地运行我的应用程序(ubuntu 20.04、python 3.8.5、django 3.1.4)时,我无法在 html 模板中显示静态文件(图标)。
在 HEROKU CLOUD 上部署时没有此问题,仅在我的本地主机上。
在我的本地主机上加载 webpabe 时,我可以在 Django wsgi 控制台中看到"GET /static/icons/graph-up.svg HTTP/1.1" 404 1781。
我的项目树:
django-project
|_ ...
|_ static
|_ icons
|_ graph-up.svg
index.html
{% load static %}
<img src="{% static 'icons/graph-up.svg' %}" />
settings.py
[...]
BASE_DIR = Path(__file__).resolve().parent.parent
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# I've tried with and without whitenoise, doesnt seem to change anything
MIDDLEWARE = [
# 'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
# ...
]
[...]
urls.py
urlpatterns = [
path('', views.home, name='index'),
...
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
我已按照https://docs.djangoproject.com/en/3.1/howto/static-files/的指示进行操作
欢迎任何想法或建议!
到目前为止我在本地尝试过的内容
没有成功(图标出现 404 错误)
-
python manage.py runserver(使用 django 的 wsgi 运行) gunicorn my_app.wsgi-
heroku local(模拟本地gunicorn的heroku web服务器) -
python manage.py runserver --insecure(来自Django Static files 404) - 在
django.middleware.security.SecurityMiddleware之后的 MIDDLEWARE 中使用/不使用whitenoise.middleware.WhiteNoiseMiddleware行在本地加载应用程序
部分成功
根据Django Static files 404的回答:
- 我替换了:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
与:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'), )
- 我重新加载了 wsgi,瞧。图标出现。
- 但是当我恢复到原来的时候
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
只是为了看看会发生什么,图标仍然出现。
结论
我不确定这是正确的做法,但它似乎工作正常。这是我解决此问题的方法。在我的 settings.py 中(对于 heroku):
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
在我的 settings_dev.py(本地主机)中:
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (os.path.join('static'), )
【问题讨论】:
-
我很确定 heroku 方面,您的 djando 应用程序有一个
reverse proxy,而python manage.py runserver没有。如果您可以发布您的 heroku 配置,那会有所帮助。 -
欢呼@tim - Heroku 云运行 gunicorn my_app.wsgi。我也尝试使用 gunicorn 在本地运行我的应用程序,但我仍然遇到同样的问题。抱歉忘了提,现在编辑我的问题。
-
嘿@tamizboule 你能找到解决方案吗?面临完全相同的问题。静态文件在 Heroku 上运行良好,但在我的本地主机上却不行