我无法使用Django访问静态文件
以cmd为单位。我收到此错误:"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__
答案 0 :(得分:0)
Django和python永远不会说谎,因为他们抛出了它,也没有关于如何解决它的文档。如果您参考link,他们会采用一种非常简洁的方法来说明如何快速启动和运行它。
您需要一个从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
答案 1 :(得分:0)
如果您使用的是 Django 1.11 + ,则将以下代码添加到settings.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
...
},
]
这将使django扫描您的应用程序以搜索templates
目录。