Join Login Create a Request

Django and React

Django and React

Learn how to structure your Django and react js project. If you have problems integrating Django and react gatsby js then you've come to the right place. This simple yet comprehensive tutorial teaches you to build web apps with Django and react js from scratch.

Django Graphene and React

Django is a python web framework that follows the MVT architecture. Since its inception, Django's popularity has been rising ever since. Many big companies are using Django to power their backend including NASA (Space Organisation). Developers love the Django framework for many reasons including the fact that it's a python framework. We'll be using Django and react js in this tutorial to create a simple blog web application. What you will learn:

  • How to build a Django GraphQL API
  • How to configure your Django project to work with react js.

GraphQL and React Gatsbyjs

React js is a frontend library built by Facebook to simplify frontend development. React is used by big companies such as Twitter, Instagram, Github, bitbucket and amazon. Gatsby is a react based framework. It is packed with GraphQL features that are not in react itself and we shall be using it to speed our development. What you will learn:

  • How to define your GraphQL API in react Gatsby js.
  • How to make react Gatsby communicate with Django API.

Let's get started and develop our website.

Create a virtual environment and install Django

A virtual environment helps us to separate our system files from the mess we might cause when developing our Django project.

mkdir blogging && cd blogging
pipenv install django==3.0.3

Note: Sometimes you will have an UnsupportedPythonVersion error - Django requires Python>=2.7.17. To solve this problem. Open your Pipfile and change the python version from 2.7 to 3.7 or 3.6 depending on which one is globally installed on your computer. and after changing the python version, run the following command:

pipenv --rm
pipenv install
pipenv shell

Now we have installed our Django. Let's create the actual project.

Note: Don't forget to activate your virtual environment by running the pipenv shell command.

Create Django Project using Pipenv

After installing Django we can go ahead and create the django-react project.

django-admin startproject django_react
cd django_react

Before we continue let's install all the necessary python requirements we'll need to integrate Django and react.

pipenv install graphene-django
pipenv install django-graphql-jwt
pipenv install django-cors-headers
pipenv install autopep8 --dev

Create Django application

Everything is set to go now, let's create our first Django app and define our blog models

python startapp blog

Django blog models

Create your model classes in the blog file.

from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.text import slugify
from django.urls import reverse
# Create your models here.
class Post(models.Model):
     title = models.CharField(_("Post title"), max_length=100)
     summary = models.CharField(_("Summary"), max_length=255)
     keywords = models.CharField(_("SEO Keywords"), max_length=255)
     body = models.TextField(_("Post body"))
     published = models.DateTimeField(auto_now=True)
     slug = models.SlugField(_("Slug"), max_length=255, default='', blank=True, unique=True)

    class Meta:
        verbose_name = _("Post")
        verbose_name_plural = _("Posts")

    def __str__(self):

    def get_absolute_url(self):
        return reverse("post_detail", kwargs={"slug": self.slug})

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super().save(*args, **kwargs)

Now that our main blog application is created and we've also defined our models. Let's register the blog application and define our Graphene settings in the file


     #Third part applications

     #Custom applications

     #To be created file inside the django_react project folder
    'SCHEMA': 'django_react.schema.schema',
    # JWT Authentication

After adding your application, register your models inside the django_react/blog/

from django.contrib import admin
from blog.models import Post

Your Post model is registered and you can view it from the Django dashboard. Now add a Django superuser that can access and create the Post in the dashboard.

python createsuperuser

Navigate to your Django admin, if you're running the default configurations it's on

You can now create your sample posts.

GraphQL Schema files

Let's create the necessary GraphQL files, We'll define our GraphQL schema in the app level and register it to the project level file.

touch django_react/
touch blog/

Before we start defining the GraphQL schema, let's migrate our database.

python makemigrations
python migrate

With our database intact, Django graphene is ready to take define our queries and mutations. There are two things needed to make queries in:

  • schema with defined object types.
  • The view that takes input and returns the output.

Objects are presented as graph structures than a hierarchical structure. Graphene needs to understand all type of object which is expected in the graph. For more information visit the graphene official website.

import graphene
from graphene_django.types import DjangoObjectType
from blog.models import Post

class PostType(DjangoObjectType):
    class Meta:
        model = Post

class Query(object):
    all_posts = graphene.List(PostType)
    get_post = graphene.Field(PostType, slug=graphene.String())

    def resolve_all_posts(self, info, **kwargs):
        return Post.objects.all()

    def resolve_get_post(self, info, **kwargs):
        slug = kwargs.get('slug')
        if slug is not None:
            return Post.objects.get(slug=slug)
        return None

The query class is a mixin inheriting from the object. Let's now create a project level query class that will combine all the application level, query classes.

import graphene
import blog.schema

class Query(blog.schema.Query, graphene.ObjectType):

schema = graphene.Schema(query=Query)

Everything in our Graphene schema is set to function well.

Let's test our Graphene API on a URL endpoint

Since we want to test our queries on the GraphQL playground, we have to configure the urls. GraphQL allows you to have only one single URL from which to access your API and all the requests to that URL is handled in Graphene GraphQLView.

from django.contrib import admin
from django.urls import path
from graphene_django.views import GraphQLView
from django.views.decorators.csrf import csrf_exempt

urlpatterns = [
    path("", csrf_exempt(GraphQLView.as_view(graphiql=True))),

If you run the server and open the browser you should see the Graphene Playground open.

Now that we've installed Django and created our Graphene API endpoint, let's create the React Gatsby frontend side.

Install React Gatsby Js

Gatsby is an open-source framework based on React js. It uses the latest technologies such as GraphQL and Webpack to speed up the site loading time. Every Gatsby website is a Progressive web app (PWA). If you're new to React but feel comfortable learning a few concepts along the way, I highly recommend you try Gatsby js.

Benefits of Gatsbyjs

  • Plugins - Just like WordPress plugins, Gatsby plugins extend the functionality of Gatsby.
  • Ready to use starters - Gatsby community of developers have build a wide range of web apps that you can choose a starter or theme from.
  • Site speed - Gatsby uses pre-build web pages thus improving server response time.

Open your terminal and create the Gatsby project inside the django_react root folder.

npm install -g gatsby-cli
gatsby new frontend
cd frontend
gatsby develop

Now make sure you're inside the newly created Gatsby project. Let's install the necessary Gatsby plugins needed to pull our Django Graphene API.

npm install --save gatsby-source-graphql

Source GraphQL Plugin Configurations.

plugins: [
  // Add the configurations
    resolve: "gatsby-source-graphql",
    options: {
      // Arbitrary name for the remote schema Query type
      typeName: "django",
      // Field under which the remote schema will be accessible. You'll use this in your Gatsby query
      fieldName: "DJANGO",
      // Url or Django Graphene Endpoint
      url: "",

Restart your frontend server and go to the graphQL server, in my case it's running on http://localhost:8001/\_\_\_graphql.


import React from "react"
import { graphql, Link } from "gatsby"
import Layout from "../components/layout"

export default ({ data }) => (
    {, i) => (
      <Link key={i} to={blog.slug}>

export const query = graphql`
  query {
    DJANGO {
      allPosts {

Open your frontend server on the browser, you should the post you added in your Django admin.


Recent Posts

Ways to differentiate your services from others as a freelancer
Ways to differentiate your services from others as a freelancer
Ways to differentiate your services from others as a freelan..
Read More
Starting a referral or affiliate program as a freelancer.
Starting a referral or affiliate program as a freelancer.
How to start a referral program as a freelancer. These are s..
Read More
How to build referrals as a freelancer
How to build referrals as a freelancer
Ways to build your referrals as a freelancer. Expand your lo..
Read More
Handling customer Service as a Freelancer
Handling customer Service as a Freelancer
How to handle customer services as a freelancer. Learn the b..
Read More