我正在根据用户选择开发动态表单。这是一个两阶段的过程:首先,用户从单选按钮列表中进行选择,并根据该选择,向用户显示相应的表单字段。我知道如何使用类型,但我使用2种不同的形式(1个用于初始选择,1个用于自定义表单字段),以及2个不同的视图。 我有两个问题: 1)将这两种形式分开并有意见是否正确? 2)一旦用户填写了第二个(自定义)表单,我怎么能在运行时知道哪些字段 为了创建对象并将其保存到DB中,她被呈现给她?
class SelectionForm(forms.Form):
choice = forms.ModelChoiceField(queryset=Fruit.objects.filter(...)
widget=forms.RadioSelect,
initial='')
# views.py
def review(request):
if request.method == 'POST':
form = SelectionForm(request.POST)
if form.is_valid():
user_choice = form.cleaned_data['choice']
return HttpResponseRedirect('/new_order/%s' % (user_choice))
else:
form = SelectionForm()
return render_to_response( '/new_order.html', {'form': form} )
def order_fruit(request, user_choice):
if request.method == 'POST':
"""
make_order_form uses Python type to create a form
depending on user_choice
"""
form = make_order_form(request.POST, user_choice)
if form.is_valid():
# How to know which fields were presented to the user -
# in order to create the Order object with the right -
# arguments ????????????????????
return HttpResponseRedirect('/thanks/')
else:
form = make_order_form(request, user_choice)
return render_to_response('/second_step_order.html', { 'form':form })
答案 0 :(得分:0)
反思您的表格。看看'form.fields'或'form.cleaned_data'。