r_31415
r_31415

Reputation: 8972

Using dynamic Choice Field in Django

I have a choiceField in order to create a select field with some options. Something like this:

forms.py
    class NewForm(forms.Form):
        title = forms.CharField(max_length=69)
        parent = forms.ChoiceField(choices = CHOICE)

But I want to be able to create the options without having a predefined tuple (which is required by ChoiceField). Basically, I need to have access to request.user to fill some options tags according to each user, but I don't know if there is any way to use request in classes of forms.Form.

An alternative would be to prepopulate the instance of NewForm via:

views.py
form = NewForm(initial={'choices': my_actual_choices})

but I have to add a dummy CHOICE to create NewForm and my_actual_choices doesn't seem to work anyway.

I think a third way to solve this is to create a subclass of ChoiceField and redefined save() but I'm not sure how to go about doing this.

Upvotes: 9

Views: 6007

Answers (1)

surfeurX
surfeurX

Reputation: 1252

You can populate them dynamically by overriding the init, basically the code will look like:

class NewForm(forms.Form):
    def __init__(self, choices, *args, **kwargs):
        super(NewForm, self).__init__(*args, **kwargs)
        self.fields["choices"] = forms.ChoiceField(choices=choices)

NewForm(my_actual_choices) or NewForm(my_actual_choices, request.POST, request.FILES) etc.

Upvotes: 9

Related Questions