title: Generating CSRF token for Backbone from Django
body: <p>I've been developing a backbone layer on top of Django and using Django to create the API and having backbone models calling django api to fill in the models. I'm trying to create a login for users using the default django models for users. Since I'm not rendering the pages through django but instead through router in backbone. I can't generate csrf token through django's template language {{ csrf_token }} and thus I can't post any forms.</p>
  
  <p>One way I thought to work around this is to generate the token by having the backbone view fetch from the api endpoint in initialize and have the endpoint generate the token through</p>
  
  <pre><code>token = csrf._get_new_csrf_key()
  </code></pre>
  
  <p>and then passing it to backbone frontend through json then following the django documentation</p>
  
  <pre><code>var csrftoken = "&lt;%=obj.csrftoken%&gt;";
  
  function csrfSafeMethod(method) {
      // these HTTP methods do not require CSRF protection
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }
  
  $.ajaxSetup({
      beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type) &amp;&amp; !this.crossDomain) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
      }
  });
  </code></pre>
  
  <p>This didn't work since I still get Forbidden (403) CSRF verification failed. Request aborted.</p>
  
  <p>Any help would be appreciated. Thanks</p>