1. URL的使用
<!-- {% url 'app_name:url_name' param %} -->
<a href="{% url 'blog:index' %}">{{ SITE_NAME }}</a>
2. 静态文件使用
{% load static %}
<link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
3. 添加项目’templates’文件夹
在项目根目录新建’templates’文件夹,然后修改settings.py文件如下
#settings.py
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',
'blog.context_processors.global_vars',
],
},
},
]
4. 修改语言和时区:
# settings.py
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
5. 配置静态文件
# settings.py
STATIC_URL = '/static/'
# ---- 一下代码是新添加的 ----
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
6. 全局上下文
# settings.py
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',
'blog.context_processors.global_vars', # 自定义上下文处理器
],
},
},
]
# context_processors.py
from django.conf import settings
def global_vars(request):
return {
'SITE_TITLE': settings.SITE_TITLE,
'SITE_DESCRIPTION': settings.SITE_DESCRIPTION,
'SITE_URL': settings.SITE_URL,
'SITE_AUTHOR': settings.SITE_AUTHOR
}
# 在模板中可以使用 {{ SITE_TITLE }} 调用全局变量
7. 模板继承
<!-- base.html -->
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>{% block title %}{{ SITE_TITLE }} - {{ SITE_DESCRIPTION }}{% endblock title %}</title>
<link rel="stylesheet" href="{% static 'global/fonts/icomoon/style.css' %}">
<link rel="stylesheet" href="{% static 'blog/css/style.css' %}">
</head>
<body>
<!-- nav start -->
{% block nav %}
<nav class="navbar js-nav-toppx">
</nav>
{% endblock nav %}
<!-- nav end ! -->
<!-- Footer Script -->
<script src="{% static 'global/js/jquery.min.js' %}"></script>
<script src="{% static 'blog/js/zpure.js' %}"></script>
</body>
</html>
<!-- index.html -->
{% extends "blog/base.html" %}
{% block title %}博客首页{% endblock title %}