Django SessionWizardView current step is missing from form_list after Ajax request

I have a process SessionWizardView

with conditional extra steps that at the end of the first step essentially asks, "Do you want to add another person", so my condition is generated by validating the cleaned data for the previous step;

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
)

      

I also have a dictionary that stores the step data behind a key accessed via a session cookie, which also contains a list of user information entered by the user. After the first form, this list appears as a select box, and when selected, triggers an Ajax call in SessionWizard

with kwargs, which invokes a method call that returns 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

      

If you step through the form without invoking the Ajax call, then the form is submitted and the dict condition behaves as expected. But if the Ajax is triggered and the data is returned to the form, after the form is submitted, the session data seems to be gone. Is there a way to change the way I got this setting so that I get_data()

can return data to the page without destroying the session?

I have it installed SESSION_ENGINE

on cached_db

on dev server, but I have a problem when you submit the first conditional form and syscalls get_next_step()

and then get_form_list()

the check condition no longer returns that first conditional form, so I am left with my default form list and ValueError

raised because which is current_step

no longer a part form_list

.

So to repeat, I go through my first form, run the first conditional form using the "add_another_person" field, which renders the form as expected, at which point form_list

it looks like this:

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

      

But as soon as additional_entrant_1

the Ajax method fires, then dispatches, form_list

runs through the dict condition and looks like this:

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

      

Could this be a problem when storing the session or is the session invalidating?

+3


source to share


1 answer


I always miss a simple explanation.

The request get()

SessionWizardView

flushes the store, and the Ajax call I was making hit the view as a get request, flushing the memory and also passing my information.



So, with a simple method override, get()

I solved this:

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

      

+1


source







All Articles