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

More Related Content

What's hot (20)

Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh AgarwalDjango app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwal
ratneshsinghparihar
 
Django a whirlwind tour
Django   a whirlwind tourDjango   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 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 StandardsAligning Ember.js with Web Standards
Aligning Ember.js with Web Standards
Matthew Beale
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb development with django - Basics Presentation
Web development with django - Basics Presentation
Shrinath Shenoy
 
Django
DjangoDjango
Django
Kangjin Jun
 
Django Heresies
Django HeresiesDjango Heresies
Django Heresies
Simon Willison
 
AJAX Transport Layer
AJAX Transport LayerAJAX 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...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 djangoTango 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 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: ModelsThe 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 FrameworkBuilding 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 @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
jeresig
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)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 WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
CalderaLearn
 
Writing Pluggable Software
Writing Pluggable SoftwareWriting Pluggable Software
Writing Pluggable Software
Tatsuhiko Miyagawa
 
Ant
AntAnt
Ant
Manav Prasad
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Django multi-tier
Django multi-tierDjango multi-tier
Django multi-tier
smirolo
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh AgarwalDjango 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 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 StandardsAligning Ember.js with Web Standards
Aligning Ember.js with Web Standards
Matthew Beale
 
Web development with django - Basics Presentation
Web development with django - Basics PresentationWeb 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...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 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: ModelsThe 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 FrameworkBuilding 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 @ YahooThe DOM is a Mess @ Yahoo
The DOM is a Mess @ Yahoo
jeresig
 
Introduction To Django (Strange Loop 2011)
Introduction To Django (Strange Loop 2011)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 WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
CalderaLearn
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Django multi-tier
Django multi-tierDjango multi-tier
Django multi-tier
smirolo
 

Viewers also liked (20)

Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Free django
Free djangoFree django
Free django
Eugen Oskin
 
Starters with Django
Starters with Django Starters with Django
Starters with Django
BeDjango
 
Efficient Django
Efficient DjangoEfficient Django
Efficient Django
David Arcos
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython 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 Threets Professional Persona Project
David Threets Professional Persona Project
David Threet
 
REST API Doc Best Practices
REST API Doc Best PracticesREST API Doc Best Practices
REST API Doc Best Practices
Marta Rauch
 
Magic Methods (Python meetup)
Magic Methods (Python meetup)Magic Methods (Python meetup)
Magic Methods (Python meetup)
Ines Jelovac
 
тайны фокусов
тайны фокусовтайны фокусов
тайны фокусов
lavrenteva
 
REST API Best (Recommended) Practices
REST API Best (Recommended) PracticesREST 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 APISDJANGO-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-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
django-and-postgresql
django-and-postgresqldjango-and-postgresql
django-and-postgresql
Oleg Churkin
 
Getting Started With Django
Getting Started With DjangoGetting 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 2014OAuth2: 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 tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
xordoquy
 
Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做
flywindy
 
那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子
flywindy
 
Django Admin (Python meeutp)
Django Admin (Python meeutp)Django Admin (Python meeutp)
Django Admin (Python meeutp)
Ines Jelovac
 
Starters with Django
Starters with Django Starters with Django
Starters with Django
BeDjango
 
Efficient Django
Efficient DjangoEfficient Django
Efficient Django
David Arcos
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython 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 Threets Professional Persona Project
David Threets Professional Persona Project
David Threet
 
REST API Doc Best Practices
REST API Doc Best PracticesREST API Doc Best Practices
REST API Doc Best Practices
Marta Rauch
 
Magic Methods (Python meetup)
Magic Methods (Python meetup)Magic Methods (Python meetup)
Magic Methods (Python meetup)
Ines Jelovac
 
тайны фокусов
тайны фокусовтайны фокусов
тайны фокусов
lavrenteva
 
REST API Best (Recommended) Practices
REST API Best (Recommended) PracticesREST 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 APISDJANGO-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-FrameworkREST Easy with Django-Rest-Framework
REST Easy with Django-Rest-Framework
Marcel Chastain
 
django-and-postgresql
django-and-postgresqldjango-and-postgresql
django-and-postgresql
Oleg Churkin
 
Getting Started With Django
Getting Started With DjangoGetting 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 2014OAuth2: 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 tricksDjango rest framework   tips and tricks
Django rest framework tips and tricks
xordoquy
 
Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做Django 實戰 - 自己的購物網站自己做
Django 實戰 - 自己的購物網站自己做
flywindy
 
那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子那些年,我用 Django Admin 接的案子
那些年,我用 Django Admin 接的案子
flywindy
 
Ad

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

Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
 
Django at the Disco
Django at the DiscoDjango at the Disco
Django at the Disco
Richard Leland
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
Gavin Roy
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
Mike Wilcox
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
Wake Liu
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
.NET Conf UY
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
DEVCON
 
Rails + Sencha = Netzke
Rails + Sencha = NetzkeRails + Sencha = Netzke
Rails + Sencha = Netzke
beffa
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
Max Claus Nunes
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
Alive Kuo
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
dwm042
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
Gavin Roy
 
Web Components v1
Web Components v1Web Components v1
Web Components v1
Mike Wilcox
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
GDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App EngineGDG Addis - An Introduction to Django and App Engine
GDG Addis - An Introduction to Django and App Engine
Yared Ayalew
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
Wake Liu
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
.NET Conf UY
 
Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4Python Code Camp for Professionals 1/4
Python Code Camp for Professionals 1/4
DEVCON
 
Rails + Sencha = Netzke
Rails + Sencha = NetzkeRails + Sencha = Netzke
Rails + Sencha = Netzke
beffa
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
Alive Kuo
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
pootsbook
 
Ad

Recently uploaded (20)

The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Electronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploitElectronic_Mail_Attacks-1-35.pdf by xploit
Electronic_Mail_Attacks-1-35.pdf by xploit
niftliyevhuseyn
 
Learn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step GuideLearn the Basics of Agile Development: Your Step-by-Step Guide
Learn the Basics of Agile Development: Your Step-by-Step Guide
Marcel David
 
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
#AdminHour presents: Hour of Code2018 slide deck from 12/6/2018
Lynda Kane
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
 
Buckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug LogsBuckeye Dreamin' 2023: De-fogging Debug Logs
Buckeye Dreamin' 2023: De-fogging Debug Logs
Lynda Kane
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Asthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdfAsthma presentación en inglés abril 2025 pdf
Asthma presentación en inglés abril 2025 pdf
VanessaRaudez
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 

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