Skip to content

Utilities

Overview

Utility functions provide various miscellaneous functionality. These are typically not used, but are available for advanced use cases.


Django Query Postprocessor

This is the default postprocessor for the use_query hook.

This postprocessor is designed to avoid Django's SynchronousOnlyException by recursively fetching all fields within a Model or QuerySet to prevent lazy execution.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from example.models import TodoItem
from reactpy import component
from reactpy_django.hooks import use_query
from reactpy_django.types import QueryOptions
from reactpy_django.utils import django_query_postprocessor


def get_items():
    return TodoItem.objects.all()


@component
def todo_list():
    # These `QueryOptions` are functionally equivalent to ReactPy-Django's default values
    item_query = use_query(
        QueryOptions(
            postprocessor=django_query_postprocessor,
            postprocessor_kwargs={"many_to_many": True, "many_to_one": True},
        ),
        get_items,
    )

    return item_query.data
1
2
3
4
5
from django.db.models import CharField, Model


class TodoItem(Model):
    text: CharField = CharField(max_length=255)
See Interface

Parameters

Name Type Description Default
data QuerySet | Model The Model or QuerySet to recursively fetch fields from. N/A
many_to_many bool Whether or not to recursively fetch ManyToManyField relationships. True
many_to_one bool Whether or not to recursively fetch ForeignKey relationships. True

Returns

Type Description
QuerySet | Model The Model or QuerySet with all fields fetched.

Register Component

The register_component function is used manually register a root component with ReactPy.

You should always call register_component within a Django AppConfig.ready() method to retain compatibility with ASGI webserver workers.

1
2
3
4
5
6
7
8
from django.apps import AppConfig
from reactpy_django.utils import register_component


class ExampleConfig(AppConfig):
    def ready(self):
        # Add components to the ReactPy component registry when Django is ready
        register_component("example_project.my_app.components.hello_world")
Do I need to register my components?

You typically will not need to use this function.

For security reasons, ReactPy does not allow non-registered components to be root components. However, all components contained within Django templates are automatically considered root components.

You only need to use this function if your host application does not contain any HTML templates that reference your components.

A common scenario where this is needed is when you are modifying the template tag host = ... argument in order to configure a dedicated Django application as a rendering server for ReactPy. On this dedicated rendering server, you would need to manually register your components.


Last update: August 26, 2023
Authors: Mark Bakhit