FormSet只保存一个表单的数据

时间:2016-09-13 06:11:50

标签: python django django-forms

当我提交表单时(但在页面上我填写了id超过1个表单) - 我的FormSet只保存了一个表单的数据,其余的数据就消失了......

我的模板:

 <div id="data">
    <form method="post" action="/lookup/" id="test_data">{% csrf_token %}
    {{ formset.management_form }}
        {% for form in formset %}
            <section id="test_data_row">
            {{ form }}
            </section>
        {% endfor %}
    </form>
</div>
<div class="bt">
    <button type="submit" class="btn btn-default" id="submit_form" form="test_data">Submit</button>
    <button type="button" class="btn btn-default" id="add" value="Add row"/>Add row</button>
</div>

我的forms.py:

class LookupForm(forms.ModelForm):
   class Meta:
      model = look
      exclude = ()
LookupFormSet = formset_factory(LookupForm, can_delete=True)

我的模特

class look(models.Model):
    class Meta():
        db_table = 'lookup'
    id_device = models.CharField(max_length=75)
    phone_number = models.CharField(max_length=100)
    phone_number_country = models.CharField(max_length=1000)
    text = models.CharField(max_length=1000, default=None)

my views.py:

def manage_articles(request):
   LookupFormSet = modelformset_factory(model=look, exclude=())
   if request.method == "POST":
      formset = LookupFormSet(
         request.POST, request.FILES,
         queryset=look.objects.none(),
      )
      if formset.is_valid():
         for form in formset:
             form.save()
      return HttpResponseRedirect('/')
   else:
      formset = LookupFormSet(queryset=look.objects.none())
   return render(request, 'req/lookup.html', {'formset': formset})

我的JS(用于添加新表单的js):

document.getElementById('add').onclick = duplicate;
var i = 0;
var original = document.getElementById('test_data');
function duplicate() {
   var clone = original.cloneNode(true); // "deep" clone
   clone.id = "test_data" + ++i; // there can only be one element with an ID
   original.parentNode.appendChild(clone);
}

1 个答案:

答案 0 :(得分:0)

您无法保存formset,因为它包含多个表单。因此我建议您将代码更改为:

   if formset.is_valid():
       for form in formset:
            form.save()
       return HttpResponseRedirect('/')

请参阅docs