Yesterday I had the same problem and thought it would help people if there is an easy way to handle this, so I wrote the jQuery plugin for it: jquery.djangocsrf . Instead of adding a CSRF token in each request, he himself intercepts the AjaxSend jQuery event and adds the client cookie to the header.
Here's how to use it:
1- enable it:
<script src="path/to/jquery.js"></script> <script src="path/to/jquery.cookie.js"></script> <script src="path/to/jquery.djangocsrf.js"></script>
2- include it in your code:
$.djangocsrf( "enable" );
Django always adds a token to the cookie if your template uses {% csrf_token %} . So that he always adds it, even if you do not use a special tag in your template, use the @ensure_csrf_cookie decorator:
from django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def my_view(request): return render(request, 'mytemplate.html')
Note: Im using Django 1.6.2.
bfontaine Mar 21 '14 at 11:32 2014-03-21 11:32
source share