Plugins

class cms.plugin_base.CMSPluginBase(model=None, admin_site=None)

Inherits django.contrib.admin.ModelAdmin and in most respects behaves like a normal subclass.

Note however that some attributes of ModelAdmin simply won’t make sense in the context of a Plugin.

get_render_template(self, context, instance, placeholder)

If you need to determine the plugin render model at render time you can implement the get_render_template() method on the plugin class; this method takes the same arguments as render.

The method must return a valid template file path.

Example:

def get_render_template(self, context, instance, placeholder):
    if instance.attr = 'one':
        return 'template1.html'
    else:
        return 'template2.html'

See also: render_plugin() , render_template()

model

If the plugin requires per-instance settings, then this setting must be set to a model that inherits from CMSPlugin. See also: Storing configuration.

alias of CMSPlugin

get_cache_expiration(request, instance, placeholder)

Provides hints to the placeholder, and in turn to the page for determining the appropriate Cache-Control headers to add to the HTTPResponse object.

Parameters:
  • request – Relevant HTTPRequest instance.

  • instance – The CMSPlugin instance that is being rendered.

Return type:

None or datetime or `time_delta or int

Must return one of:

None:

This means the placeholder and the page will not even consider this plugin when calculating the page expiration;

Datetime:

A specific date and time (timezone-aware) in the future when this plugin’s content expires;

Important

The returned datetime must be timezone-aware or the plugin will be ignored (with a warning) during expiration calculations.

Datetime.timedelta:

A timedelta instance indicating how long, relative to the response timestamp that the content can be cached;

Int:

An integer number of seconds that this plugin’s content can be cached.

There are constants are defined in cms.constants that may be useful: EXPIRE_NOW and MAX_EXPIRATION_TTL.

An integer value of 0 (zero) or EXPIRE_NOW effectively means “do not cache”. Negative values will be treated as EXPIRE_NOW. Values exceeding the value ~cms.constants.MAX_EXPIRATION_TTL will be set to that value.

Negative timedelta values or those greater than MAX_EXPIRATION_TTL will also be ranged in the same manner.

Similarly, datetime values earlier than now will be treated as EXPIRE_NOW. Values greater than MAX_EXPIRATION_TTL seconds in the future will be treated as MAX_EXPIRATION_TTL seconds in the future.

classmethod get_child_class_overrides(slot, page)

Returns a list of plugin types that are allowed as children of this plugin.

classmethod get_child_classes(slot, page, instance=None)

Returns a list of plugin types that can be added as children to this plugin.

classmethod get_child_plugin_candidates(slot, page)

Returns a list of all plugin classes that will be considered when fetching all available child classes for this plugin.

classmethod get_empty_change_form_text(obj=None)

Returns the text displayed to the user when editing a plugin that requires no configuration.

classmethod get_extra_placeholder_menu_items(request, placeholder)

Extends the placeholder context menu for all placeholders.

To add one or more custom context menu items that are displayed in the context menu for all placeholders when in structure mode, override this method in a related plugin to return a list of cms.plugin_base.PluginMenuItem instances.

classmethod get_extra_plugin_menu_items(request, plugin)

Extends the plugin context menu for all plugins.

To add one or more custom context menu items that are displayed in the context menu for all plugins when in structure mode, override this method in a related plugin to return a list of cms.plugin_base.PluginMenuItem instances.

get_fieldsets(request, obj=None)

Same as from base class except if there are no fields, show an info message.

get_plugin_urls()

Returns the URL patterns the plugin wants to register views for. They are included under django CMS’s page admin URLS in the plugin path (e.g.: /admin/cms/page/plugin/<plugin-name>/ in the default case).

get_plugin_urls() is useful if your plugin needs to talk asynchronously to the admin.

get_vary_cache_on(request, instance, placeholder)

Returns an HTTP VARY header string or a list of them to be considered by the placeholder and in turn by the page to caching behaviour.

Overriding this method is optional.

Must return one of:

None:

This means that this plugin declares no headers for the cache to be varied upon. (default)

String:

The name of a header to vary caching upon.

List of strings:

A list of strings, each corresponding to a header to vary the cache upon.

Note

This only makes sense to use with caching. If this plugin has cache = False or plugin.get_cache_expiration(…) returns 0, get_vary_cache_on() will have no effect.

icon_alt(instance)

Overwrite this if necessary if text_enabled = True Return the ‘alt’ text to be used for an icon representing the plugin object in a text editor.

Parameters:

instance (cms.models.pluginmodel.CMSPlugin instance) – The instance of the plugin model to provide specific information for the ‘alt’ text.

By default icon_alt() will return a string of the form: “[plugin type] - [instance]”, but can be modified to return anything you like.

This function accepts the instance as a parameter and returns a string to be used as the alt text for the plugin’s preview or icon.

Authors of text-enabled plugins should consider overriding this function as it will be rendered as a tooltip in most browser. This is useful, because if the same plugin is used multiple times, this tooltip can provide information about its configuration.

See also: text_enabled, icon_src().

icon_src(instance)

By default, this returns an empty string, which, if left un-overridden would result in no icon rendered at all, which, in turn, would render the plugin un-editable by the operator inside a parent text plugin.

Therefore, this should be overridden when the plugin has text_enabled set to True to return the path to an icon to display in the text of the text plugin.

Since djangocms-text-ckeditor introduced inline previews of plugins, the icon will not be rendered in TextPlugins anymore.

Parameters:

instance (cms.models.pluginmodel.CMSPlugin instance) – The instance of the plugin model.

Example:

def icon_src(self, instance):
    return settings.STATIC_URL + "cms/img/icons/plugins/link.png"

See also: text_enabled, icon_alt()

log_addition(request, obj, bypass=None)

Log that an object has been successfully added.

The default implementation creates an admin LogEntry object.

log_change(request, obj, message, bypass=None)

Log that an object has been successfully changed.

The default implementation creates an admin LogEntry object.

log_deletion(request, obj, object_repr, bypass=None)

Log that an object will be deleted. Note that this method must be called before the deletion.

The default implementation creates an admin LogEntry object.

render(context, instance, placeholder)

This method returns the context to be used to render the template specified in render_template.

Parameters:
  • context (dict) – The context with which the page is rendered.

  • instance (cms.models.pluginmodel.CMSPlugin instance) – The instance of your plugin that is rendered.

  • placeholder (str) – The name of the placeholder that is rendered.

Return type:

dict or django.template.Context

This method must return a dictionary or an instance of django.template.Context, which will be used as context to render the plugin template.

By default, this method will add instance and placeholder to the context, which means for simple plugins, there is no need to overwrite this method.

If you overwrite this method it’s recommended to always populate the context with default values by calling the render method of the super class:

def render(self, context, instance, placeholder):
    context = super().render(context, instance, placeholder)
    ...
    return context
render_change_form(request, context, add=False, change=False, form_url='', obj=None)

We just need the popup interface here

response_add(request, obj, **kwargs)

Determine the HttpResponse for the add_view stage.

response_change(request, obj)

Determine the HttpResponse for the change_view stage.

save_form(request, form, change)

Given a ModelForm return an unsaved instance. change is True if the object is being changed, and False if it’s being added.

save_model(request, obj, form, change)

Override original method, and add some attributes to obj This has to be made, because if the object is newly created, it must know where it lives.

admin_preview = False

If True, displays a preview in the admin.

allow_children = False

Allows this plugin to have child plugins - other plugins placed inside it?

If True you need to ensure that your plugin can render its children in the plugin template. For example:

{% load cms_tags %}
<div class="myplugin">
    {{ instance.my_content }}
    {% for plugin in instance.child_plugin_instances %}
        {% render_plugin plugin %}
    {% endfor %}
</div>

instance.child_plugin_instances provides access to all the plugin’s children. They are pre-filled and ready to use. The child plugins should be rendered using the {% render_plugin %} template tag.

See also: child_classes, parent_classes, require_parent.

cache = True

Is this plugin cacheable? If your plugin displays content based on the user or request or other dynamic properties set this to False.

If present and set to False, the plugin will prevent the caching of the resulting page.

Important

Setting this to False will effectively disable the CMS page cache and all upstream caches for pages where the plugin appears. This may be useful in certain cases but for general cache management, consider using the much more capable get_cache_expiration().

Warning

If you disable a plugin cache be sure to restart the server and clear the cache afterwards.

change_form_template = 'admin/cms/page/plugin/change_form.html'

The template used to render the form when you edit the plugin.

Example:

class MyPlugin(CMSPluginBase):
    model = MyModel
    name = _("My Plugin")
    render_template = "cms/plugins/my_plugin.html"
    change_form_template = "admin/cms/page/plugin_change_form.html"

See also: frontend_edit_template.

child_classes = None

A list of Plugin Class Names. If this is set, only plugins listed here can be added to this plugin. See also: parent_classes.

disable_child_plugins = False

Disables dragging of child plugins in structure mode.

form = None

Custom form class to be used to edit this plugin.

module = 'Generic'

Modules collect plugins of similar type

name = ''

Name of the plugin needs to be set in child classes

page_only = False

Set to True if this plugin should only be used in a placeholder that is attached to a django CMS page, and not other models with PlaceholderFields. See also: child_classes, parent_classes, require_parent.

parent_classes = None

A list of the names of permissible parent classes for this plugin. See also: child_classes, require_parent.

render_plugin = True

If set to False, this plugin will not be rendered at all. If True, render_template() must also be defined. See also: render_template, get_render_template().

render_template = None

The path to the template used to render the template. If render_plugin is True either this or get_render_template must be defined. See also: render_plugin , get_render_template().

require_parent = False

Is it required that this plugin is a child of another plugin? Or can it be added to any placeholder, even one attached to a page. See also: child_classes, parent_classes.

text_enabled = False

This attribute controls whether your plugin will be usable (and rendered) in a text plugin. When you edit a text plugin on a page, the plugin will show up in the CMS Plugins dropdown and can be configured and inserted. The output will even be previewed in the text editor.

Of course, not all plugins are usable in text plugins. Therefore the default of this attribute is False. If your plugin is usable in a text plugin:

  1. set this to True

  2. make sure your plugin provides its own icon_alt(), this will be used as a tooltip in

the text-editor and comes in handy when you use multiple plugins in your text.

See also: icon_alt(), icon_src().

class cms.plugin_base.PluginMenuItem(name, url, data=None, question=None, action='ajax', attributes=None)

Creates an item in the plugin / placeholder menu

Parameters:
  • name – Item name (label)

  • url – URL the item points to. This URL will be called using POST

  • data – Data to be POSTed to the above URL

  • question – Confirmation text to be shown to the user prior to call the given URL (optional)

  • action – Custom action to be called on click; currently supported: ‘ajax’, ‘ajax_add’

  • attributes – Dictionary whose content will be added as data-attributes to the menu item

class cms.models.pluginmodel.CMSPlugin(*args, **kwargs)

The base class for a CMS plugin model. When defining a new custom plugin, you should store plugin-instance specific information on a subclass of this class. (An example for this would be to store the number of pictures to display in a gallery.)

Two restrictions apply when subclassing this to use in your own models:

  1. Subclasses of CMSPlugin cannot be further subclassed

  2. Subclasses of CMSPlugin cannot define a “text” field.

exception DoesNotExist
exception MultipleObjectsReturned
copy_relations(old_instance)

Handle copying of any relations attached to this plugin. Custom plugins have to do this themselves.

See also: Handling Relations, post_copy().

Parameters:

old_instance (CMSPlugin instance) – Source plugin instance

get_action_urls(js_compat=True)
Returns:

dict of action urls for edit, add, delete, copy, and move plugin.

This method replaces the set of legacy methods get_add_url, ``get_edit_url`, get_move_url, get_delete_url, get_copy_url.

get_bound_plugin()

Returns an instance of the plugin model configured for this plugin type.

get_instance_icon_alt()

Get alt text for instance’s icon

get_instance_icon_src()

Get src URL for instance’s icon

get_plugin_instance(admin=None)

For a plugin instance (usually as a CMSPluginBase), this method returns the downcasted (i.e., correctly typed subclass of CMSPluginBase) instance and the plugin class

Returns:

Tuple (instance, plugin)

instance: The instance AS THE APPROPRIATE SUBCLASS OF CMSPluginBase and not necessarily just ‘self’, which is often just a CMSPluginBase,

plugin: the associated plugin class instance (subclass of CMSPlugin)

notify_on_autoadd(request, conf)

Method called when we auto add this plugin via default_plugins in CMS_PLACEHOLDER_CONF.

Some specific plugins may have some special stuff to do when they are auto added.

notify_on_autoadd_children(request, conf, children)

Method called when we auto add children to this plugin via default_plugins/<plugin>/children in CMS_PLACEHOLDER_CONF.

Some specific plugins may have some special stuff to do when we add children to them. ie : TextPlugin must update its content to add HTML tags to be able to see his children in WYSIWYG.

post_copy(old_instance, new_old_ziplist)

Can (should) be overridden to handle the copying of plugins which contain children plugins after the original parent has been copied.

E.g., TextPlugins use this to correct the references in the text to child plugins. copied

refresh_from_db(*args, **kwargs)

Reload field values from the database.

By default, the reloading happens from the database this instance was loaded from, or by the read router if this instance wasn’t loaded from any database. The using parameter will override the default.

Fields can be used to specify which fields to reload. The fields should be an iterable of field attnames. If fields is None, then all non-deferred fields are reloaded.

When accessing deferred fields of an instance, the deferred loading of the field will call this method.

changed_date

django:django.db.models.DateTimeField: Datetime the plugin was last changed

creation_date

django:django.db.models.DateTimeField: Datetime the plugin was created

language

django.db.models.CharField: Language of the plugin

parent

django.db.models.ForeignKey: Parent plugin or None for plugins at root level in the placeholder

placeholder

django.db.models.ForeignKey: Placeholder the plugin belongs to

plugin_type

django:django.db.models.CharField: Plugin type (name of the class as string)

position

django.db.models.SmallIntegerField: Position (unique for placeholder and language) starting with 1 for the first plugin in the placeholder

class cms.plugin_pool.PluginPool
get_plugin(name)

Retrieve a plugin from the cache.

register_plugin(plugin)

Registers the given plugin(s).

Static sanity checks is also performed.

If a plugin is already registered, this will raise PluginAlreadyRegistered.

unregister_plugin(plugin)

Unregisters the given plugin(s).

If a plugin isn’t already registered, this will raise PluginNotRegistered.

validate_templates(plugin=None)

Plugins templates are validated at this stage

Plugin utility functions

cms.utils.plugins.assign_plugins(request, placeholders, template=None, lang=None)

Fetch all plugins for the given placeholders and cast them down to the concrete instances in one query per type.

Parameters:
  • request – The current request.

  • placeholders – An iterable of placeholder objects.

  • template – (optional) The template object.

  • lang – (optional) The language code.

This method assigns plugins to the given placeholders. It retrieves the plugins from the database based on the placeholders and the language. The plugins are then downcasted to their specific plugin types.

The plugins are split up by placeholder and stored in a dictionary where the key is the placeholder ID and the value is a list of plugins.

For each placeholder, if there are plugins assigned to it, the plugins are organized as a layered tree structure. Otherwise, an empty list is assigned.

The list of all plugins for each placeholder is stored in the _all_plugins_cache attribute of the placeholder, while the list of root plugins is stored in the _plugins_cache attribute

cms.utils.plugins.copy_plugins_to_placeholder(plugins, placeholder, language=None, root_plugin=None, start_positions=None)

Copies an iterable of plugins to a placeholder

Parameters:
  • plugins (iterable) – Plugins to be copied

  • placeholder (cms.models.pluginmodel.CMSPlugin instance) – Target placeholder

  • language (str) – target language (if no root plugin is given)

  • root_plugin

  • start_positions (int) – Cache for start positions by language

The logic of this method is the following:

  1. Get bound plugins for each source plugin

  2. Get the parent plugin (if it exists)

  3. then get a copy of the source plugin instance

  4. Set the id/pk to None to it the id of the generic plugin instance above; this will effectively change the generic plugin created above into a concrete one

  5. find the position in the new placeholder

  6. save the concrete plugin (which creates a new plugin in the database)

  7. trigger the copy relations

  8. return the plugin ids

cms.utils.plugins.downcast_plugins(plugins, placeholders=None, select_placeholder=False, request=None)

Downcasts the given list of plugins to their respective classes. Ignores any plugins that are not available.

Parameters:
  • plugins (List[CMSPlugin]) – List of plugins to downcast.

  • placeholders (Optional[List[Placeholder]]) – List of placeholders associated with the plugins.

  • select_placeholder (bool) – If True, select_related the plugin queryset with placeholder.

  • request (Optional[HttpRequest]) – The current request.

Returns:

Generator that yields the downcasted plugins.

Return type:

Generator[CMSPlugin, None, None]

cms.utils.plugins.get_bound_plugins(plugins)

Get the bound plugins by downcasting the plugins to their respective classes. Raises a KeyError if the plugin type is not available.

Creates a map of plugin types and their corresponding plugin IDs for later use in downcasting. Then, retrieves the plugin instances from the plugin model using the mapped plugin IDs. Finally, iterates over the plugins and yields the downcasted versions if they have a valid parent. Does not affect caching.

Parameters:

plugins (List[CMSPlugin]) – List of CMSPlugin instances.

Returns:

Generator that yields the downcasted plugins.

Return type:

Generator[CMSPlugin, None, None]

Example:

plugins = [plugin_instance1, plugin_instance2]
for bound_plugin in get_bound_plugins(plugins):
    # Do something with the bound_plugin
    pass
cms.utils.plugins.get_plugin_class(plugin_type: str) CMSPluginBase

Returns the plugin class for a given plugin_type (str)

cms.utils.plugins.get_plugin_model(plugin_type: str) CMSPlugin

Returns the plugin model class for a given plugin_type (str)

cms.utils.plugins.get_plugin_restrictions(plugin, page=None, restrictions_cache=None)
cms.utils.plugins.get_plugins(request, placeholder, template, lang=None)

Get a list of plugins for a placeholder in a specified template. Respects the placeholder’s cache.

Parameters:
  • request – (HttpRequest) The HTTP request object.

  • placeholder – (Placeholder) The placeholder object for which to retrieve plugins.

  • template – (Template) The template object in which the placeholder resides (not used).

  • lang – (str, optional) The language code for localization. Defaults to None.

Returns:

list: A list of plugins for the specified placeholder in the template.

Raises:

None.

Examples:

# Get plugins for a placeholder in a template
plugins = get_plugins(request, placeholder, template)

# Get plugins for a placeholder in a template with specific language
plugins = get_plugins(request, placeholder, template, lang='en')
cms.utils.plugins.get_plugins_as_layered_tree(plugins)

Given an iterable of plugins ordered by position, returns a deque of root plugins with their respective children set in the child_plugin_instances attribute.

cms.utils.plugins.has_reached_plugin_limit(placeholder, plugin_type, language, template=None)

Checks if the global maximum limit for plugins in a placeholder has been reached. If not then it checks if it has reached its maximum plugin_type limit.

Parameters: - placeholder: The placeholder object to check the limit for. - plugin_type: The type of plugin to check the limit for. - language: The language code for the plugins. - template: The template object for the placeholder. Optional.

Returns: - False if the limit has not been reached.

Raises: - PluginLimitReached: If the limit has been reached for the placeholder.