Skip to content

Instantly share code, notes, and snippets.

@cmdelatorre
Created August 25, 2015 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmdelatorre/8cd3de8b2006abfa48a8 to your computer and use it in GitHub Desktop.
Save cmdelatorre/8cd3de8b2006abfa48a8 to your computer and use it in GitHub Desktop.
Integrate Backbone with Django: Add CSRF Token to Backbone Ajax calls
oldSync = Backbone.sync
Backbone.sync = (method, model, options) ->
csrfSafeMethod = (method) ->
# these HTTP methods do not require CSRF protection
/^(GET|HEAD|OPTIONS|TRACE)$/.test method
options.beforeSend = (xhr, settings) ->
if !csrfSafeMethod(settings.type) and !@crossDomain
xhr.setRequestHeader 'X-CSRFToken', $.cookie('csrftoken')
return
oldSync method, model, options
@cmdelatorre
Copy link
Author

This is based in https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax (using the jQuery cookie plugin)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment