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(...)
Why isn’t this possible?
How else can I achieve the goal of passing data into class Test?
Thanks in advance.
This is a basic Python issue. You need to think about the order these commands are executed in, and their scope.
First, you define a form class called Test. That class has three attributes: a
set_choicesmethod, aget_choicesmethod, and anoptionsfield. These definitions are evaluated when the class itself is defined. The definition ofoptionscallsget_choices(). However, there is noget_choicesmethod in scope at that point, because the class is not yet defined.Even if you somehow managed to sort out the scope issue, this would still not do what you want, because the definition of choices for
optionsis done at define time. Even if you later callset_choices,optionsstill has the value ofget_choicesthat was returned when the field was defined.So, what do you actually want to do? It seems like you want to set dynamic choices on the
optionsfield. So, you should override the__init__method and define them there.