Django inlineformset_factory and ManyToMany fields

六月ゝ 毕业季﹏ 提交于 2019-12-20 01:38:23

问题


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

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?

Thanks!


回答1:


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)

Documentation: 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 source:

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


来源:https://stackoverflow.com/questions/10302403/django-inlineformset-factory-and-manytomany-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!