How can a ChoiceField.choices callable know what choices to return?
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:
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=())
def __init__(self, *args, **kwargs):
# Let's pass the object id as a form kwarg
self.object_id = kwargs.pop('object_id')
# django metaclass magic to construct fields
super().__init__(*args, **kwargs)
# Now you can get your choices based on that object id
self.fields['my_choice_field'].choices = your_get_choices_function(self.object_id)
That supposes that you have some Class Based View that looks that has a method like this :
class MyFormView(FormView):
# ...
def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
kwargs['object_id'] = 'YOUR_OBJECT_ID_HERE'
return kwargs
# ...
P.S : The super() function call supposes you are using python 3