Skip to content

django-components/djc-ext-pydantic

Repository files navigation

djc-ext-pydantic

PyPI - Version PyPI - Python Version PyPI - License PyPI - Downloads GitHub Actions Workflow Status

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.

Validated Inputs and Outputs

  • Inputs:

    • args: Positional arguments, expected to be defined as a Tuple type.
    • kwargs: Keyword arguments, can be defined using TypedDict or Pydantic's BaseModel.
    • slots: Can also be defined using TypedDict or Pydantic's BaseModel.
  • Outputs:

    • Data returned from get_context_data(), get_js_data(), and get_css_data(), which can be defined using TypedDict or Pydantic's BaseModel.

Example Usage

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,
]):
    ...

Installation

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,
    ],
}

Release notes

Read the Release Notes to see the latest features and fixes.

Development

Tests

To run tests, use:

pytest

About

Input validation with Pydantic for Django Components

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages