[英]How to access static css files with Django
我无法在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
但你的dir结构不是你提到的Django来收集它,不是吗?
尝试以上所有内容,让我知道它是否适合您。
另一个暗示:
<link rel="stylesheet" href="{% static "my_app/admin-custom.css" %}"> # figure out the hint here
如果您使用的是Django 1.11+而不是将以下代码添加到settings.py中
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
这将使django能够扫描您的应用程序以搜索templates
目录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.