首页 > 解决方案 > 如何使用 Django 访问静态 css 文件

问题描述

我无法在 cmd 中使用 Django 访问静态文件。我收到此错误:"GET/'/static/blog/css/main.css HTTP/1.1" 404 2371。这是代码:

#settings.py

STATICFILES_DIR = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

 #base.html
   {% load static %}
<link rel="stylesheet"  type="text/css" href="'{% static 'blog/css/main.css' %}">

this is my directory
├───blog
│   ├───migrations
│   │   └───__pycache__
│   ├───templates
│   │   └───blog
│   │       └───static
│   │           └───blog
│   │               └───css
│   └───__pycache__
└───HelloDjango
    └───__pycache__

标签: pythondjangostaticroot

解决方案


Django 和 python 从来不会对他们抛出的异常撒谎,他们的文档也没有关于如何解决它的文档。如果您参考链接,他们有一个非常简洁的方法来解释如何快速启动和运行。

您需要一个位置,它将 Django 静态文件复制到它开始渲染的某个本地文件夹。

这可能是您忘记添加以下内容的问题吗?

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
    '/var/www/static/',   # -> your homework to figure what this is.
]

如何将这些添加到您的 urls.py 文件中

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

    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

也许您必须完成所有这些,但是您是否告诉 Django 通过运行以下命令来收集它们?

python manage.py collectstatic

AFAIK Django 中静态元素的首选结构是

.
├── my_app/
│   ├── static/
│   │   └── my_app/
│   │       └── admin-custom.css
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── static/
├── templates/
│   └── admin/
│       └── base.html
└── manage.py

但是你的目录结构不是你提到的 Django 来收集它的,不是吗?

尝试以上所有方法,让我知道它是否适合您。

另一个提示:

 <link rel="stylesheet" href="{% static "my_app/admin-custom.css" %}"> # figure out the hint here

推荐阅读