Joelbitar Joelbitar - 3 months ago 21
Python Question

How do I add a plugin to a Static placeholder in Django CMS

I'm begining to use Static Placeholders in Django-CMS and I want to bootstrap a pace and create a "footer" static placeholder. Something like:

static_placeholder = StaticPlaceholder(
name=static_placeholder_code,
code=static_placeholder_code,
creation_method=StaticPlaceholder.CREATION_BY_CODE
)
static_placeholder.save()


I tried adding a TextPlugin with the api.add_plugin but got an error

add_plugin(
placeholder=static_placeholder,
plugin_type='TextPlugin',
language='en',
)


Since static_placeholder is not an instance of Placeholder add_plugin does not work.
in the add_plugin function: assert isinstance(placeholder, Placeholder)

What would be the best way to add a TextPlugin to this static placeholder?

Answer

StaticPlaceholder is a model that has two foreign key relationships to the Placeholder model, one is called draft, the other is called public. Both will give you a Placeholder instance.

You could just use:

add_plugin(
    placeholder=static_placeholder.draft,
    plugin_type='TextPlugin',
    language='en',
)

and it will work, but keep in mind that you should always use draft as the example above, this is because when you publish, all plugins from draft will be copied over to the public placeholder.

Last not sure on the specifics of your app, but should point out that when the staticplaceholder is rendered in a template, it's not necessary to create it before hand. You can just do:

{% load cms_tags %}

{% static_placeholder 'footer' %}

This will then get or create the footer static placeholder.