Validate components' inputs and outputs using Pydantic.
djc-ext-pydantic
is a django-component extension that integrates Pydantic for input and data validation. It uses the types defined on the component's class to validate both inputs and outputs of Django components.
-
Inputs:
-
Outputs:
from pydantic import BaseModel
from typing import Tuple, TypedDict
# 1. Define the types
MyCompArgs = Tuple[str, ...]
class MyCompKwargs(TypedDict):
name: str
age: int
class MyCompSlots(TypedDict):
header: SlotContent
footer: SlotContent
class MyCompData(BaseModel):
data1: str
data2: int
class MyCompJsData(BaseModel):
js_data1: str
js_data2: int
class MyCompCssData(BaseModel):
css_data1: str
css_data2: int
# 2. Define the component with those types
class MyComponent(Component[
MyCompArgs,
MyCompKwargs,
MyCompSlots,
MyCompData,
MyCompJsData,
MyCompCssData,
]):
...
# 3. Render the component
MyComponent.render(
# ERROR: Expects a string
args=(123,),
kwargs={
"name": "John",
# ERROR: Expects an integer
"age": "invalid",
},
slots={
"header": "...",
# ERROR: Expects key "footer"
"foo": "invalid",
},
)
If you don't want to validate some parts, set them to Any
.
class MyComponent(Component[
MyCompArgs,
MyCompKwargs,
MyCompSlots,
Any,
Any,
Any,
]):
...
pip install djc-ext-pydantic
Then add the extension to your project:
# settings.py
COMPONENTS = {
"extensions": [
"djc_pydantic.PydanticExtension",
],
}
or by reference:
# settings.py
from djc_pydantic import PydanticExtension
COMPONENTS = {
"extensions": [
PydanticExtension,
],
}
Read the Release Notes to see the latest features and fixes.
To run tests, use:
pytest