Django:生成的静态文件路径错误 HTML

Django: path to static file is wrong in generated HTML

我有一些 javascript 想要 运行 在我正在构建的 Django 站点的特定页面上。在我目前拥有的模板中: <script type='text/javascript' src='{% static "/home_page/github_repos.js" %}'></script>

由此产生的HTML是: http://localhost:8000/home_page/github_repos.js

问题是我在 /static/home_page/ 中有 javascript。

如果我在路径中硬编码为: <script type='text/javascript' src='static/home_page/github_repos.js'></script>

一切正常。

但是,我遇到了我不理解的奇怪行为:

如果,在模板中我设置的路径是这样的: <script type='text/javascript' src='{% static "static/home_page/github_repos.js" %}'></script>

HTML 生成的 src 属性为 /static/static/home_page/github_repos.js

真正让我失望的部分是,如果我在使用模板标签时不把 /static/ 放在 src 的前面(就像我给出的第一个例子),/static/没有添加,但是,如果我在前面添加 /static/ ,它就会被添加。我需要在src属性前面加上/static/,但是只加一次

一些相关信息: 我的 home_page 应用程序解析为“/”作为 url,因此 localhost:8000/ 让您进入主页。

我已将'django.contrib.staticfiles'包含在我安装的应用程序中

最后,STATIC_URL = '/static/'

出现此问题是因为我的 home_page 应用解析为 localhost:8000/ 的根地址吗?

感谢任何帮助。

这个问题是因为static标签中的路径应该相对于静态目录。来自 the docs:

Uses the configured STATICFILES_STORAGE storage to create the full URL for the given relative path

您正在使用绝对路径。相反,您应该使用:

{% static "home_page/github_repos.js" %}

请注意前导正斜杠的省略。