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.
Making Django sites more
responsive with REST and
AngularJS
August 27th, 2014
Hi, I’m Hannes.
@hanneshapke

hanneshapke.github.io
A regular Django site
Github: https://github.com/hanneshapke/fruitloop_django
A Django site using REST and AngularJS
Github: https://github.com/hanneshapke/fruitloop_angular
Sync vs. Async
… is synchronous.
The Python heroes are 

working on a fix
PEP 3156
!
http://python-notes.curiousefficiency.org/en/latest/pep_ideas/async_pro...
But what is the solution
in the mean time?
{ }+ +
…
http://www.airpair.com/js/javascript-framework-comparison
Don’t change your project …
• … because it is hip
• Creates new and larger code base, time consuming
• Requires a differen...
If you still think it’s a good
idea, here are the steps.
Step #1
Create an API endpoint
to your Django model
REST
• Representational state transfer
• Django REST Framework, tasty-pie

PyDanny’s Choosing an API Framework for Django
...
What to do?
• `pip install djangorestframework`
• Add to your settings.py
• Create a REST serializers for your models
• Cr...
Image: http://4gbloggingcrew.global2.vic.edu.au/files/2014/07/boom-2gjd45e.jpg
That’s it with Django.
Hey Django,

meet AngularJS.
Step #2
Set up your js environment
and install AngularJS
What?
A new eco system!

Based on node.js?
Bower.io
• Package manager for front-end js
• Works like pip, but it’s pip, can be configured
• Install it with `npm instal...
What to do?
• Created a .bowerrc file to point at the js assets
folder of the django project



• Installed the angular cor...
Step #3
Create a 

static AngularJS site
30 second Intro to AngularJS
• Angular offers

Controllers - Changes site behaviour

Services - Provides data access (e.g....
What to do?
• Set up the settings path for your js assets
• Created a 'static' html site and serve with Django’s

Template...
Arhhh, it does’t work!
Step #4
Use {% verbatim %}
{{ isn’t {{
• Django and AngularJS use the same variable tag
• Django > 1.4: Use {% verbatim %} environment
• Django < 1.5...
Step #5
Make AngularJS talk 

to your API
What to do?
• Install angular-resource with 

`bower install angular-resource --save`
• Create the AngularJS in services.j...
Sample code
1 var fruitServices = angular.module('fruitServices', ['ngResource']);!
2 fruitServices.factory('FruitLocation...
Step #6
Take full advantage of the
Django REST Framework
Thoughts
• Use DRF Authentication methods
• Use Object Persmissions
• Use the serializer to the full extend

e.g. serializ...
Step #7
Use $promise,

but don’t promise too much
Example
Thoughts
• Encapsulate data-related code with $promise
• Code will be executed when data is returned from
the API
1 FruitL...
Step #8
Make your form 

talk to your API
What to do?
• Bind your form data with Angular’s ng-model
• Check your API service config and see if the
trailing slash doe...
Step #9
Clean up your settings.py
What to do?
• Make Django lightweight
• Remove unnecessary middleware and packages
• Check if you still need i18n and l18n...
Step #10
Document your API
What to do?
• Once you project is running, try to document the API
• Django REST Swagger is an option
Small Hints
Use AngularJS
Constants …
1 angular.module('myApp')!
2 .constant('settings', {!
3 // mimic the Django STATIC_URL variable!...
Decide!
urls.py vs. ng-route
What about 

site performance?
Then why using
Django?
Is that the end of
Django?
Vielen Dank.
hannes.hapke@gmail.com
@hanneshapke

hanneshapke.github.io
Resources
• PyDanny comments on JS and Django: https://pydanny-event-notes.readthedocs.org/en/
latest/DjangoConEurope2013/...
Create responsive websites with Django, REST and AngularJS
Upcoming SlideShare
Loading in …5
×

Create responsive websites with Django, REST and AngularJS

45,556 views

Published on

This presentation gives insights on the steps to change an existing Django project into a more responsive website based on Django, REST and AngularJS.

Published in: Technology

Create responsive websites with Django, REST and AngularJS

  1. 1. Making Django sites more responsive with REST and AngularJS August 27th, 2014
  2. 2. Hi, I’m Hannes. @hanneshapke
 hanneshapke.github.io
  3. 3. A regular Django site Github: https://github.com/hanneshapke/fruitloop_django
  4. 4. A Django site using REST and AngularJS Github: https://github.com/hanneshapke/fruitloop_angular
  5. 5. Sync vs. Async
  6. 6. … is synchronous.
  7. 7. The Python heroes are 
 working on a fix PEP 3156 ! http://python-notes.curiousefficiency.org/en/latest/pep_ideas/async_programming.html
  8. 8. But what is the solution in the mean time?
  9. 9. { }+ + … http://www.airpair.com/js/javascript-framework-comparison
  10. 10. Don’t change your project … • … because it is hip • Creates new and larger code base, time consuming • Requires a different eco system • Do it if your Django site should become responsive and more user-friendly
  11. 11. If you still think it’s a good idea, here are the steps.
  12. 12. Step #1 Create an API endpoint to your Django model
  13. 13. REST • Representational state transfer • Django REST Framework, tasty-pie
 PyDanny’s Choosing an API Framework for Django • Django REST Framework with GIS support • Django REST Framework 3 Kickstarter: £32,650
  14. 14. What to do? • `pip install djangorestframework` • Add to your settings.py • Create a REST serializers for your models • Create API views for your serializers • Update your urls.py
  15. 15. Image: http://4gbloggingcrew.global2.vic.edu.au/files/2014/07/boom-2gjd45e.jpg
  16. 16. That’s it with Django.
  17. 17. Hey Django,
 meet AngularJS.
  18. 18. Step #2 Set up your js environment and install AngularJS
  19. 19. What? A new eco system!
 Based on node.js?
  20. 20. Bower.io • Package manager for front-end js • Works like pip, but it’s pip, can be configured • Install it with `npm install -g bower` • Run `bower init` • Install packages: 
 `bower install [package] --save`
  21. 21. What to do? • Created a .bowerrc file to point at the js assets folder of the django project
 
 • Installed the angular core package with 
 `bower install angular --save` • Bower creates a bower.json file similar to your requirements.txt from pip 1 {! 2 "directory": "fruitloop_angular/assets/js/",! 3 "json": "bower.json"! 4 }!
  22. 22. Step #3 Create a 
 static AngularJS site
  23. 23. 30 second Intro to AngularJS • Angular offers
 Controllers - Changes site behaviour
 Services - Provides data access (e.g. REST)
 Directives - Create your own DOM elements • Angular offers DOM attributes: ng-show, ng- repeat, ng-click, etc. 1 <tr ng-repeat="item in items">! 2 <td> {{ item.name }} - {{ item.price | currency }} </td>! 3 </tr>!
  24. 24. What to do? • Set up the settings path for your js assets • Created a 'static' html site and serve with Django’s
 TemplateView • Create a sample js array to test your Angular setup • Created a controller to serve 'static' data
  25. 25. Arhhh, it does’t work!
  26. 26. Step #4 Use {% verbatim %}
  27. 27. {{ isn’t {{ • Django and AngularJS use the same variable tag • Django > 1.4: Use {% verbatim %} environment • Django < 1.5: Use code here 1 // use {$ variable $} in your template! 2 // from http://django-angular.readthedocs.org/en/latest/integration.! 3 html! 4 ! 5 var my_app = angular.module('MyApp').config(function(! 6 $interpolateProvider) {! 7 $interpolateProvider.startSymbol('{$');! 8 $interpolateProvider.endSymbol('$}');! 9 });!
  28. 28. Step #5 Make AngularJS talk 
 to your API
  29. 29. What to do? • Install angular-resource with 
 `bower install angular-resource --save` • Create the AngularJS in services.js and configure your API endpoints (if needed) • Make the Angular controller load the data
 use query() for lists, use get() for single objects • Display the list in the html page
  30. 30. Sample code 1 var fruitServices = angular.module('fruitServices', ['ngResource']);! 2 fruitServices.factory('FruitLocationService', ['$resource',! 3 function($resource){! 4 return $resource('api/', {}, {! 5 query: {method:'GET', params:{}, isArray: true}! 6 });! 7 }! 8 ]);! • ngResource loaded, $resource becomes available • Notice `$resource (‘api/’, {}, {…});` • Configure more API methods here, e.g. PUT, DELETE, etc., if needed
  31. 31. Step #6 Take full advantage of the Django REST Framework
  32. 32. Thoughts • Use DRF Authentication methods • Use Object Persmissions • Use the serializer to the full extend
 e.g. serializers.RelatedField(source=‘fruit_type’)
  33. 33. Step #7 Use $promise,
 but don’t promise too much
  34. 34. Example
  35. 35. Thoughts • Encapsulate data-related code with $promise • Code will be executed when data is returned from the API 1 FruitLocationService.query().$promise.then(! 2 function (response) {! 3 response.forEach(function(location){! 4 $scope.markers.push({! 5 lat: location.latitude,! 6 lng: location.longitude! 7 });! 8 });! 9 console.log($scope.markers);! 10 }! 11 );!
  36. 36. Step #8 Make your form 
 talk to your API
  37. 37. What to do? • Bind your form data with Angular’s ng-model • Check your API service config and see if the trailing slash doesn’t get eliminated • Set up your authentication classes for the Django REST framework 1 # Required for POST/PUT requests by the Django REST Framework! 2 REST_FRAMEWORK = {! 3 'DEFAULT_AUTHENTICATION_CLASSES': []! 4 }!
  38. 38. Step #9 Clean up your settings.py
  39. 39. What to do? • Make Django lightweight • Remove unnecessary middleware and packages • Check if you still need i18n and l18n support
 Turn it off if you can
  40. 40. Step #10 Document your API
  41. 41. What to do? • Once you project is running, try to document the API • Django REST Swagger is an option
  42. 42. Small Hints
  43. 43. Use AngularJS Constants … 1 angular.module('myApp')! 2 .constant('settings', {! 3 // mimic the Django STATIC_URL variable! 4 STATIC_URL: '/static/'! 5 });!
  44. 44. Decide! urls.py vs. ng-route
  45. 45. What about 
 site performance?
  46. 46. Then why using Django?
  47. 47. Is that the end of Django?
  48. 48. Vielen Dank. hannes.hapke@gmail.com @hanneshapke
 hanneshapke.github.io
  49. 49. Resources • PyDanny comments on JS and Django: https://pydanny-event-notes.readthedocs.org/en/ latest/DjangoConEurope2013/javascript_django.html • Lightweight Django: 
 http://shop.oreilly.com/product/0636920032502.do# • Using Tasty-pie: 
 http://glynjackson.org/weblog/entry/django-angular.html • Django, Angular and Authentication: http://richardtier.com/2014/03/15/authenticate- using-django-rest-framework-endpoint-and-angularjs/ • How the Django REST framework changed my life: http://www.ngenworks.com/blog/how- django-rest-framework-changed-my-life

×