This article shares with you what Django has to do with disabling CSRF and using CSRF operations .Learn Djangohelpful.
1. Basic Use
Add in form forms
{% Csrf_token%}
2. Disable all stations
# ' Django.middleware.csrf.CsrfViewMiddleware ',
3. Partial Disable
' Django.middleware.csrf.CsrfViewMiddleware ', # no comment
From django.views.decorators.csrf import csrf_exempt
@csrf_exemptdef Csrf1 (Request):
if Request.method = = ' GET ':
return render (Request, ' csrf1.html ')
Else:
return HttpResponse (' OK ')
4. Local use
# ' Django.middleware.csrf.CsrfViewMiddleware ', # need to comment this sentence
From django.views.decorators.csrf import Csrf_exempt,csrf_protect
@csrf_protectdef Csrf1 (Request):
if Request.method = = ' GET ':
return render (Request, ' csrf1.html ')
Else:
return HttpResponse (' OK ')
5. CBV Mode local Disable
From django.utils.decorators import method_decorator
From django.views.decorators.csrf import csrf_exempt, Csrf_protect
From django.shortcuts import Render, HttpResponse
From django.views import viewclass Cs (View):
# @method_decorator (csrf_exempt) recommend this, for specific reasons to follow up again @csrf_exempt
def dispatch (self, request, *args, **kwargs):
return Super (). Dispatch (Request, *args, **kwargs)
def get (self, request, *args, **kwargs):
return HttpResponse (' GET, Response content ')
def post (self, request, *args, **kwargs):
return HttpResponse (' Post, Response content ')
6. CBV Local Use
From django.views.decorators.csrf import csrf_exempt, Csrf_protect
From django.utils.decorators import method_decorator
From django.shortcuts import Render, HttpResponse
From django.views import viewclass Cs (View):
# @method_decorator (csrf_exempt) @method_decorator (csrf_protect)
def dispatch (self, request, *args, **kwargs):
return Super (). Dispatch (Request, *args, **kwargs)
def get (self, request, *args, **kwargs):
return HttpResponse (' GET, Response content ')
def post (self, request, *args, **kwargs):
return HttpResponse (' Post, Response content ')
7. About the use of Method_decorator
converts a function decorator into a method decorator. It can be used to decorate methods or classes; In the latter case, name was the name of the method to being decorated and is required.
The name parameter is required to decorate the Get method or Post method in the class ... Wait
From django.utils.decorators import method_decoratordef Test (func): # Adorner
def inner (*args, **kwargs):
print (' hello,23232323 ')
return func (*args, **kwargs)
return inner
@method_decorator (test, name= ' get ') class Cs (View):
# @method_decorator (csrf_exempt)
# @method_decorator (csrf_protect)
def dispatch (self, request, *args, **kwargs):
return Super (). Dispatch (Request, *args, **kwargs)
def get (self, request, *args, **kwargs):
return HttpResponse (' GET, Response content ')
def post (self, request, *args, **kwargs):
return HttpResponse (' Post, Response content ')
Source: Jane book
Django Learning disable CSRF and use CSRF operation