<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!”

React django

  • 1.
    <REACTify /> August 2018 <HeberSilva/> <Tech> <Talk /> </Tech>
  • 2.
  • 3.
    What’s Django? Is afree 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 thatare using Django 5 Instagram Pinterest National Geographic Bitbucket NASA Washington Post And more…
  • 6.
    You don’t haveto re:Invent the wheel 6
  • 7.
    What do Ineed 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 readyto 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 canstart building your first… 9
  • 10.
    Building Django application… 10 ADjango 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 Creatingnew 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 Creatingnew 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 isthe 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 3lines 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 URLMapping… 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 createa 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 $ pythonmanage.py runserver Head over http://127.0.0.1:8000/api/app/ and you’ll see the browsable API
  • 19.
    Finally Django andReact 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 wireReact 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 thenew 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 wireup 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 wireup 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’vebuilt 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
  • 26.
  • 27.
    Live code… 27 “Give ita try and happy coding!”

Editor's Notes

  • #15 Our simple app should: list a collection of models create new objects in the database The ListCreateAPIView takes a queryset and a serializer_class.
  • #17 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