SlideShare a Scribd company logo
Django Rest Framework
and React and Redux,
Oh My!
I’m Eric Palakovich Carr.
Co-Founder & Chief Architect at
Previously:
What this talk is not
• A comprehensive tutorial
• A deep dive into how these technologies works
• You WILL need to go and learn this stuff on your
own after this talk
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
Django Rest Framework and React and Redux, Oh My!
{% extends "base.html" %}
{% load staticfiles %}
{% block title %}Some Awesome Django Website{% endblock %}
{% block extrahead %}
<link rel="stylesheet" href="{% static "some.css" %}"/>
<link rel="stylesheet" href="{% static "even_more.css" %}"/>
{% endblock %}
{% block body %}
<!-- some content in Django template -->
<div id="todolist"></div>
<!-- more content in Django template -->
{% endblock %}
Django Rest Framework and React and Redux, Oh My!
Javascript Ecosystem
• We’ll be using NPM to manage your packages
• We’ll be using webpack to handle bundling our
assets.
• We’ll be using scotch to burn away the memories of
configuring the build system for our project.
in a nutshell
• The pip & cheeseshop / pypi of javascript
• packages.json works like requirements.txt &
setup.py
• `npm init` in directory with packages.json generates
node_modules. Kinda like a virtualenv directory.
• packages.json also can act like your `manage.py`
for your javascript code, but you populate it with
custom commands.
Building for Javascript
• Start coding your project, using `npm install some-package —
save` as you go. This creates and maintains your package.json.
• Setup the config file for your build tool (webpack.config.js,
gulpfile.js, Gruntfile, etc)
• Add configs for Babel, minification, and other JS stuff
• Add configs LESS, SASS, and other CSS stuff
• Plus source mapping, tests, linters, sprite sheets, etc
• Run your tool to generate bundles, having them save into your
static directory for Django to pick up.
{% extends "base.html" %}
{% load staticfiles %}
{% block title %}Some Awesome Django Website{% endblock %}
{% block extrahead %}
<link rel="stylesheet" href="{% static "bundle.css" %}"/>
<link rel="stylesheet" href="{% static "some.css" %}"/>
<link rel="stylesheet" href="{% static "even_more.css" %}"/>
{% endblock %}
{% block body %}
<!-- some content in Django template -->
<div id="todolist"></div>
<script src="{% static "bundle.js" %}"></script>
<!-- more content in Django template -->
{% endblock %}
{% extends "base.html" %}
{% load staticfiles %}
{% load render_bundle from webpack_loader %}
{% block title %}Some Awesome Django Website{% endblock %}
{% block extrahead %}
<link rel="stylesheet" href="{% static "some.css" %}"/>
<link rel="stylesheet" href="{% static "even_more.css" %}"/>
{% endblock %}
{% block body %}
<!-- some content in Django template -->
<div id="todolist"></div>
{% render_bundle 'main' 'js' %}
<!-- more content in Django template -->
{% endblock %}
DEMO
Django Rest Framework and React and Redux, Oh My!
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoHeader from './TodoHeader.jsx';
ReactDOM.render(
(
<div className="todoWidget">
<TodoHeader listName="todos" />
</div>
),
document.getElementById('todolist')
);
Django Rest Framework and React and Redux, Oh My!
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoHeader from './TodoHeader.jsx';
ReactDOM.render(
(
<div className="todoWidget">
<TodoHeader listName="todos" />
</div>
),
document.getElementById('todolist')
);
JSX
// TodoHeader.jsx
import React, { Component } from 'react';
export default class TodoHeader extends Component {
render() {
return (
<header className='todoHeadCmp'>
<h1>{this.props.listName}</h1>
</header>
);
}
}
JSX
// TodoHeader.jsx
import React, { Component } from 'react';
export default class TodoHeader extends Component {
render() {
return (
<header className='todoHeadCmp'>
<h1>{this.props.listName}</h1>
</header>
);
}
}
// TodoHeader.jsx
import React, { Component } from 'react';
export default class TodoHeader extends Component {
render() {
return React.createElement(
"header",
{className: "todoHeadCmp"},
React.createElement(
"h1",
null,
this.props.listName,
)
);
}
}
export default class TodoTextInput extends Component {
constructor(props, context) {
super(props, context);
this.state = {
text: this.props.text || ''
};
}
handleSubmit(e) {
const text = e.target.value.trim();
if (e.which === 13) {
this.props.onSave(text);
}
}
handleChange(e) {
this.setState({ text: e.target.value });
}
render() {
return (
<input type='text'
value={this.state.text}
onChange={::this.handleChange}
onKeyDown={::this.handleSubmit} />
);
}
}
React Component Lifecycle
• componentWillMount
• componentDidMount
• componentWillReceiveProps
• shouldComponentUpdate
• componentWillUpdate
• componentDidUpdate
• componentWillUnmount
Django Rest Framework
• The Web browsable API is a huge usability win for your developers.
• Authentication policies including packages for OAuth1a and
OAuth2.
• Serialization that supports both ORM and non-ORM data sources.
• Customizable all the way down - just use regular function-based
views if you don't need the more powerful features.
• Extensive documentation, and great community support.
• Used and trusted by large companies such as Mozilla and
Eventbrite.
Model->Serializer->ViewSet
class Todo(models.Model):
text = models.CharField(max_length=300)
marked = models.BooleanField(default=False)
class TodoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Todo
fields = ('id', 'text', 'marked')
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
Demo
Three Principles of Redux
• Single source of truth
• State is read-only
• Changes are made with pure functions
Redux State Tree / Store
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
Reducers
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
import * as types from '../constants/ActionTypes';
const initialState = [];
export default function todos(state=initialState, action) {
switch (action.type) {
case types.ADD_TODO:
return [...state, action.todo];
case types.DELETE_TODO:
return state.filter(todo =>
todo.id !== action.id
);
case types.EDIT_TODO:
return state.map(todo =>
todo.id === action.todo.id ? action.todo : todo
);
default:
return state;
}
}
Django Rest Framework and React and Redux, Oh My!
store.dispatch({
type: 'ADD_TODO',
todo: {
text: "Check how much time is left",
marked: false
}
})
store.dispatch({
type: 'SET_VISIBILITY_FILTER',
filter: 'SHOW_COMPLETED'
})
Presentational Components
• Are concerned with how things look.
• Use props for displaying everything
• Do not manage state at all
• Don’t emit actions, but may take callbacks that do via
props
<MyComponent
title=“No state, just props.”
barLabels={["MD", "VA", "DE", "DC"]}
barValues={[13.626332, 47.989636, 9.596008, 28.788024]}
/>
Container Component
• Are concerned with how things work.
• Responsible for providing data to presentational
components via props
• Also responsible for handling state changes
triggered inside a presentation component via
callback prop. These state changes are often
done via dispatching an action.
class TodoApp extends Component {
componentDidMount() {
this.props.actions.getTodos();
}
render() {
const { todos, actions } = this.props;
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
function mapState(state) {
return {
todos: state.todos
};
}
function mapDispatch(dispatch) {
return {
actions: bindActionCreators(TodoActions, dispatch)
};
}
export default connect(mapState, mapDispatch)(TodoApp);
Wiring Redux to DRF
• Python package “django-js-reverse" for getting
your url routes in your javascript
• NPM package “redux-promise”
import * as types from '../constants/ActionTypes';
function deleteTodo(id) {
return fetch(Urls.todo_detail(id), {
method: 'delete',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
}).then(() => ({
type: types.DELETE_TODO,
id: id
}));
}
// In a component somewhere else
store.dispatch(deleteTodo(this.props.todo.id))
import * as types from '../constants/ActionTypes';
import * as api from ‘../path/to/MyApiLibrary';
function deleteTodo(id) {
return api.deleteTodo(id).then(() => ({
type: types.DELETE_TODO,
id: id
}));
}
// In a component somewhere else
store.dispatch(deleteTodo(this.props.todo.id))
DEMO
Quick Recap
i.e. TL;DR
You need a build tool to
create bundles.
Webpack is nice for this.
{% extends "base.html" %}
{% load staticfiles %}
{% block title %}Some Awesome Django Website{% endblock %}
{% block extrahead %}
<link rel="stylesheet" href="{% static "bundle.css" %}"/>
<link rel="stylesheet" href="{% static "some.css" %}"/>
<link rel="stylesheet" href="{% static "even_more.css" %}"/>
{% endblock %}
{% block body %}
<!-- some content in Django template -->
<div id="todolist"></div>
<script src="{% static "bundle.js" %}"></script>
<!-- more content in Django template -->
{% endblock %}
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoHeader from './TodoHeader.jsx';
ReactDOM.render(
(
<div className="todoWidget">
<TodoHeader listName="todos" />
</div>
),
document.getElementById('todolist')
);
// TodoHeader.jsx
import React, { Component } from 'react';
export default class TodoHeader extends Component {
render() {
return (
<header className='todoHeadCmp'>
<h1>{this.props.listName}</h1>
</header>
);
}
}
class Todo(models.Model):
text = models.CharField(max_length=300)
marked = models.BooleanField(default=False)
class TodoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Todo
fields = ('id', 'text', 'marked')
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all()
serializer_class = TodoSerializer
import * as types from '../constants/ActionTypes';
const initialState = [];
export default function todos(state=initialState, action) {
switch (action.type) {
case types.ADD_TODO:
return [...state, action.todo];
case types.DELETE_TODO:
return state.filter(todo =>
todo.id !== action.id
);
case types.EDIT_TODO:
return state.map(todo =>
todo.id === action.todo.id ? action.todo : todo
);
default:
return state;
}
}
import * as types from '../constants/ActionTypes';
function deleteTodo(id) {
return fetch(Urls.todo_detail(id), {
method: 'delete',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
}).then(() => ({
type: types.DELETE_TODO,
id: id
}));
}
// In a component somewhere else
store.dispatch(deleteTodo(this.props.todo.id))
Thanks!
Eric Palakovich Carr
@bigsassy on twitter and github
example repo at https://github.com/bigsassy/drf-react-redux
Ad

Recommended

Geotalk presentation
Geotalk presentation
Eric Palakovich Carr
 
Scalable web application architecture
Scalable web application architecture
postrational
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Paulo Ragonha
 
Django Architecture Introduction
Django Architecture Introduction
Haiqi Chen
 
Django Introduction & Tutorial
Django Introduction & Tutorial
之宇 趙
 
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Djangocon 2014 - Django REST Framework - So Easy You Can Learn it in 25 Minutes
Nina Zakharenko
 
Making Django and NoSQL Play Nice
Making Django and NoSQL Play Nice
Alex Gaynor
 
Building a Dynamic Website Using Django
Building a Dynamic Website Using Django
Nathan Eror
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwal
ratneshsinghparihar
 
Django a whirlwind tour
Django a whirlwind tour
Brad Montgomery
 
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
Srijan Technologies
 
Aligning Ember.js with Web Standards
Aligning Ember.js with Web Standards
Matthew Beale
 
Web development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Django
Django
Kangjin Jun
 
Django Heresies
Django Heresies
Simon Willison
 
AJAX Transport Layer
AJAX Transport Layer
Siarhei Barysiuk
 
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
Anusha Chickermane
 
Tango with django
Tango with django
Rajan Kumar Upadhyay
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 
The Django Book - Chapter 5: Models
The Django Book - Chapter 5: Models
Sharon Chen
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
Christopher Foresman
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
jeresig
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
CalderaLearn
 
Writing Pluggable Software
Writing Pluggable Software
Tatsuhiko Miyagawa
 
Ant
Ant
Manav Prasad
 
Intoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Django multi-tier
Django multi-tier
smirolo
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Free django
Free django
Eugen Oskin
 

More Related Content

What's hot (20)

Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwal
ratneshsinghparihar
 
Django a whirlwind tour
Django a whirlwind tour
Brad Montgomery
 
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
Srijan Technologies
 
Aligning Ember.js with Web Standards
Aligning Ember.js with Web Standards
Matthew Beale
 
Web development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Django
Django
Kangjin Jun
 
Django Heresies
Django Heresies
Simon Willison
 
AJAX Transport Layer
AJAX Transport Layer
Siarhei Barysiuk
 
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
Anusha Chickermane
 
Tango with django
Tango with django
Rajan Kumar Upadhyay
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 
The Django Book - Chapter 5: Models
The Django Book - Chapter 5: Models
Sharon Chen
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
Christopher Foresman
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
jeresig
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
CalderaLearn
 
Writing Pluggable Software
Writing Pluggable Software
Tatsuhiko Miyagawa
 
Ant
Ant
Manav Prasad
 
Intoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Django multi-tier
Django multi-tier
smirolo
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwal
ratneshsinghparihar
 
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
[Srijan Wednesday Webinar] Rails 5: What's in It for Me?
Srijan Technologies
 
Aligning Ember.js with Web Standards
Aligning Ember.js with Web Standards
Matthew Beale
 
Web development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
SaaSy maps - using django-tenants and geodjango to provide web-gis software-a...
Anusha Chickermane
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 
The Django Book - Chapter 5: Models
The Django Book - Chapter 5: Models
Sharon Chen
 
Building an API with Django and Django REST Framework
Building an API with Django and Django REST Framework
Christopher Foresman
 
The DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
jeresig
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)
Jacob Kaplan-Moss
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
CalderaLearn
 
Intoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Django multi-tier
Django multi-tier
smirolo
 

Viewers also liked (20)

Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Free django
Free django
Eugen Oskin
 
Starters with Django
Starters with Django
BeDjango
 
Efficient Django
Efficient Django
David Arcos
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
David Threets Professional Persona Project
David Threets Professional Persona Project
David Threet
 
REST API Doc Best Practices
REST API Doc Best Practices
Marta Rauch
 
Magic Methods (Python meetup)
Magic Methods (Python meetup)
Ines Jelovac
 
тайны фокусов
тайны фокусов
lavrenteva
 
REST API Best (Recommended) Practices
REST API Best (Recommended) Practices
Rasheed Waraich
 
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
Fernando Rocha
 
Парсер: что? зачем? как?
Парсер: что? зачем? как?
STEP Computer Academy (Zaporozhye)
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
django-and-postgresql
django-and-postgresql
Oleg Churkin
 
Getting Started With Django
Getting Started With Django
jeff_croft
 
OAuth2: Uma abordagem para segurança de aplicações e APIs REST - Devcamp 2014
OAuth2: Uma abordagem para segurança de aplicações e APIs REST - Devcamp 2014
Tiago Marchetti Dolphine
 
тайны фокусов
тайны фокусов
lavrenteva
 
Django rest framework tips and tricks
Django rest framework tips and tricks
xordoquy
 
Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做
flywindy
 
那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子
flywindy
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Starters with Django
Starters with Django
BeDjango
 
Efficient Django
Efficient Django
David Arcos
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
Solution4Future
 
David Threets Professional Persona Project
David Threets Professional Persona Project
David Threet
 
REST API Doc Best Practices
REST API Doc Best Practices
Marta Rauch
 
Magic Methods (Python meetup)
Magic Methods (Python meetup)
Ines Jelovac
 
тайны фокусов
тайны фокусов
lavrenteva
 
REST API Best (Recommended) Practices
REST API Best (Recommended) Practices
Rasheed Waraich
 
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
DJANGO-REST-FRAMEWORK: AWESOME WEB-BROWSABLE WEB APIS
Fernando Rocha
 
REST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
django-and-postgresql
django-and-postgresql
Oleg Churkin
 
Getting Started With Django
Getting Started With Django
jeff_croft
 
OAuth2: Uma abordagem para segurança de aplicações e APIs REST - Devcamp 2014
OAuth2: Uma abordagem para segurança de aplicações e APIs REST - Devcamp 2014
Tiago Marchetti Dolphine
 
тайны фокусов
тайны фокусов
lavrenteva
 
Django rest framework tips and tricks
Django rest framework tips and tricks
xordoquy
 
Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做
flywindy
 
那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子
flywindy
 
Ad

Similar to Django Rest Framework and React and Redux, Oh My! (20)

React django
React django
Heber Silva
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
Server side rendering with React and Symfony
Server side rendering with React and Symfony
Ignacio Martín
 
React Django Presentation
React Django Presentation
Allison DiNapoli
 
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Angela Kristine Juvet Branaes
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
How to Webpack your Django!
How to Webpack your Django!
David Gibbons
 
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
React & Redux
React & Redux
Federico Bond
 
React js programming concept
React js programming concept
Tariqul islam
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Advanced redux
Advanced redux
Boris Dinkevich
 
Up and Running with ReactJS
Up and Running with ReactJS
Loc Nguyen
 
TPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and Flux
Jirat Kijlerdpornpailoj
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React Ecosystem
Rami Sayar
 
Getting Started with React v16
Getting Started with React v16
Benny Neugebauer
 
React lecture
React lecture
Christoffer Noring
 
Django + Vue, JavaScript de 3ª generación para modernizar Django
Django + Vue, JavaScript de 3ª generación para modernizar Django
Javier Abadía
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
Visual Engineering
 
Server side rendering with React and Symfony
Server side rendering with React and Symfony
Ignacio Martín
 
Creating a full stack web app with python, npm, webpack and react
Creating a full stack web app with python, npm, webpack and react
Angela Kristine Juvet Branaes
 
Writing HTML5 Web Apps using Backbone.js and GAE
Writing HTML5 Web Apps using Backbone.js and GAE
Ron Reiter
 
How to Webpack your Django!
How to Webpack your Django!
David Gibbons
 
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
MidwestJS 2014 Reconciling ReactJS as a View Layer Replacement
Zach Lendon
 
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
React js programming concept
React js programming concept
Tariqul islam
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
Mihail Gaberov
 
Up and Running with ReactJS
Up and Running with ReactJS
Loc Nguyen
 
TPSE Thailand 2015 - Rethinking Web with React and Flux
TPSE Thailand 2015 - Rethinking Web with React and Flux
Jirat Kijlerdpornpailoj
 
An Intense Overview of the React Ecosystem
An Intense Overview of the React Ecosystem
Rami Sayar
 
Getting Started with React v16
Getting Started with React v16
Benny Neugebauer
 
Ad

Recently uploaded (20)

Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Python Conference Singapore - 19 Jun 2025
Python Conference Singapore - 19 Jun 2025
ninefyi
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
" How to survive with 1 billion vectors and not sell a kidney: our low-cost c...
Fwdays
 
Quantum AI: Where Impossible Becomes Probable
Quantum AI: Where Impossible Becomes Probable
Saikat Basu
 
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Quantum AI Discoveries: Fractal Patterns Consciousness and Cyclical Universes
Saikat Basu
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
Mastering AI Workflows with FME by Mark Döring
Mastering AI Workflows with FME by Mark Döring
Safe Software
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Coordinated Disclosure for ML - What's Different and What's the Same.pdf
Priyanka Aash
 

Django Rest Framework and React and Redux, Oh My!

  • 1. Django Rest Framework and React and Redux, Oh My!
  • 2. I’m Eric Palakovich Carr. Co-Founder & Chief Architect at Previously:
  • 3. What this talk is not • A comprehensive tutorial • A deep dive into how these technologies works • You WILL need to go and learn this stuff on your own after this talk
  • 8. {% extends "base.html" %} {% load staticfiles %} {% block title %}Some Awesome Django Website{% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static "some.css" %}"/> <link rel="stylesheet" href="{% static "even_more.css" %}"/> {% endblock %} {% block body %} <!-- some content in Django template --> <div id="todolist"></div> <!-- more content in Django template --> {% endblock %}
  • 10. Javascript Ecosystem • We’ll be using NPM to manage your packages • We’ll be using webpack to handle bundling our assets. • We’ll be using scotch to burn away the memories of configuring the build system for our project.
  • 11. in a nutshell • The pip & cheeseshop / pypi of javascript • packages.json works like requirements.txt & setup.py • `npm init` in directory with packages.json generates node_modules. Kinda like a virtualenv directory. • packages.json also can act like your `manage.py` for your javascript code, but you populate it with custom commands.
  • 12. Building for Javascript • Start coding your project, using `npm install some-package — save` as you go. This creates and maintains your package.json. • Setup the config file for your build tool (webpack.config.js, gulpfile.js, Gruntfile, etc) • Add configs for Babel, minification, and other JS stuff • Add configs LESS, SASS, and other CSS stuff • Plus source mapping, tests, linters, sprite sheets, etc • Run your tool to generate bundles, having them save into your static directory for Django to pick up.
  • 13. {% extends "base.html" %} {% load staticfiles %} {% block title %}Some Awesome Django Website{% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static "bundle.css" %}"/> <link rel="stylesheet" href="{% static "some.css" %}"/> <link rel="stylesheet" href="{% static "even_more.css" %}"/> {% endblock %} {% block body %} <!-- some content in Django template --> <div id="todolist"></div> <script src="{% static "bundle.js" %}"></script> <!-- more content in Django template --> {% endblock %}
  • 14. {% extends "base.html" %} {% load staticfiles %} {% load render_bundle from webpack_loader %} {% block title %}Some Awesome Django Website{% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static "some.css" %}"/> <link rel="stylesheet" href="{% static "even_more.css" %}"/> {% endblock %} {% block body %} <!-- some content in Django template --> <div id="todolist"></div> {% render_bundle 'main' 'js' %} <!-- more content in Django template --> {% endblock %}
  • 15. DEMO
  • 17. // index.js import React from 'react'; import ReactDOM from 'react-dom'; import TodoHeader from './TodoHeader.jsx'; ReactDOM.render( ( <div className="todoWidget"> <TodoHeader listName="todos" /> </div> ), document.getElementById('todolist') );
  • 19. // index.js import React from 'react'; import ReactDOM from 'react-dom'; import TodoHeader from './TodoHeader.jsx'; ReactDOM.render( ( <div className="todoWidget"> <TodoHeader listName="todos" /> </div> ), document.getElementById('todolist') ); JSX
  • 20. // TodoHeader.jsx import React, { Component } from 'react'; export default class TodoHeader extends Component { render() { return ( <header className='todoHeadCmp'> <h1>{this.props.listName}</h1> </header> ); } }
  • 21. JSX // TodoHeader.jsx import React, { Component } from 'react'; export default class TodoHeader extends Component { render() { return ( <header className='todoHeadCmp'> <h1>{this.props.listName}</h1> </header> ); } }
  • 22. // TodoHeader.jsx import React, { Component } from 'react'; export default class TodoHeader extends Component { render() { return React.createElement( "header", {className: "todoHeadCmp"}, React.createElement( "h1", null, this.props.listName, ) ); } }
  • 23. export default class TodoTextInput extends Component { constructor(props, context) { super(props, context); this.state = { text: this.props.text || '' }; } handleSubmit(e) { const text = e.target.value.trim(); if (e.which === 13) { this.props.onSave(text); } } handleChange(e) { this.setState({ text: e.target.value }); } render() { return ( <input type='text' value={this.state.text} onChange={::this.handleChange} onKeyDown={::this.handleSubmit} /> ); } }
  • 24. React Component Lifecycle • componentWillMount • componentDidMount • componentWillReceiveProps • shouldComponentUpdate • componentWillUpdate • componentDidUpdate • componentWillUnmount
  • 25. Django Rest Framework • The Web browsable API is a huge usability win for your developers. • Authentication policies including packages for OAuth1a and OAuth2. • Serialization that supports both ORM and non-ORM data sources. • Customizable all the way down - just use regular function-based views if you don't need the more powerful features. • Extensive documentation, and great community support. • Used and trusted by large companies such as Mozilla and Eventbrite.
  • 26. Model->Serializer->ViewSet class Todo(models.Model): text = models.CharField(max_length=300) marked = models.BooleanField(default=False) class TodoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Todo fields = ('id', 'text', 'marked') class TodoViewSet(viewsets.ModelViewSet): queryset = Todo.objects.all() serializer_class = TodoSerializer
  • 27. Demo
  • 28. Three Principles of Redux • Single source of truth • State is read-only • Changes are made with pure functions
  • 29. Redux State Tree / Store { visibilityFilter: 'SHOW_ALL', todos: [ { text: 'Consider using Redux', completed: true, }, { text: 'Keep all state in a single tree', completed: false } ] }
  • 30. Reducers { visibilityFilter: 'SHOW_ALL', todos: [ { text: 'Consider using Redux', completed: true, }, { text: 'Keep all state in a single tree', completed: false } ] }
  • 31. import * as types from '../constants/ActionTypes'; const initialState = []; export default function todos(state=initialState, action) { switch (action.type) { case types.ADD_TODO: return [...state, action.todo]; case types.DELETE_TODO: return state.filter(todo => todo.id !== action.id ); case types.EDIT_TODO: return state.map(todo => todo.id === action.todo.id ? action.todo : todo ); default: return state; } }
  • 33. store.dispatch({ type: 'ADD_TODO', todo: { text: "Check how much time is left", marked: false } }) store.dispatch({ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_COMPLETED' })
  • 34. Presentational Components • Are concerned with how things look. • Use props for displaying everything • Do not manage state at all • Don’t emit actions, but may take callbacks that do via props <MyComponent title=“No state, just props.” barLabels={["MD", "VA", "DE", "DC"]} barValues={[13.626332, 47.989636, 9.596008, 28.788024]} />
  • 35. Container Component • Are concerned with how things work. • Responsible for providing data to presentational components via props • Also responsible for handling state changes triggered inside a presentation component via callback prop. These state changes are often done via dispatching an action.
  • 36. class TodoApp extends Component { componentDidMount() { this.props.actions.getTodos(); } render() { const { todos, actions } = this.props; return ( <div> <Header addTodo={actions.addTodo} /> <MainSection todos={todos} actions={actions} /> </div> ); } } function mapState(state) { return { todos: state.todos }; } function mapDispatch(dispatch) { return { actions: bindActionCreators(TodoActions, dispatch) }; } export default connect(mapState, mapDispatch)(TodoApp);
  • 37. Wiring Redux to DRF • Python package “django-js-reverse" for getting your url routes in your javascript • NPM package “redux-promise”
  • 38. import * as types from '../constants/ActionTypes'; function deleteTodo(id) { return fetch(Urls.todo_detail(id), { method: 'delete', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') }, }).then(() => ({ type: types.DELETE_TODO, id: id })); } // In a component somewhere else store.dispatch(deleteTodo(this.props.todo.id))
  • 39. import * as types from '../constants/ActionTypes'; import * as api from ‘../path/to/MyApiLibrary'; function deleteTodo(id) { return api.deleteTodo(id).then(() => ({ type: types.DELETE_TODO, id: id })); } // In a component somewhere else store.dispatch(deleteTodo(this.props.todo.id))
  • 40. DEMO
  • 42. You need a build tool to create bundles. Webpack is nice for this.
  • 43. {% extends "base.html" %} {% load staticfiles %} {% block title %}Some Awesome Django Website{% endblock %} {% block extrahead %} <link rel="stylesheet" href="{% static "bundle.css" %}"/> <link rel="stylesheet" href="{% static "some.css" %}"/> <link rel="stylesheet" href="{% static "even_more.css" %}"/> {% endblock %} {% block body %} <!-- some content in Django template --> <div id="todolist"></div> <script src="{% static "bundle.js" %}"></script> <!-- more content in Django template --> {% endblock %}
  • 44. // index.js import React from 'react'; import ReactDOM from 'react-dom'; import TodoHeader from './TodoHeader.jsx'; ReactDOM.render( ( <div className="todoWidget"> <TodoHeader listName="todos" /> </div> ), document.getElementById('todolist') );
  • 45. // TodoHeader.jsx import React, { Component } from 'react'; export default class TodoHeader extends Component { render() { return ( <header className='todoHeadCmp'> <h1>{this.props.listName}</h1> </header> ); } }
  • 46. class Todo(models.Model): text = models.CharField(max_length=300) marked = models.BooleanField(default=False) class TodoSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Todo fields = ('id', 'text', 'marked') class TodoViewSet(viewsets.ModelViewSet): queryset = Todo.objects.all() serializer_class = TodoSerializer
  • 47. import * as types from '../constants/ActionTypes'; const initialState = []; export default function todos(state=initialState, action) { switch (action.type) { case types.ADD_TODO: return [...state, action.todo]; case types.DELETE_TODO: return state.filter(todo => todo.id !== action.id ); case types.EDIT_TODO: return state.map(todo => todo.id === action.todo.id ? action.todo : todo ); default: return state; } }
  • 48. import * as types from '../constants/ActionTypes'; function deleteTodo(id) { return fetch(Urls.todo_detail(id), { method: 'delete', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': getCookie('csrftoken') }, }).then(() => ({ type: types.DELETE_TODO, id: id })); } // In a component somewhere else store.dispatch(deleteTodo(this.props.todo.id))
  • 49. Thanks! Eric Palakovich Carr @bigsassy on twitter and github example repo at https://github.com/bigsassy/drf-react-redux