factory和ManyToMany字段

factory和ManyToMany字段

本文介绍了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()

我收到一个错误,指出类别模型中没有ForeignKey。是否可以使用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)

to

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

文档:

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字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:11