Skip to content

Autodiscovery

Every component that you want to use in the template with the {% component %} tag needs to be registered with the ComponentRegistry. Normally, we use the @register decorator for that:

from django_components import Component, register

@register("calendar")
class Calendar(Component):
    ...

But for the component to be registered, the code needs to be executed - the file needs to be imported as a module.

One way to do that is by importing all your components in apps.py:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = "my_app"

    def ready(self) -> None:
        from components.card.card import Card
        from components.list.list import List
        from components.menu.menu import Menu
        from components.button.button import Button
        ...

However, there's a simpler way!

By default, the Python files in the COMPONENTS.dirs directories (and app-level [app]/components/) are auto-imported in order to auto-register the components.

Autodiscovery occurs when Django is loaded, during the AppConfig.ready hook of the apps.py file.

If you are using autodiscovery, keep a few points in mind:

  • Avoid defining any logic on the module-level inside the components dir, that you would not want to run anyway.
  • Components inside the auto-imported files still need to be registered with @registerp
  • Auto-imported component files must be valid Python modules, they must use suffix .py, and module name should follow PEP-8.

Autodiscovery can be disabled in the settings.

Manually trigger autodiscovery¤

Autodiscovery can be also triggered manually, using the autodiscover function. This is useful if you want to run autodiscovery at a custom point of the lifecycle:

from django_components import autodiscover

autodiscover()

To get the same list of modules that autodiscover() would return, but without importing them, use get_component_files():

from django_components import get_component_files

modules = get_component_files(".py")