How can I pass a value to Django Form's init method from a view?
Asked Answered
T

1

6

forms.py

class AddDuration(forms.Form):

    def __init__(self, *args, **kwargs): 
        super(AddDuration, self).__init__(*args, **kwargs)
        // set value to relates_to_choices
        relates_to_choices = ????????????? // Something like self.choices
        self.fields['duration'].choices = relates_to_choices

    duration = forms.ChoiceField(required=True)

Now, I have a views.py file that has a class

class AddDurationView(FormView):
    template_name = 'physician/add_duration.html'
    form_class = AddDurationForm
Terri answered 28/1, 2015 at 23:31 Comment(0)
S
8

Override the get_form_kwargs() method on the view.

views.py

class AddDurationView(FormView):
    template_name = 'physician/add_duration.html'
    form_class = AddDurationForm

    def get_form_kwargs(self):
        kwargs = super(AddDurationView, self).get_form_kwargs()
        kwargs['duration_choices'] = (
            ('key1', 'display value 1'),
            ('key2', 'display value 2'),
        )
        return kwargs

forms.py

class AddDurationForm(forms.Form):
    duration = forms.ChoiceField(required=True)

    def __init__(self, duration_choices, *args, **kwargs): 
        super(AddDurationForm, self).__init__(*args, **kwargs)
        // set value to duration_choices
        self.fields['duration'].choices = duration_choices
Series answered 28/1, 2015 at 23:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.