Search code examples
djangodjango-modelsdjango-cms

How to access the parent model of a Django-CMS plugin


I created 2 django-cms plugins, a parent "Container" that can contain multiple child "Content" plugins.

When I save the child plugin I would like to access the model of the parent plugin.

from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase

from .models import Container, Content

class ContainerPlugin(CMSPluginBase):
    model = Container
    name = "Foo Container"
    render_template = "my_package/container.html"
    allow_children = True
    child_classes = ["ContentPlugin"]

class ContentPlugin(CMSPluginBase):
    model = content
    name = "Bar Content"
    render_template = "my_package/content.html"
    require_parent = True
    parent_classes = ["ContainerPlugin"]
    allow_children = True

    def save_model(self, request, obj, form, change):
        response = super(ContentPlugin, self).save_model(
            request, obj, form, change
        )

        # here I want to access the parent's (container) model, but how?

        return response

plugin_pool.register_plugin(ContainerPlugin)
plugin_pool.register_plugin(ContentPlugin)

obj is the current plugin instance, so I can get all the properties of this model, but I can't figure out how to access the parent's plugin model. There is obj.parent, but it's not the plugin instance as far as I can tell. Also tried playing around with self.cms_plugin_instance and obj.parent.get_plugin_instance() but with no success.

Any advice?


Solution

  • Given a plugin instance,instance.get_plugin_instance() method returns a tuple containing:

    1. instance - The plugin instance
    2. plugin - the associated plugin class instance get_plugin_instance

    so something like this to get the parent object:

    instance, plugin_class = object.parent.get_plugin_instance()