The forms adapter¶
FormValidator
makes a Django form class a
Validator. The form
you already have - its fields, their validators, clean_<field>(), clean()
and, on a ModelForm, the model's own validation and uniqueness checks - is
what validates the arguments, and the adapter reads its fields into the
Parameters every transport describes itself from.
It needs nothing beyond Django, so like the dataclass adapters it is exported from the package root:
There is no presenter: a form describes what goes in, not what comes out.
To serve the form as a page,
django-spec-html's SpecFormView renders it,
dispatches the post and re-renders it with what dispatch refused. A host's own
view does the same with
a refusal, placed on a form.
A form as a Validator¶
from collections.abc import Mapping
from typing import Any
from django import forms
from django.contrib.auth import get_user_model
from django_service_specs import (
FormValidator,
Parameter,
Parameters,
PermissionCheck,
PoolSeeds,
SelectorKind,
SelectorSpec,
ServiceSpec,
Unrestricted,
ValidationContext,
update_from_input,
)
from tests.adapter_app.models import Author, Book, Status
class BookForm(forms.Form):
title = forms.CharField(max_length=100, help_text="As printed on the cover.")
price = forms.DecimalField(max_digits=6, decimal_places=2)
status = forms.ChoiceField(choices=Status.choices)
published_on = forms.DateField(required=False)
author = forms.ModelChoiceField(queryset=Author.objects.all())
shelves = forms.MultipleChoiceField(
choices=[("fiction", "Fiction"), ("poetry", "Poetry")], required=False
)
def clean(self) -> dict[str, Any]:
cleaned = super().clean() or {}
if cleaned.get("status") == Status.PUBLISHED and not cleaned.get("published_on"):
raise forms.ValidationError("A published book needs its publication date.")
return cleaned
# The form is read here, once: a field with no JSON type fails on this line.
book_validator = FormValidator(BookForm)
What book_validator.parameters() declares, then, in the form's own order:
title, a required string of at most 100 characters, advertised as its
maxLength, with the help text as its help; price, a
required string in the decimal format; status, a required string with the
choices draft and published; published_on, an optional, nullable string
in the date format; author, a required integer, because authors are matched
on their primary key; and shelves, an optional array of strings whose every
element is one of fiction and poetry.
validate() binds the arguments to a new BookForm and returns its
cleaned_data: a Decimal for the price, a date, the Author row itself
for author. The rule clean() states is the form's to enforce, and its
message comes back about the whole call:
{"non_field_errors": ["A published book needs its publication date."]}.
The form is bound to a post: its data is an immutable QueryDict holding
each argument as the strings a browser would post for it, so a form or widget
written for HTML reads it as it reads request.POST, with getlist() for a
list and .isdigit() on an id. A list is one string per element, a boolean
"True" or "False" (which CheckboxInput and NullBooleanSelect both
read, and which a choice of True or False renders as its option), a date, time or datetime its ISO spelling, a duration Django's own
spelling, and null an absent key; any other value is its str(). A
localized number field is posted its number as its widget renders it in the
active locale, which the field reads back as the same number. The shape check
in front of the form stays typed: only the bind speaks the post's strings, on
every transport.
The form is read when FormValidator is built, so a field it cannot describe
fails on that line, naming the form, the field and the field's class. Nothing
in the reading queries: a ModelChoiceField's rows are never listed. The one
thing read later is help_text, on each parameters() call, so a lazily
translated help text is in the caller's language rather than whichever was
active at import.
What each field declares¶
The first match wins, so a subclass is read as the most specific field it extends.
| Field | Declares |
|---|---|
BooleanField, NullBooleanField |
A boolean. |
DecimalField |
A string in the decimal format. It takes a JSON number too, and an integer whatever its digits. |
FloatField |
A number. An integer past a float's range is refused as the field refuses an infinity: invalid, in its own words. |
IntegerField |
An integer. |
DateTimeField, DateField |
A string in the date-time or date format. |
TimeField, DurationField |
A string. |
ChoiceField |
A string with the choices as strings, since a plain choice field cleans with str and compares against each choice's str. The empty choice is dropped and option groups are flattened. |
TypedChoiceField |
Choices, of the JSON type every value shares. Values of mixed types, or of a type JSON does not have, are refused. |
MultipleChoiceField, TypedMultipleChoiceField |
An array of the same, whose choices constrain each element. No choice field declares a length, so the SERVICE_SPECS_MAX_ARRAY_LENGTH setting bounds every list one takes. |
ModelChoiceField |
The JSON type of the model field rows are matched on - to_field_name, or the primary key - and no choices: they are rows, and listing them would query. It validates to the row. |
ModelMultipleChoiceField |
An array of the same, so one matching rows on a DecimalField declares the decimal format for each element and ?rows=12.50,9.99 is two of them. Django matches each against the column's own spelling, "12.50" and not 12.5. It validates to a queryset. |
FileField, ImageField |
A file, which a multipart request carries and a Python caller hands as a Django File. The form is bound with it as its files, where a file field reads, and its own checks run on it. An optional one also declares its clear checkbox. |
any other CharField (EmailField, URLField, SlugField, UUIDField, RegexField, GenericIPAddressField) |
A string, with its lengths advertised. |
A string's length and a number's bounds¶
A CharField, or any field extending it, whose value Django's
MaxLengthValidator bounds advertises the limit as the string's maxLength,
and a required one bounded by MinLengthValidator advertises that as its
minLength. Setting max_length or min_length appends one of those, and a
validator a project appends by hand counts the same, since the form enforces
it alike; where several bound one side, the tightest is advertised. Each goes in the parameter's json_schema_extra, so a
transport's schema states it (an MCP tools/list reads
{"type": "string", "maxLength": 32} for CharField(max_length=32)) and the
shape check does not enforce it: the form still refuses an over-long value, in
its own words and with Django's code, beside its other refusals. A ModelForm
field carries its column's max_length, which Django puts on the form field it
builds.
Only those two validators are read, matched by exact type, rather than the
field's max_length and min_length. SimpleArrayField extends CharField
and spends both on how many items its list holds, validated by subclasses of
the same two validators, so it advertises no length: a ModelForm over a sized
ArrayField builds one. A limit no schema can state, such as a callable one,
is not advertised either.
An optional field's min_length is not advertised. Django runs no validator on
an empty value, so the form takes "" whatever its min_length, and a
minLength would tell a client to refuse what the form takes. A length is
counted on the value the form cleans, which a schema cannot say: stripped of
surrounding whitespace unless the field sets strip=False, and a URLField's
with the scheme it adds. So a value padded with whitespace the form strips may
read as too long to a client that checks the schema and still be taken, and a
URL within its maxLength may still be refused: URLField(max_length=20)
refuses the 20 characters of "abcdefghijklmnop.com", counted with the scheme.
For the same reason a URLField's min_length is not advertised: counted with
the scheme it adds, "ab.co" is taken by URLField(min_length=12), and a
minLength would tell a client to refuse it.
An IntegerField's or a FloatField's min_value and max_value are not
declared. A declared minimum or maximum is enforced by the shape check,
before the form runs and in the kernel's words, so it would replace a field's
own error_messages for the bound and stop the form's other refusals coming
back beside it. They stay the form's, and the schema carries no bound for
either field.
A key past the range of the integer column rows are matched on names no row,
so either field refuses it as it refuses a key no row holds: invalid_choice,
in its own words, beside the form's other refusals. The adapter answers it
before the form queries, because Django hands a ModelMultipleChoiceField's
keys to the database driver in an __in lookup, and SQLite's raises
OverflowError for one past 64 bits on every Django version, as it does for a
ModelChoiceField's on Django 4.2. The range is the database's own for the
column, as Django reads it to answer an exact lookup past it with no rows, and
a key sent as a string of digits is the integer it spells.
A ModelForm value past the range of its model's integer column is refused in
the words, and with the code, of the validator Django's model field carries
from 5.0: max_value past its top, min_value past its bottom. Django 4.2
states no range for SQLite, so there the form took such a value, and a
uniqueness check or a constraint querying with it raised the driver's
OverflowError. The value is judged where Django 5.0 and later judge it: after
the form field, its clean_<field>() and the form's clean(), on what they
hand back, read as the model reads it, so digits a text field cleans to are
the integer they spell. So a value the field refuses is refused in the field's
words, its own bounds included, a clean_<field>() refusing it is reported in
its own words, and one that brings the value inside the range has it taken.
Only a column Django validates is judged, the ones it does not leave out of
the model's checks: a value clean() sets in cleaned_data for a column the
form has no field for, and a field the form declares over a column
Meta.fields leaves out or Meta.exclude names, are never written onto the
row by the form, and are the form's to use, whatever their size.
Every choice field's choices carry their labels as choice_labels, the label
Django displays keyed by the value as the caller sends it, so a schema states
each as a title. A choice set given as a callable is computed per form and
may query, so it is not read: the field is declared as a string with no choices, which every
choice field accepts, and the form checks the choice when it validates.
Refused, with ImproperlyConfigured:
JSONField: it takes any JSON value, and a parameter declares one type.MultiValueField, such asSplitDateTimeField: it is cleaned from several widget values at once, which only an HTML form sends. Declare a field per value.ComboField: it has no JSON type of its own.- A
ModelChoiceFieldwith no queryset, since there is no model to read its key from, or one matching rows on a model field with no JSON type. - Any field class the table does not cover, a project's own included.
Presence, null and defaults¶
The Parameters say what the form does about presence and null, so on
those the shape check in front of it never refuses what the form would take.
requiredis the field's own. For aBooleanFieldthat is a statement about presence too: an absent checkbox cleans toFalse, which a required one refuses exactly as it refusesfalse. ANullBooleanFieldis never required, whatever it says: its validation is empty, and it takes an absent value asNone.nullableisnot required, and always true for aNullBooleanField. A form readsNoneas an empty value for every field, so an optional field takesnulland cleans it to its empty value -""for a string,Nonefor a number or a row,[]for a multiple choice - and a required one refuses it. The shape check and the form agree on it field for field.- There is no
default. A field'sinitialis what an unbound form displays; a bound form cleans an absent optional field to its empty value, never to its initial.
The types are JSON's, and do not cross. A form reads its data as an HTML
post's strings, so it also takes a value of another type through str - a
number for a CharField, 1 for the choice "1". The shape check refuses
one, as it does for any declaration: a caller sends the declared type. The
empty choice is the other case. An optional choice field reads "" as no
value, and a caller says that with null.
Declare the fields on the class¶
The adapter reads base_fields: the fields the class declares. A field the
form adds or changes in its own __init__ is not described, and under
UnknownArguments.REJECT,
the default, the closed argument set refuses its key before the form is ever
built. A field declared disabled is not a parameter either: a form ignores
what a caller sends for it and cleans its initial, which validate()
returns with the rest.
That holds for a form built with keywords of its own, too: a field its
__init__ adds from them is still not a parameter. Declare the field on the
class and narrow it in __init__, as
the form in A form with keywords of its own
does.
A form class that sets a prefix, or is handed one through form_kwargs, keeps
it. The parameters are still the bare field names, and the adapter binds each
argument under the name the form reads it by, add_prefix(name), so an
add_prefix override of the form's own is followed too.
Partial updates¶
On a partial spec's call, every field the
arguments do not name is taken off the bound form before it validates, so it
is neither required nor cleaned, and validate() returns no key for it: an
absent BooleanField does not come back False, nor an absent CharField
'', which an update would write over the row. A value that is sent is
checked exactly as on a whole call, so a required field may be left out but
not sent empty. On a ModelForm the fields left out keep the target's
values, and each one's own model check skips them. Its uniqueness checks and
constraints do not: they run over the row as it would be saved, what was sent
on top of the target's values, and leave out only the model fields the form
never declares, as a whole call does. An update that sends one field of a
unique_together pair or a UniqueConstraint and collides is refused as the
whole call would be, under non_field_errors, rather than failing with an
IntegrityError when the row is saved. That needs a target row: a partial
call with none checks only what was sent. clean() sees only
what was sent, so it reads cleaned_data with get. The parameters are the
same for both calls: required says what a whole call needs.
Clearing a file¶
Django clears an optional file through its widget's clear checkbox, which a
ClearableFileInput - the default widget of a FileField and an
ImageField - posts beside the file as <name>-clear. The adapter declares
that checkbox as a parameter of its own, a boolean right after the file, so
the closed argument set, the shape check and the schema all know it. A
ModelForm over title, an attachment declared blank=True and a
required scan declares title, attachment, attachment-clear and
scan, in that order.
It is the only way a caller clears a file: null keeps the file the row
holds, as a form reads no data beside an initial value, and false is
refused as not a file.
- Checked with no upload, the form cleans the field to
False, its own value for a cleared file.validate()returns it under the field's name,{"attachment": False}, and nothing under the checkbox's. AModelFormwrites it as no file through the model field'ssave_form_data, and so do the mutation helpers: a service handing the validated values toupdate_from_input(row, data)clears the file with no more code. - Unchecked, or absent, the file is kept.
- Checked beside an upload, the form refuses the pair under the field's name, in its own words.
- On a partial call, a checked checkbox sends its file field, so
{"attachment-clear": true}alone clears the file; an unchecked one is what an absent one is, and leaves the field out.
A required file field has no checkbox, since its widget never reads one, and
neither has a file field whose widget is not a ClearableFileInput. A form
field already named as a checkbox would read the same argument, so it is
refused when the Validator is built.
A ModelForm behind an update¶
User = get_user_model()
class UsernameForm(forms.ModelForm):
class Meta:
model = User
fields = ["username"] # unique on the model
class IsThemselves(PermissionCheck):
def has_permission(self, principal: Any, spec: Any) -> bool:
return principal.is_authenticated
def has_object_permission(self, principal: Any, spec: Any, target: Any) -> bool:
return target.pk == principal.pk
def rename_user(*, instance: Any, data: dict[str, Any]) -> Any:
return update_from_input(instance, data).instance
rename_user_spec = ServiceSpec(
service=rename_user,
permissions=[IsThemselves()],
validator=FormValidator(UsernameForm),
instance_selector_spec=SelectorSpec(
kind=SelectorKind.RETRIEVE,
selector=lambda *, pk: User.objects.filter(pk=pk),
reads=Parameters.of(Parameter("pk", "integer", required=True)),
),
)
Dispatch resolves the row before it validates, and hands it to the Validator
in the
ValidationContext.
When the target is a row of the form's model, the form is built with
instance= set to a copy of it, so its uniqueness check excludes the row
being updated: renaming ada to ada is not a clash, and renaming her to
bob is refused in the form's own words,
{"username": ["A user with that username already exists."]}.
It is a copy because a ModelForm writes the cleaned values onto its instance
as it validates. Handed the target itself, it would change the row the service
receives before the service runs, and
update_from_input,
which saves only the fields whose value changed, would find nothing to save.
Any other target - the queryset a collection selector resolves, or none for a
create - builds the form as a create.
A plain form that edits an object of its own - a form over a dataclass, or
one that saves through a service - is handed the target too when its
__init__ declares a parameter named instance, but differently: the form is
built with instance= the call's target itself, whatever it is and never a
copy, so the queryset a collection selector resolves arrives as that
queryset, and None when there is none. A bare
**kwargs does not count as declaring it, so a plain form that names no
instance is built from data and files alone, as before.
A form with keywords of its own¶
The adapter builds the form from data= and files=, with instance= for a
ModelForm or a plain form that declares it. A form whose __init__ takes anything more, such as a queryset
scoped to the caller's tenant, is handed it by form_kwargs, a callable
returning those keywords:
class FeatureForm(forms.Form):
# Declared on the class, so the parameter is described; the rows it may
# name are narrowed per form, to the caller's tenant.
book = forms.ModelChoiceField(queryset=Book.objects.none())
def __init__(self, *args: Any, author: Author, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.fields["book"].queryset = Book.objects.filter(author=author)
# Each signed-in user's tenant: here, the author of their name.
tenant_seeds = PoolSeeds().extend(tenant=lambda *, user: Author.objects.get(name=user.username))
feature_spec = ServiceSpec(
service=lambda *, book: book,
permissions=[Unrestricted()],
# Named from the pool, as every spec callable is: a seed, ``user``, or the
# row as ``instance`` or ``collection``.
validator=FormValidator(FeatureForm, form_kwargs=lambda *, tenant: {"author": tenant}),
)
The callable binds through the pool, as a selector or a service does, naming what it wants:
user, the principal, on every path;progress, the call's reporter, ornull_progresswhere there is none;- every seed the call's
PoolSeedsregister; call_context, the call's context, the one dict every stage of the call shares (the call's context);- the target, under the name the service receives it by:
instancefor a spec with an instance selector,Nonewhen one declaringallow_nonefinds no row,collectionfor one with a collection selector, and neither for a create. It is the target itself, never the copy aModelFormedits. The context carries it asValidationContext.resolved.
So a caller of feature_spec names a book of their own tenant's and is
refused one of another's in the field's own words, invalid_choice, though
the row exists: the queryset the form narrowed is what matches it.
In
bind_arguments
handed pool_seeds=, the callable is handed its seeds as on dispatch: the
Validator's pool holds every seed of the registry, resolved once for the
principal, so a page checking a form scoped by a seed before it posts binds
it as the post will. Handed none, or with a
ValidationContext
built by hand, there are no seeds, so a callable naming one gives it a
default or fails with Python's own TypeError; user and progress are
there still.
form_keywords
is the off-dispatch path for building the form itself: it resolves the seeds
of the pool_seeds= it is handed that the callable would be handed. bind_arguments names the target= it is passed as dispatch
would, from the spec's selectors, and a context built by hand names none.
Under
adispatch it runs on the
thread the call's synchronous phases share, so it may query. It is called on
every validation, and a many call validates each row, so it runs once per
row: a query every row shares belongs in a seed, which resolves once per
call.
Only the bind may set data, files and instance, so a callable returning
one of them - naming instance to read the row is another matter - for a plain form as for a ModelForm, whether or not the form takes an instance, is refused with
ImproperlyConfigured naming the key, as is one returning anything but a
mapping. FormValidator(form_class, form_kwargs=...) refuses a form_kwargs
that is not callable when it is built, and keeps the callable as its
form_kwargs attribute. A transport building the form itself, for a page,
builds it the same way with
form_keywords,
which calls that callable from the pool dispatch would
(building the form before the call).
The call's context¶
FormValidator hands the call's context to form_kwargs when it names it,
and reads nothing of it otherwise. A Validator built on the adapter reads it,
and writes to it, from the
ValidationContext
its validate() is handed, as call_context: the one dict the stages of a
call share, so a later stage reuses what the Validator put there
(the call's context).
class RememberingBookValidator(FormValidator):
"""``BookForm``, leaving each author it matched in the call's context."""
def validate(self, arguments: Mapping[str, Any], context: ValidationContext) -> dict[str, Any]:
cleaned = super().validate(arguments, context)
matched = context.call_context.setdefault("forms_adapter.authors", {})
matched[cleaned["author"].pk] = cleaned["author"]
return cleaned
remembering_validator = RememberingBookValidator(BookForm)
setdefault hands back the dict an earlier validation of the same call made,
or makes it, so every validation of the call adds to one mapping: two calls of
validate() handed one context leave both authors there. The key is the
Validator's own, since every stage shares the dict. A context built by hand
has an empty dict of its own, so validate() called off dispatch writes to
that and needs no guard.
A formset over a many call¶
A many spec over a FormValidator validates each row with a form of its
own, so no rule sees the whole set. Hand it a formset class and it binds
every row into one formset instead, and the formset's clean() is the
rule over the set:
class LineForm(forms.Form):
title = forms.CharField(max_length=100)
class Lines(forms.BaseFormSet):
def clean(self) -> None:
titles = [form.cleaned_data.get("title") for form in self.forms]
if len(titles) != len(set(titles)):
raise forms.ValidationError("Each title once.", code="repeated")
LineSet = forms.formset_factory(LineForm, formset=Lines)
add_lines_spec = ServiceSpec(
service=lambda *, items: items,
permissions=[Unrestricted()],
many=True,
validator=FormValidator(LineForm, formset_class=LineSet),
)
The formset's form must be the validator's form, so for a factory that
builds its own (modelformset_factory always does) pass
FormValidator(BookSet.form, formset_class=BookSet). A refusal comes back as
the list's own node: each row's errors under the index the caller sent it at,
and what clean() or the formset's own max_num and min_num checks raise
under non_field_errors, {"items": {"non_field_errors": ["Each title once."]}}.
Every row sent is validated, even one equal to the fields' initials, which a
formset on a page would skip as an unchanged extra form. form_kwargs is
called once for the call, not once per row, and the bound formset is in the
pool as formset. A formset validates whole rows, so such a spec cannot be
partial, and a spec that is not many is refused when it is called.
Editing an existing set¶
A model formset edits the rows a collection selector resolves, and refuses a
call that resolves none. The validator then declares two more parameters
on each row: the model's key (id), optional, and DELETE, a boolean, when
the formset class says can_delete.
- A row with a key edits that row. Its form is bound to it, so an unchanged
unique field is not refused as a duplicate of itself. A key outside the
collection is refused under the row's
idasinvalid_choice: Django's own model formset would take any row of the model and quietly treat it as a new one, and the kernel holds the field to the collection. - A row with no key, or a
nullone, is a new row. - A row sent with
DELETE: trueskips its form's checks, as a formset does, and reaches the service with its key, the marker and the fields that cleaned: a field its form refused is missing from it, so it is not a whole row. Dispatch's shape check runs before the formset and refuses a row missing a required field. A row left out of the call is left alone. - Two rows naming one key are refused under
non_field_errors.
The service receives each row as its form's cleaned_data, the key cleaned
to the row it names (or None for a new one), in the order the caller sent
them; the rows it reads from the collection are not the instances the forms
wrote their values onto.
Refusals¶
A refusal is one
InvalidArguments
carrying the form's own errors and messages, {field: [messages]}. The
messages about the whole form, which Django keeps under "__all__", are
moved to non_field_errors: the key every other refusal in the kernel uses,
so a transport reads a form's refusal as it reads any other. See
Arguments and refusals for the tree.