Django Formset 只有一个有数据的表单,剩下的有空数据

Django Formset has only one form with data, remaining have empty data

我正在使用 Django Formsets 来创建多个表单。 最初我只有一种形式,我使用 JavaScript 动态添加更多形式。 当我提交此表单时,request.POST 对象只有第一个表单的数据。 顺便说一下,如果我将 formset 设置为显示两个初始表单和 submit ,它就会同时拥有这两个表单。 当我使用 javaScript

添加新的时会出现问题
//forms.py
from django import forms

class AddUserForm(forms.Form):
first_name = forms.CharField(max_length=50)
last_name = forms.CharField(max_length=50)
email = forms.EmailField()
password1 = forms.CharField(widget=forms.PasswordInput)
password2 = forms.CharField(widget=forms.PasswordInput)


//views.py (this one to handle the get)
if request.method == 'GET':
    add_user_formset = formset_factory(AddUserForm, extra=1, max_num=6)
    context['add_user_formset'] = add_user_formset

//view.py (this one to handle the post of the form)
@login_required(login_url = reverse_lazy('login') )
def add_users(request, ir_id):
    if request.method == 'POST':
        my_form = formset_factory(AddUserForm)
        my_formset = my_form(request.POST)

        if my_formset.is_valid():
            for form in my_formset:
                if form.is_valid():
                    email = form.cleaned_data['email']
                    username = form.cleaned_data['email']
                    first_name = form.cleaned_data['first_name']
                    last_name = form.cleaned_data['last_name']
                    password = form.cleaned_data['password1']
                    user = User(email=email,first_name=first_name,last_name=last_name,username=username)
                    user.set_password(password)
                    user.save()
                    new_user_profile =  UserProfile.objects.get(id=user.id)
                    new_user_profile.user_role = users_role[0][0]
                    new_user_profile.save()
                    ir_obj = IR.objects.get(ir_id=int(ir_id))
                    ir_obj.users.add(new_user_profile)
    return HttpResponseRedirect(request.META.get('HTTP_REFERER'))



//template
<form action="{% url 'add_users' ir_id %}" method="post" >{% csrf_token %}
                    {{add_user_formset.management_form}}
                    {% for item in add_user_formset%}
                        <tr>
                            <td><div>{{item.first_name}}</div></td>
                            <td><div>{{item.last_name}}</div></td>
                            <td><div>{{item.email}}</div></td>
                            <td><div>{{item.password1}}</div></td>
                            <td><div>{{item.password2}}</div></td>
                        </tr>
                    {% endfor %}
                    <input type="submit" name="submit" class="btn btn-primary" value="Create account">
                    </form>





//JavaScript

    $(document).on("click", ".irStatus-add-another-user", function () {
    var count = parseInt($('#id_form-TOTAL_FORMS').val())
    var newRow = $('.add-users-table tbody tr:last').clone(true)

    newRow.find(':input').each(function(){
        var name = $(this).attr('name').replace('-' + (count-1) + '-','-' + (count) + '-');
        var id = 'id_' + name;
        $(this).attr('id', id);
        $(this).attr('name', name);
        $(this).val('');
    })
    newRow.appendTo('.add-users-table tbody')
    $('#id_form-TOTAL_FORMS').val(''+(count+1))
});

您需要通过 java 脚本增加管理表单中的 <form>-TOTAL_FORMS 字段,以及在添加新表单时,因为表单集使用此字段来确定提供的表单数量。 Formset Management Form docs