Django循环表单集导致管理表单中的ValidationError

Django looping formsets cause ValidationError in management form

我正在尝试输出两个相同的表单并将它们保存到具有不同前缀的数据库中。我用这个 post https://collingrady.wordpress.com/2008/02/18/editing-multiple-objects-in-django-with-newforms/ 作为例子。但是我收到管理表单被篡改的验证错误。能否请您指教如何解决?谢谢。

在这种情况下,如果我想稍后检索数据进行分析,是否可以通过前缀过滤数据库。

VIEWS.PY

from django.shortcuts import render
from .forms import modelformset_factory, AssumptionsForm
from .models import Assumptions

model_names = ['Form1', 'Form2']

def get_assumptions(request):

    AssumptionsFormset = modelformset_factory(
    Assumptions, form=AssumptionsForm, extra=5)

    if request.method == 'POST':

        formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names]

        if all([formset.is_valid() for formset in formsets]):

            for formset in formsets:

                for form in formset:

                    form.save()

    else:

        formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names]

    return render(request, 'assumptions.html', {'formsets': formsets})

ASSUMPTIONS.HTML

<div class="form">
  <form action="" method="post">
  {% csrf_token %}
  {% for formset in formsets %}
  {{ formset.management_form }}
  {{ formset.non_form_errors.as_ul }}
  <h1>{{formset.prefix}}</h1>
  <table id="formset" class="form">
  {% for form in formset.forms %}
    {% if forloop.first %}
    <thead><tr>
      {% for field in form.visible_fields %}
      <th>{{ field.label|capfirst }}</th>
      {% endfor %}
    </tr></thead>
    {% endif %}
    <tr class="{% cycle 'row1' 'row2' %}">
    {% for field in form.visible_fields %}
      <td>
      {# Include the hidden fields in the form #}
      {% if forloop.first %}
        {% for hidden in form.hidden_fields %}
        {{ hidden }}
        {% endfor %}
      {% endif %}
        {{ field.errors.as_ul }}
        {{ field }}
      </td>
    {% endfor %}
    </tr>
  {% endfor %}
  </table>
  <input type="submit" value="Submit">
  {% endfor %}
  </form>
  </div>

MODELS.PY

from django.db import models
from django.forms import ModelForm

class Assumptions(models.Model):

    Worst = models.FloatField(null=True, blank=True, default=None)
    Base = models.FloatField(null=True, blank=True, default=None)
    Best = models.FloatField(null=True, blank=True, default=None)

FORMS.PY

from django import forms
from django.forms import modelformset_factory, ModelForm
from .models import Assumptions

class AssumptionsForm(ModelForm):

    class Meta:
        model = Assumptions
        fields = '__all__'

您正尝试在 GET 请求中使用 request.POST 初始化表单集,这当然行不通。

替换第二个

formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names]

formsets = [AssumptionsFormset(prefix=thing) for thing in model_names]