5

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

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 = inlineformset_factory(Category, Recipe, extra=3)
        formset = FormSet()

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

谢谢!

4

1 回答 1

1

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

所以如果你想为你的模型创建一个表单集,你必须改变

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 -同一个模型的一个外键

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``.
    """
于 2012-04-24T17:59:04.800 回答