Create responsive websites with Django, REST and AngularJS

Embed Size (px)


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 3. A regular Django site Github: 4. A Django site using REST and AngularJS Github: 5. Sync vs. Async 6. is synchronous. 7. The Python heroes are working on a x PEP 3156 ! 8. But what is the solution in the mean time? 9. { }+ + 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 Create a REST serializers for your models Create API views for your serializers Update your 15. Image: 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. 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.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! 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 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! vs. ng-route 45. What about site performance? 46. Then why using Django? 47. Is that the end of Django? 48. Vielen Dank. @hanneshapke 49. Resources PyDanny comments on JS and Django: latest/DjangoConEurope2013/javascript_django.html Lightweight Django: Using Tasty-pie: Django, Angular and Authentication: using-django-rest-framework-endpoint-and-angularjs/ How the Django REST framework changed my life: django-rest-framework-changed-my-life