Django FormWizard如何动态更改form_list

时间:2013-09-28 15:18:13

标签: python django django-forms django-formwizard

我能to dynamically call one form related to the data I chose from the step ealier

但是当我使用done方法时,我可以看到我的form_list保持不变。

这就是我所做的:

def get_form_list(request, form_list=None):
    if form_list is None:
        form_list = [ProviderForm, DummyForm, ConsummerForm, DummyForm, \
                 ServicesDescriptionForm]
    return UserServiceWizard.as_view(form_list=form_list)(request)


class UserServiceWizard(SessionWizardView):
    instance = None

    def __init__(self, **kwargs):
        self.form_list = kwargs.pop('form_list')
        return super(UserServiceWizard, self).__init__(**kwargs)

    def get_form_instance(self, step):
        if self.instance is None:
            self.instance = UserService()
        return self.instance

    def get_context_data(self, form, **kwargs):
        data = self.get_cleaned_data_for_step(self.get_prev_step(
                                                    self.steps.current))
        if self.steps.current == '1':
            service_name = str(data['provider']).split('Service')[1]
            form = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ProviderForm')
            self.form_list['1'] = form #here my form is correctly change I can see 

        elif self.steps.current == '3':
            service_name = str(data['consummer']).split('Service')[1]
            form = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ConsummerForm')
            self.form_list['3'] = form

        context = super(UserServiceWizard, self).get_context_data(form=form,
                                                              **kwargs)
        return context


    def done(self, form_list, **kwargs):
        print self.form_list #here form_list contains ProviderForm, DummyForm, ConsummerForm, DummyForm, ServicesDescriptionForm

在第0步,我的form_list没问题:

{u'0': <class 'django_th.forms.wizard.ProviderForm'>, 
u'1': <class 'django_th.forms.wizard.DummyForm'>, 
u'2': <class 'django_th.forms.wizard.ConsummerForm'>, 
u'3': <class 'django_th.forms.wizard.DummyForm'>, 
u'4': <class 'django_th.forms.base.ServicesDescriptionForm'>}

在第1步我的form_list没问题:我们可以看到第二个表单是我预期的一个

{u'0': <class 'django_th.forms.wizard.ProviderForm'>, 
u'1': <class 'th_rss.forms.RssProviderForm'>, 
u'2': <class 'django_th.forms.wizard.ConsummerForm'>, 
u'3': <class 'django_th.forms.wizard.DummyForm'>, 
u'4': <class 'django_th.forms.base.ServicesDescriptionForm'>}

在第2步,我的form_list是ko;与第0步相同:我的第二种形式是返回DummyForm

{u'0': <class 'django_th.forms.wizard.ProviderForm'>, 
u'1': <class 'django_th.forms.wizard.DummyForm'>, 
u'2': <class 'django_th.forms.wizard.ConsummerForm'>,
u'3': <class 'django_th.forms.wizard.DummyForm'>, 
u'4': <class 'django_th.forms.base.ServicesDescriptionForm'>}

如何更改self.form_list并保留我在get_context_data中所做的更改,直到向导结束而不是每一步?

修改 这是完整的代码,与Rohan的建议一起工作正常:

def get_form(self, step=None, data=None, files=None):
    """
        change the form instance dynamically from the data we entered
        at the previous step
    """
    if step is None:
        step = self.steps.current

    if step == '1':
        # change the form
        prev_data = self.get_cleaned_data_for_step('0')
        service_name = str(prev_data['provider']).split('Service')[1]
        class_name = 'th_' + service_name.lower() + '.forms'
        form_name = service_name + 'ProviderForm'
        form_class = class_for_name(class_name, form_name)
        form = form_class(data)
    elif step == '3':
        # change the form
        prev_data = self.get_cleaned_data_for_step('2')
        service_name = str(prev_data['consummer']).split('Service')[1]
        class_name = 'th_' + service_name.lower() + '.forms'
        form_name = service_name + 'ConsummerForm'
        form_class = class_for_name(class_name, form_name)
        form = form_class(data)
    else:
        # get the default form
        form = super(UserServiceWizard, self).get_form(step, data, files)
    return form

def done(self, form_list, **kwargs):
    """
        Save info to the DB
        The process is :
        1) get the infos for the Trigger from step 0, 2, 4
        2) save it to TriggerService
        3) get the infos from the "Provider" and "Consummer" services
        at step 1 and 3
        4) save all of them
    """
    # get the datas from the form for TriggerService
    i = 0
    for form in form_list:
        # cleaning
        data = form.cleaned_data
        # get the service we selected at step 0 : provider
        if i == 0:
            trigger_provider = UserService.objects.get(
                name=data['provider'],
                user=self.request.user)
            model_provider = get_service_model('provider', data)
        # get the service we selected at step 2 : consummer
        elif i == 2:
            trigger_consummer = UserService.objects.get(
                name=data['consummer'],
                user=self.request.user)
            model_consummer = get_service_model('consummer', data)
        # get the description we gave for the trigger
        elif i == 4:
            trigger_description = data['description']
        i += 1

    # save the trigger
    trigger = TriggerService(
        provider=trigger_provider, consummer=trigger_consummer,
        user=self.request.user, status=True,
        description=trigger_description)
    trigger.save()

    model_fields = {}
    # get the datas from the form for Service related
    # save the related models to provider and consummer
    i = 0
    for form in form_list:
        model_fields = {}
        data = form.cleaned_data
        # get the data for the provider service
        if i == 1:
            for field in data:
                model_fields.update({field: data[field]})
            model_fields.update({'trigger_id': trigger.id, 'status': True})
            model_provider.objects.create(**model_fields)
        # get the data for the consummer service
        elif i == 3:
            for field in data:
                model_fields.update({field: data[field]})
            model_fields.update({'trigger_id': trigger.id, 'status': True})
            model_consummer.objects.create(**model_fields)
        i += 1

    return HttpResponseRedirect('/')

2 个答案:

答案 0 :(得分:6)

我认为更合适的方法是在向导视图中实现get_context_data()方法,并根据步骤和之前的数据返回不同的表单实例。

而不是更改get_form()中的表单列表等。

这样的事情:

class UserServiceWizard(SessionWizardView):
    instance = None

    def get_form(self, step=None, data=None, files=None):
        if step is None:
            step = self.steps.current

        prev_data = self.get_cleaned_data_for_step(self.get_prev_step(
                                                    self.steps.current))
        if step == '1':
            service_name = str(prev_data['provider']).split('Service')[1]
            form_class = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ProviderForm')
            form = form_class(data)
        elif step == '3':
            service_name = str(prev_data['consummer']).split('Service')[1]
            form_class = class_for_name('th_' + service_name.lower() + '.forms',
                                  service_name + 'ConsummerForm')
            form = form_class(data)
        else:
            form = super(UserServiceWizard, self).get_form(step, data, files)

        return form

这里的技巧是不要改变表单列表的长度(你已经正确完成),而只是改变表单实例。为了这个目的,Django已经提供了覆盖get_form()方法的方法。 Django将尊重此方法,并始终使用它来获取方法的表单实例。

答案 1 :(得分:0)

我不确定它是否是您正在寻找的解决方案,但是如果您在process_step而不是在get_context_data中修改form_list,它应该可以工作。您必须更改代码,因为在提交表单后执行process_step。

根据Django doc https://docs.djangoproject.com/en/1.5/ref/contrib/formtools/form-wizard/ process_step是“用于修改向导内部状态的钩子”,至少对于self.kwargs vars(事实上你的form_list是在self.kwargs [“form_list”])我有测试了get_context_data中的所有修改都被忽略了,所以我认为self.form_list应该以相同的方式运行。