Skip to main content
 首页 » 编程设计

python之如何根据 page1 上的选择在 page2 上生成动态 MultipleChoiceField 选项

2025年05月04日12xing901022

我正在写 2 页。我想做的是,根据 page1 中选择的数据,生成一个带有 MultipleChoiceField 的表单,其中包含由 page1 结果计算的选项。或者根据文件读取也可以,只需以 page2 形式获取 MultipleChoiceField 的选项。

我用的是表单模板,在forms.py中,在page2的表单类中,

class FormPage2(forms.Form):  
    forms.MultipleChoiceField(label='sth to choose',choices=get_tochoose_choices()) 

get_tochoose_choices() 正在读取一些 txt 文件以获取选项。

但是当我加载第一页时,(我认为 python 实例化所有表单,不管它是否在这个页面上或不在一起)这个文件不存在,这意味着 FormPage2 无法实例化。即使文件在那里,也不是最新的。

那我该怎么办呢?我对网站设计很陌生,希望有人能提供帮助...

请您参考如下方法:

我相信您要做的是根据第一个表单中选择的选项动态构建第二个表单。

我不得不为我的一个项目做类似的事情,发现这个链接非常有用:http://jacobian.org/writing/dynamic-form-generation/

您需要重写第二个方法的 __init__ 方法,从而在该表单初始化期间初始化选项。

第二种形式的代码应该是这样的..

def __init__(self, *args, **kw): 
    #first remove my custom keyword from the list of keyword args 
    try: 
        customer = kw['customer'] 
        kw.pop('customer') 
    except: 
        customer=None 
 
    super(forms.Form, self).__init__(*args, **kw) 
    #now we dynamically add the customer choices - accepts partners as an input 
    partners = get_partner_list(customerid=customer.id) 
    self.fields['customer'].choices = [(p.id, p.customername) for p in partners] 

从第一个表单接收到输入后,您可以将其作为关键字参数传递给第二个表单。 然后在第二种形式的 __init__ 中弹出该关键字参数并使用它通过编辑 self.fields['fieldneedsdynamicchoices'].choices