Create responsive websites with Django, REST and AngularJS

Embed Size (px)

DESCRIPTION

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

Text of Create responsive websites with Django, REST and AngularJS

  • 1. Making Django sites more responsive with REST and AngularJS August 27th, 2014

2. Hi, Im Hannes. @hanneshapke hanneshapke.github.io 3. A regular Django site Github: https://github.com/hanneshapke/fruitloop_django 4. A Django site using REST and AngularJS Github: https://github.com/hanneshapke/fruitloop_angular 5. Sync vs. Async 6. is synchronous. 7. The Python heroes are working on a x PEP 3156 ! http://python-notes.curiousefficiency.org/en/latest/pep_ideas/async_programming.html 8. But what is the solution in the mean time? 9. { }+ + http://www.airpair.com/js/javascript-framework-comparison 10. Dont 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. If you still think its a good idea, here are the steps. 12. Step #1 Create an API endpoint to your Django model 13. REST Representational state transfer Django REST Framework, tasty-pie PyDannys Choosing an API Framework for Django Django REST Framework with GIS support Django REST Framework 3 Kickstarter: 32,650 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. Image: http://4gbloggingcrew.global2.vic.edu.au/les/2014/07/boom-2gjd45e.jpg 16. Thats it with Django. 17. Hey Django, meet AngularJS. 18. Step #2 Set up your js environment and install AngularJS 19. What? A new eco system! Based on node.js? 20. Bower.io Package manager for front-end js Works like pip, but its pip, can be congured Install it with `npm install -g bower` Run `bower init` Install packages: `bower install [package] --save` 21. What to do? Created a .bowerrc le 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 le similar to your requirements.txt from pip 1 {! 2 "directory": "fruitloop_angular/assets/js/",! 3 "json": "bower.json"! 4 }! 22. Step #3 Create a static AngularJS site 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 ! 2 {{ item.name }} - {{ item.price | currency }} ! 3 ! 24. What to do? Set up the settings path for your js assets Created a 'static' html site and serve with Djangos TemplateView Create a sample js array to test your Angular setup Created a controller to serve 'static' data 25. Arhhh, it doest work! 26. Step #4 Use {% verbatim %} 27. {{ isnt {{ 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. Step #5 Make AngularJS talk to your API 29. What to do? Install angular-resource with `bower install angular-resource --save` Create the AngularJS in services.js and congure 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. 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/, {}, {});` Congure more API methods here, e.g. PUT, DELETE, etc., if needed 31. Step #6 Take full advantage of the Django REST Framework 32. Thoughts Use DRF Authentication methods Use Object Persmissions Use the serializer to the full extend e.g. serializers.RelatedField(source=fruit_type) 33. Step #7 Use $promise, but dont promise too much 34. Example 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. Step #8 Make your form talk to your API 37. What to do? Bind your form data with Angulars ng-model Check your API service cong and see if the trailing slash doesnt 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. Step #9 Clean up your settings.py 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. Step #10 Document your API 41. What to do? Once you project is running, try to document the API Django REST Swagger is an option 42. Small Hints 43. Use AngularJS Constants 1 angular.module('myApp')! 2 .constant('settings', {! 3 // mimic the Django STATIC_URL variable! 4 STATIC_URL: '/static/'! 5 });! 44. Decide! urls.py vs. ng-route 45. What about site performance? 46. Then why using Django? 47. Is that the end of Django? 48. Vielen Dank. hannes.hapke@gmail.com @hanneshapke hanneshapke.github.io 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