Django WizardForm和第二个表单将是“动态的” [英] Django WizardForm and second form will be "dynamic"
问题描述
我有两种形式(真的4),第一种形式有单选按钮,第二种形式将不同如果用户选择x单选按钮选项。
喜欢我的英语对不起。
/ p>
First Form有一个带有单选按钮的选项,选项带有调用表单,我有3个表单等待。
我正在阅读WizardForm,但我不知道如何以动态方式带来第二种形式。
请帮助一下: (
谢谢
如果您阅读 contrib / formtools / wizard.py
代码,这是相当简单的,下面将让您更好地了解您需要做什么。
有一个 process_step
钩子,你需要在你自己的表单向导中覆盖我做的是看看我在做一些特殊处理的步骤,如果表单验证(即它有 clean_data
):
$ b $
def process_step(self,request,form,step):
如果step == 0和hasattr (form,'cleaning_data'):
#做特殊的东西
如果我明白你的问题正确地,您希望第二步根据用户从第一种形式的选择提供特定的表单。在这种情况下,我首先尝试的是为第二步构建一个动态通用表单,其中使用的字段基于第一个表单(未测试)的结果:
$ $ $ $ $ $ $ $ $ $ $ $ $ $
$ b $属性是将步骤号
#映射到应该是初始值的字典的字典。
#您可以使用/滥用此表单的构造函数
self.initial [1] = {'fields':{'field1':field,'field2':another}}
然后,在第二个表单
class MySecondForm(forms.Form):
def __init __(self,* args,** kwargs):
super(StatBuilderForm2,self).__ init __(* args,** kwargs)
名称,字段在kwargs ['initial'] ['fields']。iteritems():
self.fields [name] = field
i have 2 day's thinking how make this.
I have two forms (really 4), the first form have radio buttons, where the second form will be different if the user choice x radio button option.
Like alway's sorry with my English.
ill explain :
First Form have an options with radio buttons, with the options ill bring the "called form", i have 3 form's waiting for.
I was reading about WizardForm, but i don't know how bring the second form in dynamic way.
Please a need some help with this :(
Thanks
It will probably help if you read the contrib/formtools/wizard.py
code. It's fairly straightforward and following it will give you a better sense of what you need to do.
There is a process_step
hook in there which you'll need to override in your own form wizard. What I did is look at what step I was at do some special processing if the form validated (ie, it had cleaned_data
):
class MyFormWizard(FormWizard):
def process_step(self, request, form, step):
if step == 0 and hasattr(form, 'cleaned_data'):
# Do special stuff
If I understand your question correctly, you want the 2nd step to serve a particular form based on the user's choice from the 1st form. In that case, what I might try first is to build a dynamic generic form for the 2nd step, where the fields used are based on the results from the first form (untested):
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}}
Then, in your 2nd form
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
这篇关于Django WizardForm和第二个表单将是“动态的”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!