Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
Angular + Django 
A match made in heaven
github.com/nnja/tweeter
Django Templates 
… are not my favorite
● Need to refresh the page to submit a form 
● Tough to write JS around template tags 
● Difficult to Unit Test 
● Templat...
Forms get complex, fast.
Why Endpoints are Better (IMHO) 
● Faster - no waiting for a page to reload 
● Swap frameworks - Ability to use any javasc...
Dogfooding 
If your endpoints are public, you can eat your own 
dogfood by consuming them internally.
REST Frameworks are Standard 
Front End Devs know how to use them.
AngularJS 
● MVC - Responsibilities are separated 
● Single page app. That means no refreshes for new 
content, and a bett...
The bad 
You have to use Javascript
If you don’t like it...
Use another framework 
Excellent presentation on choosing a JS Framework 
http://brianholt.me/
Let’s build a Tweeter 
http://github.com/nnja/tweeter
Requirements 
1. Display a list of tweets from all Users 
2. Display my tweets (logged in User) 
3. Show my profile - user...
Our endpoints are created w/ DRF 
Django Rest Framework 
- Easily create a REST endpoint for your application.
Our Model 
class Tweet(models.Model): 
user = models.ForeignKey(User) 
text = models.CharField(max_length=140) 
timestamp ...
Our endpoints 
/api/users/ 
/api/tweets/ 
/api/users/:id 
/api/tweets/:id
GET /api/tweets/ 
HTTP 200 OK 
Vary: Accept 
Content-Type: text/html; charset=utf-8 
Allow: GET, POST, HEAD, OPTIONS 
[ 
{...
Configuring Angular
Step 1. 
Include angular.js 
Throw ng-app into one of your tags. 
Everything within those tags is now an angular 
app. 
<h...
{{ }} 
UH OH 
Angular tags and Django template tags conflict.
Tell angular to use different tags 
I like [[ this ]] 
or use 
{% verbatim %} {% endverbatim %}
static/js/app.js 
$interpolateProvider.startSymbol('[[').endSymbol(']]'); 
$httpProvider.defaults.xsrfCookieName = 'csrfto...
Angular Resources 
A wrapper around a REST Endpoint at a location. 
angular.module('tweeterApp.services', ['ngResource']) ...
Default Actions 
{ 'get': {method:'GET'}, 
'save': {method:'POST'}, 
'query': {method:'GET', isArray:true}, 
'remove': {me...
Creating a new object 
var newTeet = new Tweet(); 
newTweet.name = "Look, a tweet!"; 
newTweet.$save();
Callbacks 
Tweet.get({id:123}, function(tweet){ 
console.log(tweet); 
});
VS Promises 
Tweet.get({id:123}) 
.$promise.then(function(tweet) { 
$scope.tweet = tweet; 
});
Scope 
You change a value in the controller, and it’s 
automagically updated in the view. 
And vice versa.
Angular Controllers 
tweeterControllers.controller('TweetCtrl', function 
TweetCtrl($scope, Tweet) { 
... 
});
The meat 
Tweet.query(function(response) { 
$scope.tweets = response; 
}); 
$scope.submitTweet = function(text) { 
var twe...
Can’t get rid of all the templates 
Used to pass information from django-land to 
angular. 
Gives us our static URL so we ...
Interacting with Django Templates 
<script type="text/javascript"> 
angular 
.module('tweeterApp.services') 
.factory('Aut...
Angular UI Routing 
.config(function ($stateProvider, $urlRouterProvider) { 
... 
$urlRouterProvider.otherwise('/'); 
$sta...
Routing in Angular 
Drop this in your base template 
<div ui-view></div> 
Depending on the route, the correct partial will...
Partials 
Just vanilla HTML and Angular. 
Keep them in an accessible static folder.
Demo time!
Bye Everybody! 
github.com/nnja/tweeter 
@nnja
Djangocon 2014 angular + django
Djangocon 2014 angular + django
Upcoming SlideShare
Loading in …5
×

Djangocon 2014 angular + django

7,573 views

Published on

Djangocon 2014 angular + django

Published in: Software

Djangocon 2014 angular + django

  1. 1. Angular + Django A match made in heaven
  2. 2. github.com/nnja/tweeter
  3. 3. Django Templates … are not my favorite
  4. 4. ● Need to refresh the page to submit a form ● Tough to write JS around template tags ● Difficult to Unit Test ● Template tags can be hard to grok for front end devs … also end tags are annoying
  5. 5. Forms get complex, fast.
  6. 6. Why Endpoints are Better (IMHO) ● Faster - no waiting for a page to reload ● Swap frameworks - Ability to use any javascript framework, and switch them out easily. ● Reusable - Have a mobile app? Your backend is already done!
  7. 7. Dogfooding If your endpoints are public, you can eat your own dogfood by consuming them internally.
  8. 8. REST Frameworks are Standard Front End Devs know how to use them.
  9. 9. AngularJS ● MVC - Responsibilities are separated ● Single page app. That means no refreshes for new content, and a better user experience ● Scope - Variables are bound between JS & View - no nasty JQuery ● Easily Unit Tested
  10. 10. The bad You have to use Javascript
  11. 11. If you don’t like it...
  12. 12. Use another framework Excellent presentation on choosing a JS Framework http://brianholt.me/
  13. 13. Let’s build a Tweeter http://github.com/nnja/tweeter
  14. 14. Requirements 1. Display a list of tweets from all Users 2. Display my tweets (logged in User) 3. Show my profile - username, etc.
  15. 15. Our endpoints are created w/ DRF Django Rest Framework - Easily create a REST endpoint for your application.
  16. 16. Our Model class Tweet(models.Model): user = models.ForeignKey(User) text = models.CharField(max_length=140) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-timestamp']
  17. 17. Our endpoints /api/users/ /api/tweets/ /api/users/:id /api/tweets/:id
  18. 18. GET /api/tweets/ HTTP 200 OK Vary: Accept Content-Type: text/html; charset=utf-8 Allow: GET, POST, HEAD, OPTIONS [ { "text": "Bob is the coolest name EVAR", "user": "bob", "timestamp": "2014-08-29T18:51:19Z" } ]
  19. 19. Configuring Angular
  20. 20. Step 1. Include angular.js Throw ng-app into one of your tags. Everything within those tags is now an angular app. <html lang="en" ng-app="tweeterApp">
  21. 21. {{ }} UH OH Angular tags and Django template tags conflict.
  22. 22. Tell angular to use different tags I like [[ this ]] or use {% verbatim %} {% endverbatim %}
  23. 23. static/js/app.js $interpolateProvider.startSymbol('[[').endSymbol(']]'); $httpProvider.defaults.xsrfCookieName = 'csrftoken'; $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken'; $resourceProvider.defaults.stripTrailingSlashes = false;
  24. 24. Angular Resources A wrapper around a REST Endpoint at a location. angular.module('tweeterApp.services', ['ngResource']) .factory('Tweet', function($resource) { return $resource('/api/tweets/:id/'); });
  25. 25. Default Actions { 'get': {method:'GET'}, 'save': {method:'POST'}, 'query': {method:'GET', isArray:true}, 'remove': {method:'DELETE'}, 'delete': {method:'DELETE'} };
  26. 26. Creating a new object var newTeet = new Tweet(); newTweet.name = "Look, a tweet!"; newTweet.$save();
  27. 27. Callbacks Tweet.get({id:123}, function(tweet){ console.log(tweet); });
  28. 28. VS Promises Tweet.get({id:123}) .$promise.then(function(tweet) { $scope.tweet = tweet; });
  29. 29. Scope You change a value in the controller, and it’s automagically updated in the view. And vice versa.
  30. 30. Angular Controllers tweeterControllers.controller('TweetCtrl', function TweetCtrl($scope, Tweet) { ... });
  31. 31. The meat Tweet.query(function(response) { $scope.tweets = response; }); $scope.submitTweet = function(text) { var tweet = new Tweet({text: text}); tweet.$save(function(){ $scope.tweets.unshift(tweet); }) }
  32. 32. Can’t get rid of all the templates Used to pass information from django-land to angular. Gives us our static URL so we can load assets (css/js)
  33. 33. Interacting with Django Templates <script type="text/javascript"> angular .module('tweeterApp.services') .factory('AuthUser', function() { return { id: "{{ user.id|default:''}}", } }); </script>
  34. 34. Angular UI Routing .config(function ($stateProvider, $urlRouterProvider) { ... $urlRouterProvider.otherwise('/'); $stateProvider .state('tweets', { url: '/', templateUrl: 'static/tweeter/partials/tweet-list.html', controller: 'TweetCtrl', }) };
  35. 35. Routing in Angular Drop this in your base template <div ui-view></div> Depending on the route, the correct partial will be rendered and inserted.
  36. 36. Partials Just vanilla HTML and Angular. Keep them in an accessible static folder.
  37. 37. Demo time!
  38. 38. Bye Everybody! github.com/nnja/tweeter @nnja

×