SlideShare una empresa de Scribd logo
1 de 27
<REACTify />
August 2018
<HeberSilva />
<Tech>
<Talk />
</Tech>
August 2018
What’s Django?
Is a free open-source web framework written in Python, which it follows model-
view-template architectural pattern, to build scalable web applications rapidly.
With React, it turns into MVV (Model-View-View)
Its easier to build better web apps so
quickly and with less code…
Its fast, secure and scalable
Why Reactify Django?!
4
Because… react allows you to…
• Build a very small JavaScript ES6 user interface component to a entire frontend
• Very flexible based on how components works
Because… django
• Gives you backend capabilities to create models and connect
to the database, and create APIs quickly.
Popular sites that are using Django
5
Instagram Pinterest
National Geographic
Bitbucket NASA
Washington Post
And more…
You don’t have to re:Invent the wheel
6
What do I need to get started?
7
$ brew install python
First, have installed Python 3…
$ mkdir reactify-django-quickstart && cd $_
Create a new directory…
Create a new virtual environment…
$ python -m venv my_env *venv is package that comes with Python that allows to install libraries
Activate new virtual environment…
$ source <venv>/bin/activate
Windows users…
Mac users…
C:> <venv>/Scripts/activate.bat
(my_env)$
Once you activate your command prompt should look
like…
Next you’re ready to install packages…
8
Installed Django and Django REST Framework using pip …
Create a new Django project…
*pip is package management system used to install
and manage Python packages(my_env)$ pip install django djangorestframework
(my_env)$ django-admin startproject my_project
Now you can start building your first…
9
Building Django application…
10
A Django project consists of many applications. Each application should ideally do
one thing.
Django applications are modular and reusable.
[projectname]/
├── [projectname]/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
[projectname]/ <- project root
├── [projectname]/ <- Django root
│ ├── __init__.py
│ ├── settings/
│ │ ├── common.py
│ │ ├── development.py
│ │ ├── __init__.py
│ │ └── production.py
│ ├── urls.py
│ └── wsgi.py
├── apps/
│ └── __init__.py
├── manage.py
├── static/
│ └── README
└── templates/
├── base.html
├── core
│ └── login.html
└── README
Create new app…
11
Creating new Django app…
Once you create your app, then you’ll install you’re app
(my_env)$ django-admin startapp app_name
Open up ./your_project/settings.py and add the app
in INSTALLED_APPS
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
‘yourapp',
'rest_framework’
]
Create Django model…
12
Creating new Django model…
Open up ./your_app/models.py and create the App model
from django.db import models
class YourModel(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
message = models.CharField(max_length=300)
created_at = models.DateTimeField(auto_now_add=True)
With the model in place let’s create a migration by running
(my_env)$ python manage.py makemigrations your_app
and finally migrate the database with
(my_env)$ python manage.py migrate
REST serializers…
13
Serialization is the act of transforming an object into another data format
With Django REST a serializer works the other way around too: it converts JSON
to objects
Create a new file named ./your_app/serializers.py. The ModelSerializer takes
our App model and some fields
from rest_framework import serializers
from my_model.models import YourModel
class ModelSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = ('id', 'name', 'email', 'message')
Has only View, no controllers…
14
Django is a MVT framework. That is, Model – View – Template. The View takes
care of the request/response lifecycle.
There are many types of views in Django:
function views, class based views, and built-in class-based generic API
views.
It’s ListCreateAPIView
Open up ./app/views.py and create the view
from app.models import MyModel
from app.serializers import MyModelSerializer
from rest_framework import generics
class AppModelListCreate(generics.ListCreateAPIView):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
That is…
15
“With 3 lines of code we created a view for handling GET and POST requests.”
“What’s missing now? URL mapping! In other words we should map URLs
to views.”
Django uses URL Mapping…
16
Our goal is to wire up AppListCreate to api/app/
To configure the URL mapping include the app urls in ./my_project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include(‘app.urls')),
]
Next up…
17
We create a new file named ./app/urls.py
In this file we’ll wire up AppListCreate to api/app/
from django.urls import path
from app_view import views
urlpatterns = [
path('api/app/', views.AppListCreate.as_view() ),
]
Now run…
18
$ python manage.py runserver
Head over http://127.0.0.1:8000/api/app/ and you’ll see the browsable API
Finally Django and React together…
19
“How to glue Django and React together?”
“Should React router take over the routing?”
“Should React mount a component in each Django template?”
React in its own “frontend” Django app: load a single HTML template and
let React manage the frontend
Django REST as a standalone API + React as a standalone SPA
$ django-admin startapp frontend
$ ls -1
frontend
my_app
manage.py
project
Let’s Reactify…
20
$ mkdir -p ./frontend/src/components
Let’s also prepare a directory structure for holding the React components
and the static files
$ mkdir -p ./frontend/{static,templates}/frontend
$ npm i react react-dom prop-types --save-dev
How to wire React frontend?
21
First things first create a view in ./frontend/views.py
from django.shortcuts import render
def index(request):
return render(request, 'frontend/index.html')
Then create the template in ./frontend/templates/frontend/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">
<title>Reactify Django</title>
</head>
<body>
<section class="section">
<div class="container">
<div id="app" class="columns"><!-- React --></div>
</div>
</section>
</body>
{% load static %}
<script src="{% static "frontend/main.js" %}"></script>
</html>
Configure mapping…
22
Configure the new URL mapping to include the frontend in ./project/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('leads.urls')),
path('', include('frontend.urls')), #Mapping frontend
]
Next up wire up the view to our root…
23
Create a new file named ./frontend/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index ),
]
Finally enable the frontend app in ./project/settings.py
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
‘my_app',
'rest_framework',
'frontend',
]
Next up wire up the view to our root…
24
Create a new file named ./frontend/src/components/App.js
import React from "react";
import ReactDOM from "react-dom";
import DataProvider from "./DataProvider";
import Table from "./Table";
import Form from "./Form";
class App extends React.Component {
handleUpdateData = () => {
this.refs.dataProvider.fetchLeads()
}
render() {
return (
<React.Fragment>
<DataProvider
ref="dataProvider"
endpoint="api/lead/"
render={data => <Table data={data} />}
/>
<Form endpoint="api/lead/" onSubmit={this.handleUpdateData}/>
</React.Fragment>
)
}
}
const wrapper = document.getElementById("app");
wrapper ? ReactDOM.render(<App />, wrapper) : null;
Wrapping up…
25
• We’ve built a simple Django REST API
• Structure a Django project with React
• Connect React to the Django REST API
Django is DRY. DRY equals less code. And less code equals
less bugs
It’s fantastic. Isn’t it?
26
Live code…
27
“Give it a try and happy coding!”

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Ionic으로 모바일앱 만들기 #4
Ionic으로 모바일앱 만들기 #4Ionic으로 모바일앱 만들기 #4
Ionic으로 모바일앱 만들기 #4
 
Gettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJSGettings started with the superheroic JavaScript library AngularJS
Gettings started with the superheroic JavaScript library AngularJS
 
jQuery For Developers Stack Overflow Dev Days Toronto
jQuery For Developers Stack Overflow Dev Days TorontojQuery For Developers Stack Overflow Dev Days Toronto
jQuery For Developers Stack Overflow Dev Days Toronto
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
JavaScript, React Native and Performance at react-europe 2016
JavaScript, React Native and Performance at react-europe 2016JavaScript, React Native and Performance at react-europe 2016
JavaScript, React Native and Performance at react-europe 2016
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
The Art of AngularJS - DeRailed 2014
The Art of AngularJS - DeRailed 2014The Art of AngularJS - DeRailed 2014
The Art of AngularJS - DeRailed 2014
 
Javascript MVVM with Vue.JS
Javascript MVVM with Vue.JSJavascript MVVM with Vue.JS
Javascript MVVM with Vue.JS
 
An introduction to Vue.js
An introduction to Vue.jsAn introduction to Vue.js
An introduction to Vue.js
 
Angular js
Angular jsAngular js
Angular js
 
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
Universal JS Web Applications with React - Luciano Mammino - Codemotion Rome ...
 
Angular Best Practices v2
Angular Best Practices v2Angular Best Practices v2
Angular Best Practices v2
 
A gently introduction to AngularJS
A gently introduction to AngularJSA gently introduction to AngularJS
A gently introduction to AngularJS
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
AngularJS: an introduction
AngularJS: an introductionAngularJS: an introduction
AngularJS: an introduction
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular js
 
AngularJS best-practices
AngularJS best-practicesAngularJS best-practices
AngularJS best-practices
 
Muhammad azamuddin introduction-to-reactjs
Muhammad azamuddin   introduction-to-reactjsMuhammad azamuddin   introduction-to-reactjs
Muhammad azamuddin introduction-to-reactjs
 
Ionic으로 모바일앱 만들기 #3
Ionic으로 모바일앱 만들기 #3Ionic으로 모바일앱 만들기 #3
Ionic으로 모바일앱 만들기 #3
 

Similar a React django

Similar a React django (20)

Django by rj
Django by rjDjango by rj
Django by rj
 
Django
DjangoDjango
Django
 
بررسی چارچوب جنگو
بررسی چارچوب جنگوبررسی چارچوب جنگو
بررسی چارچوب جنگو
 
Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)Rapid web application development using django - Part (1)
Rapid web application development using django - Part (1)
 
Mini Curso de Django
Mini Curso de DjangoMini Curso de Django
Mini Curso de Django
 
Django simplified : by weever mbakaya
Django simplified : by weever mbakayaDjango simplified : by weever mbakaya
Django simplified : by weever mbakaya
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Introduction to django framework
Introduction to django frameworkIntroduction to django framework
Introduction to django framework
 
DJango
DJangoDJango
DJango
 
Django Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python DevelopersDjango Framework Overview forNon-Python Developers
Django Framework Overview forNon-Python Developers
 
Virtual Environment and Web development using Django
Virtual Environment and Web development using DjangoVirtual Environment and Web development using Django
Virtual Environment and Web development using Django
 
Django 1.10.3 Getting started
Django 1.10.3 Getting startedDjango 1.10.3 Getting started
Django 1.10.3 Getting started
 
Django Architecture Introduction
Django Architecture IntroductionDjango Architecture Introduction
Django Architecture Introduction
 
Treinamento django
Treinamento djangoTreinamento django
Treinamento django
 
Mini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico CesMini Curso Django Ii Congresso Academico Ces
Mini Curso Django Ii Congresso Academico Ces
 
Web Development in Django
Web Development in DjangoWeb Development in Django
Web Development in Django
 
Introduction To Django
Introduction To DjangoIntroduction To Django
Introduction To Django
 
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST FrameworkEasy Step-by-Step Guide to Develop REST APIs with Django REST Framework
Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue Solutions
 

Último

AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Último (20)

Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 

React django

  • 1. <REACTify /> August 2018 <HeberSilva /> <Tech> <Talk /> </Tech>
  • 3. What’s Django? Is a free open-source web framework written in Python, which it follows model- view-template architectural pattern, to build scalable web applications rapidly. With React, it turns into MVV (Model-View-View) Its easier to build better web apps so quickly and with less code… Its fast, secure and scalable
  • 4. Why Reactify Django?! 4 Because… react allows you to… • Build a very small JavaScript ES6 user interface component to a entire frontend • Very flexible based on how components works Because… django • Gives you backend capabilities to create models and connect to the database, and create APIs quickly.
  • 5. Popular sites that are using Django 5 Instagram Pinterest National Geographic Bitbucket NASA Washington Post And more…
  • 6. You don’t have to re:Invent the wheel 6
  • 7. What do I need to get started? 7 $ brew install python First, have installed Python 3… $ mkdir reactify-django-quickstart && cd $_ Create a new directory… Create a new virtual environment… $ python -m venv my_env *venv is package that comes with Python that allows to install libraries Activate new virtual environment… $ source <venv>/bin/activate Windows users… Mac users… C:> <venv>/Scripts/activate.bat (my_env)$ Once you activate your command prompt should look like…
  • 8. Next you’re ready to install packages… 8 Installed Django and Django REST Framework using pip … Create a new Django project… *pip is package management system used to install and manage Python packages(my_env)$ pip install django djangorestframework (my_env)$ django-admin startproject my_project
  • 9. Now you can start building your first… 9
  • 10. Building Django application… 10 A Django project consists of many applications. Each application should ideally do one thing. Django applications are modular and reusable. [projectname]/ ├── [projectname]/ │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py [projectname]/ <- project root ├── [projectname]/ <- Django root │ ├── __init__.py │ ├── settings/ │ │ ├── common.py │ │ ├── development.py │ │ ├── __init__.py │ │ └── production.py │ ├── urls.py │ └── wsgi.py ├── apps/ │ └── __init__.py ├── manage.py ├── static/ │ └── README └── templates/ ├── base.html ├── core │ └── login.html └── README
  • 11. Create new app… 11 Creating new Django app… Once you create your app, then you’ll install you’re app (my_env)$ django-admin startapp app_name Open up ./your_project/settings.py and add the app in INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ‘yourapp', 'rest_framework’ ]
  • 12. Create Django model… 12 Creating new Django model… Open up ./your_app/models.py and create the App model from django.db import models class YourModel(models.Model): name = models.CharField(max_length=100) email = models.EmailField() message = models.CharField(max_length=300) created_at = models.DateTimeField(auto_now_add=True) With the model in place let’s create a migration by running (my_env)$ python manage.py makemigrations your_app and finally migrate the database with (my_env)$ python manage.py migrate
  • 13. REST serializers… 13 Serialization is the act of transforming an object into another data format With Django REST a serializer works the other way around too: it converts JSON to objects Create a new file named ./your_app/serializers.py. The ModelSerializer takes our App model and some fields from rest_framework import serializers from my_model.models import YourModel class ModelSerializer(serializers.ModelSerializer): class Meta: model = YourModel fields = ('id', 'name', 'email', 'message')
  • 14. Has only View, no controllers… 14 Django is a MVT framework. That is, Model – View – Template. The View takes care of the request/response lifecycle. There are many types of views in Django: function views, class based views, and built-in class-based generic API views. It’s ListCreateAPIView Open up ./app/views.py and create the view from app.models import MyModel from app.serializers import MyModelSerializer from rest_framework import generics class AppModelListCreate(generics.ListCreateAPIView): queryset = MyModel.objects.all() serializer_class = MyModelSerializer
  • 15. That is… 15 “With 3 lines of code we created a view for handling GET and POST requests.” “What’s missing now? URL mapping! In other words we should map URLs to views.”
  • 16. Django uses URL Mapping… 16 Our goal is to wire up AppListCreate to api/app/ To configure the URL mapping include the app urls in ./my_project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include(‘app.urls')), ]
  • 17. Next up… 17 We create a new file named ./app/urls.py In this file we’ll wire up AppListCreate to api/app/ from django.urls import path from app_view import views urlpatterns = [ path('api/app/', views.AppListCreate.as_view() ), ]
  • 18. Now run… 18 $ python manage.py runserver Head over http://127.0.0.1:8000/api/app/ and you’ll see the browsable API
  • 19. Finally Django and React together… 19 “How to glue Django and React together?” “Should React router take over the routing?” “Should React mount a component in each Django template?” React in its own “frontend” Django app: load a single HTML template and let React manage the frontend Django REST as a standalone API + React as a standalone SPA $ django-admin startapp frontend $ ls -1 frontend my_app manage.py project
  • 20. Let’s Reactify… 20 $ mkdir -p ./frontend/src/components Let’s also prepare a directory structure for holding the React components and the static files $ mkdir -p ./frontend/{static,templates}/frontend $ npm i react react-dom prop-types --save-dev
  • 21. How to wire React frontend? 21 First things first create a view in ./frontend/views.py from django.shortcuts import render def index(request): return render(request, 'frontend/index.html') Then create the template in ./frontend/templates/frontend/index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css"> <title>Reactify Django</title> </head> <body> <section class="section"> <div class="container"> <div id="app" class="columns"><!-- React --></div> </div> </section> </body> {% load static %} <script src="{% static "frontend/main.js" %}"></script> </html>
  • 22. Configure mapping… 22 Configure the new URL mapping to include the frontend in ./project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('leads.urls')), path('', include('frontend.urls')), #Mapping frontend ]
  • 23. Next up wire up the view to our root… 23 Create a new file named ./frontend/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index ), ] Finally enable the frontend app in ./project/settings.py # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ‘my_app', 'rest_framework', 'frontend', ]
  • 24. Next up wire up the view to our root… 24 Create a new file named ./frontend/src/components/App.js import React from "react"; import ReactDOM from "react-dom"; import DataProvider from "./DataProvider"; import Table from "./Table"; import Form from "./Form"; class App extends React.Component { handleUpdateData = () => { this.refs.dataProvider.fetchLeads() } render() { return ( <React.Fragment> <DataProvider ref="dataProvider" endpoint="api/lead/" render={data => <Table data={data} />} /> <Form endpoint="api/lead/" onSubmit={this.handleUpdateData}/> </React.Fragment> ) } } const wrapper = document.getElementById("app"); wrapper ? ReactDOM.render(<App />, wrapper) : null;
  • 25. Wrapping up… 25 • We’ve built a simple Django REST API • Structure a Django project with React • Connect React to the Django REST API Django is DRY. DRY equals less code. And less code equals less bugs
  • 27. Live code… 27 “Give it a try and happy coding!”

Notas del editor

  1. Our simple app should: list a collection of models create new objects in the database The ListCreateAPIView takes a queryset and a serializer_class.
  2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list of django.urls.path() we want to make GET and POST requests to api/app/ for listing and creating models