Django formset只保存多个表单的第一种形式

时间:2015-05-26 23:00:09

标签: javascript django django-forms formset

我有一个渲染表单集的视图,但是当我在数据库中提交表单时,只保存了第一个表单。

查看

@login_required(login_url='/login/')
def PrecioFechaView(request):
    class RequiredFormSet(BaseFormSet):
          def __init__(self, *args, **kwargs):
              super(RequiredFormSet, self).__init__(*args, **kwargs)
              for form in self.forms:
                  form.empty_permitted = False

    pfformset = formset_factory(PrecioFechaForm, max_num=50, formset=RequiredFormSet)

    if request.method == 'POST':
       formset = pfformset(request.POST)
       for form in formset.forms:
           if form.is_valid():
              obj = form.save(commit=False)
              obj.usuario = request.user
              obj.save()
              return HttpResponseRedirect('/preciofecha/')
    else:
       formset = pfformset()

    return render_to_response("preciofecha.html",
                              {'cformset':formset},
                              context_instance=RequestContext(request))

为了渲染模板,我使用了这个JS函数:

$(document).ready(function () { 
    function updateElementIndex(el, prefix, ndx) {
        var id_regex = new RegExp('(' + prefix + '-\\d+-)');
        var replacement = prefix + '-' + ndx + '-';
        if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex,
        replacement));
        if (el.id) el.id = el.id.replace(id_regex, replacement);
        if (el.name) el.name = el.name.replace(id_regex, replacement);
    }

    function deleteForm(btn, prefix) {
        var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
        if (formCount > 1) {
            $(btn).parents('.item').remove();
            var forms = $('.item'); // Get all the forms  
            $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
            var i = 0;
            for (formCount = forms.length; i < formCount; i++) {
                $(forms.get(i)).children().children().each(function () {
                    if ($(this).attr('type') == 'text') updateElementIndex(this, prefix, i);
                });
            }
        } // End if
        else {
            alert("You have to enter at least one todo item!");
        }
        return false;
    }
    function addForm(btn, prefix) {
        var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
        // You can only submit a maximum of 10 todo items 
        if (formCount < 10) {
            var row = $(".item:first").clone(false).get(0);
            $(row).removeAttr('id').hide().insertAfter(".item:last").slideDown(300);
            $(".errorlist", row).remove();
            $(row).children().removeClass("error");
            $(row).children().children().each(function () {
                updateElementIndex(this, prefix, formCount);
                $(this).val("");
            });
            $(row).find(".delete").click(function () {
                return deleteForm(this, prefix);
            });
            $("#id_" + prefix + "-TOTAL_FORMS").val(formCount + 1);
        } 
        else {
            alert("Sorry, you can only enter a maximum of ten items.");
        }
        return false;
    }
    $("#add").click(function () {
        return addForm(this, "form");
    });

    $(".delete").click(function () {
        return deleteForm(this, "form");
    });
});

在模板中:

<div class="module filtered" id="changelist">
   <form action="" method="POST">{% csrf_token %}
      <div class="results">
          {{ cformset.management_form }}
          {% for form in cformset.forms %}
            <div class="item">
               {{ form.as_p }}     
               <p style=""><a class="delete" href="#">Delete</a></p>
            </div>
          {% endfor %}
          <p><a id="add" href="#">Add another item</a></p>
          <input type="submit" value=" Submit " />
      </div><!-- results -->
   </form>
</div><!-- module-filtered -->

我不知道我的错误是什么。 我不知道我的错误是在JS函数中还是我试图在视图中保存所有表单。

我有另一个带有formset的视图,并保存所有表单没有任何问题。唯一的区别是:

无错误地查看:

...
if request.method == 'POST':
       formset = ccformset(request.POST)
       for form in formset.forms:
           if form.is_valid():
              form.save()
       return HttpResponseRedirect('/home/')
...

查看错误

...
if request.method == 'POST':
   formset = pfformset(request.POST)
   for form in formset.forms:
       if form.is_valid():
          obj = form.save(commit=False)
          obj.usuario = request.user
          obj.save()
          return HttpResponseRedirect('/preciofecha/')
...

任何建议或建议??

提前致谢

0 个答案:

没有答案