Skip to content Skip to sidebar Skip to footer

Dynamically Populating Choicefield In Django

I can't initialize the Choicefield form inside the views.py. I tried passing the option variable in the __init__ function but I got an error: __init__() takes at least 2 arguments

Solution 1:

try this change(I comment changed line):

forms.py:

classSomeForm(forms.Form):
    def__init__(self, *args, **kwargs): #this line changed
        choice = kwargs.pop('choice', None) #this line added
        self.fields['choices'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in choice])
        super(SomeForm, self).__init__(*args, **kwargs)

views.py:

classSomeWizard(SessionWizardView):

    defget_form(self, step=None, data=None, files=None):
        form = super(SomeWizard, self).get_form(step, data, files)

        if step == "step2":
            option = self.get_cleaned_data_for_step("step1")['choice']

            choice = Choice.objects.filter(question__text__exact=option)

            form = SomeForm(choice=choice) #this line changedreturn form

    defget_template_names(self):
        return [TEMPLATES[self.steps.current]]

    defdone(self, form_list, **kargs):
        return render_to_response('done.html')

Solution 2:

FYI I had to init the form with the data attribute for this to work. For example:

classSomeWizard(SessionWizardView):

    defget_form(self, step=None, data=None, files=None):
        form = super(SomeWizard, self).get_form(step, data, files)

        # determine the step if not givenif step isNone:
            step = self.steps.current

        if step == "2":
            option = self.get_cleaned_data_for_step("1")['choice']

            choice = Choice.objects.filter(question__text__exact=option)


            ## Pass the data when initing the form, which is the POST## data if the got_form function called during a post## or the self.storage.get_step_data(form_key) if the form wizard## is validating this form again in the render_done methodform 
            form = SomeForm(choice=choice, data=data) 

        return form

defget_template_names(self):
    return [TEMPLATES[self.steps.current]]

defdone(self, form_list, **kargs):
    return render_to_response('done.html')

Otherwise when the form was submitted it just returned my back to this first form. For a full explanation see here. I am using django 1.8 though.

Post a Comment for "Dynamically Populating Choicefield In Django"