【问题标题】:Usage related_name queryset with Django CMS plugin使用 Django CMS 插件的相关名称查询集
【发布时间】:2016-04-04 21:55:38
【问题描述】:

Python 3

Django 1.9

Django-CMS 3.2.2

我有这样的事情:

models.py

class PluginModel(CMSPlugin):
    title = models.CharField(max_length=60)

class InlineModel(models.Model):
    title = models.CharField(max_length=60)
    plugin_key = models.ForeignKey('PluginModel' related_name='breakpoints')

cms_plugins.py

class InlineModelInline(admin.StackedInline):
    model = InlineModel

class PluginModelPlugin(CMSPluginBase):
    model = PluginModel
    inlines = [InlineModelInline,]

    def render(self, context, instance, placeholder):
        context = super(CarouselPlugin, self).render(context, instance, placeholder)
        print(instance.breakpoints.all()) #for simple debug

我添加了一些内联然后保存。在编辑中,所有内联显示正常,但如果我发布页面,则只返回一个空列表。我知道这是发布系统的故障,但我怎样才能让它工作呢?

【问题讨论】:

  • 对吗context = super(CarouselPlugin, self)
  • 这很有趣,我进入文档向您展示这是真的,并且偶然发现那里与您的问题相对应。

标签: python django django-cms


【解决方案1】:

这样的事情应该可以工作。 @atterratio 的答案只适用于多对多关系:

class PluginModel(CMSPlugin):
    title = models.CharField(max_length=60)

    def copy_relations(self, oldinstance):
        for breakpoint in oldinstance.breakpoints.all():
            breakpoint.pk = None
            breakpoint.plugin_key = self
            breakpoint.save()

【讨论】:

  • 文档中的这段代码对我不起作用,但我的工作,虽然我使用 ForeginKey。可能是 Django 的一些变化,我用的是最新的?
  • 根据是使用 M2M 还是 FK 关系,实现会有所不同。在您的问题中,您使用的是 FK,因此我发布的 sn-p 应该可以工作。
  • 我告诉 U 我使用 FK,而 U 代码对我不起作用,我的工作。
【解决方案2】:

需要补充

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

到我的 PluginModel。 http://docs.django-cms.org/en/3.2.2/how_to/custom_plugins.html#handling-relations

【讨论】:

    猜你喜欢
    • 2021-01-24
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多