Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass csrf_token to javascript file in django?

Here is my javascript code that works fine. but I like to keep javascript files seperate and not use as inline script tags

<script>
    $('.book').click(function() {
         var id= $(this).attr('id');
         data={
              'id':id,
              'csrfmiddlewaretoken':'{{ csrf_token }}',
              };
          $.ajax({
            url: '/post/book/',
            cache:'false',
            dataType:'json',
            type:'POST',
            data:data,
            success: function(data){
               //do something
              else {
                  //do something
              }
            }, 
            error: function(error){
              alert('error; '+ eval(error));
            }
          });
          return false;
      });
     });
</script>

I want to include this in my custom.js file that I have included in my base.html. which is

{% load static from staticfiles %}
{% load bootstrap3 %}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>{% block title %}{% endblock %}</title>
  {% bootstrap_css %}
  <!-- Optional theme -->
  <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
  <link href="{% static "css/custom.css" %}" rel="stylesheet">
  <!-- Latest compiled and minified JavaScript -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  <script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.js"></script>
  <script src="{% static "js/custom.js" %}" ></script>
  <script src="{% static "js/jquery.blockUI.js" %}"></script>
  {% bootstrap_javascript %}
  {% load bootstrap3 %}
{% load static from staticfiles %}
{% block content %} {% endblock %}

I am not able to reference csrf_token that is available in the current template in Django to the static js file. how can I get this to work?

like image 340
brain storm Avatar asked Apr 28 '14 19:04

brain storm


2 Answers

If you want to reference template tags then you need that file to be templated (rendered) by Django. And I wouldn't recommend rendering all your static files via django...

You can either put the csrf_token in a global variable that you then access from your script. Something like this in your base.html:

<script>
    var csrftoken = '{{ csrf_token }}';
</script>

Or you can pull the csrftoken from the cookies in your javascript file. See this question for a solution for that. The cookie is called csrftoken. You can view it by opening up your dev tools and looking at the cookies for your domain.

like image 95
aychedee Avatar answered Sep 30 '22 20:09

aychedee


You can either access the CSRF token from 'csrftoken' cookie at the client using following function:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

And calling it like:

getCookie('csrftoken');

Or you may simply define a variable in HTML template and use that in your client side script.

<script>
    var CSRF_TOKEN = '{{ csrf_token }}';
</script>
like image 38
Debanshu Kundu Avatar answered Sep 30 '22 21:09

Debanshu Kundu