SlideShare a Scribd company logo
Making Django sites more
responsive with REST and
AngularJS
August 27th, 2014
Hi, I’m Hannes.
@hanneshapke

hanneshapke.github.io
Create responsive websites with Django, REST and AngularJS
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_programming.html
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 different eco system
• Do it if your Django site should become
responsive and more user-friendly
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
• Django REST Framework with GIS support
• Django REST Framework 3 Kickstarter: £32,650
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
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 install -g bower`
• Run `bower init`
• Install packages: 

`bower install [package] --save`
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 }!
Step #3
Create a 

static AngularJS site
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>!
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
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: 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 });!
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.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
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
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. serializers.RelatedField(source=‘fruit_type’)
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 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 );!
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 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 }!
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 support

Turn it off if you can
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!
4 STATIC_URL: '/static/'!
5 });!
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/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

More Related Content

PDF
Hybrid Web Applications
PDF
Django Introduction & Tutorial
PPTX
The Django Web Application Framework 2
PDF
Django Rest Framework and React and Redux, Oh My!
PDF
Django a whirlwind tour
PDF
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
PPT
jQuery For Beginners - jQuery Conference 2009
PDF
The Best (and Worst) of Django
Hybrid Web Applications
Django Introduction & Tutorial
The Django Web Application Framework 2
Django Rest Framework and React and Redux, Oh My!
Django a whirlwind tour
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
jQuery For Beginners - jQuery Conference 2009
The Best (and Worst) of Django

What's hot (20)

PPT
High Performance Ajax Applications
PPT
Django
PDF
jQuery UI and Plugins
PDF
Djangocon 2014 angular + django
PPTX
django Forms in a Web API World
ODP
Django for Beginners
PDF
Django Heresies
KEY
HTML 5 & CSS 3
PPT
WordPress and Ajax
PDF
API Design & Security in django
PDF
Game Development Using HTML 5
PDF
Django REST Framework
PDF
Keypoints html5
KEY
Geotalk presentation
PPTX
jQuery from the very beginning
PDF
Aligning Ember.js with Web Standards
PDF
Tek 2013 - Building Web Apps from a New Angle with AngularJS
PPTX
PPT
Writing Pluggable Software
PPTX
Django Architecture Introduction
High Performance Ajax Applications
Django
jQuery UI and Plugins
Djangocon 2014 angular + django
django Forms in a Web API World
Django for Beginners
Django Heresies
HTML 5 & CSS 3
WordPress and Ajax
API Design & Security in django
Game Development Using HTML 5
Django REST Framework
Keypoints html5
Geotalk presentation
jQuery from the very beginning
Aligning Ember.js with Web Standards
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Writing Pluggable Software
Django Architecture Introduction
Ad

Similar to Create responsive websites with Django, REST and AngularJS (20)

PDF
Flask and Angular: An approach to build robust platforms
PDF
Django for mobile applications
PDF
Building an API with Django and Django REST Framework
PDF
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
PDF
Build REST API clients for AngularJS
PDF
Django Restful Web Services Gaston C Hillar
PPTX
React django
PDF
Lightweight Django 1st Edition Julia Elman
KEY
Javascript Frameworks for Well Architected, Immersive Web Apps
PDF
GDG Addis - An Introduction to Django and App Engine
PDF
Free django
PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
PPTX
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
KEY
Approaches to mobile site development
PPTX
Building REST APIs with Django
PDF
Modern Web Applications Utilizing HTML5 (Dev Con TLV 06-2013)
PDF
Modern Web Applications Utilizing HTML5 APIs
ODP
Desenvolvimento Mobile Híbrido
PDF
How to connect AngularJS to servers
PDF
Utilizing HTML5 APIs
Flask and Angular: An approach to build robust platforms
Django for mobile applications
Building an API with Django and Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Build REST API clients for AngularJS
Django Restful Web Services Gaston C Hillar
React django
Lightweight Django 1st Edition Julia Elman
Javascript Frameworks for Well Architected, Immersive Web Apps
GDG Addis - An Introduction to Django and App Engine
Free django
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Write an API for Almost Anything: The Amazing Power and Flexibility of Django...
Approaches to mobile site development
Building REST APIs with Django
Modern Web Applications Utilizing HTML5 (Dev Con TLV 06-2013)
Modern Web Applications Utilizing HTML5 APIs
Desenvolvimento Mobile Híbrido
How to connect AngularJS to servers
Utilizing HTML5 APIs
Ad

More from Hannes Hapke (6)

PDF
PDXPortland - Dockerize Django
PDF
Introduction to Convolutional Neural Networks
PDF
Introduction to Neural Networks - Perceptron
PDF
PyDX Presentation about Python, GeoData and Maps
PDF
Share your code with the Python world by
 creating pip packages
PDF
Python Ecosystem for Beginners - PyCon Uruguay 2013
PDXPortland - Dockerize Django
Introduction to Convolutional Neural Networks
Introduction to Neural Networks - Perceptron
PyDX Presentation about Python, GeoData and Maps
Share your code with the Python world by
 creating pip packages
Python Ecosystem for Beginners - PyCon Uruguay 2013

Recently uploaded (20)

PDF
Modernizing your data center with Dell and AMD
PPTX
A Presentation on Artificial Intelligence
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Machine learning based COVID-19 study performance prediction
PDF
KodekX | Application Modernization Development
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Approach and Philosophy of On baking technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Big Data Technologies - Introduction.pptx
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
Modernizing your data center with Dell and AMD
A Presentation on Artificial Intelligence
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
NewMind AI Monthly Chronicles - July 2025
Machine learning based COVID-19 study performance prediction
KodekX | Application Modernization Development
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Approach and Philosophy of On baking technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Encapsulation_ Review paper, used for researhc scholars
Big Data Technologies - Introduction.pptx
Review of recent advances in non-invasive hemoglobin estimation
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
“AI and Expert System Decision Support & Business Intelligence Systems”

Create responsive websites with Django, REST and AngularJS

  • 1. Making Django sites more responsive with REST and AngularJS August 27th, 2014
  • 4. A regular Django site Github: https://github.com/hanneshapke/fruitloop_django
  • 5. A Django site using REST and AngularJS Github: https://github.com/hanneshapke/fruitloop_angular
  • 8. The Python heroes are 
 working on a fix PEP 3156 ! http://python-notes.curiousefficiency.org/en/latest/pep_ideas/async_programming.html
  • 9. But what is the solution in the mean time?
  • 11. 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
  • 12. If you still think it’s a good idea, here are the steps.
  • 13. Step #1 Create an API endpoint to your Django model
  • 14. 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
  • 15. 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
  • 17. That’s it with Django.
  • 19. Step #2 Set up your js environment and install AngularJS
  • 20. What? A new eco system!
 Based on node.js?
  • 21. 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`
  • 22. 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 }!
  • 23. Step #3 Create a 
 static AngularJS site
  • 24. 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>!
  • 25. 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
  • 27. Step #4 Use {% verbatim %}
  • 28. {{ 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 });!
  • 29. Step #5 Make AngularJS talk 
 to your API
  • 30. 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
  • 31. 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
  • 32. Step #6 Take full advantage of the Django REST Framework
  • 33. Thoughts • Use DRF Authentication methods • Use Object Persmissions • Use the serializer to the full extend
 e.g. serializers.RelatedField(source=‘fruit_type’)
  • 34. Step #7 Use $promise,
 but don’t promise too much
  • 36. 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 );!
  • 37. Step #8 Make your form 
 talk to your API
  • 38. 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 }!
  • 39. Step #9 Clean up your settings.py
  • 40. 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
  • 42. What to do? • Once you project is running, try to document the API • Django REST Swagger is an option
  • 44. Use AngularJS Constants … 1 angular.module('myApp')! 2 .constant('settings', {! 3 // mimic the Django STATIC_URL variable! 4 STATIC_URL: '/static/'! 5 });!
  • 46. What about 
 site performance?
  • 48. Is that the end of Django?
  • 50. 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