Search code examples
pythondjango-cms

How to render the HTML of a django CMS plugin by id from Python


My use case is the need to render a pdf out of the given plugin, although that function might also be used for eg search index composition.


Solution

  • In the django CMS codebase there's cms.templatetags.render_alias_plugin which code isn't straightforward, but when stripped out it can look as following:

    def render_plugin(plugin: CMSPlugin, request: HttpRequest) -> str:
        plugins = plugin.get_descendants().order_by('placeholder', 'path')
        plugins = [plugin] + list(plugins)
        plugins = downcast_plugins(plugins, request=request)
        plugins = list(plugins)
        plugins[0].parent_id = None
        plugins = build_plugin_tree(plugins)
        renderer = get_toolbar_from_request(request).content_renderer
        html: str = renderer.render_plugin(
            instance=plugins[0],
            context={'request': request},
            editable=False,
        )
        return mark_safe(html)
    
    
    cms_plugin = CMSPlugin.objects.get(id=cms_plugin_id)
    render_plugin(cms_plugin, request)
    

    If needed the http request can also be faked, an example of that can be found here.