Django CMS:没有ForiengKey的应用程序插件



我是CMS Django的新手,我正在尝试创建一个将连接到Blog应用程序的插件。我想在每一页上显示5篇最新的博客文章。问题是,每个插件实例都必须连接到博客应用程序中的某个实例,因为在我们的模板中,我们将使用类似于instance.article.all()instance.blog.article.all()的插件的instance

是否可以选择在不使用BlogPlugininstance的情况下将Article的实例放入我的BlogPlugin模板的模板中?

谢谢。

您不需要将插件连接到博客。您可以在插件的渲染方法中获取对象。render方法有点像视图的get_context_data。例如,您可以在该方法中添加插件所需的内容;

class BlogPlugin(CMSPluginBase):
...
def render(self, context, instance, placeholder):
context = super(MyPlugin, self).render(context, instance, placeholder)
# If you know that the higher the `id`, the newer the object, 
# this gets the latest 5 by ID in reverse order
context['articles'] = Article.objects.all().order_by('-id')[:5]
return context

最新更新