Wednesday 11 a.m.–11:50 a.m.

AngularJS + Django = A Perfect Match

Nina Zakharenko

Audience level:

Experienced

Description

AngularJS is a powerful MVC framework that can easily integrate with Django templates.

Let's walk through integrating the two for fantastic results. The result is a fast, dynamic single page application.

Abstract

Integrating AngularJS with Django (45 min)
Django Templates
  • I’ll be honest. Django templates are my least favorite part of the framework.
  • Simple views and forms are easy, but as your app gets more complicated forms grow in complexity too.
  • Ajax in template views is hard. jQuery is no longer the de-facto Javascript framework.
  • But they still serve their purpose. By using a base Django template, we can use built-in session authentication by using the most basic View. (TemplateView to consume endpoints code example)
Why angular?
  • AngularJS provides scope binding - easier than fussing with jquery. (code sample)
  • Plays nicely with REST frameworks. The angular $resource lets you interact with an endpoint as if it were an object.
  • If you already have public endpoints, you can eat your own dog food instead of duplicating logic with a template.
  • AngularJS is built with unit testing in mind - it’s easier than testing logic in Django templates.
  • Custom validation is a breeze - no need to hit the server before giving user feedback
  • But most importantly - single page apps rock. They’re fast and responsive, no need to wait for a whole page reload before displaying information.
Your REST Api
  • We’ll assume you already have a REST Api that you’d like to consume
  • There are many options available for creating one, with my favorite being Django REST Api.
Configuration
  • If using session authentication between the API and your app, your TempateViews must have an ensure_csrf decorator if calling operations that modify, such as POST and PUT
  • To enable angular in your application, link to the angular js file, create a minimal app.js, and add an app=”myApp” to any tag in your template.
  • AngularJS configurations needed to work with Django CSRF
  • angular and django templates share the same tags - {{ }}, need to configure angular to use something else. I prefer [[ ]]. Another option is to wrap all angular specific code in {% verbatim %} tags.
  • To pass back CSRF cookies to django, you must configure the xsrf Cookie and Header name in your angular app settings. (Code example)
AngularJS scope binding in action (code example)
  • class conditionals
AngularJS resources (code example)
  • ng-model Resources con’t. (code example)
  • filtering and sorting results
Angular Routing vs. Django Routing (code example)
Unit Testing AngularJS (code example)
Conclusion
  • Getting started can be tricky, and configuration may be difficult at first but the results pay off!