Django Formset只有一个包含数据的表单,剩下的都是空数据

时间:2016-04-03 15:28:32

标签: django forms django-forms formsets

我使用Django Formsets来拥有多种形式。 最初我只有一个表单,我动态地使用JavaScript添加更多表单。 当我提交此表单时,request.POST对象只有第一个表单的数据。 顺便说一句,如果我将formset设置为显示两个初始表单并提交,则它具有两者。 当我使用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))
});

1 个答案:

答案 0 :(得分:0)

当您添加新表单时,您还需要通过java脚本从管理表单中增加$('tr#colors td').each(function(i){ var elem=$('td[orderId="'+i+'"]'); elem.remove(); $('tr#colors').append(elem); }); 字段,因为表单集使用此字段来确定提供的表单数量。 Formset Management Form docs

相关问题