Skip to content

Settings¤

You can configure django_components with a global COMPONENTS variable in your Django settings file, e.g. settings.py. By default you don't need it set, there are resonable defaults.

To configure the settings you can instantiate ComponentsSettings for validation and type hints. Or, for backwards compatibility, you can also use plain dictionary:

# settings.py
from django_components import ComponentsSettings

COMPONENTS = ComponentsSettings(
    autodiscover=True,
    ...
)

# or

COMPONENTS = {
    "autodiscover": True,
    ...
}

Settings defaults¤

Here's overview of all available settings and their defaults:

defaults = ComponentsSettings(
    autodiscover=True,
    context_behavior=ContextBehavior.DJANGO.value,  # "django" | "isolated"
    # Root-level "components" dirs, e.g. `/path/to/proj/components/`
    dirs=[Path(settings.BASE_DIR) / "components"],
    # App-level "components" dirs, e.g. `[app]/components/`
    app_dirs=["components"],
    dynamic_component_name="dynamic",
    libraries=[],  # E.g. ["mysite.components.forms", ...]
    multiline_tags=True,
    reload_on_file_change=False,
    static_files_allowed=[
        ".css",
        ".js", ".jsx", ".ts", ".tsx",
        # Images
        ".apng", ".png", ".avif", ".gif", ".jpg",
        ".jpeg", ".jfif", ".pjpeg", ".pjp", ".svg",
        ".webp", ".bmp", ".ico", ".cur", ".tif", ".tiff",
        # Fonts
        ".eot", ".ttf", ".woff", ".otf", ".svg",
    ],
    static_files_forbidden=[
        # See https://marketplace.visualstudio.com/items?itemName=junstyle.vscode-django-support
        ".html", ".django", ".dj", ".tpl",
        # Python files
        ".py", ".pyc",
    ],
    tag_formatter="django_components.component_formatter",
    template_cache_size=128,
)

app_dirs ¤

app_dirs: Optional[Sequence[str]] = None

See source code

Specify the app-level directories that contain your components.

Defaults to ["components"]. That is, for each Django app, we search <app>/components/ for components.

The paths must be relative to app, e.g.:

COMPONENTS = ComponentsSettings(
    app_dirs=["my_comps"],
)

To search for <app>/my_comps/.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

Set to empty list to disable app-level components:

COMPONENTS = ComponentsSettings(
    app_dirs=[],
)

autodiscover ¤

autodiscover: Optional[bool] = None

See source code

Toggle whether to run autodiscovery at the Django server startup.

Defaults to True

COMPONENTS = ComponentsSettings(
    autodiscover=False,
)

context_behavior ¤

context_behavior: Optional[ContextBehaviorType] = None

See source code

Configure whether, inside a component template, you can use variables from the outside ("django") or not ("isolated"). This also affects what variables are available inside the {% fill %} tags.

Also see Component context and scope.

Defaults to "django".

COMPONENTS = ComponentsSettings(
    context_behavior="isolated",
)

NOTE: context_behavior and slot_context_behavior options were merged in v0.70.

If you are migrating from BEFORE v0.67, set context_behavior to "django". From v0.67 to v0.78 (incl) the default value was "isolated".

For v0.79 and later, the default is again "django". See the rationale for change here.

dirs ¤

See source code

Specify the directories that contain your components.

Defaults to [Path(settings.BASE_DIR) / "components"]. That is, the root components/ app.

Directories must be full paths, same as with STATICFILES_DIRS.

These locations are searched during autodiscovery, or when you define HTML, JS, or CSS as separate files.

COMPONENTS = ComponentsSettings(
    dirs=[BASE_DIR / "components"],
)

Set to empty list to disable global components directories:

COMPONENTS = ComponentsSettings(
    dirs=[],
)

dynamic_component_name ¤

dynamic_component_name: Optional[str] = None

See source code

By default, the dynamic component is registered under the name "dynamic".

In case of a conflict, you can use this setting to change the component name used for the dynamic components.

# settings.py
COMPONENTS = ComponentsSettings(
    dynamic_component_name="my_dynamic",
)

After which you will be able to use the dynamic component with the new name:

{% component "my_dynamic" is=table_comp data=table_data headers=table_headers %}
    {% fill "pagination" %}
        {% component "pagination" / %}
    {% endfill %}
{% endcomponent %}

forbidden_static_files ¤

forbidden_static_files: Optional[List[Union[str, Pattern]]] = None

libraries ¤

libraries: Optional[List[str]] = None

See source code

Configure extra python modules that should be loaded.

This may be useful if you are not using the autodiscovery feature, or you need to load components from non-standard locations. Thus you can have a structure of components that is independent from your apps.

Expects a list of python module paths. Defaults to empty list.

Example:

COMPONENTS = ComponentsSettings(
    libraries=[
        "mysite.components.forms",
        "mysite.components.buttons",
        "mysite.components.cards",
    ],
)

This would be the equivalent of importing these modules from within Django's AppConfig.ready():

class MyAppConfig(AppConfig):
    def ready(self):
        import "mysite.components.forms"
        import "mysite.components.buttons"
        import "mysite.components.cards"

Manually loading libraries¤

In the rare case that you need to manually trigger the import of libraries, you can use the import_libraries() function:

from django_components import import_libraries

import_libraries()

multiline_tags ¤

multiline_tags: Optional[bool] = None

See source code

Enable / disable multiline support for template tags. If True, template tags like {% component %} or {{ my_var }} can span multiple lines.

Defaults to True.

Disable this setting if you are making custom modifications to Django's regular expression for parsing templates at django.template.base.tag_re.

COMPONENTS = ComponentsSettings(
    multiline_tags=False,
)

reload_on_file_change ¤

reload_on_file_change: Optional[bool] = None

See source code

This is relevant if you are using the project structure where HTML, JS, CSS and Python are in separate files and nested in a directory.

In this case you may notice that when you are running a development server, the server sometimes does not reload when you change component files.

Django's native live reload logic handles only Python files and HTML template files. It does NOT reload when other file types change or when template files are nested more than one level deep.

The setting reload_on_file_change fixes this, reloading the dev server even when your component's HTML, JS, or CSS changes.

If True, django_components configures Django to reload when files inside COMPONENTS.dirs or COMPONENTS.app_dirs change.

See Reload dev server on component file changes.

Defaults to False.

Warning

This setting should be enabled only for the dev environment!

reload_on_template_change ¤

reload_on_template_change: Optional[bool] = None

static_files_allowed ¤

static_files_allowed: Optional[List[Union[str, Pattern]]] = None

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs are treated as static files.

If a file is matched against any of the patterns, it's considered a static file. Such files are collected when running collectstatic, and can be accessed under the static file endpoint.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, JS, CSS, and common image and font file formats are considered static files:

COMPONENTS = ComponentsSettings(
    static_files_allowed=[
        ".css",
        ".js", ".jsx", ".ts", ".tsx",
        # Images
        ".apng", ".png", ".avif", ".gif", ".jpg",
        ".jpeg",  ".jfif", ".pjpeg", ".pjp", ".svg",
        ".webp", ".bmp", ".ico", ".cur", ".tif", ".tiff",
        # Fonts
        ".eot", ".ttf", ".woff", ".otf", ".svg",
    ],
)

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

static_files_forbidden ¤

static_files_forbidden: Optional[List[Union[str, Pattern]]] = None

See source code

A list of file extensions (including the leading dot) that define which files within COMPONENTS.dirs or COMPONENTS.app_dirs will NEVER be treated as static files.

If a file is matched against any of the patterns, it will never be considered a static file, even if the file matches a pattern in static_files_allowed.

Use this setting together with static_files_allowed for a fine control over what file types will be exposed.

You can also pass in compiled regexes (re.Pattern) for more advanced patterns.

By default, any HTML and Python are considered NOT static files:

COMPONENTS = ComponentsSettings(
    static_files_forbidden=[
        ".html", ".django", ".dj", ".tpl",
        # Python files
        ".py", ".pyc",
    ],
)

Warning

Exposing your Python files can be a security vulnerability. See Security notes.

tag_formatter ¤

tag_formatter: Optional[Union[TagFormatterABC, str]] = None

See source code

Configure what syntax is used inside Django templates to render components. See the available tag formatters.

Defaults to "django_components.component_formatter".

Learn more about Customizing component tags with TagFormatter.

Can be set either as direct reference:

from django_components import component_formatter

COMPONENTS = ComponentsSettings(
    "tag_formatter": component_formatter
)

Or as an import string;

COMPONENTS = ComponentsSettings(
    "tag_formatter": "django_components.component_formatter"
)

Examples:

  • "django_components.component_formatter"

    Set

    COMPONENTS = ComponentsSettings(
        "tag_formatter": "django_components.component_formatter"
    )
    

    To write components like this:

    {% component "button" href="..." %}
        Click me!
    {% endcomponent %}
    
  • django_components.component_shorthand_formatter

    Set

    COMPONENTS = ComponentsSettings(
        "tag_formatter": "django_components.component_shorthand_formatter"
    )
    

    To write components like this:

    {% button href="..." %}
        Click me!
    {% endbutton %}
    

template_cache_size ¤

template_cache_size: Optional[int] = None

See source code

Configure the maximum amount of Django templates to be cached.

Defaults to 128.

Each time a Django template is rendered, it is cached to a global in-memory cache (using Python's lru_cache decorator). This speeds up the next render of the component. As the same component is often used many times on the same page, these savings add up.

By default the cache holds 128 component templates in memory, which should be enough for most sites. But if you have a lot of components, or if you are overriding Component.get_template() to render many dynamic templates, you can increase this number.

COMPONENTS = ComponentsSettings(
    template_cache_size=256,
)

To remove the cache limit altogether and cache everything, set template_cache_size to None.

COMPONENTS = ComponentsSettings(
    template_cache_size=None,
)

If you want to add templates to the cache yourself, you can use cached_template():

from django_components import cached_template

cached_template("Variable: {{ variable }}")

# You can optionally specify Template class, and other Template inputs:
class MyTemplate(Template):
    pass

cached_template(
    "Variable: {{ variable }}",
    template_cls=MyTemplate,
    name=...
    origin=...
    engine=...
)