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 with teach 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 it's inception, django popularity has being rising ever since. Many big companies are using django to power their backend including NASA (Space Organisation). Developers love 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 a frontend library build 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
Note: Sometimes you will 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 which one is globally installed on your computer. and after changing the python version, run the following command:
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.
Before we continue let's install all the necessary python requirements we'll need to integrate django and react.
Create Django application
Everything is set to go now, let's create our first django app and define our blog models
Django blog models
Create your model classes in the blog app.models.py file.
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 django_react.settings.py file
After adding your application,register your models inside the django_react/blog/admin.py
Your Post model is registered and you can view from the django dashboard. Now add a django super user that can access and create the Post in the dashboard.
Navigate to your django admin,if you're running the default configurations it's on http://127.0.0.1:8000/admin/.
You can now create your sample posts.
GraphQL Schema files
Let's create the necessary GraphQL schema.py files, We'll define our GraphQL schema in the app level schama.py and register it to the project level schema.py file.
Before we start defining the graphql schema, let's migrate our database
With our database intact, django graphene is ready to take define our queries and mutations. There two things needed to make queries in:
- schema with defined object types.
- View that takes input and returns output.
Objects are presented as graph structure 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.
The query calss is a mixin inheriting from object. Lets now create a project level query class that will combine all the application level query classes.
Everything in our Graphene schema is set to function well.
Lets 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.
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 extends 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.
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.
Source GraphQL Plugin Configurations.
Restart your frontend server and go to graphQL server, in my case it's running on http://localhost:8001/___graphql.
Open your frontend server on the browser, you should the post you added in your django admin.
These days I'm seeing new tutorials on using webpack with Django popping up. Like:
Let's see what I mean.
webpack and Django without code splitting
With this configuration, given an entry point at
./index.js, webpack produces the corresponding bundle in
In the Django template you'll load the bundle as:
Again, this approach works fine for a single bundle. But, if the resulting files are too big we need to apply code splitting.
webpack offers a powerful optimization technique called splitChunks. In
webpack.config.js you can add an
It's this little bugger here that hurts Django, but it's great for optimizing the bundle:
React And Django Web App
There's even a more powerful technique for splitting each dependency with splitChunks:
With this setup you get a static folder like the following (don't mind development dependencies like prop-types, I'm on local):
Consider also a variation with
chunkFilename, where each chunk gets a hash:
Are you sure you want to see the result? Here you go:
How do you load all these chunks in Django templates, in the exact order, and with the exact chunk name? This is a question that most tutorials can't answer.
Why do we need this madness?
Option 2. Django REST as a standalone API + React/Vue/Whatever as a standalone SPA.
Option 3. Mix and match: mini React/Vue/Whatever apps inside Django templates (not so maintainable in the long run?).
How about django-webpack-loader?
There is this package django-webpack-loader that was supposed to make Django and webpack work seamlessly, until it didn't anymore when webpack 4 introduced splitChunks.
Maintaining open source projects is hard. This issue about splitChunks in django-webpack-loader is still open, and so this one.
Django React Csrf
I touched the topic in my talk Decoupling Django with Django REST suggesting a Django package like Rails webpacker.
A solution with Nginx
There is a solution for integrating Django and a single-page application together. If you control your own Django deployments with Nginx, or with an equivalent reverse proxy, serving say React inside a Django project becomes extremely less complex:
- in Django, you can use a
TemplateViewto serve your SPA index.html
- in Nginx, you point a
/staticlocation to the JS build folder
Here's an example:
Thanks for reading!