django 1.9.7 css控制模板样式
问题:css样式不能控制html样式(针对开发环境,不针对生产环境)
现象:
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 6: '/s
tatic/css/main.css'. Did you forget to register or load this tag?
操作步骤:
1、首先查看setting.py文件INSTALLED_APPS中是否有 'django.contrib.staticfiles'
INSTALLED_APPS = [ 'country.apps.CountryConfig', 'west.apps.WestConfig', 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', #该静态文件app一定加上 ]
2、查看setting.py文件,TEMPLATES是否有'django.core.context_processors.static'
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'django.core.context_processors.static',#一定要加上 ], }, }, ]
3、setting文件静态文件URL路径,静态文件路径
STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "/country/static"),#country是生成的APP ]
4、urls.py(和setting.py同目录下的url.py),在urlpatterns 中添加
url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_ROOT})
from django.conf import settings urlpatterns = [ url(r'country/', include('country.urls')), url(r'^west/', include('west.urls')), url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), url(r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_ROOT})# 注意添加 ]
5、在自定义的APP目录下添加静态文件夹和静态文件(css)
6、在html文件引入css外部文件(步骤5中文件)
{% load static %}# 载入静态文件 {% load staticfiles %} <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="/static/css/main.css" /> # 注意外部CSS连接href书写格式 <meta charset="UTF-8"> <title>{{Title}}</title> </head>