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

This function is used manually register a root component with ReactPy.

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")
Only use this within AppConfig.ready()

You should always call register_component within a Django AppConfig.ready() method. This ensures you will retain multiprocessing compatibility, such as with ASGI web server workers.

Do I need to use this?

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.

This is typically only needed when you have a dedicated Django application as a rendering server that doesn't have templates, such as when modifying the template tag host argument. On this dedicated rendering server, you would need to manually register your components.


Last update: September 7, 2023
Authors: Mark Bakhit