如何在 Django 的多步表单向导中创建一个选择按钮,该按钮呈现输出而不继续下一步?

How to make a selection button inside a multistep form wizard in Django that renders an output without proceeding to the next step?

我是 Django 的新手,我正在使用 django-formtools 制作一个包含多步表单的项目。问题是,在我的第 2 步表单中,我需要在后端传递选择字段以执行一些计算,然后呈现输出。用户可以根据输出随时进行更改。我做了一个 apply changes 按钮,它应该触发后端进程和一个 proceed to next step 按钮,如果用户决定完成选定的更改。但是,当我单击 apply changes 按钮时,它会引导我进入下一步。

这是我的 HTML 代码:

<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 '&#8249; Previous Step' %}</button>
  {% endif %}
  <input type="submit" value="{% trans 'Finish' %}"> 
</form>

这是我的 SessionWizardView 方法代码片段:

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

我需要有关如何正确完成它的帮助。提前致谢!

因此,对于遇到与我相同问题的未来 django 开发人员,这是我的问题的答案:

1) 验证步骤2中的数据,这些数据暂时是我选择字段的默认值;和 2) 使用goto_step 向导函数覆盖post 方法加载当前页面并将其嵌入apply changes 按钮

You can find the guide here :)

然后开始吧!用户单击 apply changes 按钮后,页面将重新加载并在表单中呈现输出。

不过还是需要优化:D