我根据初始用户选择动态生成表单。问题是:如何验证动态生成的字段?到目前为止,这是我的代码:
#forms.py
class SelectionForm(forms.Form):
what_to_order = forms.ChoiceField(
label=_('What do you want to order?'),
widget=forms.Select,
choices=[['invalid', 'Please Choose']] + sorted(choices.SELECTION_CHOICES))
def __init__(self, *args, **kwargs):
super(SelectionForm, self).__init__(*args, **kwargs)
self.fields['what_to_order'].choices = \
list(self.fields['what_to_order'].choices) + [('other', 'Other')]
def clean_what_to_order(self):
if self.cleaned_data['what_to_order'] == 'invalid':
raise forms.ValidationError('Please Make a Choice!')
return self.cleaned_data['what_to_order']
class OrderForm(forms.Form):
name = forms.CharField(label='Name')
def __init__(self, user_choice, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
# CHOICES is a dict of choices and their fields' detail
if user_choice in choices.CHOICES:
for field in choices.CHOICES[user_choice]:
self.fields[field] = form.CharField(
label=choices.CHOICES[user_choice][field]['label'],
help_text=choices.CHOICES[user_choice][field]['help_txt']
def clean_name(self):
if not self.cleaned_data['name']:
raise forms.ValidationError('Missing')
return self.cleaned_data['name']
def clean_category(self):
if not self.cleaned_data['category']:
raise forms.ValidationError('Missing')
return self.cleaned_data['category']
#views.py
def order(request):
if request.method == 'POST':
form = SelectionForm(request.POST)
if form.is_valid():
user_choice = form.cleaned_data['what_to_order']
# this will use - make_order() - below
return HttpResponseRedirect('/new_order/%s/' % (user_choice))
else:
form = SelectionForm()
return render_to_response('app_name/new_order.html', { 'form': form })
def make_order(request, user_choice):
if request.method == 'POST':
form = OrderForm(None, request.POST)
if form.is_valid():
form.process()
return HttpResponseRedirect('/new_order/thanks/')
else:
form = OrderForm(user_choice)
return render_to_response('app_name/last_step_order.html', { 'form': form })
当OrderForm无效时,仅返回“name”字段。其他字段(基于用户输入生成的字段)从表单中消失。我不明白是什么导致它。