Skip to content

Components API Reference

All component base classes live in dj_design_system.components. Any new component class added to that module will appear here automatically.

dj_design_system.components

BaseComponent(**kwargs)

Source code in dj_design_system/components.py
45
46
47
48
49
50
51
def __init__(self, **kwargs):
    self.context = {}
    for var_name, var_value in kwargs.items():
        setattr(self, var_name, var_value)

    self._validate_meta_constraints()
    self.validate_params()

__init_subclass__(**kwargs)

Validate Meta constraint declarations at class definition time.

Source code in dj_design_system/components.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def __init_subclass__(cls, **kwargs) -> None:
    """Validate Meta constraint declarations at class definition time."""
    super().__init_subclass__(**kwargs)
    from dj_design_system.services.component import get_own_meta, is_abstract

    if is_abstract(cls):
        return

    meta = get_own_meta(cls)
    param_names = set(cls.get_params().keys())

    for a, b in getattr(meta, "mutually_exclusive", []):
        for name in (a, b):
            if name not in param_names:
                raise ValueError(
                    f"{cls.__name__}.Meta.mutually_exclusive references unknown param '{name}'."
                )

    for dependent, dependency in getattr(meta, "requires", []):
        for name in (dependent, dependency):
            if name not in param_names:
                raise ValueError(
                    f"{cls.__name__}.Meta.requires references unknown param '{name}'."
                )

docstring() classmethod

Return a string describing the API of this component, including its parameters and their types.

Source code in dj_design_system/components.py
138
139
140
141
142
143
144
145
146
147
148
149
@classmethod
def docstring(cls) -> str:
    """
    Return a string describing the API of this component, including its parameters and their types.
    """
    params = cls.get_params()
    api_docs = f"{cls.__doc__}\n\n"
    if len(params) > 0:
        api_docs += "Parameters:\n"
    for parameter_spec in params.values():
        api_docs += f"- {parameter_spec.docstring()}\n"
    return api_docs

get_app_label() classmethod

Return the app label this component was discovered in.

Source code in dj_design_system/components.py
158
159
160
161
162
163
@classmethod
def get_app_label(cls) -> str:
    """Return the app label this component was discovered in."""
    from dj_design_system import component_registry

    return component_registry.get_info(cls).app_label

get_classes_string()

Get a string of CSS classes based on the context. This can be used in the template to apply conditional styling.

Source code in dj_design_system/components.py
 95
 96
 97
 98
 99
100
101
102
103
def get_classes_string(self):
    """
    Get a string of CSS classes based on the context. This can be used in the template to apply conditional styling.
    """
    classes = []
    for param_name, spec in self.params.items():
        param_value = getattr(self, param_name)
        classes.extend(spec.get_css_classes(param_name, param_value))
    return " ".join(classes)

get_context()

Get the context for rendering the component. This method can be overridden by subclasses to add additional or edit other context variables.

Source code in dj_design_system/components.py
84
85
86
87
88
89
90
91
92
93
def get_context(self) -> dict[str, Any]:
    """
    Get the context for rendering the component. This method can be overridden by subclasses to add additional or edit other context variables.
    """
    self.context["classes"] = self.get_classes_string()
    for param_name, spec in self.params.items():
        value = getattr(self, param_name)
        self.context[param_name] = value
        self.context.update(spec.get_extra_context(param_name, value))
    return self.context

get_media() classmethod

Return the CSS and JS static URL paths required by this component.

Delegates to ComponentInfo.media — see that property for full documentation of auto-discovery and Media class override behaviour.

Source code in dj_design_system/components.py
172
173
174
175
176
177
178
179
180
181
@classmethod
def get_media(cls) -> "ComponentMedia":
    """Return the CSS and JS static URL paths required by this component.

    Delegates to ``ComponentInfo.media`` — see that property for full
    documentation of auto-discovery and ``Media`` class override behaviour.
    """
    from dj_design_system import component_registry

    return component_registry.get_info(cls).media

get_name() classmethod

Return the component's registered name from the registry.

Source code in dj_design_system/components.py
151
152
153
154
155
156
@classmethod
def get_name(cls) -> str:
    """Return the component's registered name from the registry."""
    from dj_design_system import component_registry

    return component_registry.get_info(cls).name

get_params() classmethod

Get the parameters for this component. Returns a dictionary of all BaseParam descriptors defined on the class (or any subclass in the MRO).

Source code in dj_design_system/components.py
125
126
127
128
129
130
131
132
133
134
135
136
@classmethod
def get_params(cls) -> dict[str, "BaseParam"]:
    """
    Get the parameters for this component. Returns a dictionary of all
    BaseParam descriptors defined on the class (or any subclass in the MRO).
    """
    result = {}
    for klass in cls.__mro__:
        for attr_name, attr_value in vars(klass).items():
            if isinstance(attr_value, BaseParam) and attr_name not in result:
                result[attr_name] = attr_value
    return result

get_positional_args() classmethod

Return the list of positional arg names from the class's own Meta.positional_args.

Only looks at the class's own Meta — positional_args are NOT inherited from parent classes, matching Django's convention that Meta is not inherited. This avoids silent ordering surprises when subclassing.

Source code in dj_design_system/components.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
@classmethod
def get_positional_args(cls) -> list[str]:
    """Return the list of positional arg names from the class's own Meta.positional_args.

    Only looks at the class's own ``Meta`` — positional_args are NOT
    inherited from parent classes, matching Django's convention that
    Meta is not inherited. This avoids silent ordering surprises when
    subclassing.
    """
    from dj_design_system.services.component import get_own_meta

    meta = get_own_meta(cls)
    positional = getattr(meta, "positional_args", None)
    return list(positional) if positional else []

get_relative_path() classmethod

Return the relative path within the app's components directory.

Source code in dj_design_system/components.py
165
166
167
168
169
170
@classmethod
def get_relative_path(cls) -> str:
    """Return the relative path within the app's components directory."""
    from dj_design_system import component_registry

    return component_registry.get_info(cls).relative_path

map_positional_args(positional_args, args, kwargs) staticmethod

Map positional arguments to keyword arguments using the positional_args spec.

Source code in dj_design_system/components.py
198
199
200
201
202
203
204
205
206
@staticmethod
def map_positional_args(
    positional_args: list[str], args: tuple, kwargs: dict
) -> dict:
    """Map positional arguments to keyword arguments using the positional_args spec."""
    for i, arg_name in enumerate(positional_args):
        if i < len(args):
            kwargs[arg_name] = args[i]
    return kwargs

render()

Render the component as an HTML string.

Source code in dj_design_system/components.py
105
106
107
108
109
def render(self) -> str:
    """
    Render the component as an HTML string.
    """
    return format_html(format_string=self.template_format_str, **self.get_context())

validate_params()

An override hook allowing param combinations or values to raise exceptions if necessary

Source code in dj_design_system/components.py
53
54
55
def validate_params(self) -> None:
    """An override hook allowing param combinations or values to raise exceptions if necessary"""
    ...

BlockComponent(content, **kwargs)

Bases: BaseComponent

A component registered as a Django simple_block_tag, allowing for nested template content.

The template should include a {content} placeholder where the inner content will be rendered. content is always the first positional argument and should NOT appear in Meta.positional_args.

Use Meta.positional_args to declare additional positional args beyond content::

class SectionComponent(BlockComponent):
    title = StrParam("Section title.")

    class Meta:
        positional_args = ["title"]

This allows {% section "My Title" %}...{% endsection %}.

Source code in dj_design_system/components.py
269
270
271
def __init__(self, content: SafeString, **kwargs):
    self.content = content
    super().__init__(**kwargs)

as_tag() classmethod

Return a template tag function with content as first arg, plus any Meta.positional_args.

Source code in dj_design_system/components.py
284
285
286
287
288
289
290
291
292
293
@classmethod
def as_tag(cls):
    """Return a template tag function with content as first arg, plus any Meta.positional_args."""
    positional_args = cls.get_positional_args()

    def _tag(content, *args, **kwargs):
        cls.map_positional_args(positional_args, args, kwargs)
        return cls(content=content, **kwargs)

    return _tag

get_context()

Add content to the context automatically.

content is the block body passed by the template engine — it is NOT a declared BaseParam and should not appear in Meta.positional_args or docstring() output.

Source code in dj_design_system/components.py
273
274
275
276
277
278
279
280
281
282
def get_context(self) -> dict[str, Any]:
    """Add ``content`` to the context automatically.

    ``content`` is the block body passed by the template engine — it is
    NOT a declared BaseParam and should not appear in ``Meta.positional_args``
    or ``docstring()`` output.
    """
    context = super().get_context()
    context["content"] = self.content
    return context

TagComponent(**kwargs)

Bases: BaseComponent

A component registered as a Django simple_tag.

Subclass this for components that produce a single HTML fragment without wrapping nested template content.

Use Meta.positional_args to declare parameters that can be passed as positional arguments in the template tag::

class IconComponent(TagComponent):
    name = StrParam("The icon name.")

    class Meta:
        positional_args = ["name"]

This allows {% icon "check" %} instead of {% icon name="check" %}.

Source code in dj_design_system/components.py
45
46
47
48
49
50
51
def __init__(self, **kwargs):
    self.context = {}
    for var_name, var_value in kwargs.items():
        setattr(self, var_name, var_value)

    self._validate_meta_constraints()
    self.validate_params()

as_tag() classmethod

Return a template tag function mapping positional args via Meta.positional_args.

Source code in dj_design_system/components.py
231
232
233
234
235
236
237
238
239
240
@classmethod
def as_tag(cls):
    """Return a template tag function mapping positional args via Meta.positional_args."""
    positional_args = cls.get_positional_args()

    def _tag(*args, **kwargs):
        cls.map_positional_args(positional_args, args, kwargs)
        return cls(**kwargs)

    return _tag

options: members: true show_root_heading: false show_source: true show_symbol_type_heading: true show_symbol_type_toc: true docstring_style: google merge_init_into_class: true group_by_category: true