Search code examples
pythondjangodjango-cms

Django CMS: Plugin to app without ForiengKey


I'm new in CMS Django, and I'm trying to create a plugin which will be connected to Blog app. I want to show on every page 5 newest blog articles. Problem is that every plugin instance must be connected to some instance from blog app, because in our template we will use instance of plugin like: instance.article.all() or instance.blog.article.all().

Is some option to get instances of Article into the template of my BlogPlugins template without using instance of BlogPlugin?

Thank you.


Solution

  • You wouldn't need the plugin to be connected to the blog. You can just get the objects in the plugin's render method. The render method is a bit like the get_context_data of a view. You can add what you need for the plugin in that method, for example;

    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