当前位置:网站首页>On "CSRF verification failed. Request aborted" in Django

On "CSRF verification failed. Request aborted" in Django

2020-11-10 17:23:31 wushengchn

The situation in which the problem is encountered : stay Django Used in Ajax Submit Form , It's about cross domain issues .

 Sample questions

Solutions :

  1. stay html Add the following code to the form on the page :
{% csrf_token %}
  1. Where the view function is located py Add the following code to the file :
from django.views.decorators.csrf import csrf_exempt

#  If it is FBV, Add... To the view function that receives the form data @csrf_exempt
@csrf_exempt
def func():
    pass

#  If it is CBV, Add a method decorator to a class or class method 
#  Method one is as follows , Decorator name Parameter indicates the name of the function to decorate 
@method_decorator(csrf_exempt, name="dispatch")
class ClassView(View):
      def post(self, request, *args, **kwargs):
            pass

#  Method 2 is as follows , Direct decoration dispatch Method 
class ClassView(View):
      @method_decorator(csrf_exempt)
      def dispatch(self, request, *args, **kwargs):
            return super(StudentsView, self).dispatch(request, *args, **kwargs)
      
      def post(self, request, *args, **kwargs):
            pass

stay Django in , have access to @csrf_exempt Annotations to identify a view can be dispensed with csrf verification .

The original explanation of this method is as follows :
Mark a view function as being exempt from the CSRF view protection.


版权声明
本文为[wushengchn]所创,转载请带上原文链接,感谢