2014-10-13 5 views
0

Я не могу инициализировать форму Choicefield внутри views.py. Я попытался прохождения переменной option в функции __init__ но я получил ошибку:Динамически заполняемое поле выбора в Django

__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') 

EDIT

Я попробовал решение Hasan и Django Form Wizard прошел {'files': None, 'prefix': 'step2', 'initial': {}, 'data': None} в **kwarg в функции __init__ от SomeForm.

Я напечатал содержание в **kwarg и я получил:

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

+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') 
+0

У меня есть объект «NoneType», который не является итерируемым », тогда я попытался удалить' None' в 'choice = kwargs.pop ('choice', None)' и получил 'KeyError' с' choice'. – jtd92

+1

эта ошибка возникла из-за 'choice = Choice.objects.filter (question__text__exact = option)' return 'None'. –

+0

С помощью KeyError он связан с мастером формы Django, проходящим в '{'files': None, 'prefix': 'step2', 'initial': {}, 'data': None}' в 'kwarg' , Я не могу понять, как остановить это. – jtd92

0

FYI Мне нужно было создать форму с атрибутом данных, чтобы это работало. Например:

class SomeWizard(SessionWizardView): 

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

     # determine the step if not given 
     if step is None: 
      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 

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

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

В противном случае, когда форма была отправлена, она вернулась обратно в эту первую форму. Полное описание см. В разделе here. Я использую django 1.8.

Смежные вопросы