Django inlineformset_factory 和 ManyToMany 字段

ben*_*nto 6 python django django-forms

我正在尝试为以下模型创建表单集:

class Category(models.Model):

    name = models.CharField(max_length=100, unique=True)
    description = models.TextField(null = True, blank=True)

class Recipe(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()
    user = models.ForeignKey(User)
    categories = models.ManyToManyField(Category, null = True, blank = True)
Run Code Online (Sandbox Code Playgroud)

但每当我尝试实现表单集时,就像这样:

FormSet = inlineformset_factory(Category, Recipe, extra=3)
        formset = FormSet()
Run Code Online (Sandbox Code Playgroud)

我收到一条错误消息,指出类别模型中不存在外键。是否可以使用 ManyToManyField 构建表单集,或以某种方式复制此功能?

谢谢!

Efr*_*rin 1

根据源代码和文档,它仅适用于外键

因此,如果您想为模型创建表单集,则必须进行更改

categories = models.ManyToManyField(Category, null = True, blank = True)
Run Code Online (Sandbox Code Playgroud)

categories = models.ForeignKey("Category", null = True, blank = True)
Run Code Online (Sandbox Code Playgroud)

文档: https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#inline-formsets https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#more-than -同型号的一外键

姜戈来源:

def inlineformset_factory(parent_model, model, form=ModelForm,
                          formset=BaseInlineFormSet, fk_name=None,
                          fields=None, exclude=None,
                          extra=3, can_order=False, can_delete=True, max_num=None,
                          formfield_callback=None):
    """
    Returns an ``InlineFormSet`` for the given kwargs.

    You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
    to ``parent_model``.
    """
Run Code Online (Sandbox Code Playgroud)