动态的字段数取决于Django上另一个字段的值

时间:2015-12-04 22:22:24

标签: python django python-2.7 django-forms

我想用字段room创建表单,它是整数字段。根据此字段的值,应创建相同数量的其他字段adultchildren,并且根据字段children,应创建相同数量的字段children_age。但当我将children字段留空时,它会上升"所有字段都需要" forms.py

class RoomsForm(forms.Form):
        rooms = forms.IntegerField(min_value=1)

class TouristsForm(forms.Form):
        adult = forms.IntegerField(label=(u'Adults'), min_value=1, initial=1, widget = forms.HiddenInput)
        children = forms.IntegerField(label=(u'Children'), min_value=1, required=False, widget = forms.HiddenInput)

class ChildrenAgeForm(forms.Form):
        children_age = forms.IntegerField(min_value=2, max_value=10, required=False, widget = forms.HiddenInput)

views.py

def RoomsForm(request):
        TouristsFormSet = formset_factory(TouristsForm)
        ChildrenAgeFormSet = formset_factory(ChildrenAgeForm)
        if request.method == 'POST':
                rooms_form = RoomsForm(request.POST, prefix='rooms_form')
                tourists_formset = TouristsFormSet(request.POST, prefix='tourists')
                childrenage_formset = ChildrenAgeFormSet(request.POST, prefix='childrenage')
                if rooms_form.is_valid() and tourists_formset.is_valid() and childrenage_formset.is_valid():
                        rooms = 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

我不知道为什么会这样。也许我选择错误的方式来实现它。希望你能帮助我。

0 个答案:

没有答案