
* refactor: cleanup docs, add docs on Render API, allow get_context_data return None * refactor: fix linter and tests
3.4 KiB
django-components automatically register all components found in the
COMPONENTS.dirs
and
COMPONENTS.app_dirs
directories by loading all Python files in these directories.
Manually register components
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 - and for that, the file needs to be imported as a module.
This is the "discovery" part of the process.
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!
Autodiscovery
By default, the Python files found in the
COMPONENTS.dirs
and
COMPONENTS.app_dirs
are auto-imported in order to 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 directories, that you would not want to run anyway.
- Components inside the auto-imported files still need to be registered with
@register
- Auto-imported component files must be valid Python modules, they must use suffix
.py
, and module name should follow PEP-8. - Subdirectories and files starting with an underscore
_
(except__init__.py
) are ignored.
Autodiscovery can be disabled in the settings with autodiscover=False
.
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")