2022-01-03 Django and HTMX Forms - with django-forms-dynamic by https://fediverse.org/bugbytesio

Description

In this post, we’ll look at a new Django Form library called django-forms-dynamic written by Jamie Matthews ( https://fediverse.org/j4mie ).

This library “resolves form field arguments dynamically when a form is instantiated, not when it’s declared” - allowing dynamic forms to be created, where the values of one field can be dependent on another.

This makes the library suitable for use with tools such as HTMX and Unpoly .

We are going to convert our example from this post, and instead make use of Django Forms, along with the django-forms-dynamic library.

The library provides a DynamicField form field that takes the normal field type as its first argument - for example, forms.ModelChoiceField or forms.CharField.

Any additional arguments are passed to the normal, wrapped field, but importantly can be callables which are called when the form is being instantiated.

The callable form of the field arguments takes the form instance itself as an argument, allowing for dynamic behaviour such as making a field’s values be contingent on the value of another form field.