如果您阅读contrib/formtools/wizard.py 代码可能会有所帮助。它相当简单,遵循它会让您更好地了解您需要做什么。
其中有一个process_step 挂钩,您需要在自己的表单向导中覆盖它。我所做的是看看如果表单经过验证(即它有cleaned_data),我在哪一步做一些特殊处理:
class MyFormWizard(FormWizard):
def process_step(self, request, form, step):
if step == 0 and hasattr(form, 'cleaned_data'):
# Do special stuff
如果我正确理解您的问题,您希望第二步根据用户从第一个表单中的选择提供特定表单。在这种情况下,我可能首先尝试为第二步构建一个动态通用表单,其中使用的字段基于第一个表单的结果(未经测试):
def process_step(self, request, form, step):
if step == 0 and hasattr(form, 'cleaned_data'):
# The initial attribute is a dictionary which maps the step number
# to a dictionary of what should be initial values.
# You can use/abuse this in a form's constructor
self.initial[1] = {'fields': {'field1': field, 'field2': another}}
然后,在你的第二种形式
class MySecondForm(forms.Form):
def __init__(self, *args, **kwargs):
super(StatBuilderForm2, self).__init__(*args, **kwargs)
for name, field in kwargs['initial']['fields'].iteritems():
self.fields[name] = field