Наборы форм Django
Наборы форм в Django - это продвинутый способ обработки нескольких форм на одной веб-странице. Другими словами, наборы форм - это группа форм в Django. Может потребоваться инициализировать несколько форм на одной странице, каждая из которых может включать несколько запросов POST, например
из форм импорта django класс GeeksForm (forms.Form): title = forms.CharField () pub_date = forms.DateField ()
Теперь можно разрешить пользователю создавать статьи сразу, поэтому, если мыслить обычным образом, можно использовать несколько форм и разные имена для каждой формы для обработки данных на одной странице, но это усложнит код, а также функциональность. Набор форм - это уровень абстракции для работы с несколькими формами на одной странице. Лучше всего его сравнить с сеткой данных.
Теперь, чтобы создать набор форм этой GeeksForm ,
из django.forms импортировать formset_factory GeeksFormSet = formset_factory (GeeksForm)
Создание и использование наборов форм Django
Illustration of Rendering Django Forms Manually using an Example. Consider a project named geeksforgeeks
having an app named geeks
.
Refer to the following articles to check how to create a project and an app in Django.
- How to Create a Basic Project using MVT in Django?
- How to Create an App in Django ?
In your geeks app make a new file called forms.py where you would be making all your forms. To create a Django form you need to use Django Form Class. Let’s demonstrate how,
In your forms.py
Enter the following,
from django import forms # create a form class GeeksForm(forms.Form): title = forms.CharField() description = forms.CharField() |
Let’s explain what exactly is happening, left side denotes the name of the field and to right of it, you define various functionalities of an input field correspondingly. A field’s syntax is denoted as
Syntax :
Field_name = forms.FieldType(attributes)
Now to create a simple formset of this form, move to views.py and create a formset_view
as below.
from django.shortcuts import render # relative import of forms from .forms import GeeksForm # importing formset_factory from django.forms import formset_factory def formset_view(request): context = {} # creating a formset GeeksFormSet = formset_factory(GeeksForm) formset = GeeksFormSet() # Add the formset to context dictionary context[ "formset" ] = formset return render(request, "home.html" , context) |
To render the formset through HTML, create a html file “home.html”. Now let’s edit templates > home.html
< form method = "POST" enctype = "multipart/form-data" > {% csrf_token %} {{ formset.as_p }} < input type = "submit" value = "Submit" > </ form > |
All set to check if our formset is working or not let’s visit http://localhost:8000/.
.
Our formset is working completely. Let’s learn how to modify this formset to use extra features of this formset.
How to create Multiple forms using Django Formsets
Django formsets are used to handle multiple instances of a form. One can create multiple forms easily using extra
attribute of Django Formsets. In geeks/views.py,
from django.shortcuts import render # relative import of forms from .forms import GeeksForm # importing formset_factory from django.forms import formset_factory def formset_view(request): context = {} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 5 ) formset = GeeksFormSet() # Add the formset to context dictionary context[ "formset" ] = formset return render(request, "home.html" , context) |
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 if 5 forms are created.
Handling Multiple forms using Django Formsets
Creating a form is much easier than handling the data entered into those fields at the back end. Let’s try to demonstrate how one can easily use the data of a formset in a view. When trying to handle formset, Django formsets required one extra argument {{ formset.management_data }}. To know more about Management data, visit Understanding the ManagementForm.
In templates/home.html
,
< form method = "POST" enctype = "multipart/form-data" > <!-- Management data of formset --> {{ formset.management_data }} <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ formset.as_p }} < input type = "submit" value = "Submit" > </ form > |
Now to check how and what type of data is being rendered edit formset_view to print the data. In geeks/view.py
,
from django.shortcuts import render # relative import of forms from .forms import GeeksForm # importing formset_factory from django.forms import formset_factory def formset_view(request): context = {} # creating a formset and 5 instances of GeeksForm GeeksFormSet = formset_factory(GeeksForm, extra = 3 ) formset = GeeksFormSet(request.POST or None ) # print formset data if it is valid if formset.is_valid(): for form in formset: print (form.cleaned_data) # Add the formset to context dictionary context[ "formset" ] = formset return render(request, "home.html" , context) |
Now let’s try to enter data in the formset through http://localhost:8000/
Hit submit and data will be display in command line where server is running. One can use this data in any manner conveniently now.
Formset is advanced stuff which can be used to resolve a number of problems but should be used with correct syntax and field validations otherwise conflicts and errors will disrupt the normal functioning. To know more about Formsets, Visit Official Documentation for Formsets.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course