如何在单个Django表单中创建2个内联表单?

时间:2016-03-29 14:07:01

标签: django django-forms django-views

在我的 models.py 中,我有3个班级

class Member(models.Model):
    name = models.CharField(max_length=255)
    occupation = models.CharField(max_length=255)

class FamilyMember(models.Model):
    name = models.CharField(max_length=255)
    relationship = models.CharField(max_length=255)
    member = models.ForeignKey(Member)

class OtherClub(models.Model):
    name = models.CharField(max_length=255)
    member = models.ForeignKey(Member)

在我的 forms.py 中,我使用内联formset工厂来执行此操作:

class MemberForm(forms.ModelForm):
    class Meta:
        model = Member
        fields = [
            'name', 'occupation',
        ]

FamilyMemberFormSet = inlineformset_factory(Member, FamilyMember, fields=('name', 'relationship'))
OtherClubFormSet = inlineformset_factory(Member, OtherClub, fields=('name',))

然而,我迷失的部分是观点。如何在视图中实际将内联表单添加到我的表单变量中?目前,我的观点如下:

def member_edit(request, pk):
    member = Member.objects.get(pk=pk)

    if not request.user == member.user:
        return HttpResponse("You do not have the permission to do that.")

    if request.method == 'POST':
        member_form = MemberForm(request.POST, instance=member)

        if member_form.is_valid():
            member = member_form.save()
            return redirect('myapp:index')
    else:
        member_form = MemberForm(instance=member)

    return render(request, 'myapp/member_edit.html', {
        'member' : member,
        'member_form' : member_form,
    })

基本上简单的表单处理,但我不知道如何将内联表单添加到组合中,因为我处理2个内联表单,所以文档根本没用。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我喜欢使用django crispy form。请在此处http://django-crispy-forms.readthedocs.org/en/latest/crispy_tag_forms.html#rendering-several-forms-with-helpers查看以呈现多个表单