A
A
Alexey2015-12-01 03:08:31
Django
Alexey, 2015-12-01 03:08:31

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)

views.py
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,' })

When filling out the form in the template and submitting the data, I am informed that each field is required, although I have filled in all the fields correctly. I understand that this is due to the fact that I am not using the is_valid method correctly. Please help me figure it out. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Skver0, 2015-12-01
@Skver0

djbook.ru/rel1.7/ref/contrib/formtools/form-wizard.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question