【问题标题】:Receiving the 404 error in getting of static django files在获取静态 django 文件时收到 404 错误
【发布时间】:2016-09-25 13:24:42
【问题描述】:

请帮助理解我做错了什么。

我的 settings.py 中有:

PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/'

在 index.html 中:

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

但我仍然有错误 404:

"GET /var/cardsite/cardsite/static/css/table.css HTTP/1.1" 404 1696

我有这个文件:

ls -la /var/cardsite/cardsite/static/css/table.css
-rw-r--r-- 1 root root 77 Sep 25 16:15 /var/cardsite/cardsite/static/css/table.css

那到底是怎么回事?

附:我的项目存储在“/var/cardsite”上,我想在每个应用程序上创建静态文件夹,例如默认应用程序“cardsite”

谢谢

【问题讨论】:

  • 您在使用静态文件之前是否运行过命令collectstatic
  • 是的,但没有帮助
  • 我已经添加了一个答案,看看它是否有帮助。

标签: python html css django static


【解决方案1】:

阅读Django_Docs
您还必须设置 STATIC_ROOT 选项才能使用静态文件,这里有一些帮助 将此添加到您的代码中:

STATIC_URL = os.path.join(PROJECT_ROOT, 'static').replace('\\','')+'/'

# Here you can add all the directories from where you want to use your js, css etc
STATICFILES_DIRS = [
  # This can be same as the static url
  os.path.join(PROJECT_ROOT, "static"),

  # also any other dir you wanna use
  "/any/other/static/path/you/wanna/use",
]

# This is the static root dir from where django uses the files from.
STATIC_ROOT = os.path.join(PROJECT_ROOT, "static_root")

您还需要在urls.py 文件中指定它,只需将以下代码添加到urls.py 文件中:

from django.conf import settings
from django.conf.urls.static import static

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

添加后,运行命令:

python manage.py collectstatic

这会将您需要的所有静态数据复制到静态根目录。

【讨论】:

    猜你喜欢
    • 2022-10-13
    • 2016-04-08
    • 2019-12-06
    • 2018-05-24
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    • 2019-01-23
    相关资源
    最近更新 更多