在Django中动态填充选择域

时间:2014-10-13 18:20:27

标签: python django django-forms choicefield

我无法在Choicefield内初始化views.py表单。我尝试在option函数中传递__init__变量,但是我收到了错误:

__init__() takes at least 2 arguments (1 given)` coming from the `form = super(SomeeWizard, self).get_form(step, data, files)

forms.py

class SomeForm(forms.Form):
        def __init__(self, choice, *args, **kwargs):
            super(SomeForm, self).__init__(*args, **kwargs)
            self.fields['choices'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in choice])

views.py

class SomeWizard(SessionWizardView):

    def get_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)

        return form

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

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

修改

我尝试了Hasan解决方案,Django表单向导将{'files': None, 'prefix': 'step2', 'initial': {}, 'data': None}传递到**kwarg __init__函数中的SomeForm

我在**kwarg打印了内容,我得到了:

{'files': None, 'prefix': 'step2', 'initial': {}, 'data': None} {'choices': [<Choice: Blue>, <Choice: Red>]}

2 个答案:

答案 0 :(得分:0)

尝试此更改(我评论更改了行):

forms.py

class SomeForm(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

class SomeWizard(SessionWizardView):

    def get_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 changed

        return form

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

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

答案 1 :(得分:0)

仅供参考我必须使用data属性初始化表单才能生效。例如:

extend self

否则,当表单提交时,它只是返回到第一个表单。有关完整说明,请参阅here。我虽然使用django 1.8。