Django inlineformset_factory和ManyToMany字段

时间:2012-04-24 16:51:35

标签: python django django-forms

我正在尝试为以下模型创建一个formset:

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)

但是每当我尝试实现一个formset时,就像这样:

FormSet = inlineformset_factory(Category, Recipe, extra=3)
        formset = FormSet()

我收到一条错误,指出Category模型中没有ForeignKey。是否可以使用ManyToManyField构建表单集,或以某种方式复制此功能?

谢谢!

1 个答案:

答案 0 :(得分:2)

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

因此,如果您想为模型创建一个formset,则必须更改

categories = models.ManyToManyField(Category, null = True, blank = True)

categories = models.ForeignKey("Category", null = True, blank = True)

文档: https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#inline-formsets https://docs.djangoproject.com/en/1.4/topics/forms/modelforms/#more-than-one-foreign-key-to-the-same-model

Django来源:

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``.
    """