Skip to content

Add ReactPy to a Django Project

Overview

If you want to add some interactivity to your existing Django project, you don't have to rewrite it in ReactPy. Use ReactPy-Django to add ReactPy to your existing stack, and render interactive components anywhere.

Note

These docs assumes you have already created a Django project, which involves creating and installing at least one Django app.

If do not have a Django project, check out this 9 minute YouTube tutorial created by IDG TECHtalk.


Step 1: Install from PyPI

Run the following command to install reactpy-django in your Python environment.

pip install reactpy-django

Step 2: Configure settings.py

Add "reactpy_django" to INSTALLED_APPS in your settings.py file.

1
2
3
4
INSTALLED_APPS = [
    ...,
    "reactpy_django",
]
Enable ASGI and Django Channels (Required)

ReactPy-Django requires Django ASGI and Django Channels WebSockets.

If you have not enabled ASGI on your Django project yet, here is a summary of the django and channels installation docs:

  1. Install channels[daphne]
  2. Add "daphne" to INSTALLED_APPS.

    INSTALLED_APPS = [
        "daphne",
        ...,
    ]
    
  3. Set your ASGI_APPLICATION variable.

    ASGI_APPLICATION = "example_project.asgi.application"
    
Configure ReactPy settings (Optional)

ReactPy's has additional configuration available to fit a variety of use cases.

See the ReactPy settings documentation to learn more.

Step 3: Configure urls.py

Add ReactPy HTTP paths to your urlpatterns in your urls.py file.

1
2
3
4
5
6
from django.urls import include, path

urlpatterns = [
    ...,
    path("reactpy/", include("reactpy_django.http.urls")),
]

Step 4: Configure asgi.py

Register ReactPy's WebSocket using REACTPY_WEBSOCKET_ROUTE in your asgi.py file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import os

from django.core.asgi import get_asgi_application

# Ensure DJANGO_SETTINGS_MODULE is set properly based on your project name!
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example_project.settings")

# Fetch ASGI application before importing dependencies that require ORM models.
django_asgi_app = get_asgi_application()


from channels.routing import ProtocolTypeRouter, URLRouter  # noqa: E402
from reactpy_django import REACTPY_WEBSOCKET_ROUTE  # noqa: E402

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": URLRouter([REACTPY_WEBSOCKET_ROUTE]),
    }
)
Add AuthMiddlewareStack (Optional)

There are many situations where you need to access the Django User or Session objects within ReactPy components. For example, if you want to:

  1. Access the User that is currently logged in
  2. Access Django's Session object
  3. Login or logout the current User

In these situations will need to ensure you are using AuthMiddlewareStack.

from channels.auth import AuthMiddlewareStack  # noqa: E402

application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AuthMiddlewareStack(URLRouter([REACTPY_WEBSOCKET_ROUTE])),
    }
)
Where is my asgi.py?

If you do not have an asgi.py, follow the channels installation guide.

Step 5: Run database migrations

Run Django's migrate command to initialize ReactPy-Django's database table.

python manage.py migrate

Step 6: Check your configuration

Run Django's check command to verify if ReactPy was set up correctly.

python manage.py check

Step 7: Create your first component

The next step will show you how to create your first ReactPy component.

Prefer a quick summary? Read the At a Glance section below.

At a Glance

my_app/components.py

You will need a file to define your ReactPy components. We recommend creating a components.py file within your chosen Django app to start out. Within this file, we will create a simple hello_world component.

1
2
3
4
5
from reactpy import component, html

@component
def hello_world(recipient: str):
    return html.h1(f"Hello {recipient}!")

my_app/templates/my-template.html

In your Django app's HTML template, you can now embed your ReactPy component using the component template tag. Within this tag, you will need to type in the dotted path to the component.

Additionally, you can pass in args and kwargs into your component function. After reading the code below, pay attention to how the function definition for hello_world (from the previous example) accepts a recipient argument.

1
2
3
4
5
6
7
{% load reactpy %}
<!DOCTYPE html>
<html>
  <body>
    {% component "example_project.my_app.components.hello_world" recipient="World" %}
  </body>
</html>

Last update: January 19, 2024
Authors: Mark Bakhit