Django React Boilerplate - With Free Samples
Tags: react, django, webdev, appseed
Published: 2021-08-31 17:08:02

---
title: Django React Boilerplate - With Free Samples
published: true
description: Learn how to bundle Django and React and code a full-stack boilerplate using this modern stack - with free samples.
tags: react, django, webdev, appseed
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/da9ompqr6ri39bl408tm.jpg
canonical_url: https://blog.appseed.us/django-react-boilerplate/
---
Hello Coders!

This article explains how to bundle together **[Django and React](https://blog.appseed.us/django-react-boilerplate/)** and code a full-stack **boilerplate** that can be reused over multiple projects. For newcomers, **Django** is a leading Python Framework used for backend development, and **React** is the most popular JS library used to code user interfaces backed by Facebook. To make this article more useful, a shortlist with open-source full-stack starters is provided.

> *Thanks for reading!* - Content provided by **[App Generator](https://appseed.us/)**.

---

- Section #1: The **general view** of the project
- Section #2: **Django** - Short presentation
- Section #3: **What is React**
- Section #4: Set up **Django API Backend**
- Section #5: **Test the Django API** using POSTMAN
- Section #6: **Code React UI** to communicate with Django
- Section #7: **Compile the samples** (backend and frontend)

---

> Note: All article resources are available for download from Github. 

The React dashboard is configured to work with a simple Django API Server. For [support](https://appseed.us/support) feel free to drop any question you might have on [Discord](https://discord.gg/fZC6hup).

- [Django API Server](https://github.com/app-generator/api-server-django) - open-source project (MIT License)
- [React Berry Dashboard](https://github.com/app-generator/react-berry-dashboard) - compatible React Dashboard

---

## 1# - Project Overview

Web development has been evolved a lot in the last few years and we can code the same features using different combinations and patterns. For instance, if our goal is to build a simple one-page website we can use Wix, Gatsby, Next, Eleventy (11ty), or the old-school Php bundled with jQuery.  The possibilities are infinite and the final stack depends on many factors: the technologies we know, project budget, and the will to learn something new.  In this article, we will focus on a modern stack that uses Django as the backend technology and a simple UI powered by React.  

The product will use a "two-tier" architecture where the React Frontend communicates with the backend via a simple API powered by Django.

**How It Works**

- The Django API exposes a simple authentication interface
- React UI is started and loaded by the browser
- The UI initiate the login at startup and authenticate the user
- The server gets the user credentials and allows the login
- React gets back the server response
- The user can access the private pages of the React UI  

The complete this tutorial the workstation must have installed a few tools and libraries used to edit and compile this basic boilerplate. Let's start with the mandatory ones:

- **Node JS** - used by React UI
- **Python v3** - the language used by Django
- **GIT** - command-line versioning tool  
- **PIP** - the official package manager shipped by Python3
- **NPM** - a package manager for Javascript
- (optional) **Yarn** - a faster alternative to NPM
- (optional) **VsCode** or Atom - modern code editors

The ability to work using the system console might be a plus in this process.

---

## 2# - [What is Django](https://docs.appseed.us/content/what-is/django)

Django is a modern web framework that comes with the "batteries-included" concept which means it provides modules and libraries for many common features required in modern web development:

- Session-based authentication
- Abstract Database access via a powerful ORM
- Built-in security patterns
- Helpers: forms, models, and data validation

Django can be installed in many ways and the most recommended way is to use PIP, the official Python package manager. Here is the complete list with commands:

---

> **Step #1** - Create a virtual environment

```bash
$ # Create the environment
$ virtualenv env 
$
$ # Activate the virtual environment
$ source env/bin/activate
```

---

> **Step #2** - Install the latest Django version

```bash
$ pip install Django
```

---

> **Step #3** - Build a basic Django project

```bash
$ mkdir hellodjango 
$ cd hellodjango 
$
$ django-admin startproject config .
```

---

> **Step #4** - Start the project

```bash
$ python manage.py runserver 
```

If all goes well, we should see the default Django splash screen when accessing `http://localhost:8000`.

![Django - Default Starter Page.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/edlotaw3bkl75gnbg4j6.png)

---

## 3# - [What is React](https://docs.appseed.us/content/what-is/react)

React is an open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. React can be used as a base in the development of single-page or mobile applications.

Another important fact is the proven popularity: in 2021 the stats shows that React is used as the primary technology in frontend development superseding other frameworks like Vue, Angular or Svelte. For more information about this amazing library feel free to access:

- [React JS](https://reactjs.org/) - official website
- [React JS](https://reactjs.org/docs/getting-started.html) - documentation

By following the official React tutorial, we can scaffold a project skeleton with just a few commands typed in the terminal.

---

> **Step #1** - Install create-react-app (CRA) tool

```bash
$ npm install -g create-react-app
```

---

> **Step #2** - Create the React app skeleton

```bash
$ npx create-react-app reactapp
```

---

> **Step #3** - Install React Dependencies 

```bash
$ npm run start
// OR 
$ yarn start 
```

The above command should open automatically the browser window with the React default page.

![React App - The Default Page.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odwaork94c62sk3gcokj.png)

---

## 4# - Code the [Django API](https://github.com/app-generator/api-server-django) backend

Being such a mature framework with its first release in 2003, Django is known as a complete, `batteries-included` library. To serve successfully the React interface, our simple Django server will implement a simple authentication service using `JWT web tokens` that exposes a few basic methods:

- `/api/users/register`: create a new user
- `/api/users/login`: authenticate an existing user
- `/api/users/logout`: delete the associated JWT token
- `/api/users/edit` - edit the information associated with a registered user

To keep things simple as possible, the backend server will use the default SQLite persistence and [Django REST Framework](https://www.django-rest-framework.org/) (DRF) for the API nodes.  

Inside the previously created project, let's create a new Django application called "API": 

```bash
$ cd hellodjango
$ python manage.py startapp app
```

The `startapp` command should create a new directory `api` with this structure:

```bash
api/
    __init__.py
    admin.py
    apps.py
    migrations/
        __init__.py
    models.py
    tests.py
    views.py
```

Creating an API interface to manage transactions usually go this way :

- Creating the model
- Creating the serializer
- Write the views or the viewsets
- Register the viewsets by creating routes

Here is a simple User Model definition:

```python
class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(db_index=True, max_length=255)
    email = models.EmailField(db_index=True, unique=True)
    is_active = models.BooleanField(default=True)
    date = models.DateTimeField(auto_now_add=True)
```

---

> **Create the serializer** for the User model

A serializer allows us to convert complex Django complex data structures such as querysets or model instances in Python native objects that can be easily converted JSON/XML format, but a serializer also serializes JSON/XML to native Python.

```python
class UserSerializer(serializers.ModelSerializer):
    date = serializers.DateTimeField(read_only=True)

    class Meta:
        model = User
        fields = ["id", "username", "email", "date"]
        read_only_field = ["id"]
```

---

> **Code the viewsets** - The code will provided only for Login method (the full code is available at the end of the article)

The routes for the API interface should look like this:

- `/api/users/register`: create a new user
- `/api/users/login`: authenticate an existing user
- `/api/users/logout`: delete the associated JWT token
- `/api/users/edit` - edit the information of a registered user

The ViewSet class comes with built-in actions like `list`, `retrieve`, `create`, `update`, `destroy`.

```python
from api.authentication.serializers import LoginSerializer

class LoginViewSet(viewsets.GenericViewSet, mixins.CreateModelMixin):
    permission_classes = (AllowAny,)
    serializer_class = LoginSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)

        serializer.is_valid(raise_exception=True)

        return Response(serializer.validated_data, status=status.HTTP_200_OK)
```

---

> `Register the viewsets` - aka routes

```python
from rest_framework import routers
from api.user.viewsets import UserViewSet

router = routers.SimpleRouter(trailing_slash=False)
router.register(r"edit", UserViewSet, basename="user-edit")
router.register(r"register", RegisterViewSet, basename="register")
router.register(r"login", LoginViewSet, basename="login")
router.register(r"checkSession", ActiveSessionViewSet, basename="check-session")
router.register(r"logout", LogoutViewSet, basename="logout")

urlpatterns = [
    *router.urls,
]
```

---

> **Note for Beginners**

The above section aims to suggest the concept without providing the full implementation. Curious minds can analyze the whole project, published on Github. For questions, feel free to ask for support in [Discord](https://discord.gg/fZC6hup).  

- [Django REST API](https://github.com/app-generator/api-server-django) - source code published on Github

![Django API Server - Cover Image.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e2agyrm6al1k4xnykk43.png)

---

## 5# - Test Django API using POSTMAN

Once our API is up and running we can use POSTMAN, a popular free tool to test the backend code. We assume the Django API server is started on port 5000 and the registration method is fully coded and functional.
 
> Postman - Create a new collection and request with properties

- Request: POST over `http://localhost:5000/api/users/register`
- Header Content-type: `application-json`
- Body data: `user/password` and `email`

![Django API POSTMAN - Registration Header](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mngrufuhctnul7b7lo1k.png)

---

> The **Body Content** specifies the credentials for the new user.

![Django API POSTMAN - Registration Body](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g2rjccwf3wls6r72xcix.png)

---

> The Registration API Response

![Django API POSTMAN - Registration Response.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8qyfu1d4f0wg8d8es9u2.png)
 
At this point, the user is created in the database and we can authenticate and move on with our full-stack project.

---

## 6# - Code React UI

The React part of this tutorial is coded on top of an open-source project cloned from Github, **React Berry Dashboard**, a Material-UI template provided by `CodedThemes`. The initial project, basically a lifeless React template, will be improved with a few simple features:

- Usable authentication flow compatible with the Django API
- Actions: Login, Logout, and Register
- Guest users are redirected to the login page
- Private pages are visible only to the authenticated users.

---

> React Berry - Clone the template sources from the [public repository](https://github.com/codedthemes/berry-free-react-admin-template)

```bash
$ git clone https://github.com/codedthemes/berry-free-react-admin-template.git
$ cd berry-free-react-admin-template
```

---

> Install Dependencies - via NPM or Yarn

```bash
$ npm i
// OR
$ yarn 
```

---

> **React Datta Able** - Start project in development mode

```bash
$ npm run start
// OR
$ npm start
```

![React Template - Berry Dashboard.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/evref1zmyrjo3uwpcg13.png)

---

To code the new features the project dependencies should be updated with a few useful libraries:

- [Formik](https://formik.org/) - used to enhance and manage the registration forms
- [Axios](https://axios-http.com/) - used to manage the communication with Django API

Once the new dependencies are properly installed, we can proceed further with the code.

---

> Project configuration - URL of the backend API

The application will use a common set of variables imported in different places like login, logout, etc. To make our life easier, it might be a good idea to define all variables in a single file: `src/config.js`.

```javascript
const config = {
    basename: '',
    defaultPath: '/dashboard/default',
    ... 
    API_SERVER: 'http://localhost:5000/api/' <-- The magic line
};

export default config;
```

The most important value is saved by the `API_SERVER` variable, basically the address of our Flask API. When the project goes into production, this address should be updated accordingly with the address of the public API.

Because we want to redirect the guest users to authenticate a Guard Component is provided to check the authentication context for each client request.

```javascript
import React from 'react';
import { Redirect } from 'react-router-dom';
import { useSelector } from 'react-redux';
import { BASE_URL } from '../../config/constant';

const GuestGuard = ({ children }) => {
    const account = useSelector((state) => state.account);
    const { isLoggedIn } = account;

    if (isLoggedIn) {
        return <Redirect to={BASE_URL} />;
    }

    return <React.Fragment>{children}</React.Fragment>;
};

export default GuestGuard;
```

The next step is to declare a global `store` where the user's state is saved. The `redux-store` provides this information in a simple way using a few variables and objects:

```javascript
export const initialState = {
    token: '',
    isLoggedIn: false,
    isInitialized: false,
    user: null
};

const accountReducer = (state = initialState, action) => {
    switch (action.type) {
        case ACCOUNT_INITIALIZE: {
            const { isLoggedIn, user, token } = action.payload;
            return {
                ...state,
                isLoggedIn,
                isInitialized: true,
                token,
                user
            };
        }
        case LOGIN: {
            const { user } = action.payload;
            return {
                ...state,
                isLoggedIn: true,
                user
            };
        }
        case LOGOUT: {
            return {
                ...state,
                isLoggedIn: false,
                token: '',
                user: null
            };
        }
        default: {
            return { ...state };
        }
    }
};
```
 
The variables associated with the current user should be updated based on the actions performed in the session:

- Guest access: the session user is Null and `isLoggedIn` state is false
- Login: the user is successfully authenticated by the backend and. Of course, `isLoggedIn` state becomes true
- Logout: all session data is deleted and `isLoggedIn` becomes false again

At this point, the React UI can be used to register and authenticate users.

---

## 7# - Compile the Free Samples

All the above code is already provided on Github in two separate projects:

- [Django API Server](https://github.com/app-generator/api-server-django) - open-source project (MIT License)
- [React Berry Dashboard](https://github.com/app-generator/react-berry-dashboard) - compatible React Dashboard

---

> **Step #1** - Compile the **Django API Server**

```bash
$ git clone https://github.com/app-generator/api-server-django.git
$ cd api-server-django
$
$ virtualenv -p python3 venv
$ source venv/bin/activate
$
$ pip install -r requirements.txt
$
$ python manage.py migrate
$ python manage.py runserver 5000
```

At this point, we can use POSTMAN to test the authentication interface as described in the product documentation: [Unified API Interface](https://docs.appseed.us/boilerplate-code/api-unified-definition).

---

> **Step #2** - Compile the [React Template](https://github.com/app-generator/react-berry-dashboard)

```bash
$ git clone https://github.com/app-generator/react-berry-dashboard.git
$ cd react-berry-dashboard
$
$ npm i
$
$ npm run start 
```

At this point, with the front end and backend up & running we can start using this open-source React UI powered by a simple Django API.

![Django React Boilerplate - Login Page.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owhsbl0jh5bm9rm71gay.png)

---

> **Thanks for reading!**

During this long post we've tried to cover the basic concepts of a full-stack **boilerplate built with React and Django**. For more resources, please access:

- More [React Apps](https://appseed.us/apps/react) - index provided by [AppSeed](https://appseed.us/)
- [Open-source Dashboards](https://appseed.us/admin-dashboards/open-source) - crafted in Flask and Django
- Free [React Dashboards](https://dev.to/sm0ke/react-dashboards-open-source-apps-1c7j) - a curated list published here on Dev.to