How to Use Django with React

1382 VIEWS

·

Django is a batteries-included Python framework for building web applications. It is used for backend programming; however, it also provides some tools for managing frontend templates. React is a web-based user interface (UI) library created by Facebook that handles UI elements as components. These two frameworks are very popular, have large active communities, and from personal experience, I can say they are good at what they do. If you have tried or heard of the above tools and have been wondering how to use them together, you are in the right place.

Setting up Django

The recommended setup for Django is to use a virtual environment. To do that, install a virtual environment by typing the following in your terminal/command line after navigating to your project folder:

pip install virtualenv

… and type the following commands to create a virtual environment and activate it.

virtualenv venv
source ./venv/bin/activate

The name of your virtual environment should show in the prompt of your terminal or command line. Next, install Django and djangorestframework with:

pip install django
pip install djangorestframework

The Django REST framework will be used to create a RESTful API for React to interact with the Django backend. Create a Django project by typing:

django-admin startproject sweetcode

Navigate to the Django folder and type:

django-admin startapp sweetapp

… to create a Django app called sweetapp. You can then add it to your INSTALLED_APPS in settings.py so that you inform Django that you intend to use it. Next, add ‘rest_framework’ to your installed apps to enable the REST framework. Your INSTALLED_APPS field should now look like this:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
	'sweetapp',
	'rest_framework',
]

You can now type:

python manage.py runserver

… and go to http://127.0.0.1:8000/ to check if your app is working. Everything is fine if you see a page like the image below. If you don’t, there’s a chance you missed some steps.

Let’s now create a model and a serializer to set up our REST API. A model in Python is a class definition that gets translated to a database table and columns. A serializer, in this case, will be responsible for converting models to JSON format for our API, and vice versa.

To create a model, paste the following code in your models.py folder. This creates a simple model that represents a blog post.

from django.db import models
class Post(models.Model):
	author = models.CharField(max_length=100)
	title = models.CharField(max_length=100)
	content = models.TextField(max_length=10000)

We will need to have some sample data in the database when we run our app. Django provides a convenient way of populating the database using fixtures, which are JSON files containing sample data. The data can then be loaded into the database with a simple command. To do this, create a file called “sweetapp_fixtures.json” in ./sweetapp/fixtures and paste the following JSON string.

[{
	"model": "sweetapp.post",
	"pk": 4,
    "fields": {
      "author": "John Wick",
      "title": "Better not Kill that Dog",
      "content": "You know what comes next."
	}
},
{
	"model": "sweetapp.post",
	"pk": 5,
    "fields": {
      "author": "Thanos",
      "title": "Bringing Balance to the Universe",
      "content": "I'll do it myself."
	}
}]

Next, create a file called “serializers.py” in the sweetapp folder and paste the following code:

from rest_framework import serializers
from .models import Post
class PostSerializer(serializers.ModelSerializer):
	class Meta:
    	model = Post
    	fields = '__all__'

We will now create a view that will allow us to expose our API using the following code in views.py within sweetapp. In Django, views are responsible for handling the logic of your application.

from .models import Post
from .serializers import PostSerializer
from rest_framework import generics
 
class PostAPI(generics.ListCreateAPIView):
	queryset = Post.objects.all()
	serializer_class = PostSerializer

We are now one step away from creating our API. The last step is to map the API definition we have in views.py to a URL. In Django, this is done by specifying a urlpatterns variable in your urls.py file. For this example, we will point the project’s urls.py to our app’s urls.py, which will then point to our API definition. (If this doesn’t make sense immediately, hang in there — the following steps should help clear things up.)

First, the urls.py file (in sweetcode) so that it looks like this:

from django.contrib import admin
from django.urls import path, include
 
urlpatterns = [
	path('admin/', admin.site.urls),
	path('api', include('sweetapp.urls')),
]

This tells Django to forward any path that starts with “api” to sweetapp.urls. Now, create a urls.py file in sweetapp and paste the following code into it.

from django.urls import path
from . import views
 
urlpatterns = [
	path(‘’, views.PostAPI.as_view())
]

This maps http://127.0.0.1:8000/api to your API. Run the following commands in the given order to make your database migrations, load our sample data, and run the server. After running the server, visit this URL (http://127.0.0.1:8000/api) to see the graphical representation of your API. Feel free to play around with it and get ready to build the UI with React.

python manage.py makemigrations
python manage.py migrate
python manage.py loaddata sweetapp_fixtures
python manage.py runserver

React

Now that we have set up our backend, the next step is to set up our frontend and integrate the two parts. To do this, we will create a Django app to serve the React app. Use the following commands to create the app and create the necessary folders that will contain the code for the React app, as well as some static files and the main React template:

django-admin startapp frontend
mkdir -p ./frontend/src/components
mkdir -p ./frontend/{static,templates}/frontend

Add the frontend to your installed apps to use it with Django. Add the following line to the urlpatterns of your main urls.py file to connect with your new app:

path('', include('frontend.urls'))

… and create a urls.py file in ./frontend with the following code:

from django.urls import path
from . import views
urlpatterns = [
	path('', views.index)
]

Paste the following code in views.py:

from django.shortcuts import render
def index(request):
	return render(request, 'frontend/index.html')

Create a file called “index” in ./frontend/templates/frontend (which will serve as the entry point for React) and paste the following code in it:


 


  
  
  
  Sweetcode | Django-React

 

  
{% load static %}

We have now set up Django to serve our React app. The next step is to install Webpack with the following commands, after navigating to the root folder of the project:

npm init -y
npm i webpack webpack-cli --save-dev

… and configuring it by editing your package.json to look like this:

  "scripts": {
	"dev": "webpack --mode development ./sweetcode/frontend/src/components/index.jsx --output ./sweetcode/frontend/static/frontend/main.js",
	"build": "webpack --mode production ./sweetcode/frontend/src/components/index.jsx --output ./sweetcode/frontend/static/frontend/main.js"
  },

Install Babel and React with the following commands:

npm i @babel/core babel-loader @babel/preset-env @babel/preset-react babel-plugin-transform-class-properties --save-dev
 
npm i react react-dom prop-types --save-dev

… and configure Babel by creating a .babelrc file with the following code:

{
    "presets": [
        "@babel/preset-env", "@babel/preset-react"
	],
    "plugins": [
        "transform-class-properties"
	]
}

Create the last configuration file (called “webpack.config.js”) with the following code:

module.exports = {
  module: {
	rules: [
  	{
    	test: /\.js$/,
    	exclude: /node_modules/,
    	use: {
      	loader: "babel-loader"
    	}
  	}
	]
  }
};

Now that React is configured, we can move on to the last phase of this process, which is to create the React app. For this post, we will create a very simple app that fetches the data we put in the database and displays it on a webpage in JSON format. This is for the purpose of demonstrating the connectivity between React and Django. You can build on this template to create more complex applications.

To create our app, we’ll need two JavaScript files called “App.js” and “index.js” in ./frontend/source/components. Paste the following code in App.js:

import React, { Component } from "react";
import ReactDOM from "react-dom";
 
 
class App extends Component {
 
	state = {
    	data: ''
	};
 
    componentDidMount() {
        fetch("/api")
          .then(response => {
        	return response.json();
      	})
      	.then(data => this.setState({ data: JSON.stringify(data)}));
  }
 
	render(){
 
    	return (
            

Jason data = {this.state.data}

) } } const wrapper = document.getElementById("app"); wrapper ? ReactDOM.render(, wrapper) : null;

… and paste the following code in index.js:

import App from "./App.js";

Now, build the React app with the following command:

npm run dev

And run the Django server:

python manage.py runserver

You should see a page similar to the screenshot below if you visit 127.0.0.1:8000 from your browser.

Congratulations! You have successfully created a React app using Django as your backend.


Stephan is a third-year student at Ashesi pursuing an undergraduate degree in computer engineering. Stephan is passionate about technology and is focused on continuous learning to gain new skills. He has worked in software development, and has worked on IoT projects and designing products for the health sector.


Discussion

  • I ran into a build issue when I got to the contents of App.js, here is the correction for it to work

    const wrapper = document.getElementById(“app”);
    wrapper ? ReactDOM.render(, wrapper) : null;

    Alex Merced 09/08/2019 10:46 am Reply
Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu