首页 > 代码库 > Django之CSRF以及CBV补充
Django之CSRF以及CBV补充
1.CSRF
a.基本应用
form表单中添加
{% csrf_token %}
b.全栈禁用
# ‘django.middleware.csrf.CsrfViewMiddleware‘,
c. 局部禁用
‘django.middleware.csrf.CsrfViewMiddleware‘,
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def csrf1(request):
if request.method == ‘GET‘:
return render(request,‘csrf1.html‘)
else:
return HttpResponse(‘ok‘)
d.局部使用
# ‘django.middleware.csrf.CsrfViewMiddleware‘,
from django.views.decorators.csrf import csrf_exempt,csrf_protect
@csrf_protect
def csrf1(request):
if request.method == "GET":
return render(request,‘csrf1.html‘)
else:
return HttpResponse(‘OK‘)
c.特殊CBV
form django.views import View
from django.utls.decorators import method_decorator
@method_decorator(csrf_protect,name=‘dispatch‘)
class Foo(View):
def get(self,request):
pass
def post(self,request):
pass
PS:CBV中添加装饰器
def wrapper(func):
def inner(*args,**kwargs):
return func(*args,**kwargs)
return inner
#1.指定方法上添加装饰器
class Foo(View):
@method_decorator(wrapper)
def get(self,request):
pass
def post(self,request):
pass
2.在类上添加
@method_decorator(wrapper,name=‘dispatch‘)
class Foo(View):
def get(self,request):
pass
def post(self,request):
pass
Django之CSRF以及CBV补充