视图代码:
def index(request):
return render(request, 'temtest/index2.html',
{
't1': '<h1>hello</h1>'
})
模板代码:
{{t1}}
会被自动转义的字符
< 会转换为<
> 会转换为>
' (单引号) 会转换为'
" (双引号)会转换为 "
& 会转换为 &
{{t1|escape}}
关闭转义
{{ data|safe }}
{ % autoescape off %}
{{ body }}
{ % endautoescape %}
字符串字面值
{ { data|default:"<b>123</b>" }}
{ { data|default:"<b>123</b>" }}
def csrf1(request):
return render(request,'booktest/csrf1.html')
def csrf2(request):
uname=request.POST['uname']
return render(request,'booktest/csrf2.html',{'uname':uname})
url(r'^csrf1/$', views.csrf1),
url(r'^csrf2/$', views.csrf2),
<html>
<head>
<title>Title</title>
</head>
<body>
<form method="post" action="/crsf2/">
<input name="uname"><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
<html>
<head>
<title>Title</title>
</head>
<body>
{{ uname }}
</body>
</html>
防csrf的使用
<form>
{% csrf_token %}
...
</form>
取消保护
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def csrf2(request):
uname=request.POST['uname']
return render(request,'booktest/csrf2.html',{'uname':uname})
保护原理
<input type='hidden' name='csrfmiddlewaretoken' value='nGjAB3Md9ZSb4NmG1sXDolPmh3bR2g59' />