环境同前django文章。
启动dajngo的web服务:
]# cd py3/django-test1/test4]# python manage.py runserver 192.168.255.70:8000
定义2个视图,其中csrf1提交表单,csrf2接收提交的表单:
]# vim bookshop/views.pyfrom django.shortcuts import renderfrom django.http import HttpResponsefrom .models import *#csrfdef 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':'html 转义
'} return render(request, 'bookshop/htmlTest.html',context)
定义html模板:
]# vim templates/bookshop/csrf1.htmlTitle
添加应用url路由:
]# vim bookshop/urls.pyfrom django.conf.urls import urlfrom . import viewsurlpatterns = [ 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),]
访问浏览器:
输入一个单词,点击提交,此时,没有在html模板文件中使用csrf开启功能,会显示403:
下面在html模板文件中, templates/bookshop/csrf1.html添加防csrf跨站***:即在form标签之间添加{%csrf_token%}
]# cat templates/bookshop/csrf1.htmlTitle
使用shift+F5,强制刷新后,再次访问:
输入单词,提交:
可以正常显示了。