How to disable Django's CSRF validation?

前端 未结 9 1218
梦毁少年i
梦毁少年i 2020-11-30 21:23

I have commented out csrf processor and middleware lines in settings.py:

122 
123 TEMPLATE_CONTEXT_PROCESSORS = (
124     \'django.contrib.auth.         


        
相关标签:
9条回答
  • 2020-11-30 22:16

    If you want disable it in Global, you can write a custom middleware, like this

    from django.utils.deprecation import MiddlewareMixin
    
    class DisableCsrfCheck(MiddlewareMixin):
    
        def process_request(self, req):
            attr = '_dont_enforce_csrf_checks'
            if not getattr(req, attr, False):
                setattr(req, attr, True)
    

    then add this class youappname.middlewarefilename.DisableCsrfCheck to MIDDLEWARE_CLASSES lists, before django.middleware.csrf.CsrfViewMiddleware

    0 讨论(0)
  • 2020-11-30 22:21

    If you just need some views not to use CSRF, you can use @csrf_exempt:

    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def my_view(request):
        return HttpResponse('Hello world')
    

    You can find more examples and other scenarios in the Django documentation:

    • https://docs.djangoproject.com/en/dev/ref/csrf/#edge-cases
    0 讨论(0)
  • 2020-11-30 22:24

    CSRF can be enforced at the view level, which can't be disabled globally.

    In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.

    https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps

    0 讨论(0)
提交回复
热议问题