【问题标题】:Custom Django CMS plugin template shows ManyToManyField as empty in published view自定义 Django CMS 插件模板在已发布视图中显示 ManyToManyField 为空
【发布时间】:2014-06-25 02:38:34
【问题描述】:

使用 ManyToMany 字段作为自定义 Django CMS 插件的一部分可能会在打开编辑模式时显示,但一旦发布,模板的行为就好像该字段中没有关联的对象一样。例如,如果您在 models.py 中将 authorized_personnel = models.ManyToManyField(Employee, blank=True, verbose_name='Authorized Personnel' 作为定义模型的一部分,则模板中的 {{ instance.authorized_personnel.all }} 在已发布视图中返回 [],即使它在编辑模式视图中按预期工作并返回列表从您的数据库中填充。你如何解决这个问题?

【问题讨论】:

    标签: python django plugins foreign-keys django-cms


    【解决方案1】:

    对于自定义模型,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

    【讨论】:

    • 在 DjangoCMS 3 中略有不同:def copy_relations(self, oldinstance): for associated_item in oldinstance.associated_item.all(): associated_item.pk = None associated_item.plugin = self associated_item.save() 更多信息:docs.django-cms.org/en/support-3.0.x/how_to/…
    猜你喜欢
    • 2017-03-20
    • 2012-05-26
    • 2012-09-24
    • 1970-01-01
    • 2019-09-20
    • 2019-08-07
    • 2013-04-05
    • 2014-07-18
    相关资源
    最近更新 更多