cookiecutter-django icon indicating copy to clipboard operation
cookiecutter-django copied to clipboard

Add Ajax csrf_token to base.html

Open mmmcorpsvit opened this issue 6 years ago • 4 comments

Add this code to base.html

  <script>
    $.ajaxSetup({
      data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
    });
  </script>

this allow easy use Ajax forms + csrf token

mmmcorpsvit avatar Aug 27 '19 05:08 mmmcorpsvit

can help too: https://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request

mmmcorpsvit avatar Aug 27 '19 05:08 mmmcorpsvit

Quoting from the documentation

All subsequent Ajax calls using any function will use the new settings, unless overridden by the individual calls, until the next invocation of $.ajaxSetup().

If I am reading this correctly, if you make any ajax call that will contain request data (i.e. overriding the data parameter), and this is highly likely, then you would need to specify the csrf token again. Therefore, there is little benefit to add it by default.

demestav avatar Aug 29 '19 11:08 demestav

no, this add csrfmiddlewaretoken token to data dict, so if you already use JQuery and use data usual this not must be problem)

mmmcorpsvit avatar Aug 29 '19 20:08 mmmcorpsvit

@demestav agreed with you.

However, there is a better solution for CSRF and jQuery ajax, which is also mentioned in django's docs.

If you think that having an X-CSRFToken header with a csrftoken value in every ajax call1 will give some benefits to this project, then the suggestion from Django's docs could be a solution for this issue.

1 except those((GET|HEAD|OPTIONS|TRACE)) which doesn't require CSRF protection

Base on my experience this is something that is needed very often in Django/jQuery projects. Let me know your thoughts about that.

davitovmasyan avatar Sep 30 '19 14:09 davitovmasyan