ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python – Django inlineformset_factory和ManyToMany字段

2019-07-04 10:46:59  阅读:192  来源: 互联网

标签:python django django-forms


我正在尝试为以下模型创建一个formset:

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时,就像这样:

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

我收到一条错误,指出Category模型中没有ForeignKey.是否可以使用ManyToManyField构建表单集,或以某种方式复制此功能?

谢谢!

解决方法:

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

因此,如果您想为模型创建一个formset,则必须进行更改

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,django-forms
来源: https://codeday.me/bug/20190704/1376281.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有