响应-返回模板
原创...小于 1 分钟
配置
# 配置模板
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["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",
],
},
},
]
模板内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<p>我是模板文件</p>
{{name}}
</body>
</html>
render 方法
- 必需的参数
- request:用于生成此响应的请求对象
- template_name:要使用的模板的全名或模板名称的列表
- 可选参数
- context:要添加到模板上下文的值的字典。默认情况下,这是一个空字典。如果字典中的值是可调用的,视图将在渲染模板之前调用它
- content_type:用于生成文档的 MIME 类型。默认为 DEFAULT_CONTENT_TYPE 设置的值
- status:响应的状态码。默认为 200
- using:用于加载模板的模板引擎名
from django.shortcuts import render
def loginFunc1(request):
return render(
request,
"index.html", # templates 文件夹下要有一个index.html
{"name": "刘春龙"},
)
loader 方法
from django.http import HttpResponse
from django.template import loader
def loginFunc1(request):
t = loader.get_template("index.html")
c = {"name": "刘春龙"}
return HttpResponse(t.render(c, request))
Powered by Waline v2.15.7