首页 > 解决方案 > 找不到 Heroku Django 静态文件

问题描述

引用静态文件(例如 CSS)时,我在 Heroku 上的 Django 应用程序出现错误。这些文件是在我的本地 Linux 机器上运行站点时找到的,但在 Heroku 上部署时却没有。我查看了与静态文件相关的Django 文档,但我不明白我做错了什么。

django.contrib.staticfiles包含在我的INSTALLED_APPS.

my_site/settings.py我有STATIC_URL = '/static/'.

在我的 HTML 模板中,我有

{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'reco/style.css' %}">

结果是在本地运行时找到了 CSS 文件,但在 Heroku 上却没有。我怎样才能解决这个问题?我想要最简单的解决方案 - 这是一个非常小的站点。

# Log message when running the app on the local machine: file is found and has not changed (correct)
[13/May/2020 15:02:52] "GET /static/reco/style.css HTTP/1.1" 304 0
# Log message when running the app on Heroku: not found. Why?
2020-05-13T20:09:20.327218+00:00 app[web.1]: Not Found: /static/reco/style.css

更新:根据评论的建议,我已按照Heroku Django 文档中的建议配置了站点

STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'    
# Extra places for collectstatic to find static files.
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'reco', 'static'),
)

现在,当我部署到 Heroku 时,我看到它collectstatic正在收集我的静态文件 - 但 Heroku 在运行时仍然找不到它们。

标签: djangoheroku

解决方案


根据Heroku 的开发中心...

您需要安装whitenoise才能在生产模式下提供静态文件。

按照此处的安装说明进行操作。


推荐阅读