作为一个Web框架,Django需要一种方便的方式来动态生成HTML。最常用的方法依赖于模板。模板包含所需HTML输出的静态部分以及描述如何插入动态内容的特殊语法。
对模板引擎的一般支持和Django模板语言的实现都存在于 django.template 命名空间中
在settings中配置:
# 配置模板
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates',# 使用默认的Django的模板'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',],},},
]
笔记:
get_template
该函数使用给定名称加载模板并返回一个 Template对象,找到第一个匹配的模板即返回
template = get_template('story_detail.html')
Django将要查找的文件,依次为:
示例:
# 最常用的renderfrom django.shortcuts import renderdef my_view(request):# View code here...return render(request, 'myapp/index.html', {'foo': 'bar',}, content_type='application/xhtml+xml')# 相当于基础的get_template:from django.http import HttpResponsefrom django.template import loaderdef my_view(request):# View code here...template = loader.get_template('myapp/index.html')context = {'foo': 'bar'}# 注意,这个 render 和 快捷键 render 不是一个对象return HttpResponse(template.render(context, request), content_type='application/xhtml+xml')
select_template
select_template() 用法类似 get_template() ,除了它需要一个模板名称的列表。它按顺序尝试每个名称并返回存在的第一个模板
template = select_template(['story_253_detail.html','story_detail.html'])
Django将要查找的文件,依次为:
Django模板只是一个文本文档或使用Django模板语言标记的Python字符串。一些结构被模板引擎识别和解释,主要的是变量( {{ 变量 }} )和标签( {% 标签 %} )。
其中也包含模板渲染变量的测试
首先创建一个主应用,子应用。在子应用中创建一个templates文件夹并在下面创建一个template_app文件夹,还有创建一个urls.py路由文件。
配置主应用中的settings
INSTALLED_APPS = ['template_app',
]import os
TEMPLATES = [{'BACKEND': 'django.template.backends.django.DjangoTemplates','DIRS': [os.path.join(BASE_DIR,'templates')],
配置子应用的路由地址(主应用的urls中)
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
urlpatterns = [path('admin/', admin.site.urls),path('template_app/', include('template_app.urls'))
]
以上配置基本完成
开始测试模板渲染的变量
子应用url配置
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from . import views
urlpatterns = [path('var_test/', views.var_test)
]
子应用的views
from django.shortcuts import render# Create your views here.
def var_test(request):# 传递变量给模板context_name = {"first_name":'tom',"last_name":"zhang"}return render(request, 'template_app/var_test.html', context_name) # 返回模板携带变量
模板
Document
first_name:{{first_name}}
last_name: {{last_name}}
创建数据模型
from django.db import models# Create your models here.
class Person(models.Model):pname = models.CharField(max_length=30)age = models.IntegerField()password = models.CharField(max_length=8)sex = models.CharField(max_length=5)salary = models.FloatField()
配置数据库
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'template_study',"HOST":'127.0.0.1',"USER": 'root',"PASSWORD": 'root','PORT':3306 }
}
迁移数据库命令
python manage.py makemigrations template_app
python manage.py migrate template_app
views视图
from django.shortcuts import render
from template_app.models import *
# 在页面中渲染实体_字典_列表
def data_test(request,id):p = Person.objects.get(pk=id)person_list = Person.objects.all()address_dict = {'bj':'北京','sh':'上海','gz':'广州'}return render(request, 'template_app/data_test.html',{'person':p,'person_list':person_list, 'address_dict':address_dict})
template模板
在页面中渲染实体_字典_列表
实体的渲染
- {{ person.pname }}
- {{ person.age }}
- {{ person.sex }}
- {{ person.salary }}
列表的渲染
{{ person_list.0.pname }}{{ person_list.1.pname }}{{ person_list.2.pname }}{{ person_list.3.pname }}{{ person_list.4.pname }}字典的渲染
{{ address_dict.bj }}
{{ address_dict.sh }}
{{ address_dict.gz }}
url
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from . import views
urlpatterns = [path('data_test//', views.data_test)
]
测试代码思路:我们创建一个views视图,然后返回一个模板,内容是form表单的输入账号密码。点击按钮只会,需要跳转到一个登录成功的新路由中。这时候,就需要我们使用csrf_token防跨域攻击
无参数标签 csrf_token ,这个标签是用于html进行 form 表单提交时,包含一个 随机变化的字符串,在html页面中,其实就是一个 inputtype=‘hidden’ 作用是用于防止跨域攻击
{% csrf_token %}
传参的标签 cycle , 参数 ‘odd’ ‘even’ ,空格间隔
标签本身也支持 关键字参数 {% 标签 key1=‘value’ key1=‘even’ %}
{% cycle ‘odd’ ‘even’ %}
代码展示
views
from django.shortcuts import render, HttpResponse
from template_app.models import *
def login_html(request):return render(request, "template_app/login.html")def login(request):return HttpResponse("登录成功")
urls
from django.contrib import admin
from django.urls import path
from django.urls.conf import include
from . import views
urlpatterns = [path('login_html/',views.login_html),path('login/',views.login,name="login")
]
template模板—— csrf_token