SlideShare una empresa de Scribd logo
1 de 50
Descargar para leer sin conexión
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_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

Más contenido relacionado

La actualidad más candente

High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsJulien Lecomte
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + djangoNina Zakharenko
 
django Forms in a Web API World
django Forms in a Web API Worlddjango Forms in a Web API World
django Forms in a Web API WorldTareque Hossain
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for BeginnersJason Davies
 
API Design & Security in django
API Design & Security in djangoAPI Design & Security in django
API Design & Security in djangoTareque Hossain
 
Game Development Using HTML 5
Game Development Using HTML 5Game Development Using HTML 5
Game Development Using HTML 5osa_ora
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST FrameworkLoad Impact
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5dynamis
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
Aligning Ember.js with Web Standards
Aligning Ember.js with Web StandardsAligning Ember.js with Web Standards
Aligning Ember.js with Web StandardsMatthew Beale
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSPablo Godel
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture IntroductionHaiqi Chen
 

La actualidad más candente (20)

High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
 
Django
DjangoDjango
Django
 
jQuery UI and Plugins
jQuery UI and PluginsjQuery UI and Plugins
jQuery UI and Plugins
 
Djangocon 2014 angular + django
Djangocon 2014 angular + djangoDjangocon 2014 angular + django
Djangocon 2014 angular + django
 
django Forms in a Web API World
django Forms in a Web API Worlddjango Forms in a Web API World
django Forms in a Web API World
 
Django for Beginners
Django for BeginnersDjango for Beginners
Django for Beginners
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
 
HTML 5 & CSS 3
HTML 5 & CSS 3HTML 5 & CSS 3
HTML 5 & CSS 3
 
WordPress and Ajax
WordPress and AjaxWordPress and Ajax
WordPress and Ajax
 
API Design & Security in django
API Design & Security in djangoAPI Design & Security in django
API Design & Security in django
 
Game Development Using HTML 5
Game Development Using HTML 5Game Development Using HTML 5
Game Development Using HTML 5
 
Django REST Framework
Django REST FrameworkDjango REST Framework
Django REST Framework
 
Keypoints html5
Keypoints html5Keypoints html5
Keypoints html5
 
Geotalk presentation
Geotalk presentationGeotalk presentation
Geotalk presentation
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Aligning Ember.js with Web Standards
Aligning Ember.js with Web StandardsAligning Ember.js with Web Standards
Aligning Ember.js with Web Standards
 
Tek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJSTek 2013 - Building Web Apps from a New Angle with AngularJS
Tek 2013 - Building Web Apps from a New Angle with AngularJS
 
Django
DjangoDjango
Django
 
Writing Pluggable Software
Writing Pluggable SoftwareWriting Pluggable Software
Writing Pluggable Software
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 

Similar a Create responsive websites with Django, REST and AngularJS

End to-End SPA Development Using ASP.NET and AngularJS
End to-End SPA Development Using ASP.NET and AngularJSEnd to-End SPA Development Using ASP.NET and AngularJS
End to-End SPA Development Using ASP.NET and AngularJSGil Fink
 
AngularJS One Day Workshop
AngularJS One Day WorkshopAngularJS One Day Workshop
AngularJS One Day WorkshopShyam Seshadri
 
Play Framework workshop: full stack java web app
Play Framework workshop: full stack java web appPlay Framework workshop: full stack java web app
Play Framework workshop: full stack java web appAndrew Skiba
 
European Collaboration Summit - SharePoint Framework Angular & Azure Functions
European Collaboration Summit - SharePoint Framework Angular & Azure FunctionsEuropean Collaboration Summit - SharePoint Framework Angular & Azure Functions
European Collaboration Summit - SharePoint Framework Angular & Azure FunctionsSébastien Levert
 
Untangling spring week11
Untangling spring week11Untangling spring week11
Untangling spring week11Derek Jacoby
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSébastien Levert
 
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure FunctionsSharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure FunctionsSébastien Levert
 
Building a Single Page Application with VueJS
Building a Single Page Application with VueJSBuilding a Single Page Application with VueJS
Building a Single Page Application with VueJSdanpastori
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem vAkash Rajguru
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Matt Raible
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Derek Jacoby
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGuillaume Laforge
 
SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...
SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...
SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...Sébastien Levert
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkMarcel Chastain
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation Phan Tuan
 

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

Angularjs
AngularjsAngularjs
Angularjs
 
End to-End SPA Development Using ASP.NET and AngularJS
End to-End SPA Development Using ASP.NET and AngularJSEnd to-End SPA Development Using ASP.NET and AngularJS
End to-End SPA Development Using ASP.NET and AngularJS
 
I18n of java script
I18n of java scriptI18n of java script
I18n of java script
 
AngularJS One Day Workshop
AngularJS One Day WorkshopAngularJS One Day Workshop
AngularJS One Day Workshop
 
Play Framework workshop: full stack java web app
Play Framework workshop: full stack java web appPlay Framework workshop: full stack java web app
Play Framework workshop: full stack java web app
 
European Collaboration Summit - SharePoint Framework Angular & Azure Functions
European Collaboration Summit - SharePoint Framework Angular & Azure FunctionsEuropean Collaboration Summit - SharePoint Framework Angular & Azure Functions
European Collaboration Summit - SharePoint Framework Angular & Azure Functions
 
Untangling spring week11
Untangling spring week11Untangling spring week11
Untangling spring week11
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
SharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure FunctionsSharePoint Framework, Angular and Azure Functions
SharePoint Framework, Angular and Azure Functions
 
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure FunctionsSharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
SharePoint Fest Seattle - SharePoint Framework, Angular & Azure Functions
 
Django Girls Tutorial
Django Girls TutorialDjango Girls Tutorial
Django Girls Tutorial
 
Building a Single Page Application with VueJS
Building a Single Page Application with VueJSBuilding a Single Page Application with VueJS
Building a Single Page Application with VueJS
 
Akash rajguru project report sem v
Akash rajguru project report sem vAkash rajguru project report sem v
Akash rajguru project report sem v
 
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
Comparing Hot JavaScript Frameworks: AngularJS, Ember.js and React.js - Sprin...
 
Angular js
Angular jsAngular js
Angular js
 
Untangling - fall2017 - week 9
Untangling - fall2017 - week 9Untangling - fall2017 - week 9
Untangling - fall2017 - week 9
 
Google App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and GaelykGoogle App Engine Java, Groovy and Gaelyk
Google App Engine Java, Groovy and Gaelyk
 
SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...
SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...
SharePoint Saturday New York 2017 - SharePoint Framework, Angular and Azure F...
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 

Más de Hannes Hapke

PDXPortland - Dockerize Django
PDXPortland - Dockerize DjangoPDXPortland - Dockerize Django
PDXPortland - Dockerize DjangoHannes Hapke
 
Introduction to Convolutional Neural Networks
Introduction to Convolutional Neural NetworksIntroduction to Convolutional Neural Networks
Introduction to Convolutional Neural NetworksHannes Hapke
 
Introduction to Neural Networks - Perceptron
Introduction to Neural Networks - PerceptronIntroduction to Neural Networks - Perceptron
Introduction to Neural Networks - PerceptronHannes Hapke
 
PyDX Presentation about Python, GeoData and Maps
PyDX Presentation about Python, GeoData and MapsPyDX Presentation about Python, GeoData and Maps
PyDX Presentation about Python, GeoData and MapsHannes Hapke
 
Share your code with the Python world by
 creating pip packages
Share your code with the Python world by
 creating pip packagesShare your code with the Python world by
 creating pip packages
Share your code with the Python world by
 creating pip packagesHannes Hapke
 
Python Ecosystem for Beginners - PyCon Uruguay 2013
Python Ecosystem for Beginners - PyCon Uruguay 2013Python Ecosystem for Beginners - PyCon Uruguay 2013
Python Ecosystem for Beginners - PyCon Uruguay 2013Hannes Hapke
 

Más de Hannes Hapke (6)

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

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Create responsive websites with Django, REST and AngularJS

  • 1. Making Django sites more responsive with REST and AngularJS August 27th, 2014
  • 3.
  • 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