Analytics Vidhya
Published in

Analytics Vidhya

How to Use React in Django — the Hard Way

In the previous article, we’ve went through a basic tutorial on how to use React.js in Django. It mainly focuses on front-end and has little connection to Django view. I know it’s not enough. Here comes the hard way.

In this article, we are going to dig into a common feature in web application — form submission. The Django conventional way is to build form in backend and render it in a main template. Add JS code if you need some interactions between user and GUI. The downside is that if form GUI is complex, front-end codes can be very hard to maintain. Because very likely form needs be rendered manually. Plus, we may also need to create and import an exclusive JS file for form interaction. Keep in mind that sometimes a page could have more than one form. What a headache! We need something that can put HTML and JS together in a single file. Then React comes to rescue. Thanks to its component-based design, we can maintain both template and interaction codes in a JS file per each form. It makes main template clean. You will know what I mean as you read conclusion at the end of this article.

Following steps in this article, we will architect a complete workflow that relies on both React in the front-end and Django in the back-end. As what I mentioned in the previous article, still I am going to use Django as a web framework. This article might require you have basic knowledge on React component, JSX syntax, Django form and Bootstrap. At the end of tutorial, we will create a form widget and be able to submit a POST request.


  1. Python 3.7
  2. Django 2.2.x
  3. React 17
  4. AdminLTE 3.0.5 (see my previous tutorial here for this theming library)

Step 0. Scratch project and goal

I’ve upload scratch project in release 1.0.0. Click the link below and download “ScratchProject”.zip file.

Let’s start project and see what we’ve got. In page, our goal is to add a form widget in white box.

Target page

The schema of scratch project is as below. We will mainly work in polls app and index.html template. React and JSX libraries are maintained in static/plugins/react/ folder.

Schema of scratch project

Step 1 Add CSRF script

One of Django’s security mechanism is to provide protection against cross site request forgeries through CSRF middleware. It is required whenever a POST request is made. Since we use React to render form in template, the convention way of using {% csrf_token %} does not work anymore. Instead, we need to manually do it. The goal of this script is to produce a CSRF token <input> element that needs be added into form down the road. Code snippet is as below.

Let’s import this script into index.html file in extra_js block.

{% block extra_js %}
<script src="{% static 'dist/js/csrftoken.js' %}" type="text/babel"></script>
{% endblock %}

Step 2 Add form division and React form script

In index.html file, add a division and assign id “registration_form”. We will render React form in this division. Here is the code snippet.

<div class="col-lg-12">
<div class="card">
<div class="card-body">
<h5 class="card-title">Registration</h5>
<p class="card-text">
Fill in neccessary info and submit.
<div id="registration_form"></div>

Create a static folder in polls app. In static folder we just created, create polls folder. Then create registration_form.js in polls folder we just created. This can be confusing. A pic means thousands of words. You would expect the schema as below.

registration_form.js file path

In registration_form.js file, we will build React form as a component. I will paste code snippet in minutes. Something worth mentioning are

  1. This form widget has two steps. GUI is controlled by “Go Back” and “Next’ buttons. The visibility of <input> elements is controlled by d-none class.
  2. CSRF token input is declared within <form> tag through <CSRFToken/>.
  3. Submit behavior is controlled by handleSubmit function.

Code snippet is as below.

Finally, import this script into index.html in extra_js block. We would expect following result.

{% block extra_js %}
<script src="{% static 'dist/js/csrftoken.js' %}" type="text/babel"></script>
<script src="{% static 'polls/registration_form.js' %}" type="text/babel"></script>
{% endblock %}

Start project and check result. Form widget is live! At this point, submit button will raise exception. Let’s fix that in next step.

Screenshot of target page

Step 3 Add Django form

The usage of Django form is to validate form inputs. We call it back-end validation. In polls app, create a file. And add following codes. Please be aware that we use form.EmailField to validate the pattern of email value.

Step 4 Modify view function

In polls/ file, our goal is to do the followings.

  1. Add a POST request case
  2. Validate inputs by using RegistrationForm that we built in previous step
  3. Produce message

We would expect codes as below. Notice that we will print inputs in console.

Now we need to render message in template. In polls/templates/polls/index.html file, add following codes before main content division. This piece of codes covers following cases.

  1. If submission is successful, it displays success message in a green box.
  2. If form input is invalid, it displays error message in a red box.
<div class="content">
<div class="container-fluid">
{% if messages %}
{% for message in messages %}
{% if message.tags == 'error' %}
<div class="alert alert-danger" role="alert">
{% else %}
<div class="alert alert-{{ message.tags }}" role="alert">
{% endif %}
{{ message }}
{% endfor %}
{% endif %}

{% if form.errors %}
<div class="alert alert-danger" role="alert">
{{ form.non_field_errors }}
{% for field in form %}
{% for error in field.errors %}
{{ error }}
{% endfor %}
{% endfor %}
{% endif %}

The below is complete polls/templates/polls/index.html file.

At this point, we have completed everything. Let’s check out final product! Fill in data and submit. We should expect similar inputs printed in console as below.

console print

Front-end should have success message as below.

success message in target page

Error messages are as below.

error message in target page

Final schema is as below.

Final schema


In this tutorial, we have taken full usage of Django and React. React is responsible for rendering a complex GUI. index.html file is main template. Rather than dumping form template and js codes into main template, we build a registration_form.js to encapsulates form component. All we need to do is to import it and tell React in which division we would like to render form into. In addition, this React form component can be reused in other pages as well. Django is responsible for handling HTTP request and provide necessary validation. The whole piece is running on Django web framework that provides security mechanism through CSRF token. Now enjoy fancy GUI without a worry on security! Hope this architect can give you a hint on your current project.

If you are interested, I’ve uploaded this project on my GitHub. Project name is DjangoAndReactComponentForm.

Thanks for reading. I would like to know your thoughts on React + Django combination. Please leave your comments below. Stay tuned.

I’ve made video on it. Please check out the below.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store