Web Application to Manage Customer Information with Django and React on Ubuntu

Sanket Lolge   07 November,2020  

  •  
  • React, a JavaScript framework that allows developers to build web and native frontends for their REST API backends.
  • Django, a free and open-source Python web framework that follows the model view controller (MVC) software architectural pattern.
  • Django REST framework, a powerful and flexible toolkit for building REST APIs in Django.

In this blog, you will build a modern web application with a separate REST API backend and frontend using React, Django, and the Django REST Framework. By using React with Django, you’ll be able to benefit from the latest advancements in JavaScript and front-end development. Instead of building a Django application that uses a built-in template engine, you will use React as a UI library, taking advantage of its virtual Document Object Model (DOM), declarative approach, and components that quickly render changes in data.

The web application you will build stores records about customers in a database, and you can use it as a starting point for a CRM application. When you are finished you’ll be able to create, read, update, and delete records using a React interface styled with Bootstrap 4.

Prerequisites

Step 1 — Creating a Python Virtual Environment and Installing Dependencies

In this step, we’ll create a virtual environment and install the required dependencies for our application, including Django, the Django REST framework, and django-cors-headers.

Our application will use two different development servers for Django and React. They will run on different ports and will function as two separate domains. Because of this, we need to enable cross-origin resource sharing (CORS) to send HTTP requests from React to Django without being blocked by the browser.

 Create a project folder for Django by creating a virtual environment. You must have installed virtualenv package.

If not installed install it by typing a command on the terminal.

$ python3 -m pip install --user virtualenv

Create a virtual environment. 

$ python3 -m venv ENV

Activate the created virtual environment using source:

$ source ENV/bin/activate

Install the below packages by using pip

$ pip install django

$ pip install djangorestframework

$ python -m pip install django-cors-headers

Step 2 — Creating the Django Project

In this step, we’ll generate the Django project using the following commands and utilities:

  • django-admin startproject project-namedjango-admin is a command-line utility used to accomplish tasks with Django. The startproject command creates a new Django project.

  • python manage.py startapp myapp: manage.py is a utility script, automatically added to each Django project, that performs a number of administrative tasks: creating new applications, migrating the database, and serving the Django project locally. Its startapp command creates a Django application inside the Django project. In Django, the term application describes a Python package that provides some set of features in a project.

To begin, create the Django project with django-admin startproject. We will call our project djangoreactproject:

$ django-admin startproject djangoreactproject

Before moving on, let’s look at the directory structure of our Django project using the tree command.

Tip: tree is a useful command for viewing file and directory structures from the command line. You can install it with the following command:

$ sudo apt-get install tree

To use it, cd into the directory you want and type tree or provide the path to the starting point with

$ tree /home/amit/Django_projects/djreact/djreact_project/djangoreactproject


The ~/djangoreactproject folder is the root of the project. Within this folder, there are several files that will be important to your work:

  • manage.py: The utility script that does a number of administrative tasks.
  • settings.py: The main configuration file for the Django project where you can modify the project’s settings. These settings include variables such as INSTALLED_APPS, a list of strings designating the enabled applications for your project. The Django documentation has more information about available settings.
  • urls.py: This file contains a list of URL patterns and related views. Each pattern maps a connection between a URL and the function that should be called for that URL. For more on URLs and views, please refer to our tutorial on How To Create Django Views.

Our first step in working with the project will be to configure the packages we installed in the previous step, including the Django REST framework and the Django CORS package, by adding them to settings.py. Open the file with nano or your favorite editor:

Next, add the corsheaders.middleware.CorsMiddleware middleware from the previously installed CORS package to the MIDDLEWARE setting. This setting is a list of middlewares, a Python class that contains code processed each time your web application handles a request or response:

Next, you can enable CORS. The CORS_ORIGIN_ALLOW_ALL setting specifies whether or not you want to allow CORS for all domains, and CORS_ORIGIN_WHITELIST is a Python tuple that contains allowed URLs. In our case, because the React development server will be running at http://localhost:3000, we will add new CORS_ORIGIN_ALLOW_ALL = False and CORS_ORIGIN_WHITELIST('https://localhost:3000',) settings to our settings.py file. Add these settings anywhere in the file:

You can find more configuration options in the django-cors-headers docs.

Save the file and exit the editor when you are finished.

Still in the ~/djangoreactproject directory, make a new Django application called customers:

$ python manage.py startapp customers

This will contain the models and views for managing customers. Models define the fields and behaviors of our application data, while views enable our application to properly handle web requests and return the required responses.

Next, add this application to the list of installed applications in your project’s settings.py file so Django will recognize it as part of the project. Open settings.py again:

Add the customers application:

Next, migrate the database and start the local development server. Migrations are Django’s way of propagating the changes you make to your models into your database schema. These changes can include things like adding a field or deleting a model, for example. For more on models and migrations, see How To Create Django Models.

Migrate the database:

$ python manage.py migrate

Start the local development server:

$ python manage.py runserver

Your web application will be running from http://127.0.0.1:8000. If you navigate to this address in your web browser you should see the following page:

At this point, leave the application running and open a new terminal to continue developing the project.

Step 3 — Creating the React Frontend

In this section, we’re going to create the front-end application of our project using React.

React has an official utility that allows you to quickly generate React projects without having to configure Webpack directly. Webpack is a module bundler used to bundle web assets such as JavaScript code, CSS, and images. Typically, before you can use Webpack you need to set various configuration options, but thanks to the create-react-app utility you don’t have to deal with Webpack directly until you decide you need more control. To run create-react-app you can use npx, a tool that executes npm package binaries.

In your second terminal, make sure you are in your project directory djangoreactproject

Create a React project called frontend using create-react-app and npx:

$ npx create-react-app frontend

Next, navigate inside your React application and start the development server:
 

$ cd frontend

$ npm start

You application will be running from http://localhost:3000/:

Leave the React development server running and open another terminal window to proceed.

To see the directory structure of the entire project at this point, navigate to the root folder and run tree again:

$ tree 

You’ll see a structure like this:

├── customers
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── djangoreactproject
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── frontend
│   ├── package.json
│   ├── public
│   │   ├── favicon.ico
│   │   ├── index.html
│   │   └── manifest.json
│   ├── README.md
│   ├── src
│   │   ├── App.css
│   │   ├── App.js
│   │   ├── App.test.js
│   │   ├── index.css
│   │   ├── index.js
│   │   ├── logo.svg
│   │   └── registerServiceWorker.js
│   └── yarn.lock
└── manage.py

 

Our application will use Bootstrap 4 to style the React interface, so we will include it in the frontend/src/App.css file, which manages our CSS settings. Open the file:

Add the following import to the beginning of the file. You can delete the file’s existing content, though that’s not required:

Here, @import is a CSS instruction that’s used to import style rules from other style sheets.

Now that we have created both the back-end and front-end applications, let’s create the Customer model and some demo data.

Step 4 — Creating the Customer Model and Initial Data

After creating the Django application and the React frontend, our next step will be to create the Customer model, which represents the database table that will hold information about customers. You don’t need any SQL since the Django Object Relational Mapper (ORM) will handle database operations by mapping Python classes and variables to SQL tables and columns. In this way the Django ORM abstracts SQL interactions with the database through a Python interface.

Activate your virtual environment again:

$ source env/bin/activate

Move to the customers directory, and open models.py, a Python file that holds the models of your application:

The Customer model’s API is already imported in the file thanks to the from django.db import models import statement. You will now add the Customer class, which extends models.Model. Each model in Django is a Python class that extends django.db.models.Model.

The Customer model will have these database fields:

  • first_name — The first name of the customer.
  • last_name — The last name of the customer.
  • email — The email address of the customer.
  • phone — The phone number of the customer.
  • address — The address of the customer.
  • description — The description of the customer.
  • createdAt — The date when the customer is added.

We will also add the __str__() function, which defines how the model will be displayed. In our case, it will be with the customer’s first name. For more on constructing classes and defining objects, please see How To Construct Classes and Define Objects in Python 3.

Add the following code to the file:

Next, migrate the database to create the database tables. The makemigrations command creates the migration files where model changes will be added, and migrate applies the changes in the migrations files to the database.

Navigate back to the project’s root folder:

Run the following to create the migration files:

$ python manage.py makemigrations

Apply these changes to the database:

$ python manage.py migrate

We can test to see that CRUD operations work on the React model we created using the admin interface that Django provides out of the box, but first, we will do a little configuration.

Open the customers/admin.py file and update it accordingly:

We will create a superuser account to access the admin interface with this command:

$ python manage.py createsuperuser

You will be prompted to enter a username, email, and password for the superuser. Be sure to enter details that you can remember because you will need them to log in to the admin dashboard shortly.

$ python manage.py runserver

Let’s start the server once more and log in on the address — http://localhost:8000/admin:

With the Customer model and demo data created, we can move on to building the REST API.

Step 5 — Creating the REST API

In this step we’ll create the REST API using the Django REST Framework. We’ll create several different API views. An API view is a function that handles an API request or call, while an API endpoint is a unique URL that represents a touchpoint with the REST system. For example, when the user sends a GET request to an API endpoint, Django calls the corresponding function or API view to handle the request and return any possible results.

We’ll also make use of serializers. A serializer in the Django REST Framework allows complex model instances and QuerySets to be converted into JSON format for API consumption. The serializer class can also work in the other direction, providing mechanisms for parsing and deserializing data into Django models and QuerySets.

Our API endpoints will include:

  • api/customers: This endpoint is used to create customers and returns paginated sets of customers.
  • api/customers/<pk>: This endpoint is used to get, update, and delete single customers by primary key or id.

We’ll also create URLs in the project’s urls.py file for the corresponding endpoints (i.e api/customers and api/customers/<pk>).

Let’s start by creating the serializer class for our Customer model.

Adding the Serializer Class

Creating a serializer class for our Customer model is necessary for transforming customer instances and QuerySets to and from JSON. To create the serializer class, first, make a serializers.py file inside the customers application:

Add the following code to import the serializers API and Customer model and create a serializer class that extends serializers.ModelSerializer and specifies the fields that will be serialized:

The Meta class specifies the model and fields to serialize: pk,first_name, last_name, email, phone, address,description.

Now that we’ve created our serializer class, we can add the API views.

Adding the API Views

In this section, we’ll create the API views for our application that will be called by Django when the user visits the endpoint corresponding to the view function.

Open ~/djangoreactproject/customers/views.py:

Delete what’s there and add the following imports:

We are importing the serializer we created, along with the Customer model and the Django and Django REST Framework APIs.

Next, add the view for processing POST and GET HTTP requests:

First we use the @api_view(['GET', 'POST']) decorator to create an API view that can accept GET and POST requests. A decorator is a function that takes another function and dynamically extends it.

In the method body we use the request.method variable to check the current HTTP method and execute the corresponding logic depending on the request type:

  • If it’s a GET request, the method paginates the data using Django Paginator, and returns the first page of data after serialization, the count of available customers, the number of available pages, and the links to the previous and next pages. Paginator is a built-in Django class that paginates a list of data into pages and provides methods to access the items for each page.
  • If it’s a POST request, the method serializes the received customer data and then calls the save() method of the serializer object. It then returns a Response object, an instance of HttpResponse, with a 201 status code. Each view you create is responsible for returing an HttpResponse object. The save() method saves the serialized data in the database.

For more about HttpResponse and views, see this discussion of creating view functions.

Now add the API view that will be responsible for processing the GET, PUT, and DELETE requests for getting, updating, and deleting customers by pk (primary key):

The method is decorated with @api_view(['GET', 'PUT', 'DELETE']) to denote that it’s an API view that can accept GET, PUT, and DELETE requests.

The check in the request.method field verifies the request method, and depending on its value calls the right logic:

  • If it’s a GET request, customer data is serialized and sent using a Response object.
  • If it’s a PUT request, the method creates a serializer for new customer data. Next, it calls the save() method of the created serializer object. Finally, it sends a Response object with the updated customer.
  • If it’s a DELETE request, the method calls the delete() method of the customer object to delete it, then returns a Response object with no data.

We can now move on to creating our endpoints.

Adding API Endpoints

We will now create the API endpoints: api/customers/, for querying and creating customers, and api/customers/<pk>, for getting, updating, or deleting single customers by their pk.

Open ~/djangoreactproject/djangoreactproject/urls.py:

Leave what’s there, but add the import to the customers views at the top of the file:

With our REST endpoints created, let’s see how we can consume them.

Step 6 — Consuming the REST API with Axios

In this step, we’ll install Axios, the HTTP client we’ll use to make API calls. We’ll also create a class to consume the API endpoints we’ve created.

First, deactivate your virtual environment:

$ deactivate

Next, navigate to your frontend folder and Install axios from npm using:

$ npm install axios --save

The --save option adds the axios dependency to your application’s package.json file.

Next, create a JavaScript file called CustomersService.js, which will contain the code to call the REST APIs. We’ll make this inside the src folder, where the application code for our project will live:

Add the following code, which contains methods to connect to the Django REST API:

import axios from 'axios';
const API_URL = 'http://localhost:8000';

export default class CustomersService{

    constructor(){}


    getCustomers() {
        const url = `${API_URL}/api/customers/`;
        return axios.get(url).then(response => response.data);
    }
    getCustomersByURL(link){
        const url = `${API_URL}${link}`;
        return axios.get(url).then(response => response.data);
    }
    getCustomer(pk) {
        const url = `${API_URL}/api/customers/${pk}`;
        return axios.get(url).then(response => response.data);
    }
    deleteCustomer(customer){
        const url = `${API_URL}/api/customers/${customer.pk}`;
        return axios.delete(url);
    }
    createCustomer(customer){
        const url = `${API_URL}/api/customers/`;
        return axios.post(url,customer);
    }
    updateCustomer(customer){
        const url = `${API_URL}/api/customers/${customer.pk}`;
        return axios.put(url,customer);
    }
}

The CustomersService class will call the following Axios methods:

  • getCustomers(): Gets first page of customers.
  • getCustomersByURL(): Gets customers by URL. This makes it possible to get the next pages of customers by passing links such as /api/customers/?page=2.
  • getCustomer(): Gets a customer by primary key.
  • createCustomer(): Creates a customer.
  • updateCustomer(): Updates a customer.
  • deleteCustomer(): Deletes a customer.

We can now display the data from our API in our React UI interface by creating a CustomersList component.

Step 7 — Displaying Data from the API in the React Application

In this step, we’ll create the CustomersList React component. A React component represents a part of the UI; it also lets you split the UI into independent, reusable pieces.

Begin by creating CustomersList.js in frontend/src:

Start by importing React and Component to create a React component:

import  React, { Component } from  'react';

Next, import and instantiate the CustomersService module you created in the previous step, which provides methods that interface with the REST API backend:

import  CustomersService  from  './CustomersService';

const  customersService  =  new  CustomersService();

Next, create a CustomersList component that extends Component to call the REST API. A React component should extend or subclass the Component class. For more about E6 classes and inheritence, please see our tutorial on Understanding Classes in JavaScript.

Add the following code to create a React component that extends react.Component:

class  CustomersList  extends  Component {

    constructor(props) {
        super(props);
        this.state  = {
            customers: [],
            nextPageURL:  ''
        };
        this.nextPage  =  this.nextPage.bind(this);
        this.handleDelete  =  this.handleDelete.bind(this);
    }
}
export  default  CustomersList;

 

Inside the constructor, we are initializing the state object. This holds the state variables of our component using an empty customers array. This array will hold customers and a nextPageURL that will hold the URL of the next page to retrieve from the back-end API. We are also binding the nextPage() and handleDelete() methods to this so they will be accessible from the HTML code.

Next, add the componentDidMount() method and a call to getCustomers() within the CustomersList class, before the closing curly brace.

The componentDidMount() method is a lifecycle method of the component that is called when the component is created and inserted into the DOM. getCustomers() calls the Customers Service object to get the first page of data and the link of the next page from the Django backend:

componentDidMount() {
    var  self  =  this;
    customersService.getCustomers().then(function (result) {
        self.setState({ customers:  result.data, nextPageURL:  result.nextlink})
    });
}

 

Now add the handleDelete() method, which handles deleting a customer, below componentDidMount():

handleDelete(e,pk){
    var  self  =  this;
    customersService.deleteCustomer({pk :  pk}).then(()=>{
        var  newArr  =  self.state.customers.filter(function(obj) {
            return  obj.pk  !==  pk;
        });
        self.setState({customers:  newArr})
    });
}

 

The handleDelete() method calls the deleteCustomer() method to delete a customer using its pk (primary key). If the operation is successful, the customers array is filtered out for the removed customer.

Next, add a nextPage() method to get the data for the next page and update the next page link:

nextPage(){
    var  self  =  this;
    customersService.getCustomersByURL(this.state.nextPageURL).then((result) => {
        self.setState({ customers:  result.data, nextPageURL:  result.nextlink})
    });
}

 

The nextPage() method calls a getCustomersByURL() method, which takes the next page URL from the state object, this.state.nextPageURL, and updates the customers array with the returned data.

Finally, add the component render() method, which renders a table of customers from the component state:

render() {

    return (
    <div  className="customers--list">
        <table  className="table">
            <thead  key="thead">
            <tr>
                <th>#</th>
                <th>First Name</th>
                <th>Last Name</th>
                <th>Phone</th>
                <th>Email</th>
                <th>Address</th>
                <th>Description</th>
                <th>Actions</th>
            </tr>
            </thead>
            <tbody>
                {this.state.customers.map( c  =>
                <tr  key={c.pk}>
                    <td>{c.pk}  </td>
                    <td>{c.first_name}</td>
                    <td>{c.last_name}</td>
                    <td>{c.phone}</td>
                    <td>{c.email}</td>
                    <td>{c.address}</td>
                    <td>{c.description}</td>
                    <td>
                    <button  onClick={(e)=>  this.handleDelete(e,c.pk) }> Delete</button>
                    <a  href={"/customer/" + c.pk}> Update</a>
                    </td>
                </tr>)}
            </tbody>
        </table>
        <button  className="btn btn-primary"  onClick=  {  this.nextPage  }>Next</button>
    </div>
    );
}

 

Now that we’ve created the CustomersList component for displaying the list of customers, we can add the component that handles customer creation and updates.

Step 8 — Adding the Customer Create and Update React Component

In this step, we’ll create the CustomerCreateUpdate component, which will handle creating and updating customers. It will do this by providing a form that users can use to either enter data about a new customer or update an existing entry.

In frontend/src, create a CustomerCreateUpdate.js file:

Add the following code to create a React component, importing React and Component:

We can also import and instantiate the CustomersService class we created in the previous step, which provides methods that interface with the REST API backend:

Next, create a CustomerCreateUpdate component that extends Component to create and update customers:

Within the class definition, add the render() method of the component, which renders an HTML form that takes information about the customer:

render() {
        return (
          <form onSubmit={this.handleSubmit}>
          <div className="form-group">
            <label>
              First Name:</label>
              <input className="form-control" type="text" ref='firstName' />

            <label>
              Last Name:</label>
              <input className="form-control" type="text" ref='lastName'/>

            <label>
              Phone:</label>
              <input className="form-control" type="text" ref='phone' />

            <label>
              Email:</label>
              <input className="form-control" type="text" ref='email' />

            <label>
              Address:</label>
              <input className="form-control" type="text" ref='address' />

            <label>
              Description:</label>
              <textarea className="form-control" ref='description' ></textarea>


            <input className="btn btn-primary" type="submit" value="Submit" />
            </div>
          </form>
        );
  }

 

For each form input element, the method adds a ref property to access and set the value of the form element.

Next, above the render() method, define a handleSubmit(event) method so that you have the proper functionality when a user clicks on the submit button:

The handleSubmit(event) method handles the form submission and, depending on the route, calls either the handleUpdate(pk) method to update the customer with the passed pk, or the handleCreate() method to create a new customer. We will define these methods shortly.

Back on the component constructor, bind the newly added handleSubmit() method to this so you can access it in your form:

Next, define the handleCreate() method to create a customer from the form data. Above the handleSubmit(event) method, add the following code:

The handleCreate() method will be used to create a customer from inputted data. It calls the corresponding CustomersService.createCustomer() method that makes the actual API call to the backend to create a customer.

Next, below the handleCreate() method, define the handleUpdate(pk) method to implement updates:

The updateCustomer() method will update a customer by pk using the new information from the customer information form. It calls the customersService.updateCustomer() method.

Next, add a componentDidMount() method. If the the user visits a customer/:pk route, we want to fill the form with information related to the customer using the primary key from the URL. To do that, we can add the getCustomer(pk) method after the component gets mounted in the lifecycle event of componentDidMount(). Add the following code below the component constructor to add this method:

With the CustomerCreateUpdate component created, we can update the main App component to add links to the different components we’ve created.

Step 9 — Updating the Main App Component

In this section, we’ll update the App component of our application to create links to the components we’ve created in the previous steps.

From the frontend folder, run the following command to install the React Router, which allows you to add routing and navigation between various React components:

$ npm install --save react-router-dom

Next, open ~/djangoreactproject/frontend/src/App.js:

Delete everything that’s there and add the following code to import the necessary classes for adding routing. These include BrowserRouter, which creates a Router component, and Route, which creates a route component:

BrowserRouter keeps the UI in sync with the URL using the HTML5 history API.

Next, create a base layout that provides the base component to be wrapped by the BrowserRouter component:

onst  BaseLayout  = () => (
<div  className="container-fluid">
    <nav  className="navbar navbar-expand-lg navbar-light bg-light">
        <a  className="navbar-brand"  href="#">Django React Demo</a>
        <button  className="navbar-toggler"  type="button"  data-toggle="collapse"  data-target="#navbarNavAltMarkup"  aria-controls="navbarNavAltMarkup"  aria-expanded="false"  aria-label="Toggle navigation">
        <span  className="navbar-toggler-icon"></span>
    </button>
    <div  className="collapse navbar-collapse"  id="navbarNavAltMarkup">
        <div  className="navbar-nav">
            <a  className="nav-item nav-link"  href="/">CUSTOMERS</a>
            <a  className="nav-item nav-link"  href="/customer">CREATE CUSTOMER</a>
        </div>
    </div>
    </nav>
    <div  className="content">
        <Route  path="/"  exact  component={CustomersList}  />
        <Route  path="/customer/:pk"  component={CustomerCreateUpdate}  />
        <Route  path="/customer/"  exact  component={CustomerCreateUpdate}  />
    </div>
</div>
)

 

We use the Route component to define the routes of our application; the component the router should load once a match is found. Each route needs a path to specify the path to be matched and a component to specify the component to load. The exact property tells the router to match the exact path

Finally, create the App component, the root or top-level component of our React application:

We have wrapped the BaseLayout component with the BrowserRouter component since our app is meant to run in the browser.

After adding routing to our application, we are now ready to test the application. Navigate to http://localhost:3000. You should see the first page of the application:

0
Like