How to pass a csrf token between django and javascript

I know very little about javascript.

I have a GeoDjango project, and am adding a map view of some of the data using Leaflet. There is a lot of data so I am using a Leaflet uGeoJSON Layer to display the data (this allows leaflet to post a bounding box so Django can filter results and only pass visible data).

I am adding leaflet to a django view.

I have this working with a function based view in django which I decorate with @csrf_exempt, but would like to pass the proper csrf headers so I can use the generic class based django views.

The documentation for [Leaflet uGeoJSON Layer][1] suggests:

var headers = {};

  // CSRF headers
  var token = jQuery("meta[name='_csrf']").attr("content");
  var header = jQuery("meta[name='_csrf_header']").attr("content");
  if (header) {
    headers[header]= token;
  }

  var customers = new L.uGeoJSONLayer({
    endpoint : "/layers/customers",
    headers: headers
  }).addTo(map);

I added this to my javascript but token and header are always null.

Here is my javascript.

map.js

var headers = {};

  // CSRF headers
  var token = jQuery("meta[name='_csrf']").attr("content");
  var header = jQuery("meta[name='_csrf_header']").attr("content");
  if (header) {
    headers[header]= token;
  }

// Point Styles
var 
  DmseJobStyle = {
  fillColor: "#FFFFE0",
  color: "#FFFF00",
  opacity: 1,
  fillOpacity: 0.8
}

var
... 
  DmseJobData = new L.uGeoJSONLayer({endpoint: "data.jobs/",
    usebbox: true,
    headers: headers,
    pointToLayer: function (feature, latlng) {
            return L.circleMarker(latlng, DmseJobStyle)
    },
    onEachFeature:function(feature, layer) {
        layer.bindPopup('Job: ' + feature.properties.num + '</br>Desc: ' + feature.properties.desc);
    } 
  }),


var map = L.map('map', {
    center: [45.75, -64.99],
    zoom: 10,
    layers: [osm]
});

var overlayMaps = {
    ...
    "DMSE Jobs": DmseJobData,
};

This is in a file map.js which is loaded in my django template using:

<script src="{% static 'core\map.js' %}"></script>

If I add a breakpoint, token and header will both be null when loading the map. If I allow it to keep going, I get a POST ... 403 error

In my project I use:

var csrf_token = $('input[name="csrfmiddlewaretoken"]').val();

Back to Top