Django 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 with teach you to build web apps with django and react js from scratch.

  1. Django React
  2. React And Django Web App
  3. Django React Csrf

Django Graphene and React

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. On the other hand, React is detailed as ' A JavaScript library for building user interfaces '. Lots of people use React as the V in MVC. Popular React scaffolding tools like Create React Appdon't offer you a clear way to integrate with Django, leaving you to figure it out yourself. Even worse, there isn't just one way to set up a Django/React project. There are dozens of possible methods, each with different pros and cons. But equally, in Django and React we have two frameworks that should be complementary to each other — one is a backend framework, the other is for the frontend. As Simon Willison pointed out, there are relatively simple ways to have a React-built user interface that gets data from a Django backend as needed. In part 1 of this series we will setup a Django app and create a REST API with the Django Rest Framework. We will use Postman for API testing.Sponsor: DevMou. Django React Hooks example Overview. We will build a full-stack Django & React Hooks Tutorial CRUD Application in that: Each Tutorial has id, title, description, published status. We can create, retrieve, update, delete Tutorials. We can also find Tutorials by title. The images below shows screenshots of our System. – Create an item.

Django 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.

Django react boilerplate

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.

Most approaches to using webpack with Django work until the JavaScript app is tiny. What happens when the bundle grows?

These days I'm seeing new tutorials on using webpack with Django popping up. Like:

I don't mean to bash on them, but, the problem with the approaches showed there is that they work for smaller JavaScript applications. I mean tiny applications.

Imagine instead a medium-size React/Vue application with some state management solution like Redux or Vuex. Imagine also a bunch of JavaScript libraries needed by this application, and imagine a JavaScript bundle resulting from this app that goes over 200KB.

Let's see what I mean.

webpack and Django without code splitting

A typical webpack configuration for Django configured to produce a JavaScript bundle in the static folder looks like the following:

With this configuration, given an entry point at ./index.js, webpack produces the corresponding bundle in ../static/custom_webpack_conf_2/js.

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 splitChunks

webpack offers a powerful optimization technique called splitChunks. In webpack.config.js you can add an optimization property:

It's this little bugger here that hurts Django, but it's great for optimizing the bundle:

React And Django Web App

Why it hurts Django? If you bundle up your JavaScript with splitChunks, webpack generates something like this in static:

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?

Django React

Why don't we 'just' decouple Django with DRF, and make the frontend a single page application? Good question! As I already said in Django REST with React there are mainly three ways to use Django and a JavaScript frontend together:

Option 1. React/Vue/Whatever in its own frontend Django app: load a single HTML template and let JavaScript manage the frontend.

Django ReactDjango react authentication

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?).

Option 2 seems more convenient over option 1, but keep in mind that the moment you decouple the backend from the frontend, you need to think about authentication. Not authentication based on sessions (unless JavaScript is in the same domain as Django), but tokens, specifically JWT, which have their own problems.

With option 1 instead, since the JavaScript bundle continues to live inside a Django template you can use Django's built-in authentication, which is totally fine for most projects.

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 TemplateView to serve your SPA index.html
  • in Nginx, you point a /static location to the JS build folder

Here's an example:

Thanks for reading!