本文和大家分享的是django中关于禁用csrf和使用csrf操作相关内容,一起来看看吧,希望对大家 学习django 有所帮助。 1. 基本使用 form表单中添加 {% csrf_token %} 2. 全站禁用 # 'django.middleware.csrf.CsrfViewMiddleware', 3. 局部禁用 'django.middleware.csrf.CsrfViewMiddleware',# 不注释 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. 局部使用 # 'django.middleware.csrf.CsrfViewMiddleware', # 需要注释这一句话 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模式局部禁用 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) 建议用这个,具体原因后续再讲 @csrf_exempt def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return HttpResponse('GET,响应内容') def post(self, request, *args, **kwargs): return HttpResponse('Post,响应内容') 6. CBV 局部使用 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,响应内容') def post(self, request, *args, **kwargs): return HttpResponse('Post,响应内容') 7. 关于method_decorator的使用 Converts a function decorator into a method decorator. It can be used to decorate methods or classes; in the latter case, name is the name of the method to be decorated and is required. name这个参数是必备的,是为了装饰类中的get方法还是post方法。。。等等 from django.utils.decorators import method_decoratordef test(func): # 装饰器 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,响应内容') def post(self, request, *args, **kwargs): return HttpResponse('Post,响应内容') 来源:简书