0

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

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

意见.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})

假设.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>

模型.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)

表格.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__'
4

1 回答 1

1

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

更换第二个

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

formsets = [AssumptionsFormset(prefix=thing) for thing in model_names]
于 2018-07-09T18:55:43.570 回答