假设我想要一个系统,其中5个人想要一次注册服务,所有这些都是从同一天开始的。
明确:5个名称字段(传递额外= 5)和一个日期字段。
我尝试过BaseFormSet和add_fields,但后来我也得到了五个日期字段。
示例forms.py:
class NameForm(forms.Form):
name = forms.CharField()
class DateForm(form.Form):
date = forms.DateField()
示例views.py:
NameFormSet = formset_factory(NameForm, extra=5)
#The line under will not work, but illustrates what I want to do.
NameFormSet.append(DateForm)
if request.method = 'POST':
formset = NameFormSet(request.POST)
#Do validation etc..
else:
formset = NameFormSet()
return render_to_response('template.html', { 'formset' : formset })
请帮助=)
答案 0 :(得分:3)
你可以只包含另一个DateForm吗?
NameFormSet = formset_factory(NameForm, extra=5)
if request.method = 'POST':
formset = NameFormSet(request.POST)
date_form = DateForm(request.POST)
if formset.is_valid() and date_Form.is_valid():
date = date_form.cleaned_data['date']
for form in formset:
name = form.cleaned_data['name']
# replace registration with registration model name
registration = Registration(name=name, date=date)
registration.save()
return
else:
formset = NameFormSet()
date_form = DateForm()
return render_to_response('template.html', { 'formset' : formset, 'date_form' : date_form })