FBV
Application 1: In the form form, add a random csrf string
<body> <form method="post" action="csrf1.html"></form> {% csrf_token %} <input type="text" name="user"/> <input type="submit" value="提交"/> </body>
<input type='hidden' name='csrfmiddlewaretoken' value='EZ5ww0bjRs9YysjESYJh5Jz2OO4XRZj2YICEv6Dppj0OzQNAiU3qqF9EezuqO1gl' />
def csrf1(request): if request.method =='GET': return render(request,'csrf1.html') else: return HttpResponse('ok')
'django.middleware.csrf.CsrfViewMiddleware',
{% csrf_token %}
##not only generates a hidden input box in the form, but also takes it with it when submitting it.
##Also in the local cookie, it will also add a random string.
Application 2: Disable the whole site. Comment out csrf.
'django.middleware.csrf.CsrfViewMiddleware',
application three, partially disabled
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') #Partial disable, add a decorator on a function alone #On the premise of using the whole station, partial disable will appear
Application 4: Topical Use
from django.views.decorators.csrf import csrf_protect
@csrf_protect
def csrf1(request):
if request.method =='GET':
return render(request,'csrf1.html')
else:
return HttpResponse('ok')
CBV
from django.views import view from django.utils.decorators import method_decorator def wrapper(func) def inner(*args,**kwargs): return func(*args,**kwargs) return inner @method_decorator(wrapper,name='get') @method_decorator(wrapper,name='post') @method_decorator(wrapper,name = ' dispatch ' ) #Add class Foo(view) to everything def dispatch(self,request,*args,** kwargs): return xxx #@method_decorator(wrapper) def get(self,request): pass # @method_decorator(wrapper) def post(self,request): pass # ## Directly adding @csrf is not allowed in django CBV # ## CBV application decorator must use method_decorator # ##@method_decorator(wrapper,name='dispatch') # #When the request comes, go to the dispatch first, and the dispatch executes get/post through reflection.
1. Add a decorator to the specified method.
Don't add name='dispatch'
@method_decorator(wrapper)
from django.views import view from django.utils.decorators import method_decorator 1 , add a decorator to the specified method class Foo(view) @method_decorator(wrapper) def get(self,request): pass def post(self,request): pass
2, add on the class, you need to specify the name
from django.views import view from django.utils.decorators import method_decorator 2. Add to the specified class @method_decorator(csrf_protect,name='dispatch') class Foo(view) def get(self,request): pass def post(self,request): pass