Django CSRF check failing with an Ajax POST request

前端 未结 22 1415
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 03:46

I could use some help complying with Django\'s CSRF protection mechanism via my AJAX post. I\'ve followed the directions here:

http://docs.djangoproject.com/en/dev/r

22条回答
  •  抹茶落季
    2020-11-22 03:59

    for someone who comes across this and is trying to debug:

    1) the django csrf check (assuming you're sending one) is here

    2) In my case, settings.CSRF_HEADER_NAME was set to 'HTTP_X_CSRFTOKEN' and my AJAX call was sending a header named 'HTTP_X_CSRF_TOKEN' so stuff wasn't working. I could either change it in the AJAX call, or django setting.

    3) If you opt to change it server-side, find your install location of django and throw a breakpoint in the csrf middleware.f you're using virtualenv, it'll be something like: ~/.envs/my-project/lib/python2.7/site-packages/django/middleware/csrf.py

    import ipdb; ipdb.set_trace() # breakpoint!!
    if request_csrf_token == "":
        # Fall back to X-CSRFToken, to make things easier for AJAX,
        # and possible for PUT/DELETE.
        request_csrf_token = request.META.get(settings.CSRF_HEADER_NAME, '')
    

    Then, make sure the csrf token is correctly sourced from request.META

    4) If you need to change your header, etc - change that variable in your settings file

提交回复
热议问题