Django inlineformset_factory 和 ManyToMany 字段 [英] Django inlineformset_factory and ManyToMany fields

查看:30
本文介绍了Django inlineformset_factory 和 ManyToMany 字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm attempting to create a formset for the following models:

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)

但是任何时候我尝试实现一个表单集,就像这样:

But any time I try to implement a formset, like so:

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

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

I get an error stating that no ForeignKey is present in the Category model. Is it possible to build a formset using a ManyToManyField, or to replicate this functionality in some way?

谢谢!

推荐答案

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

According to source code and documentation its only for foreign keys

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

So if you want create a formset for your models you have to change

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

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

文档:https://docs.djangoproject.com/en/1.4/主题/表单/modelforms/#inline-formsetshttps://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``.
    """

这篇关于Django inlineformset_factory 和 ManyToMany 字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆