使用Django内联formset获取'modelformset_factory而不定义'字段'错误'。我究竟做错了什么?

时间:2016-03-29 13:39:01

标签: python django django-forms

我的 models.py 如下所示:

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)
    relation = models.CharField(max_length=255)
    member = models.ForeignKey(Member)

我正在尝试为成员表单中的家庭成员创建内联表单。为此,我使用inlineformset_factory

from django import forms
from myapp.models import *
from django.forms.models import inlineformset_factory

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

FamilyMemberFormSet = inlineformset_factory(Member, FamilyMember)

当我运行服务器时,出现以下错误:

"Calling modelformset_factory without defining 'fields' or "
django.core.exceptions.ImproperlyConfigured: Calling >modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited.

我做错了什么?

2 个答案:

答案 0 :(得分:14)

我不确定,但我认为您忘记将表单传递给inlineformset_factory

FamilyMemberFormSet = inlineformset_factory(Member, FamilyMember, form=MemberForm)

或者您应使用fields参数或exclude指定应包含/排除哪些字段。

请参阅Django doc about inlineformset_factory中的一些示例。

答案 1 :(得分:0)

你在这里:

FamilyMemberFormSet = inlineformset_factory(Member, FamilyMember, fields =['name', 'occupation',])