cookiecutter-django
cookiecutter-django copied to clipboard
Add Ajax csrf_token to base.html
Add this code to base.html
<script>
$.ajaxSetup({
data: {csrfmiddlewaretoken: '{{ csrf_token }}'},
});
</script>
this allow easy use Ajax forms + csrf token
can help too: https://stackoverflow.com/questions/5100539/django-csrf-check-failing-with-an-ajax-post-request
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.
no, this add csrfmiddlewaretoken token to data dict, so if you already use JQuery and use data usual this not must be problem)
@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.