User Tools

Site Tools


Implement CSRF Protection for Django and Dojo Toolkit

Dec 2014


Client side we have Dojo Toolkit and some elements capable of ajax calls to the server (but not regular forms with the classic hidden html element). Server side we have a Django app with CSRF Middleware enabled.

Our goal will be to connect our dojo UI ajax calls to the Django protection system.

For this example I use dojo toolkit ver 1.10 and Django 1.7.

Client Side

The main question client side is: how can we inject a specific header into any ajax call made by dojo?. This specific header would be our CSRF cookie content.

The answer is: use notify

], function(notify, Cookie) {
    notify("send", function(response, cancel){
        response.xhr.setRequestHeader('X-CSRFToken', Cookie("csrftoken"));

This piece of code should be placed somewhere before your js code (some kind of bootstrap.js file).

Server Side

Django has CSRF protection included by default (in CSRF Middleware) but if you're not using regular forms, you have to call a simple trick in order to send the CSRF cookie along with a view.

In my example I have a base view method (index) calling a very generic template. Within the template I have custom dojo grid and other elements created dynamically (client side).

from django.views.decorators.csrf import ensure_csrf_cookie
def index(request):
    template_data = {}
    return render_to_response('jukebox/dashboard.html',

Expected result

Beside lack of 403 Forbidden Responses, you should be able to see in your preferred debugging tool something as:

python/django-dojo-csrf-token.txt · Last modified: 2014/12/13 12:49 by admin