### Install django-pydantic-field Package Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Instructions for installing the `django-pydantic-field` package using pip, which is the standard Python package installer. ```Shell pip install django-pydantic-field ``` -------------------------------- ### Define Django Model Fields with Pydantic Schemas Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Demonstrates how to integrate Pydantic models (`Foo`, `Bar`) with Django models using `SchemaField`. It shows inferring schemas from field annotations, explicitly passing schemas, and handling Pydantic exportable types like `date` and `UUID`. Includes an example of model instantiation, saving, and data validation against the defined Pydantic schemas. ```Python import pydantic from datetime import date from uuid import UUID from django.db import models from django_pydantic_field import SchemaField class Foo(pydantic.BaseModel): count: int size: float = 1.0 class Bar(pydantic.BaseModel): slug: str = "foo_bar" class MyModel(models.Model): # Infer schema from field annotation foo_field: Foo = SchemaField() # or explicitly pass schema to the field bar_list: typing.Sequence[Bar] = SchemaField(schema=list[Bar]) # Pydantic exportable types are supported raw_date_map: dict[int, date] = SchemaField() raw_uids: set[UUID] = SchemaField() ... model = MyModel( foo_field={"count": "5"}, bar_list=[{}], raw_date_map={1: "1970-01-01"}, raw_uids={"17a25db0-27a4-11ed-904a-5ffb17f92734"} ) model.save() assert model.foo_field == Foo(count=5, size=1.0) assert model.bar_list == [Bar(slug="foo_bar")] assert model.raw_date_map == {1: date(1970, 1, 1)} assert model.raw_uids == {UUID("17a25db0-27a4-11ed-904a-5ffb17f92734")} ``` -------------------------------- ### Integrate Pydantic SchemaField with Django ModelForm Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Shows how `django_pydantic_field` automatically supports `ModelForm` and `modelform_factory` for fields backed by Pydantic schemas. It includes examples for both. ```Python class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = ["foo_field"] form = MyModelForm(data={"foo_field": '{"count": 5}'}) assert form.is_valid() assert form.cleaned_data["foo_field"] == Foo(count=5) ... # ModelForm factory support AnotherModelForm = modelform_factory(MyModel, fields=["foo_field"]) form = AnotherModelForm(data={"foo_field": '{"count": 5}'}) assert form.is_valid() assert form.cleaned_data["foo_field"] == Foo(count=5) ``` -------------------------------- ### Use Forward References with SchemaField Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Illustrates how to use `SchemaField` with string literal type annotations for Pydantic models that are defined later in the code. This allows for forward referencing of schemas, with type resolution postponed until the first model instantiation, and is supported by internal checks during Django management commands. ```Python class MyModel(models.Model): foo_field: "Foo" = SchemaField() bar_list: typing.Sequence["Bar"] = SchemaField(schema=typing.ForwardRef("list[Bar]")) class Foo(pydantic.BaseModel): count: int size: float = 1.0 class Bar(pydantic.BaseModel): slug: str = "foo_bar" ``` -------------------------------- ### Use django-jsonform Widget with SchemaField Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Explains how to integrate `django-jsonform` widgets with `SchemaField` for dynamic form construction, specifically for Pydantic v2. ```Python from django_pydantic_field.forms import SchemaField from django_jsonform.widgets import JSONFormWidget class FooForm(forms.Form): field = SchemaField(Foo, widget=JSONFormWidget) ``` -------------------------------- ### Define Django Form with Pydantic SchemaField Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Demonstrates how to create a Django form using `SchemaField` to validate against a Pydantic `BaseModel`. It shows form instantiation, validation, and accessing cleaned data. ```Python from django import forms from django_pydantic_field.forms import SchemaField class Foo(pydantic.BaseModel): slug: str = "foo_bar" class FooForm(forms.Form): field = SchemaField(Foo) # `typing.ForwardRef("Foo")` is fine too, but only in Django 4+ form = FooForm(data={"field": '{"slug": "asdf"}'}) assert form.is_valid() assert form.cleaned_data["field"] == Foo(slug="asdf") ``` -------------------------------- ### Implement Django REST Framework Serializer with SchemaField Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Demonstrates using `SchemaField` within a `ModelSerializer` for Django REST Framework and enabling OpenAPI schema generation with `AutoSchema` for `RetrieveAPIView`. ```Python from rest_framework import generics, serializers from django_pydantic_field.rest_framework import SchemaField, AutoSchema class MyModelSerializer(serializers.ModelSerializer): foo_field = SchemaField(schema=Foo) class Meta: model = MyModel fields = '__all__' class SampleView(generics.RetrieveAPIView): serializer_class = MyModelSerializer # optional support of OpenAPI schema generation for Pydantic fields schema = AutoSchema() ``` -------------------------------- ### Apply Global SchemaParser and SchemaRenderer in DRF Views Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Illustrates a global approach for handling Pydantic schemas in Django REST Framework views using `@parser_classes` and `@renderer_classes` decorators for function-based views, and `parser_classes`/`renderer_classes` attributes for class-based views. It also shows `AutoSchema` for OpenAPI generation. ```Python from rest_framework import views from rest_framework.decorators import api_view, parser_classes, renderer_classes from django_pydantic_field.rest_framework import SchemaRenderer, SchemaParser, AutoSchema @api_view(["POST"]) @parser_classes([SchemaParser[Foo]]): @renderer_classes([SchemaRenderer[list[Foo]]]) def foo_view(request): assert isinstance(request.data, Foo) count = request.data.count + 1 return Response([Foo(count=count)]) class FooClassBasedView(views.APIView): parser_classes = [SchemaParser[Foo]] renderer_classes = [SchemaRenderer[list[Foo]]] # optional support of OpenAPI schema generation for Pydantic parsers/renderers schema = AutoSchema() def get(self, request, *args, **kwargs): assert isinstance(request.data, Foo) return Response([request.data]) def put(self, request, *args, **kwargs): assert isinstance(request.data, Foo) count = request.data.count + 1 return Response([request.data]) ``` -------------------------------- ### Override Django Admin Widget for PydanticSchemaField Source: https://github.com/surenkov/django-pydantic-field/blob/master/README.md Shows how to globally override the default form widget for `PydanticSchemaField` in the Django Admin site using `formfield_overrides` without writing custom admin forms. ```Python from django.contrib import admin from django_jsonform.widgets import JSONFormWidget # NOTE: Importing direct field class instead of `SchemaField` wrapper. from django_pydantic_field.v2.fields import PydanticSchemaField @admin.site.register(MyModel) class MyModelAdmin(admin.ModelAdmin): formfield_overrides = { PydanticSchemaField: {"widget": JSONFormWidget}, } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.