python - 如何使用 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__
解决方案
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
推荐阅读
- python - Python多处理无法从共享集中读取
- python - 有没有办法知道传递给函数的参数值?
- linux - 如何将 libname.so 链接到 C?
- c# - 使用 iText 打印扭曲的粗体文本
- c++ - 基于模板变量参数的类模板内的函数指针定义
- hive - HiveSQL 的 REPLACE() 函数,REGEXP_REPLACE() 未按预期工作
- r - 直接在一个因子上使用 case_when
- nginx - Nginx 条件代理通过配置
- node.js - 为什么我可以从浏览器访问 url 但从节点(axios.get)得到 403 错误(API)
- flutter - Flutter如何在类中保存数组并在任何页面中打印