环境同前django文章。
启动dajngo的web服务:
]# cd py3/django-test1/test4 ]# python manage.py runserver 192.168.255.70:8000
定义2个视图,其中csrf1提交表单,csrf2接收提交的表单:
]# vim bookshop/views.py from django.shortcuts import render from django.http import HttpResponse from .models import * #csrf def csrf1(request): return render(request, 'bookshop/csrf1.html') def csrf2(request): uname = request.POST['usernmae'] return HttpResponse(uname) #查询一个值 #def index(request): # hero = HeroInfo.objects.get(pk=1) #查询主键(pk)=1的条目 # context = {'hero':hero} # return render(request,'bookshop/index.html',context) #查询多个值,在html模板中循环 def index(request): #list = HeroInfo.objects.all() list = HeroInfo.objects.filter(isDelete=False) context = {'list1':list} return render(request,'bookshop/index.html',context) def show(request,id): context = {'id':id} return render(request,'bookshop/show.html',context) #模板继承 def index2(request): return render(request,'bookshop/index2.html') def user1(request): context = {'username':'python-django'} return render(request, 'bookshop/user1.html', context) def user2(request): return render(request, 'bookshop/user2.html') #html转义 def htmlTest(request): context = {'key1':'<h1>html 转义</h1>'} return render(request, 'bookshop/htmlTest.html',context)
定义html模板:
]# vim templates/bookshop/csrf1.html <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> <form action="csrf2" method="post"> <input type="text" name="username"> <input type="submit" value="提交"> </form> </body> </html>
添加应用url路由:
]# vim bookshop/urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(\d+)$', views.show, name='show'), url(r'^(\d+)/(\d+)$', views.show, name='show'), url(r'^index2$', views.index2, name='index2'), url(r'^user1', views.user1, name='user1'), url(r'^user2', views.user2, name='user2'), url(r'^htmlTest',views.htmlTest), url(r'^csrf1$',views.csrf1), url(r'^csrf2$',views.csrf2), ]
访问浏览器:http://192.168.255.70:8000/csrf1
输入一个单词,点击提交,此时,没有在html模板文件中使用csrf开启功能,会显示403:
下面在html模板文件中, templates/bookshop/csrf1.html添加防csrf跨站***:即在form标签之间添加{%csrf_token%}
]# cat templates/bookshop/csrf1.html <!DOCTYPE html> <html> <head> <title>Title</title> </head> <body> <form action="csrf2" method="post"> {% csrf_token %} <input type="text" name="username"> <input type="submit" value="提交"> </form> </body> </html>
使用shift+F5,强制刷新后,再次访问:http://192.168.255.70:8000/csrf1
输入单词,提交:
可以正常显示了。