Python Django inlineformset_工厂和许多领域
我正在尝试为以下模型创建表单集:Python Django inlineformset_工厂和许多领域,python,django,django-forms,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 =
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()
我得到一个错误,指出类别模型中不存在ForeignKey。是否可以使用ManyToManyField构建表单集,或者以某种方式复制此功能
谢谢 根据源代码和文档,它只适用于外键 因此,如果你想为你的模型创建一个表单集,你必须改变
categories = models.ManyToManyField(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``.
"""
是的,看起来你是对的。我正试图通过使用自己的init和save方法创建自定义字段来解决这个问题。@bento,我知道这有点过时了,但是你找到解决办法了吗?我和你的处境一样,我想知道你是如何解决的。不幸的是,我很久没有使用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``.
"""