我需要将css合并到模板中以帮助它们看起来更好,但是尽管添加了静态url和root,但我仍然无法将其加载到模板中。我在这里附上相关代码。请告诉我我在做什么错。预先感谢。
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATIC_URL = '/static/'
STATIC_ROOT = [STATIC_DIR,],
index.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}">
</head>
答案 0 :(得分:1)
settings.py
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'project_name/static')
]
index.html
<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
<link href="{% static 'css/index.css' %}" rel="stylesheet">
</head>
有关更多信息,check here
答案 1 :(得分:0)
要加载静态文件,您还需要添加静态网址
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
......
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
将它们添加到项目的根网址中
答案 2 :(得分:0)
没有名为STATIC_DIR
的设置,应为STATICFILES_DIRS
并应这样声明:
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR,'staticroot') # Static Dir and Static root needs to be different
关于提供静态文件,根据documentation
,如果在django.contrib.staticfiles
中添加INSTALLED_APPS
,则当DEBUG
为True
时django将自动提供静态文件。但是在生产中,您需要使用反向代理服务器来处理静态文件。或者,您可以使用whitenoise
。也可以在documentation
中找到更多信息。
答案 3 :(得分:0)
按如下所示更改网址基础urls.py
urlpatterns = [
# your url here
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
还在模板中包含{% load static %}
标签
答案 4 :(得分:0)
您使用哪个版本的Django?从2.0开始,有一些更改,而不是
TEMPLATE_DIR = os.path.join(BASE_DIR,'templates')
有
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},]
还检查您的静态文件夹是否存在 并确保您选择了静态文件夹的正确路径(例如,我将此文件夹保存在模板文件夹中,因此我的代码如下所示)
STATIC_URL = '/templates/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "templates/static"),]
而且我发现您没有将csrf_token放到您的html中,因此请将其添加到您的html
{% csrf_token %}