2014-05-07 57 views
0

使用多對多字段的自定義Django的CMS插件的一部分可能會顯示在編輯模式被打開,但一旦公佈,模板的行爲就好像沒有關聯在該領域的對象。例如,如果在models.py中將authorized_personnel = models.ManyToManyField(Employee, blank=True, verbose_name='Authorized Personnel'作爲定義模型的一部分,則模板中的{{ instance.authorized_personnel.all }}將在發佈視圖中返回[],即使它在編輯模式視圖中按預期工作並返回從數據庫填充的列表。你如何解決這個問題?自定義Django的CMS插件模板顯示ManyToManyField爲空,在發佈視圖

回答

4

對於自定義模型,copy_relations(self, oldinstance)方法必須被定義爲模型的一部分。在這種情況下,您會使用類似於:

def copy_relations(self, oldinstance): 
    self.authorized_personnel = oldinstance.authorized_personnel.all() 

這提供了Django在製作插件實例的已發佈副本時需要的信息。欲瞭解更多信息,請參閱文檔:http://docs.django-cms.org/en/latest/extending_cms/custom_plugins.html#handling-relations

+1

在DjangoCMS 3這是稍有不同: '高清copy_relations(個體經營,返回oldInstance): 在oldinstance.associated_item.all()associated_item: associated_item.pk =無 associated_item。插件=自 associated_item.save()' 更多信息:http://docs.django-cms.org/en/support-3.0.x/how_to/custom_plugins.html?highlight=copy_relations#for-foreign-key-關係 - 距其它物體 – jobima

相關問題