Django访问formset数据

时间:2013-08-21 16:33:05

标签: django forms formset

我无法访问通过我的formset提交的数据。这是我的代码:

模板:

<form action="" method="post">
    {% csrf_token %}
    {{ formset.management_form }}
    {% for form in formset %}

    {{ form.as_p }}

    {% endfor %}

    <input type="submit" value="Submit">

</form>

查看:

def addMembers(request, id, members):
    if request.user.is_authenticated():
        members = int(members)
        MemberFormSet = formset_factory(MemberForm, extra = members)
        if request.method == 'POST':
            print 'post'
            formset = MemberFormSet(request.POST)
            if formset.is_valid():
                cd = formset.cleaned_data
                for f in formset:
                    first_name = cd.first_name
                    last_name = cd.last_name
                    email = cd.email
                    house = House.objects.get(id = id)
                    member = Member(first_name = first_name, last_name = last_name, email = email, house = house, created_on = timezone.now())
                    member.save()
                return HttpResponseRedirect(reverse('houses:controlPanel'))
        else:
            formset = MemberFormSet()
        return render_to_response('houses/add_members.html', {'formset' : formset}, context_instance = RequestContext(request))
    return HttpResponseRedirect(reverse('allauth.account.views.login'))

除了目前编写的内容之外,我尝试了几种访问数据的方法,包括: f['attribute'] cd['attribute'] request.POST['attribute'] formset.cleaned_data['attribute']

我收到的错误范围从u"Key 'email' not found in Form"list indices must be integers, not str

我应该如何访问formset提交的数据? Django的文档未能给出明确的答案,并且我在周围搜索找到了许多不同的方法,但没有一种方法可以使用。谢谢你的帮助。

2 个答案:

答案 0 :(得分:16)

cd是一本字典。此外,您可能希望从单个表单而不是formset

中获取字典值
if request.method == 'POST':
    formset = MemberFormSet(request.POST)
    if formset.is_valid():
        for f in formset: 
            cd = f.cleaned_data
            first_name = cd.get('first_name')
            last_name = cd.get('last_name')
            email = cd.get('email')
            house = House.objects.get(id = id)
            member = Member(first_name = first_name, last_name = last_name, email = email, house = house, created_on = timezone.now())
            member.save()
        return HttpResponseRedirect(reverse('houses:controlPanel'))

答案 1 :(得分:0)

我认为你应该使用model_formsetfactory,甚至更好的是inlineformset_factory。您正在从表单数据中填充模型,这是它们的设计目标。使用commit = False从formset中获取脏模型,并添加House关系。像这样:

MemberFormSet = model_formset_factory(Member, extra= members)
if request.method == POST:
    formset = MemberFormSet(request.POST)
    if formset.is_valid():
        house = House.objects.get(id = id)
        models = formset.save(commit=False)
        for member in models:
            member.house = house
            member.save()
        return render(<your data>)
else:
    formset = MemberFormSet()
return render(<your data>)

注意,如果House对象不存在,你的get()也会抛出异常。只是一个设计考虑因素。