2012-04-24 98 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