将数据传递到django表单

Rus*_*ell 3 python django

class Test(forms.Form):

    def set_choices(self, choices):
        self.choices = choices

    def get_choices(self):
        return self.choices

    options  = forms.ChoiceField(choices=get_choices())

f = Test()
f.set_choices(...)
Run Code Online (Sandbox Code Playgroud)

为什么这不可能?
如何才能实现将数据传递到Test类的目标?
提前致谢.

Dan*_*man 9

这是一个基本的Python问题.您需要考虑执行这些命令的顺序及其范围.

首先,定义一个名为Test的表单类.该类有三个属性:set_choices方法,get_choices方法和options字段.定义类本身时,将评估这些定义.options电话的定义get_choices().但是,get_choices此时范围内没有方法,因为尚未定义类.

即使你以某种方式设法解决了范围问题,这仍然不会做你想要的,因为选择的定义options 是在定义时完成的.即使您稍后调用set_choices,options仍然具有在get_choices定义字段时返回的值.

那么,你真的想做什么?看起来你想在options场上设置动态选择.因此,您应该覆盖该__init__方法并在那里定义它们.

class Test(forms.Form):
    options = forms.ChoiceField(choices=())

    def __init__(self, *args, **kwargs):
        choices = kwargs.pop('choices', None)
        super(Test, self).__init__(*args, **kwargs)
        if choices is not None:
            self.fields['options'].choices = choices
Run Code Online (Sandbox Code Playgroud)