I am new to Django and I am making a project with a multistep form using django-formtools
. The problem is, in my step 2 form, I have selection fields that I need to pass in the backend to perform some calculations and then render the output. The user can make changes anytime based on the output. I made an apply changes
button which should trigger the backend process and a proceed to next step
button if the user decides to finalize the selected changes. However, when I click the apply changes
button, it leads me to the next step instead.
Here's my HTML
code:
<form action="" method="POST">
{% csrf_token %}
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ form }} # three selection fields
<button name="apply_changes">Apply Changes</button>
{% endif %}
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans '‹ Previous Step' %}</button>
{% endif %}
<input type="submit" value="{% trans 'Finish' %}">
</form>
Here's my SessionWizardView
method code snippet:
def get_context_data(self, form, **kwargs):
context = super(StepWizard, self).get_context_data(form=form, **kwargs)
if self.steps.current == 'step_1':
# save step 1 data to sessions
if self.steps.current == 'step_2':
step1_data = self.get_all_cleaned_data()
# if apply changes button is clicked
data = self.request.POST.get('apply_changes')
# process data
# add output to context
return context
I need help on how can it rightly be done. Thanks in advance!
So for future django developers who encountered the same problem as me, here's the answer to my question:
1) validate the data in step 2 which is temporarily the default values of my selection fields; and
2) override the post
method to load the current page using the goto_step
wizard function and embed it in the apply changes
button
You can find the guide here :)
And then there 'ya go! Once the user clicks the apply changes
button, the page reloads and the output is rendered in the form.
Still needs to optimize it though :D