4

Is there a way to create an Html form from a pydantic model?

Let's start with an easy example. I have a model User:

from pydantic import BaseModel

class User(BaseModel):
    id: int
    name: str = 'Jane Doe'

and some magic function that transforms the User model into the following form:

<form>
  <label for="id">ID:</label><br>
  <input type="number" id="id" name="id"><br>
  <label for="name">Name:</label><br>
  <input type="text" id="name" name="name">
</form>

Of course, this can be arbitrarily complex e.g. when your model has Lists which might be a Dropdown selection field.

So I'm interested if this is somehow already possible? I would be using this in the context of FastAPI.

user7638008
  • 137
  • 9
  • I suppose that no such method exists. Maybe there's a 3rd party library, but writing such a method by yourself shouldn't be so complicated either, I suppose: Iterate over the non-private members of the class, and add an HTML string according to their type and properties. Finally, join the HTML strings to produce a HTML snippet. – Green绿色 May 24 '22 at 12:36
  • Piccolo Admin supports pydantic models in their form config object: https://piccolo-orm.com/blog/easy-forms-using-pydantic-and-piccolo-admin/ - reforms is also an option, although currently unmaintained: https://github.com/boardpack/reforms – MatsLindh May 24 '22 at 16:19

2 Answers2

1

You can generate a form from Pydantic's schema output. There are a few options, jsonforms seems to be best.

First generate json-schema from your model:

from pydantic import BaseModel, Field

class MyClass(BaseModel):
  name: str 
  # ... etc... 

json_schema = MyClass.schema() 

This outputs:

# -> {'title': 'MyClass', 'type': 'object', 'properties': {'name': {'title': 
# -> 'Name', #'type': 'string'}}, 'required': ["name"]}

You can use this output to automatically make a form with jsonforms (see example on homepage) it handles nested lists and objects fine and has lots of validation options on the front-end

For a more back-end solution you could use something like django forms, and there's a library for using jsonforms with django forms django-jsonforms it provides a JSONSchemaField that can be used like this:

class CustomForm(Form):    
    first_name = JSONSchemaField(schema = schema_from_above)

This can be used with a template engine like Jinja as the other answer points out...

Reed Jones
  • 1,367
  • 15
  • 26
-1

You are looking for a templating engine. A very popular one is Jinja.

There is also a whole chapter about templating with Jinja in the FastAPI docs.

This allows you the specify html templates that contain python like syntax to build what you want. You can pass in any data model and reference it inside the template.

thisisalsomypassword
  • 1,423
  • 1
  • 6
  • 17
  • OP is not looking for a template engine, they're looking for something to automagically generate and validate forms according to their pydantic models – MatsLindh May 24 '22 at 16:20