gpt4 book ai didi

python - Django inlineformset_factory 和 ManyToMany 字段

转载 作者:太空宇宙 更新时间:2023-11-03 11:33:52 26 4
gpt4 key购买 nike

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

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()

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

谢谢!

最佳答案

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

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

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

关于python - Django inlineformset_factory 和 ManyToMany 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302403/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com