A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/django-components/djc-ext-pydantic below:

django-components/djc-ext-pydantic: Input validation with Pydantic for Django Components

Validate components' inputs and outputs using Pydantic.

djc-ext-pydantic is a django-component extension that integrates Pydantic for input and data validation.

from django_components import Component, SlotInput
from djc_pydantic import ArgsBaseModel
from pydantic import BaseModel

# 1. Define the Component with Pydantic models
class MyComponent(Component):
    class Args(ArgsBaseModel):
        var1: str

    class Kwargs(BaseModel):
        name: str
        age: int

    class Slots(BaseModel):
        header: SlotInput
        footer: SlotInput

    class TemplateData(BaseModel):
        data1: str
        data2: int

    class JsData(BaseModel):
        js_data1: str
        js_data2: int

    class CssData(BaseModel):
        css_data1: str
        css_data2: int

    ...

# 2. 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",
    },
)
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,
    ],
}

By default, Pydantic's BaseModel requires all fields to be passed as keyword arguments. If you want to validate positional arguments, you can use a custom subclass ArgsBaseModel:

from pydantic import BaseModel
from djc_pydantic import ArgsBaseModel

class MyTable(Component):
    class Args(ArgsBaseModel):
        a: int
        b: str
        c: float

MyTable.render(
    args=[1, "hello", 3.14],
)

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

To run tests, use:


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4