In Django 1.8, the ChoiceField
's choices
argument can accept a callable:
def get_choices():
return [(1, "one"), (2, "two")]
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=get_choices)
In the above example, get_choices()
always returns the same choices. However, being able to assign a callable to choices
does not make much sense unless that callable knows something like, say, an object id, each time it is called. How can I pass such a thing to it?
You can't do it in the form declaration because the CallableChoiceIterator calls the function without arguments that he gets from here. Doing in the
__init__
Form method is easier than creating your own ChoiceField I guess. Here is what I suggest:That supposes that you have some Class Based View that looks that has a method like this :
P.S : The super() function call supposes you are using python 3