API Reference¶
- class PydanticForm(*, csrf, fields, model=None)¶
Note
You will not manually construct this class, but instead use one of two classmethods for instantiation.
This serves as the main manager for handling form resolution with Pydantic. The object itself subclasses pydantic.BaseModel and has all features of a Pydantic model.
- Parameters
csrf (str) –
Represents a csrf token string that is generated by a Strategy.
create()creates the attribute to allow the user to embed it in hidden fields on the client.validate_request()will have the results of the form data
Pydantic-Forms expects and requires you to embed this token on each one of your HTML forms whether as a hidden field or otherwise.
fields (Dict[str, pydantic_forms.objects.FormField]) – A dictionary of all fields that are in the schema with the key being the form field name and the value being a FormField object.
model (Optional[pydantic_forms.forms.T]) –
The populated schema from the Pydantic model itself.
create()will always have the model as Nonevalidate_request <Pydantic.validate_request()will have the model as the pydantic model if validation was successful. Otherwise, None
- Return type
None
- async classmethod create(request, schema, strategy=<pydantic_forms.strategies.DefaultStrategy object>)¶
Creates the PydanticForm object from a typical request object. This method is generally called on a GET method for a particular endpoint.
# Fast API Example from pydantic import BaseModel from fastapi.requests import Request templates = Jinja2Templates(directory="my/template/directory") class MyForm(BaseModel): name: str age: int @app.get('/form', response_class=HTMLResponse) async def my_form(request: Request): form = PydanticForm.create(request, MyForm) return templates.TemplateResponse("/users/register.html", {"request": request, 'form': form})
- Parameters
request (Any) – The webserver ‘request’ object that is returned from the user.
schema (Type[pydantic.main.BaseModel]) – The class on which will act as the storage point for form data. This means that Pydantic models are flat with no nested models. All the magic of a normal BaseModel will work towards server-side validation such as validators.
strategy (pydantic_forms.interfaces.BaseStrategy) –
An instance that is inherited from BaseStrategy that is used to interpret the request object, insert csrf tokens into the session, and to parse validation errors that are returned from pydantic.
If no instance is supplied, a DefaultStrategy is used which is compatable with FastAPI async request objects.
- Returns
- Return type
- property is_valid: bool¶
A check if the form submission is valid and the model exists. :returns: :rtype:
bool
- async classmethod validate_request(request, schema, strategy=<pydantic_forms.strategies.DefaultStrategy object>)¶
Creates the PydanticForm object from a typical request object. This method is generally called on a POST method for a particular endpoint where it will then retrieve the form data.
# Fast API Example from pydantic import BaseModel from fastapi.requests import Request templates = Jinja2Templates(directory="my/template/directory") class MyForm(BaseModel): name: str age: int @app.post('/form', response_class=HTMLResponse) async def my_form(request: Request): form = await PydanticForm.validate_request(request, MyForm) if form.is_valid: model = form.model return f"Hello {model.name}, you are {model.age} years old" else: return templates.TemplateResponse("/users/register.html", {"request": request, 'form': form})
- If the form data received from the request object is valid
The model attribute will contain the Pydantic instance from schema.
- The FormField information in fields will be
error will contain an empty string
value will contain the validated value the user submitted and is equal to the attribute on the model
- If the form data caused a ValidationError
The model attribute will be None
- The FormField information in fields will be
error will contain the validation error message
value will contain the data the form data that was submitted by the user
- Parameters
request (Any) – The webserver ‘request’ object that is returned from the user.
schema (Type[pydantic.main.BaseModel]) – The class on which will act as the storage point for form data. This means that Pydantic models are flat with no nested models. All the magic of a normal BaseModel will work towards server-side validation such as validators.
strategy (pydantic_forms.interfaces.BaseStrategy) –
An instance that is inherited from BaseStrategy that is used to interpret the request object as well as provide csrf generation and checks
If no instance is supplied, a DefaultStrategy is used which is compatible with FastAPI async request objects
- Returns
- Return type
- property validated¶
Checks if the form has been validated. Useful for determining form state for client-side formatting.
- Returns
- Return type
bool
- class FormField(*, name, error='', value=None)¶
A Pydantic model that is created when using
PydanticForm- Parameters
name (str) – The name of the field from the HTML output. Corresponds to the field of the pydantic model.
error (str) – The error string if applicable after validation. For convenience, this is set as an empty string to make it easily injectable into HTML forms.
value (Optional[Any]) –
The value of the form field that the user submitted. This should not be used to access validated data. Use
PydanticForm.modelfor that.This is helpful to auto-populate forms with data the user entered after a server-side validation.
- Return type
None