From the View, how do I pass custom "choices" into a form's ChoiceField?
The get_initial
method is made to populate the initial value of the fields of your form. Not to set the available choices
or to modify your fields attributes.
To successfully passing your choices from your view to the form, you need to implement the get_form_kwargs
method in your view:
class PairRequestView(FormView):
form_class = PairRequestForm
def get_form_kwargs(self):
"""Passing the `choices` from your view to the form __init__ method"""
kwargs = super().get_form_kwargs()
# Here you can pass additional kwargs arguments to the form.
kwargs['favorite_choices'] = [('choice_value', 'choice_label')]
return kwargs
And in your form, get the choices from the kwargs argument in the __init__
method and set the choices on the field:
class PairRequestForm(forms.Form):
favorite_choices = forms.ChoiceField(choices=[], widget=RadioSelect, required=False)
def __init__(self, *args, **kwargs):
"""Populating the choices of the favorite_choices field using the favorites_choices kwargs"""
favorites_choices = kwargs.pop('favorite_choices')
super().__init__(*args, **kwargs)
self.fields['favorite_choices'].choices = favorites_choices
And voilà !
Another simple way of doing this would be:
class PairRequestView(FormView):
form_class = PairRequestForm
def get_form(self, *args, **kwargs):
requester_obj = Profile.objects.get(user__username=self.request.user)
favorites_set = requester_obj.get_favorites()
form = super().get_form(*args, **kwargs)
form.fields['favorite_choices'].choices = favorites_set
return form