Angular.js with Django

Struggling with Angular.js with Django application? There is an easy fix.

At AngelHack London I built in less than 24 hours a webapp for my side project: a newsreader (open source).

I used Django with Tastypie to serve REST API for iOS. The Angular WebApp was not planned until I found out that I could simply use the endpoints to make it. This simplifies the job a lot. I used the angular-generator with yeoman to make a new project.

How to deal with Login

Login box

Django needs a CRSF token and a session based identifier to log the user in and let user make POST and DELETE requests. For the login side, I just made a login box within Django, using Django templating system.

So the Login part is entirely on Django, when a user successfully logs in, it will be redirected to /reader/, where the actual Angular.js application is served by Nginx.

On Tastypie side, when I created new resources I authenticated my users using the SessionAuthentication() from tastypie.authentication. This will let you authenticate your users using the internal Django Session Engine.

Now on Angular side every GET requests just works, the problem is to deal with the CSRF Token and passing it to Django when making POST requests.To solve this issue just place this two lines in

$[‘X-CSRFToken’] = $cookies.csrftoken;
$http.defaults.headers.common[‘X-CSRFToken’] = $cookies.csrftoken;

Ensure to inject in your app dependencies ngCookies.

Now to deal with non-authenticated users you can just use Angular-HTTP-Auth and placing this in

$rootScope.$on(‘event:auth-loginRequired’, function () { window.location = ‘/’; });

So, when Tastypie now rejects a request with a 401, Angular will redirect the user to the main page.

Feel free to drop me an email or a tweet.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.