Python Ajax请求后,Django SessionWizardView表单_列表中缺少当前步骤

Python Ajax请求后,Django SessionWizardView表单_列表中缺少当前步骤,python,django,session,Python,Django,Session,我有一个SessionWizardView流程,其中包含有条件的额外步骤,在第一步结束时基本上会询问“是否要添加其他人”,因此我的条件是通过检查前一步的清理数据生成的 def function_factory(prev_step): """ Creates the functions for the condition dict controlling the additional entrant steps in the process. :param prev_st

我有一个
SessionWizardView
流程,其中包含有条件的额外步骤,在第一步结束时基本上会询问“是否要添加其他人”,因此我的条件是通过检查前一步的清理数据生成的

def function_factory(prev_step):
    """ Creates the functions for the condition dict controlling the additional
    entrant steps in the process.

    :param prev_step: step in the signup process to check
    :type prev_step: unicode
    :return: additional_entrant()
    :rtype:
    """
    def additional_entrant(wizard):
        """
        Checks the cleaned_data for the previous step to see if another entrant
        needs to be added
        """
        # try to get the cleaned data of prev_step
        cleaned_data = wizard.get_cleaned_data_for_step(prev_step) or {}

        # check if the field ``add_another_person`` was checked.
        return cleaned_data.get(u'add_another_person', False)

    return additional_entrant

def make_condition_stuff(extra_steps, last_step_before_repeat):
    cond_funcs = {}
    cond_dict = {}
    form_lst = [
        (u"main_entrant", EntrantForm),
    ]

    for x in range(last_step_before_repeat, extra_steps):
        key1 = u"{}_{}".format(ADDITIONAL_STEP_NAME, x)
        if x == 1:
            prev_step = u"main_entrant"
        else:
            prev_step = u"{}_{}".format(ADDITIONAL_STEP_NAME, x-1)
        cond_funcs[key1] = function_factory(prev_step)
        cond_dict[key1] = cond_funcs[key1]
        form_lst.append(
            (key1, AdditionalEntrantForm)
        )

    form_lst.append(
        (u"terms", TermsForm)
    )

    return cond_funcs, cond_dict, form_lst

last_step_before_extras = 1
extra_steps = settings.ADDITIONAL_ENTRANTS

cond_funcs, cond_dict, form_list = make_condition_stuff(
    extra_steps,
    last_step_before_extras
)
我还有一个字典,它将步骤数据存储在通过会话cookie访问的密钥后面,该密钥还包含用户输入的人员详细信息列表。在第一个表单之后,这个列表被呈现为一个选择框&on selection使用kwargs触发对
SessionWizard
的Ajax调用,kwargs触发对返回
JsonResponse
的方法的调用

class SignupWizard(SessionWizardView):
    template_name = 'entrant/wizard_form.html'
    form_list = form_list
    condition_dict = cond_dict
    model = Entrant
    main_entrant = None
    data_dict = dict()

    def get_data(self, source_step, step):
        session_data_dict = self.get_session_data_dict()
        try:
            data = session_data_dict[source_step].copy()
            data['event'] = self.current_event.id
            for key in data.iterkeys():
                if step not in key:
                    newkey = u'{}-{}'.format(step, key)
                    data[newkey] = data[key]
                    del data[key]
        except (KeyError, RuntimeError):
            data = dict()
            data['error'] = (
                u'There was a problem retrieving the data you requested. '
                u'Please resubmit the form if you would like to try again.'
            )

        response = JsonResponse(data)
        return response

    def dispatch(self, request, *args, **kwargs):
        response = super(SignupWizard, self).dispatch(
            request, *args, **kwargs
        )
        if 'get_data' in kwargs:
            data_id = kwargs['get_data']
            step = kwargs['step']
            response = self.get_data(data_id, step)

        # update the response (e.g. adding cookies)
        self.storage.update_response(response)
        return response

    def process_step(self, form):
        form_data = self.get_form_step_data(form)
        current_step = self.storage.current_step or ''
        session_data_dict = self.get_session_data_dict()

        if current_step in session_data_dict:
            # Always replace the existing data for a step.
            session_data_dict.pop(current_step)

        if not isinstance(form, TermsForm):
            entrant_data = dict()
            fields_to_remove = [
                'email', 'confirm_email', 'password',
                'confirm_password', 'csrfmiddlewaretoken'
            ]
            for k, v in form_data.iteritems():
                entrant_data[k] = v
            for field in fields_to_remove:
                if '{}-{}'.format(current_step, field) in entrant_data:
                    entrant_data.pop('{}-{}'.format(current_step, field))
                if '{}'.format(field) in entrant_data:
                    entrant_data.pop('{}'.format(field))

            for k in entrant_data.iterkeys():
                new_key = re.sub('{}-'.format(current_step), u'', k)
                entrant_data[new_key] = entrant_data.pop(k)

            session_data_dict[current_step] = entrant_data
            done = False
            for i, data in enumerate(session_data_dict['data_list']):
                if data[0] == current_step:
                    session_data_dict['data_list'][i] = (
                        current_step, u'{} {}'.format(
                            entrant_data['first_name'],
                            entrant_data['last_name']
                        )
                    )
                    done = True

            if not done:
                session_data_dict['data_list'].append(
                    (
                        current_step, u'{} {}'.format(
                            entrant_data['first_name'],
                            entrant_data['last_name']
                        )
                    )
                )

        return form_data
如果在不触发Ajax调用的情况下单步执行表单,那么表单将提交,并且条件dict的行为符合预期。但是如果Ajax被触发,并且数据被返回到表单,那么一旦提交表单,会话数据就会消失。是否有办法更改我的设置方式,以便
get_data()
可以将数据返回到页面,而不会破坏会话

我在开发服务器上将
会话引擎设置为
缓存的\u db
,但我遇到了一个问题,即当您提交第一个条件表单时,系统调用
get\u next\u step()
后跟
get\u form\u list()
并且条件检查不再返回第一个条件表单,因此我留下了默认表单列表,并引发了一个
ValueError
,因为
current\u step
不再是
表单列表的一部分

因此,总而言之,我一步一步地浏览我的第一个表单,使用“添加另一个人”字段触发第一个条件表单,该字段按预期呈现表单,此时
表单列表
如下所示

form_list   
    u'main_entrant' <class 'online_entry.forms.EntrantForm'>
    u'additional_entrant_1' <class 'online_entry.forms.EntrantForm'>
    u'terms' <class 'online_entry.forms.TermsForm'>
form_list   
    u'main_entrant' <class 'online_entry.forms.EntrantForm'>
    u'terms' <class 'online_entry.forms.TermsForm'>

这是会话存储的问题还是会话变得无效?

我总是忽略简单的解释

SessionWizardView
get()
请求重置存储,我正在进行的Ajax调用将视图作为get请求命中,重置存储,但也传回我的信息

通过对
get()
方法的简单重写,我解决了这个问题

def get(self, request, *args, **kwargs):
    if 'get_data' in kwargs:
        data_id = kwargs['get_data']
        step = kwargs['step']
        response = self.get_data(data_id, step)
    else:
        self.storage.reset()

        # reset the current step to the first step.
        self.storage.current_step = self.steps.first
        response = self.render(self.get_form())
    return response

用于确定向导中是否包含步骤的条件应在整个向导中保持一致。我的意思是,你可以决定进一步的步骤,但不能决定之前的步骤。检查前一步的条件是否在另一个步骤上突然改变。“LorenzoPe Na A,我会考虑我的条件是一致的,第一个表单具有相同的字段,因此条件是剩下的直到最后一个表格,因为这只是一个条款和条件复选框。是否有可能
向导。为步骤()获取数据get\u cleaned\u data\u结果。如果条件的计算结果不再为true,则数据将以某种方式更改。这有助于确定在哪里。