Answer the question
In order to leave comments, you need to log in
What is the correct way to use a Django form along with a formset?
Hello, I want to create a form in which there is a numeric field, depending on the value of the numeric field, additional fields are added to the form. I decided to implement this by creating two forms, one form is a numeric value, and the second is a set of forms that are added depending on the value of the field in the first form.
Here is an example of my forms.py
class HotelForm(forms.Form):
rooms = forms.IntegerField(label=(u'Количество номеров'), min_value=1, initial=1)
class TouristsForm(forms.Form):
adult = forms.IntegerField(label=(u''), min_value=1, initial=1)
children = forms.IntegerField(label=(u''), min_value=1, required=False)
def bookingForm(request):
TouristsFormSet = formset_factory(TouristsForm)
if request.method == 'POST':
booking_form = HotelForm(request.POST, prefix='booking_form')
tourists_formset = TouristsFormSet(request.POST, prefix='tourists')
if booking_form.is_valid() and tourists_formset.is_valid():
rooms = form.cleaned_data['rooms']
for i in range(0, tourists_formset.total_form_count()):
tourists_form = tourists_formset.forms[i]
print tourists_form.cleaned_data
...
else:
booking_form = HotelForm()
tourists_formset = TouristsFormSet(prefix='tourists')
return render(request, 'booking/booking.html', { 'booking_form' : booking_form, 'tourists_formset' : tourists_formset,' })
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question