I am developing a dynamic form based on user selection. It is a two-staged process: first the user selects from a list of radio buttons and depending on that selection, the user will be presented with appropriate form fields. I know how to do that using type, but I am using 2 different forms (1 for initial selection and 1 for the custom form fields), and 2 different views.
I have two questions:
1) is it right to separate these 2 forms and there views?
2) once the user has filled the 2nd (custom) form, how can I know at run time which fields
were presented to her in order to create the object and save it into the 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 })
Introspect your form. Have a look inside ‘form.fields‘ or ‘form.cleaned_data‘.