Django and React in Modern Web Apps

Django and React in Modern Web Apps

Presented at PyCon LT 2017.

Looks at why and how to combine Django and React, making your user interface more modular and easier to work with. Also briefly covers creating APIs, and running everything in Docker.

895ac7b84a280f686b70e2a70a8f5cd9?s=128

Rivo Laks

May 13, 2017
Tweet

Transcript

  1. 4.
  2. 5.

    Who is Rivo? Rivo Laks Python for ~8 yrs, Django

    for ~6 yrs CTO of Thorgate Thorgate is Estonian web agency / VC
  3. 6.

    Who is Rivo? Rivo Laks Python for ~8 yrs, Django

    for ~6 yrs CTO of Thorgate Thorgate is Estonian web agency / VC Mostly web-based projects, using Django & React
  4. 8.

    Motivation Django is very good choice for backend dev For

    frontend though, Javascript cannot be ignored
  5. 9.

    Motivation Django is very good choice for backend dev For

    frontend though, Javascript cannot be ignored Python is great for glueing together various technologies
  6. 10.

    Motivation Django is very good choice for backend dev For

    frontend though, Javascript cannot be ignored Python is great for glueing together various technologies Let's combine the two!
  7. 11.
  8. 13.

    Goals Use Django for backend Use modern JS & React

    for dynamic frontend Frontend should use APIs to access data
  9. 14.

    Goals Use Django for backend Use modern JS & React

    for dynamic frontend Frontend should use APIs to access data Use Docker for easy deploys
  10. 17.

    React JS library for building user interfaces Built by Facebook,

    open-sourced in March 2015 Not a full framework, easy to get started with
  11. 18.

    React JS library for building user interfaces Built by Facebook,

    open-sourced in March 2015 Not a full framework, easy to get started with Brings declarative thinking to JS
  12. 21.

    Single Page Apps Should we create an SPA? SPAs have

    steep learning curve React makes it easy to start incrementally
  13. 22.

    Single Page Apps Should we create an SPA? SPAs have

    steep learning curve React makes it easy to start incrementally Can move to full SPA later (or immediately), if desired
  14. 23.

    Single Page Apps Should we create an SPA? SPAs have

    steep learning curve React makes it easy to start incrementally Can move to full SPA later (or immediately), if desired Use your Django expertise, add React where needed
  15. 24.
  16. 27.

    Tooling Django REST framework for APIs Webpack for bundling JS/CSS

    Docker for easy & consistent environments
  17. 29.

    Existing Django View + Template # myapp/views.py class MyAppView(TemplateView): template_name

    = 'myapp.html' <!-- myapp.html --> {% extends "base.html" %} {% block content %} Hello! {% endblock %}
  18. 30.

    Add a container HTML element to your page: {% block

    content %} <div id="container"> <div class="loading-indicator"> Loading... </div> </div> {% endblock %}
  19. 31.

    Add a container HTML element to your page: {% block

    content %} <div id="container"> <div class="loading-indicator"> Loading... </div> </div> {% endblock %} {% block scripts %}{{ block.super }} <script> myapp.init(); </script> {% endblock %}
  20. 32.

    De ne the JS init() function to render the React

    component into container function init() { const container = document.getElementById('container'); ReactDOM.render(<HelloMessage name="PyCon LT" />, container); } HelloMessage is a React component.
  21. 33.

    Simple React components function HelloMessage(props) { return ( <div className="message">

    Hello {props.name}! </div> ); } // init() function ReactDOM.render(<HelloMessage name="PyCon LT" />, container);
  22. 36.

    Stateful React components For more complex components Add local state,

    de ne event handlers, etc There will be some code duplication
  23. 37.

    class MyApp extends React.Component { constructor(props) { super(props); this.state =

    { counter: 1, }; } increaseCount() { this.setState({counter: this.state.counter + 1}); } render() { return ( <div className="app"> <HelloMessage name={this.prop.name} /> Counter: {this.state.counter} <button onClick={() => this.increaseCount()}>Increase</button> </div> ); } }
  24. 40.

    What next? Use React Devtools in browser Add Redux for

    managing data Look at React Router and SPAs
  25. 41.

    What next? Use React Devtools in browser Add Redux for

    managing data Look at React Router and SPAs Don't do it all at once
  26. 43.

    Initial data can be passed in Django template, as JSON:

    <script> var MYAPP_DATA = { user: { email: "{{ request.user.email|escapejs }}", name: "{{ request.user.name|escapejs }}", }, // 'items' is JSON-serialized data items: {{ items|safe }}, }; </script> function init() { const container = document.getElementById('container'); ReactDOM.render(<MyApp items={MYAPP_DATA.items} />, container); }
  27. 45.

    Using APIs For loading interactive data, create APIs with Django

    REST framework. Integrates with Django's models and authentication
  28. 46.

    Using APIs For loading interactive data, create APIs with Django

    REST framework. Integrates with Django's models and authentication Built-in functionality includes paging, throttling, validation, etc
  29. 47.

    Using APIs For loading interactive data, create APIs with Django

    REST framework. Integrates with Django's models and authentication Built-in functionality includes paging, throttling, validation, etc Browsable APIs
  30. 48.
  31. 51.

    Javascript side fetch() is the standard approach async / await

    help keep your code clean class MyApp extends React.Component { async loadData() { const response = await fetch('/api/data/', {credentials: 'include'}); const data = await response.json(); this.setState(data); } onRefresh() { this.loadData(); }
  32. 54.

    Bundling JS & CSS with Webpack We have Javascript /

    React sources We want nal JS that browsers can read
  33. 55.

    Bundling JS & CSS with Webpack We have Javascript /

    React sources We want nal JS that browsers can read Webpack – JS module bundler
  34. 59.

    Webpack Advantages Bundles everything into one (or few) les Mini

    es the bundles You can use ES2015, Sass, etc
  35. 62.

    Docker We use Docker in dev & production Reproducability and

    consistency Makes dev env easy to setup
  36. 65.

    Docker 101 Easily run speci c version of Python: docker

    run -it python:3.6.1 Volumes for persisting data: docker run -it -v $PWD:/app python:3.6.1
  37. 66.

    Docker 101 Easily run speci c version of Python: docker

    run -it python:3.6.1 Volumes for persisting data: docker run -it -v $PWD:/app python:3.6.1 Run Jupyter SciPy notebook: docker run -p 8888:8888 -v $PWD:/home/jovyan/work jupyter/scipy-notebook
  38. 67.

    Docker Compose Docker Compose is “a tool for de ning

    and running multi-container Docker applications”
  39. 68.

    Docker Compose Docker Compose is “a tool for de ning

    and running multi-container Docker applications” de ne & control multiple containers at once
  40. 69.

    Docker Compose Docker Compose is “a tool for de ning

    and running multi-container Docker applications” de ne & control multiple containers at once easier networking among single app's services
  41. 70.
  42. 73.

    How Docker helps us Consistent & easy envs Setup dev

    env with make setup Much easier to add dependent services
  43. 79.

    Conclusions Don't let Javascript scare you, embrace it You can

    start using React incrementally Use Django REST framework for APIs
  44. 80.

    Conclusions Don't let Javascript scare you, embrace it You can

    start using React incrementally Use Django REST framework for APIs Docker helps with env setup
  45. 81.

    Thanks! Rivo Laks ⋅ @rivolaks ⋅ rivolaks.com CTO at Thorgate

    ⋅ thorgate.eu Have a look at our Django project template: https://github.com/thorgate/django-project-template