Django在一个视图中的多个表单集不起作用

时间:2018-07-09 17:17:34

标签: python django view formset

我正在尝试在同一视图中使用多个表单集,并使用列表对其进行缩放。但是,它不起作用。我基于documentation为该代码建模。 但是,它会给管理表单篡改带来确认错误。

VIEWS.PY

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

model_names = ['A', 'B', 'C', 'D', 'E', 'F', 'G']

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="hidden" name="save" />
  {% endfor %}
  <input type="submit" value="Submit">
  </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__'

0 个答案:

没有答案