fh-pydantic-form 0.1.3__py3-none-any.whl → 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of fh-pydantic-form might be problematic. Click here for more details.

@@ -0,0 +1,675 @@
1
+ Metadata-Version: 2.4
2
+ Name: fh-pydantic-form
3
+ Version: 0.2.1
4
+ Summary: a library to turn any pydantic BaseModel object into a fasthtml/monsterui input form
5
+ Project-URL: Homepage, https://github.com/Marcura/fh-pydantic-form
6
+ Project-URL: Repository, https://github.com/Marcura/fh-pydantic-form
7
+ Project-URL: Documentation, https://github.com/Marcura/fh-pydantic-form
8
+ Author-email: Oege Dijk <o.dijk@marcura.com>
9
+ Maintainer-email: Oege Dijk <o.dijk@marcura.com>
10
+ License-File: LICENSE
11
+ Keywords: fasthtml,forms,monsterui,pydantic,ui,web
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Content Management System
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: monsterui>=1.0.19
22
+ Requires-Dist: pydantic>=2.0
23
+ Requires-Dist: python-fasthtml>=0.12.12
24
+ Description-Content-Type: text/markdown
25
+
26
+ # fh-pydantic-form
27
+
28
+ [![PyPI](https://img.shields.io/pypi/v/fh-pydantic-form)](https://pypi.org/project/fh-pydantic-form/)
29
+ [![GitHub](https://img.shields.io/github/stars/Marcura/fh-pydantic-form?style=social)](https://github.com/Marcura/fh-pydantic-form)
30
+
31
+ **Generate HTML forms from Pydantic models for your FastHTML applications.**
32
+
33
+ `fh-pydantic-form` simplifies creating web forms for [FastHTML](https://github.com/AnswerDotAI/fasthtml) by automatically generating the necessary HTML input elements based on your Pydantic model definitions. It integrates seamlessly with and leverages [MonsterUI](https://github.com/AnswerDotAI/monsterui) components for styling.
34
+
35
+ <img width="1348" alt="image" src="https://github.com/user-attachments/assets/59cc4f10-6858-41cb-80ed-e735a883cf20" />
36
+
37
+
38
+
39
+ <details >
40
+ <summary>show demo screen recording</summary>
41
+ <video src="https://private-user-images.githubusercontent.com/27999937/436237879-feabf388-22af-43e6-b054-f103b8a1b6e6.mp4" controls="controls" style="max-width: 730px;">
42
+ </video>
43
+ </details>
44
+
45
+ ## Table of Contents
46
+ 1. [Purpose](#purpose)
47
+ 2. [Installation](#installation)
48
+ 3. [Quick Start](#quick-start)
49
+ 4. [Key Features](#key-features)
50
+ 5. [Spacing & Styling](#spacing--styling)
51
+ 6. [Working with Lists](#working-with-lists)
52
+ 7. [Nested Models](#nested-models)
53
+ 8. [Literal & Enum Fields](#literal--enum-fields)
54
+ 9. [Initial Values & Enum Parsing](#initial-values--enum-parsing)
55
+ 10. [Disabling & Excluding Fields](#disabling--excluding-fields)
56
+ 11. [Refreshing & Resetting](#refreshing--resetting)
57
+ 12. [Label Colors](#label-colors)
58
+ 13. [Schema Drift Resilience](#schema-drift-resilience)
59
+ 14. [Custom Renderers](#custom-renderers)
60
+ 15. [API Reference](#api-reference)
61
+ 16. [Contributing](#contributing)
62
+
63
+ ## Purpose
64
+
65
+ - **Reduce Boilerplate:** Automatically render form inputs (text, number, checkbox, select, date, time, etc.) based on Pydantic field types and annotations.
66
+ - **Data Validation:** Leverage Pydantic's validation rules directly from form submissions.
67
+ - **Nested Structures:** Support for nested Pydantic models and lists of models/simple types with accordion UI.
68
+ - **Dynamic Lists:** Built-in HTMX endpoints and JavaScript for adding, deleting, and reordering items in lists within the form.
69
+ - **Customization:** Easily register custom renderers for specific Pydantic types or fields.
70
+ - **Robust Schema Handling:** Gracefully handles model changes and missing fields in initial data.
71
+
72
+ ## Installation
73
+
74
+ You can install `fh-pydantic-form` using either `pip` or `uv`.
75
+
76
+ **Using pip:**
77
+
78
+ ```bash
79
+ pip install fh-pydantic-form
80
+ ```
81
+
82
+ Using uv:
83
+ ```bash
84
+ uv add fh-pydantic-form
85
+ ```
86
+
87
+ This will also install necessary dependencies like `pydantic`, `python-fasthtml`, and `monsterui`.
88
+
89
+ ## Quick Start
90
+
91
+ ```python
92
+ # examples/simple_example.py
93
+ import fasthtml.common as fh
94
+ import monsterui.all as mui
95
+ from pydantic import BaseModel, ValidationError
96
+
97
+ # 1. Import the form renderer
98
+ from fh_pydantic_form import PydanticForm
99
+
100
+ app, rt = fh.fast_app(
101
+ hdrs=[
102
+ mui.Theme.blue.headers(),
103
+ # Add list_manipulation_js() if using list fields
104
+ # from fh_pydantic_form import list_manipulation_js
105
+ # list_manipulation_js(),
106
+ ],
107
+ pico=False, # Using MonsterUI, not PicoCSS
108
+ live=True, # Enable live reload for development
109
+ )
110
+
111
+ # 2. Define your Pydantic model
112
+ class SimpleModel(BaseModel):
113
+ """Model representing a simple form"""
114
+ name: str = "Default Name"
115
+ age: int
116
+ is_active: bool = True
117
+
118
+ # 3. Create a form renderer instance
119
+ # - 'my_form': Unique name for the form (used for prefixes and routes)
120
+ # - SimpleModel: The Pydantic model class
121
+ form_renderer = PydanticForm("my_form", SimpleModel)
122
+
123
+ # (Optional) Register list manipulation routes if your model has List fields
124
+ # form_renderer.register_routes(app)
125
+
126
+ # 4. Define routes
127
+ @rt("/")
128
+ def get():
129
+ """Display the form"""
130
+ return fh.Div(
131
+ mui.Container(
132
+ mui.Card(
133
+ mui.CardHeader("Simple Pydantic Form"),
134
+ mui.CardBody(
135
+ # Use MonsterUI Form component for structure
136
+ mui.Form(
137
+ # Render the inputs using the renderer
138
+ form_renderer.render_inputs(),
139
+ # Add standard form buttons
140
+ fh.Div(
141
+ mui.Button("Submit", type="submit", cls=mui.ButtonT.primary),
142
+ form_renderer.refresh_button("🔄"),
143
+ form_renderer.reset_button("↩️"),
144
+ cls="mt-4 flex items-center gap-2",
145
+ ),
146
+ # HTMX attributes for form submission
147
+ hx_post="/submit_form",
148
+ hx_target="#result", # Target div for response
149
+ hx_swap="innerHTML",
150
+ # Set a unique ID for the form itself for refresh/reset inclusion
151
+ id=f"{form_renderer.name}-form",
152
+ )
153
+ ),
154
+ ),
155
+ # Div to display validation results
156
+ fh.Div(id="result"),
157
+ ),
158
+ )
159
+
160
+ @rt("/submit_form")
161
+ async def post_submit_form(req):
162
+ """Handle form submission and validation"""
163
+ try:
164
+ # 5. Validate the request data against the model
165
+ validated_data: SimpleModel = await form_renderer.model_validate_request(req)
166
+
167
+ # Success: Display the validated data
168
+ return mui.Card(
169
+ mui.CardHeader(fh.H3("Validation Successful")),
170
+ mui.CardBody(
171
+ fh.Pre(
172
+ validated_data.model_dump_json(indent=2),
173
+ )
174
+ ),
175
+ cls="mt-4",
176
+ )
177
+ except ValidationError as e:
178
+ # Validation Error: Display the errors
179
+ return mui.Card(
180
+ mui.CardHeader(fh.H3("Validation Error", cls="text-red-500")),
181
+ mui.CardBody(
182
+ fh.Pre(
183
+ e.json(indent=2),
184
+ )
185
+ ),
186
+ cls="mt-4",
187
+ )
188
+
189
+ if __name__ == "__main__":
190
+ fh.serve()
191
+ ```
192
+
193
+ ## Key Features
194
+
195
+ - **Automatic Field Rendering:** Handles `str`, `int`, `float`, `bool`, `date`, `time`, `Optional`, `Literal`, nested `BaseModel`s, and `List`s out-of-the-box.
196
+ - **Sensible Defaults:** Uses appropriate HTML5 input types (`text`, `number`, `date`, `time`, `checkbox`, `select`).
197
+ - **Labels & Placeholders:** Generates labels from field names (converting snake_case to Title Case) and basic placeholders.
198
+ - **Descriptions as Tooltips:** Uses `Field(description=...)` from Pydantic to create tooltips (`uk-tooltip` via UIkit).
199
+ - **Required Fields:** Automatically adds the `required` attribute based on field definitions (considering `Optional` and defaults).
200
+ - **Disabled Fields:** Disable the whole form with `disabled=True` or disable specific fields with `disabled_fields`
201
+ - **Collapsible Nested Models:** Renders nested Pydantic models in accordion-style components for better form organization and space management.
202
+ - **List Manipulation:**
203
+ - Renders lists of simple types or models in accordion-style cards with an enhanced UI.
204
+ - Provides HTMX endpoints (registered via `register_routes`) for adding and deleting list items.
205
+ - Includes JavaScript (`list_manipulation_js()`) for client-side reordering (moving items up/down).
206
+ - Click list field labels to toggle all items open/closed.
207
+ - **Form Refresh & Reset:**
208
+ - Provides HTMX-powered "Refresh" and "Reset" buttons (`form_renderer.refresh_button()`, `form_renderer.reset_button()`).
209
+ - Refresh updates list item summaries or other dynamic parts without full page reload.
210
+ - Reset reverts the form to its initial values.
211
+ - **Custom Renderers:** Register your own `BaseFieldRenderer` subclasses for specific Pydantic types or complex field logic using `FieldRendererRegistry` or by passing `custom_renderers` during `PydanticForm` initialization.
212
+ - **Form Data Parsing:** Includes logic (`form_renderer.parse` and `form_renderer.model_validate_request`) to correctly parse submitted form data (handling prefixes, list indices, nested structures, boolean checkboxes, etc.) back into a dictionary suitable for Pydantic validation.
213
+
214
+ ## Spacing & Styling
215
+
216
+ `fh-pydantic-form` ships with two spacing presets to fit different UI requirements:
217
+
218
+ | Theme | Purpose | Usage |
219
+ |-------|---------|-------|
220
+ | **normal** (default) | Comfortable margins & borders – great for desktop forms | `PydanticForm(..., spacing="normal")` |
221
+ | **compact** | Ultra-dense UIs, mobile layouts, or forms with many fields | `PydanticForm(..., spacing="compact")` |
222
+
223
+ ```python
224
+ # Example: side-by-side normal vs compact forms
225
+ form_normal = PydanticForm("normal_form", MyModel, spacing="normal")
226
+ form_compact = PydanticForm("compact_form", MyModel, spacing="compact")
227
+ ```
228
+
229
+
230
+ **Important:** The compact CSS is now scoped with `.fhpf-compact` classes and only affects form inputs, not layout containers. This prevents conflicts with your application's layout system.
231
+
232
+ ## Working with Lists
233
+
234
+ When your Pydantic models contain `List[str]`, `List[int]`, or `List[BaseModel]` fields, `fh-pydantic-form` provides rich list manipulation capabilities:
235
+
236
+ ### Basic Setup
237
+
238
+ ```python
239
+ from fh_pydantic_form import PydanticForm, list_manipulation_js
240
+ from typing import List
241
+
242
+ app, rt = fh.fast_app(
243
+ hdrs=[
244
+ mui.Theme.blue.headers(),
245
+ list_manipulation_js(), # Required for list manipulation
246
+ ],
247
+ pico=False,
248
+ live=True,
249
+ )
250
+
251
+ class ListModel(BaseModel):
252
+ name: str = ""
253
+ tags: List[str] = Field(["tag1", "tag2"])
254
+ addresses: List[Address] = Field(default_factory=list)
255
+
256
+ form_renderer = PydanticForm("list_model", ListModel)
257
+ form_renderer.register_routes(app) # Register HTMX endpoints
258
+ ```
259
+
260
+ ### List Features
261
+
262
+ - **Add Items:** Each list has an "Add Item" button that creates new entries
263
+ - **Delete Items:** Each list item has a delete button with confirmation
264
+ - **Reorder Items:** Move items up/down with arrow buttons
265
+ - **Toggle All:** Click the list field label to expand/collapse all items at once
266
+ - **Refresh Display:** Use the 🔄 icon next to list labels to update item summaries
267
+ - **Smart Defaults:** New items are created with sensible default values
268
+
269
+ The list manipulation uses HTMX for seamless updates without page reloads, and includes JavaScript for client-side reordering.
270
+
271
+ ## Nested Models
272
+
273
+ Nested Pydantic models are automatically rendered in collapsible accordion components:
274
+
275
+ ```python
276
+ class Address(BaseModel):
277
+ street: str = "123 Main St"
278
+ city: str = "Anytown"
279
+ is_billing: bool = False
280
+
281
+ class User(BaseModel):
282
+ name: str
283
+ address: Address # Rendered as collapsible accordion
284
+ backup_addresses: List[Address] # List of accordions
285
+ ```
286
+
287
+ **Key behaviors:**
288
+ - Nested models inherit `disabled` and `spacing` settings from the parent form
289
+ - Field prefixes are automatically managed (e.g., `user_address_street`)
290
+ - Accordions are open by default for better user experience
291
+ - Schema drift is handled gracefully - missing fields use defaults, unknown fields are ignored
292
+
293
+ ## Literal & Enum Fields
294
+
295
+ `fh-pydantic-form` provides comprehensive support for choice-based fields through `Literal`, `Enum`, and `IntEnum` types, all automatically rendered as dropdown selects:
296
+
297
+ ### Literal Fields
298
+
299
+ ```python
300
+ from typing import Literal, Optional
301
+
302
+ class OrderModel(BaseModel):
303
+ # Required Literal field - only defined choices available
304
+ shipping_method: Literal["STANDARD", "EXPRESS", "OVERNIGHT"] = "STANDARD"
305
+
306
+ # Optional Literal field - includes "-- None --" option
307
+ category: Optional[Literal["ELECTRONICS", "CLOTHING", "BOOKS", "OTHER"]] = None
308
+ ```
309
+
310
+ ### Enum Fields
311
+
312
+ ```python
313
+ from enum import Enum, IntEnum
314
+
315
+ class OrderStatus(Enum):
316
+ """Order status enum with string values."""
317
+ PENDING = "pending"
318
+ CONFIRMED = "confirmed"
319
+ SHIPPED = "shipped"
320
+ DELIVERED = "delivered"
321
+ CANCELLED = "cancelled"
322
+
323
+ class Priority(IntEnum):
324
+ """Priority levels using IntEnum for numeric ordering."""
325
+ LOW = 1
326
+ MEDIUM = 2
327
+ HIGH = 3
328
+ URGENT = 4
329
+
330
+ class OrderModel(BaseModel):
331
+ # Required Enum field with default
332
+ status: OrderStatus = OrderStatus.PENDING
333
+
334
+ # Optional Enum field without default
335
+ payment_method: Optional[PaymentMethod] = None
336
+
337
+ # Required IntEnum field with default
338
+ priority: Priority = Priority.MEDIUM
339
+
340
+ # Optional IntEnum field without default
341
+ urgency_level: Optional[Priority] = Field(
342
+ None, description="Override priority for urgent orders"
343
+ )
344
+
345
+ # Enum field without default (required)
346
+ fulfillment_status: OrderStatus = Field(
347
+ ..., description="Current fulfillment status"
348
+ )
349
+ ```
350
+
351
+ ### Field Rendering Behavior
352
+
353
+ | Field Type | Required | Optional | Notes |
354
+ |------------|----------|----------|-------|
355
+ | **Literal** | Shows only defined choices | Includes "-- None --" option | String values displayed as-is |
356
+ | **Enum** | Shows enum member values | Includes "-- None --" option | Displays `enum.value` in dropdown |
357
+ | **IntEnum** | Shows integer values | Includes "-- None --" option | Maintains numeric ordering |
358
+
359
+ **Key features:**
360
+ - **Automatic dropdown generation** for all choice-based field types
361
+ - **Proper value handling** - enum values are correctly parsed during form submission
362
+ - **Optional field support** - includes None option when fields are Optional
363
+ - **Field descriptions** become tooltips on hover
364
+ - **Default value selection** - dropdowns pre-select the appropriate default value
365
+
366
+ ## Initial Values & Enum Parsing
367
+
368
+ `fh-pydantic-form` intelligently parses initial values from dictionaries, properly converting strings and integers to their corresponding enum types:
369
+
370
+ ### Setting Initial Values
371
+
372
+ ```python
373
+ # Example initial values from a dictionary
374
+ initial_values_dict = {
375
+ "shipping_method": "EXPRESS", # Literal value as string
376
+ "category": "ELECTRONICS", # Optional Literal value
377
+ "status": "shipped", # Enum value (parsed to OrderStatus.SHIPPED)
378
+ "payment_method": "paypal", # Optional Enum (parsed to PaymentMethod.PAYPAL)
379
+ "priority": 3, # IntEnum as integer (parsed to Priority.HIGH)
380
+ "urgency_level": 4, # Optional IntEnum as integer (parsed to Priority.URGENT)
381
+ "fulfillment_status": "confirmed" # Required Enum (parsed to OrderStatus.CONFIRMED)
382
+ }
383
+
384
+ # Create form with initial values
385
+ form_renderer = PydanticForm("order_form", OrderModel, initial_values=initial_values_dict)
386
+ ```
387
+
388
+ ### Parsing Behavior
389
+
390
+ The form automatically handles conversion between different value formats:
391
+
392
+ | Input Type | Target Type | Example | Result |
393
+ |------------|-------------|---------|--------|
394
+ | String | Enum | `"shipped"` | `OrderStatus.SHIPPED` |
395
+ | String | Optional[Enum] | `"paypal"` | `PaymentMethod.PAYPAL` |
396
+ | Integer | IntEnum | `3` | `Priority.HIGH` |
397
+ | Integer | Optional[IntEnum] | `4` | `Priority.URGENT` |
398
+ | String | Literal | `"EXPRESS"` | `"EXPRESS"` (unchanged) |
399
+
400
+ **Benefits:**
401
+ - **Flexible data sources** - works with database records, API responses, or any dictionary
402
+ - **Type safety** - ensures enum values are valid during parsing
403
+ - **Graceful handling** - invalid enum values are passed through for Pydantic validation
404
+ - **Consistent behavior** - same parsing logic for required and optional fields
405
+
406
+ ### Example Usage
407
+
408
+ ```python
409
+ @rt("/")
410
+ def get():
411
+ return mui.Form(
412
+ form_renderer.render_inputs(), # Pre-populated with parsed enum values
413
+ fh.Div(
414
+ mui.Button("Submit", type="submit", cls=mui.ButtonT.primary),
415
+ form_renderer.refresh_button("🔄"),
416
+ form_renderer.reset_button("↩️"), # Resets to initial parsed values
417
+ cls="mt-4 flex items-center gap-2",
418
+ ),
419
+ hx_post="/submit_order",
420
+ hx_target="#result",
421
+ id=f"{form_renderer.name}-form",
422
+ )
423
+
424
+ @rt("/submit_order")
425
+ async def post_submit_order(req):
426
+ try:
427
+ # Validates and converts form data back to proper enum types
428
+ validated_order: OrderModel = await form_renderer.model_validate_request(req)
429
+
430
+ # Access enum properties
431
+ print(f"Status: {validated_order.status.value} ({validated_order.status.name})")
432
+ print(f"Priority: {validated_order.priority.value} ({validated_order.priority.name})")
433
+
434
+ return success_response(validated_order)
435
+ except ValidationError as e:
436
+ return error_response(e)
437
+ ```
438
+
439
+ This makes it easy to work with enum-based forms when loading data from databases, APIs, or configuration files.
440
+
441
+ ## Disabling & Excluding Fields
442
+
443
+ ### Disabling Fields
444
+
445
+ You can disable the entire form or specific fields:
446
+
447
+ ```python
448
+ # Disable all fields
449
+ form_renderer = PydanticForm("my_form", FormModel, disabled=True)
450
+
451
+ # Disable specific fields only
452
+ form_renderer = PydanticForm(
453
+ "my_form",
454
+ FormModel,
455
+ disabled_fields=["field1", "field3"]
456
+ )
457
+ ```
458
+
459
+ ### Excluding Fields
460
+
461
+ Exclude specific fields from being rendered in the form:
462
+
463
+ ```python
464
+ form_renderer = PydanticForm(
465
+ "my_form",
466
+ FormModel,
467
+ exclude_fields=["internal_field", "computed_field"]
468
+ )
469
+ ```
470
+
471
+ **Important:** When fields are excluded from the UI, `fh-pydantic-form` automatically injects their default values during form parsing and validation. This ensures:
472
+
473
+ - **Hidden fields with defaults** are still included in the final validated data
474
+ - **Required fields without defaults** will still cause validation errors if not provided elsewhere
475
+ - **Default factories** are executed to provide computed default values
476
+ - **Nested BaseModel defaults** are converted to dictionaries for consistency
477
+
478
+ This automatic default injection means you can safely exclude fields that shouldn't be user-editable while maintaining data integrity.
479
+
480
+ ## Refreshing & Resetting
481
+
482
+ Forms support dynamic refresh and reset functionality:
483
+
484
+ ```python
485
+ mui.Form(
486
+ form_renderer.render_inputs(),
487
+ fh.Div(
488
+ mui.Button("Submit", type="submit", cls=mui.ButtonT.primary),
489
+ form_renderer.refresh_button("🔄 Refresh"), # Update display
490
+ form_renderer.reset_button("↩️ Reset"), # Restore initial values
491
+ cls="mt-4 flex items-center gap-2",
492
+ ),
493
+ # ... rest of form setup
494
+ )
495
+ ```
496
+
497
+ - **Refresh button** updates the form display based on current values (useful for updating list item summaries)
498
+ - **Reset button** restores all fields to their initial values with confirmation
499
+ - Both use HTMX for seamless updates without page reloads
500
+
501
+
502
+ ## Label Colors
503
+
504
+ Customize the appearance of field labels with the `label_colors` parameter:
505
+
506
+ ```python
507
+ form_renderer = PydanticForm(
508
+ "my_form",
509
+ MyModel,
510
+ label_colors={
511
+ "name": "text-blue-600", # Tailwind CSS class
512
+ "score": "#E12D39", # Hex color value
513
+ "status": "text-green-500", # Another Tailwind class
514
+ },
515
+ )
516
+ ```
517
+
518
+ **Supported formats:**
519
+ - **Tailwind CSS classes:** `"text-blue-600"`, `"text-red-500"`, etc.
520
+ - **Hex color values:** `"#FF0000"`, `"#0066CC"`, etc.
521
+ - **CSS color names:** `"red"`, `"blue"`, `"darkgreen"`, etc.
522
+
523
+ This can be useful for e.g. highlighting the values of different fields in a pdf with different highlighting colors matching the form input label color.
524
+
525
+
526
+ ## Setting Initial Values
527
+
528
+ You can set initial form values of the form by passing a model instance or dictionary:
529
+
530
+ ```python
531
+ initial_data = MyModel(name="John", tags=["happy", "joy"])
532
+ form_renderer = PydanticForm("my_form", MyModel, initial_values=initial_data)
533
+
534
+
535
+ initial_data_dict = {"name": "John"}
536
+ form_renderer = PydanticForm("my_form", MyModel, initial_values=initial_values_dict)
537
+ ```
538
+
539
+ The dictionary does not have to be complete, and we try to handle schema drift gracefully. If you exclude fields from the form, we fill those fields with the initial_values or the default values.
540
+
541
+
542
+
543
+ ### Schema Drift Resilience
544
+
545
+ `fh-pydantic-form` gracefully handles model evolution and schema changes:
546
+
547
+ Initial values can come from **older or newer** versions of your model – unknown fields are ignored gracefully and missing fields use defaults.
548
+
549
+ ```python
550
+ # Your model evolves over time
551
+ class UserModel(BaseModel):
552
+ name: str
553
+ email: str # Added in v2
554
+ phone: Optional[str] # Added in v3
555
+
556
+ # Old data still works
557
+ old_data = {"name": "John"} # Missing newer fields
558
+ form = PydanticForm("user", UserModel, initial_values=old_data)
559
+
560
+ # Newer data works too
561
+ new_data = {"name": "Jane", "email": "jane@example.com", "phone": "555-1234", "removed_field": "ignored"}
562
+ form = PydanticForm("user", UserModel, initial_values=new_data)
563
+ ```
564
+
565
+ **Benefits:**
566
+ - **Backward compatibility:** Old data structures continue to work
567
+ - **Forward compatibility:** Unknown fields are silently ignored
568
+ - **Graceful degradation:** Missing fields fall back to model defaults
569
+ - **Production stability:** No crashes during rolling deployments
570
+
571
+ ## Custom Renderers
572
+
573
+ The library is extensible through custom field renderers for specialized input types:
574
+
575
+ ```python
576
+ from fh_pydantic_form.field_renderers import BaseFieldRenderer
577
+ from fh_pydantic_form import FieldRendererRegistry
578
+
579
+ class CustomDetail(BaseModel):
580
+ value: str = "Default value"
581
+ confidence: Literal["HIGH", "MEDIUM", "LOW"] = "MEDIUM"
582
+
583
+ def __str__(self) -> str:
584
+ return f"{self.value} ({self.confidence})"
585
+
586
+ class CustomDetailFieldRenderer(BaseFieldRenderer):
587
+ """Display value input and dropdown side by side"""
588
+
589
+ def render_input(self):
590
+ value_input = fh.Div(
591
+ mui.Input(
592
+ value=self.value.get("value", ""),
593
+ id=f"{self.field_name}_value",
594
+ name=f"{self.field_name}_value",
595
+ placeholder=f"Enter {self.original_field_name.replace('_', ' ')} value",
596
+ cls="uk-input w-full",
597
+ ),
598
+ cls="flex-grow",
599
+ )
600
+
601
+ confidence_options = [
602
+ fh.Option(
603
+ opt, value=opt, selected=(opt == self.value.get("confidence", "MEDIUM"))
604
+ )
605
+ for opt in ["HIGH", "MEDIUM", "LOW"]
606
+ ]
607
+
608
+ confidence_select = mui.Select(
609
+ *confidence_options,
610
+ id=f"{self.field_name}_confidence",
611
+ name=f"{self.field_name}_confidence",
612
+ cls_wrapper="w-[110px] min-w-[110px] flex-shrink-0",
613
+ )
614
+
615
+ return fh.Div(
616
+ value_input,
617
+ confidence_select,
618
+ cls="flex items-start gap-2 w-full",
619
+ )
620
+
621
+ # Register the custom renderer (multiple ways)
622
+ FieldRendererRegistry.register_type_renderer(CustomDetail, CustomDetailFieldRenderer)
623
+
624
+ # Or pass directly to PydanticForm
625
+ form_renderer = PydanticForm(
626
+ "my_form",
627
+ MyModel,
628
+ custom_renderers=[(CustomDetail, CustomDetailFieldRenderer)],
629
+ )
630
+ ```
631
+
632
+ ### Registration Methods
633
+
634
+ - **Type-based:** `register_type_renderer(CustomDetail, CustomDetailFieldRenderer)`
635
+ - **Type name:** `register_type_name_renderer("CustomDetail", CustomDetailFieldRenderer)`
636
+ - **Predicate:** `register_type_renderer_with_predicate(lambda field: isinstance(field.annotation, CustomDetail), CustomDetailFieldRenderer)`
637
+
638
+ ## API Reference
639
+
640
+ ### PydanticForm Constructor
641
+
642
+ | Parameter | Type | Default | Description |
643
+ |-----------|------|---------|-------------|
644
+ | `form_name` | `str` | Required | Unique identifier for the form (used for HTMX routes and prefixes) |
645
+ | `model_class` | `Type[BaseModel]` | Required | The Pydantic model class to render |
646
+ | `initial_values` | `Optional[Union[BaseModel, Dict]]` | `None` | Initial form values as model instance or dictionary |
647
+ | `custom_renderers` | `Optional[List[Tuple[Type, Type[BaseFieldRenderer]]]]` | `None` | List of (type, renderer_class) pairs for custom rendering |
648
+ | `disabled` | `bool` | `False` | Whether to disable all form inputs |
649
+ | `disabled_fields` | `Optional[List[str]]` | `None` | List of specific field names to disable |
650
+ | `label_colors` | `Optional[Dict[str, str]]` | `None` | Mapping of field names to CSS colors or Tailwind classes |
651
+ | `exclude_fields` | `Optional[List[str]]` | `None` | List of field names to exclude from rendering (auto-injected on submission) |
652
+ | `spacing` | `SpacingValue` | `"normal"` | Spacing theme: `"normal"`, `"compact"`, or `SpacingTheme` enum |
653
+
654
+ ### Key Methods
655
+
656
+ | Method | Purpose |
657
+ |--------|---------|
658
+ | `render_inputs()` | Generate the HTML form inputs (without `<form>` wrapper) |
659
+ | `refresh_button(text=None, **kwargs)` | Create a refresh button component |
660
+ | `reset_button(text=None, **kwargs)` | Create a reset button component |
661
+ | `register_routes(app)` | Register HTMX endpoints for list manipulation |
662
+ | `parse(form_dict)` | Parse raw form data into model-compatible dictionary |
663
+ | `model_validate_request(req)` | Extract, parse, and validate form data from request |
664
+
665
+ ### Utility Functions
666
+
667
+ | Function | Purpose |
668
+ |----------|---------|
669
+ | `list_manipulation_js()` | JavaScript for list reordering and toggle functionality |
670
+ | `default_dict_for_model(model_class)` | Generate default values for all fields in a model |
671
+ | `default_for_annotation(annotation)` | Get sensible default for a type annotation |
672
+
673
+ ## Contributing
674
+
675
+ Contributions are welcome! Please feel free to open an issue or submit a pull request.
@@ -0,0 +1,14 @@
1
+ fh_pydantic_form/__init__.py,sha256=auqrMQyy6WsEeiMIdXVrjHpSuW_L7CpW2AZ1FOXb8QE,4058
2
+ fh_pydantic_form/defaults.py,sha256=IzBA_soBOdXP_XAUqfFAtniDQaW6N23hiXmWJD2xq0c,5168
3
+ fh_pydantic_form/field_renderers.py,sha256=OsyN1SLHE18GT42Oe1fs2xXXFErSU8Qx86h8DkeZ6-4,53504
4
+ fh_pydantic_form/form_parser.py,sha256=9jSJya4TR5q2LMGV_PK-xiAjoEhq-FYKDN27lFNn5n0,24389
5
+ fh_pydantic_form/form_renderer.py,sha256=2f1n--_DD891x1-2ci4JFBVmO8yO7X_b5Ol8W5SA42E,35580
6
+ fh_pydantic_form/list_path.py,sha256=AA8bmDmaYy4rlGIvQOOZ0fP2tgcimNUB2Re5aVGnYc8,5182
7
+ fh_pydantic_form/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ fh_pydantic_form/registry.py,sha256=sufK-85ST3rc3Vu0XmjjjdTqTAqgHr_ZbMGU0xRgTK8,4996
9
+ fh_pydantic_form/type_helpers.py,sha256=bWHOxu52yh9_79d_x5L3cfMqnZo856OsbL4sTttDoa4,4367
10
+ fh_pydantic_form/ui_style.py,sha256=6QeE4mw0IUEmaTkXPPkKwxjOTwRLpa5auH4S2Dho7nc,4233
11
+ fh_pydantic_form-0.2.1.dist-info/METADATA,sha256=S44iSa9r6R5CZzo-1h4aCgGhEl1DFAGD4s5IWJZSDN4,26356
12
+ fh_pydantic_form-0.2.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
13
+ fh_pydantic_form-0.2.1.dist-info/licenses/LICENSE,sha256=AOi2eNK3D2aDycRHfPRiuACZ7WPBsKHTV2tTYNl7cls,577
14
+ fh_pydantic_form-0.2.1.dist-info/RECORD,,