跳过Django FormWizard中的步骤
我有一个应用程序,里面有一个包含5个步骤的表单向导,其中有一个步骤只有在满足某些条件时才会出现。
这个表单是用于在线购物车的支付向导,其中一个步骤只有在有促销活动可供选择时才会显示,但如果没有促销活动,我希望跳过这个步骤,而不是显示一个空的促销列表。
所以我想要有两种可能的流程:
step1 - step2 - step3
step1 - step3
4 个回答
1
我用了另一种方法,重写了render_template这个方法。这里是我的解决方案。我之前不知道process_step()这个东西...
def render_template(self, request, form, previous_fields, step, context):
if not step == 0:
# A workarround to find the type value!
attr = 'name="0-type" value='
attr_pos = previous_fields.find(attr) + len(attr)
val = previous_fields[attr_pos:attr_pos+4]
type = int(val.split('"')[1])
if step == 2 and (not type == 1 and not type == 2 and not type == 3):
form = self.get_form(step+1)
return super(ProductWizard, self).render_template(request, form, previous_fields, step+1, context)
return super(ProductWizard, self).render_template(request, form, previous_fields, step, context)
4
如果你想让某些表单变成可选的,可以在你传给 FormView 的表单列表中加入一些条件,这样就能控制哪些表单是必填的,哪些是可以跳过的,具体的做法是在你的 urls.py 文件里进行设置。
contact_forms = [ContactForm1, ContactForm2]
urlpatterns = patterns('',
(r'^contact/$', ContactWizard.as_view(contact_forms,
condition_dict={'1': show_message_form_condition}
)),
)
想要查看完整的例子,可以参考 Django 的文档:https://django-formtools.readthedocs.io/en/latest/wizard.html#conditionally-view-skip-specific-steps
7
这个钩子方法 process_step() 正好给了你这样的机会。在表单验证通过后,你可以修改 self.form_list 这个变量,删除那些你不需要的表单。
当然,如果你的逻辑非常复杂,建议为每个步骤或表单创建单独的视图,这样可能会更好,而不必使用 FormWizard。