Search code examples
pythondjangodjango-cms

How to loop over custom plugin data on the template in django cms 3.5.3


I am trying to implement a website that uses RSS Feeds. My use case is to be able to display one RSS feed at a time, then loop over to the next maybe after 5 seconds. These RSS feeds need to be displayed on the same placeholder. I am new to django cms in case you need more info please let me know.

I have googled a lot but all I can see is how to add plugins from the frontend and they will all automatically show inside the placeholder. Or modify the render method of the custom plugin class to display what you want. But I want to display everything but one at a time in a continuous manner

@plugin_pool.register_plugin
class ExternalArticlePlugin(CMSPluginBase):
    model = ExternalArticle
    name = _("External article")
    render_template = "external_article.html"
    cache = False

    def render(self, context, instance, placeholder):
        context = super(ExternalArticlePlugin, self).render(
            context, instance, placeholder
        )
        return context

I expect to display one RSS feed at a time inside my placeholder. Those feeds are links to the actual webpage with more info.


Solution

  • one way would be to write a function random_rss_feed_url() in ExternalArticle Model which renders a random rss instance.

    model.py

    class ExternalArticle(models.Model):
    
        def random_rss_feed_link(self):
            return ExternalArticle.objects.order_by('?')[0].link
    

    then you do in plugins external_article.html:

    {{ instance.random_rss_feed_link }}
    

    Edited:

    if you want to change automatically without page reload, then you need something like this in javascript in your template:

    var rss_links = ['link_1', 'link_2', 'link_3']; 
    
    setInterval(function() {
    
        // take random rss link
        var random_link = rss_links[Math.floor(Math.random()*rss_links.length)];
    
        // change the link 
        document.getElementById('rss_link_element').href = random_link;
    
    }, 5000);