2012-04-24 94 views
4

我试图创建以下型号一个formset:Django的inlineformset_factory和多对多领域

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

我得到一个错误,说明类别模型中没有ForeignKey。是否可以使用ManyToManyField构建一个formset,或以某种方式复制此功能?

谢谢!

回答

2

据其仅适用于外键

所以,如果你想为你的模型,你必须改变

categories = models.ManyToManyField(Category, null = True, blank = True) 

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

文档一个formset源代码和文档: 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``. 
    """ 
+1

是啊,看起来像你说得对。我试图通过使用我自己的init和save方法创建自定义字段来解决这个问题。 – bento 2012-04-24 19:43:12

+0

@bento,我知道这很老掉牙了,但是你有没有办法解决这个问题?我和你的情况一样,想知道你是如何解决它的。 – vleong 2015-09-16 14:11:11

+0

很久很久以来我很久以前就使用过Django了,我真的不记得我最终做了什么。抱歉! – bento 2015-09-16 17:43:58