![]() |
VOOZH | about |
Django Formsets allow managing multiple instances of the same form on a single page. Instead of creating each form Django Formsets simplify managing multiple instances of the same form on a single page. Instead of creating each form separately, formsets group them together, allowing all forms to be displayed, validated, and processed simultaneously.
For instance, when users need to add multiple articles at once, a formset can render several article forms together, making it easier to handle multiple inputs efficiently.
Consider a project named 'geeksforgeeks' having an app named 'geeks'.
In forms.py, define a simple form, syntax:
field_name = forms.FieldType(attributes)
Each field name appears on the left, and its type and attributes are defined on the right.
In views.py, import formset_factory and create a view to render the formset:
In templates/home.html, display the formset:
management_form is required for Django to track and validate formset data.
Run the server:
python manage.py runserver
Visit: "http://localhost:8000/"
The formset is now functional. Next, modify it to explore additional features and customization options available in Django Formsets.
By default, a formset displays one form. To show multiple forms, use the extra parameter:
GeeksFormSet = formset_factory(GeeksForm, extra=5) # Shows 5 forms
formset = GeeksFormSet()
The keyword argument "extra" makes multiple copies of same form. If one wants to create 5 forms enter extra = 5 and similarly for others.
Visit: "http://localhost:8000/" to check 5 forms:
To handle submitted data, update view to bind POST data and validate:
Enter data in the formset through:
👁 enter-formset-data-django-formsets
Data will be display in command line where server is running:
👁 django-formsets-use-data1Read Next Article:Django ModelFormSets