Inheritsdjango.contrib.admin.ModelAdmin
and in most respects behaves like anormal subclass.
Note however that some attributes ofModelAdmin
simply won’t make sense in thecontext of a Plugin.
If you need to determine the plugin render model at render timeyou can implement theget_render_template()
method on the pluginclass; this method takes the same arguments asrender
.
The methodmust return a valid template file path.
Example:
defget_render_template(self,context,instance,placeholder):ifinstance.attr='one':return'template1.html'else:return'template2.html'
See also:render_plugin()
,render_template()
If the plugin requires per-instance settings, then this setting must be set to a model that inherits fromCMSPlugin
. See also:Storing configuration.
alias ofCMSPlugin
Returns a list of plugin types that are allowedas children of this plugin.
Returns a list of plugin types that can be addedas children to this plugin.
Returns a list of all plugin classesthat will be considered when fetchingall available child classes for this plugin.
Returns the text displayed to the user when editing a pluginthat requires no configuration.
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 whenin structure mode, override this method in a related plugin to return a list ofcms.plugin_base.PluginMenuItem
instances.
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 instructure mode, override this method in a related plugin to return a list ofcms.plugin_base.PluginMenuItem
instances.
Provides hints to the placeholder, and in turn to the page fordetermining the appropriate Cache-Control headers to add to theHTTPResponse object.
request – RelevantHTTPRequest
instance.
instance – TheCMSPlugin
instance that is being rendered.
None
ordatetime
ortime_delta
orint
Must return one of:
This means the placeholder and the page will not evenconsider this plugin when calculating the page expiration;
A specific date and time (timezone-aware) in the futurewhen this plugin’s content expires;
Important
The returneddatetime
must be timezone-awareor the plugin will be ignored (with a warning)during expiration calculations.
A timedelta instance indicating how long, relative tothe response timestamp that the content can be cached;
An integer number of seconds that this plugin’s content can be cached.
There are constants are defined incms.constants
that may beuseful:EXPIRE_NOW
andMAX_EXPIRATION_TTL
.
An integer value of 0 (zero) orEXPIRE_NOW
effectively means “do notcache”. Negative values will be treated asEXPIRE_NOW
. Values exceeding the valueMAX_EXPIRATION_TTL
will be set to that value.
Negativetimedelta values or those greater thanMAX_EXPIRATION_TTL
will also be ranged in the same manner.
Similarly,datetime
values earlier than now will be treated asEXPIRE_NOW
. Values greater thanMAX_EXPIRATION_TTL
seconds in thefuture will be treated asMAX_EXPIRATION_TTL
seconds in the future.
Same as from base class except if there are no fields, show an info message.
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.
Returns an HTTP VARY header string or a list of them to be considered by the placeholderand in turn by the page to caching behaviour.
Overriding this method is optional.
Must return one of:
This means that this plugin declares no headers for the cacheto be varied upon. (default)
The name of a header to vary caching upon.
A list of strings, each corresponding to a header to vary thecache upon.
Note
This only makes sense to use with caching. If this plugin hascache=False
or plugin.get_cache_expiration(…) returns 0,get_vary_cache_on() will have no effect.
Overwrite this if necessary iftext_enabled=True
Return the ‘alt’ text to be used for an icon representingthe plugin object in a text editor.
instance (cms.models.pluginmodel.CMSPlugin
instance) – The instance of the plugin model to provide specific informationfor 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 theinstance
as a parameter and returns a string to beused as thealt
text for the plugin’s preview or icon.
Authors of text-enabled plugins should consider overriding this function asit will be rendered as a tooltip in most browser. This is useful, because ifthe same plugin is used multiple times, this tooltip can provide information aboutits configuration.
See also:text_enabled
,icon_src()
.
Deprecated: Since djangocms-text-ckeditor introduced inline previews of plugins, the icon will not berendered in TextPlugins anymore.
By default, this returns an empty string, which, if left un-overridden would result in no iconrendered at all, which, in turn, would render the plugin un-editable by the operator inside a parenttext plugin.
Therefore, this should be overridden when the plugin has text_enabled set to True to return the pathto an icon to display in the text of the text plugin.
instance (cms.models.pluginmodel.CMSPlugin
instance) – The instance of the plugin model.
Example:
deficon_src(self,instance):returnstatic("cms/img/icons/plugins/link.png")
See also:text_enabled
,icon_alt()
Log that an object has been successfully added.
The default implementation creates an admin LogEntry object.
Log that an object has been successfully changed.
The default implementation creates an admin LogEntry object.
Log that an object will be deleted. Note that this method must becalled before the deletion.
The default implementation creates an admin LogEntry object.
This method returns the context to be used to render the templatespecified inrender_template
.
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.
dict ordjango.template.Context
This method must return a dictionary or an instance ofdjango.template.Context
, which will be used as context to render theplugin template.
By default, this method will addinstance
andplaceholder
to thecontext, which means for simple plugins, there is no need to overwrite thismethod.
If you overwrite this method it’s recommended to always populate the contextwith default values by calling the render method of the super class:
defrender(self,context,instance,placeholder):context=super().render(context,instance,placeholder)...returncontext
We just need the popup interface here
Renders the close frame for a CMS plugin in the Django admin interface.
This method is used to send information to the javascript frontendafter an edit action has taken place. It allows the javascript frontendto update the structure and content on the edit endpoints.
request (HttpRequest): The HTTP request object.obj (CMSPlugin): The CMS plugin instance being rendered.action (Optional[str]): The action being performed on the plugin.
Defaults to “edit”. Possible values are “add”, “edit”, “move”, and “delete”.
the data bridge to the frontend. Defaults to None.
the rendering. Defaults to None.
HttpResponse: The rendered confirmation form as an HTTP response.
plugin tree cannot be fetched.
Handles edge cases where the parent plugin is a ghost plugin.
Constructs the plugin tree structure and gathers plugin-specificdata for rendering.
Includes messages from the request in the context.
Determine the HttpResponse for the add_view stage.
Determine the HttpResponse for the change_view stage.
Given a ModelForm return an unsaved instance.change
is True ifthe object is being changed, and False if it’s being added.
Override original method, and add some attributes to objThis has to be made, because if the object is newly created, it must knowwhere it lives.
Allows this plugin to have child plugins - other plugins placed inside it?
IfTrue
you need to ensure that your plugin can render its children in the plugin template. For example:
{%loadcms_tags%}<divclass="myplugin">{{instance.my_content}}{%forpluginininstance.child_plugin_instances%}{%render_pluginplugin%}{%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 usingthe{%render_plugin%}
template tag.
See also:child_classes
,parent_classes
,require_parent
.
Is this plugin cacheable? If your plugin displays content based on the user orrequest or other dynamic properties set this toFalse
.
If present and set toFalse
, the plugin will prevent the caching ofthe resulting page.
Important
Setting this toFalse
will effectively disable theCMS page cache and all upstream caches for pages wherethe plugin appears. This may be useful in certain casesbut for general cache management, consider using the muchmore capableget_cache_expiration()
.
Warning
If you disable a plugin cache be sure to restart the server and clear the cache afterwards.
The template used to render the form when you edit the plugin.
Example:
classMyPlugin(CMSPluginBase):model=MyModelname=_("My Plugin")render_template="cms/plugins/my_plugin.html"change_form_template="admin/cms/page/plugin_change_form.html"
See also:frontend_edit_template
.
A list of Plugin Class Names. If this is set, only plugins listed here can be added to this plugin.See also:parent_classes
.
Disablesdragging of child plugins in structure mode.
Disablesediting of this plugin in structure mode. Useful for plugins which, for example, are managed bytheir parent plugins.
If editing is disabled, the plugin will be rendered in structure mode normally, but double-clicking on it willnot open the plugin edit dialog. The user will not have a direct way to change the plugin instance.
Moving or adding child plugins are not affected.
Custom form class to be used to edit this plugin.
The plugin does not modify the context or request and its rendering is not influenced by its parentplugins. Defaults toTrue
unlessCMS_ALWAYS_REFRESH_CONTENT
is set toTrue
.
Modules collect plugins of similar type
Name of the plugin needs to be set in child classes
Set toTrue
if this plugin should only be used in a placeholder that is attached to a django CMS page,and not other models withPlaceholderRelationFields
. See also:child_classes
,parent_classes
,require_parent
.
A list of the names of permissible parent classes for this plugin. See also:child_classes
,require_parent
.
If set toFalse
, this plugin will not be rendered at all. IfTrue
,render_template()
must alsobe defined. See also:render_template
,get_render_template()
.
The path to the template used to render the template. Ifrender_plugin
isTrue
either this orget_render_template
must be defined. See also:render_plugin
,get_render_template()
.
Is it required that this plugin is a child of another plugin? Or can it be added to any placeholder, even oneattached to a page. See also:child_classes
,parent_classes
.
Determines if the add plugin modal is shown for this plugin (default: yes). Useful for plugins which have nofields to fill, or which have valid default values forall fields.If the plugin’s form will not validate with the default values the add plugin modal is shown with the formerrors.
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 intheCMS Plugins dropdown and can be configured and inserted. The output will evenbe previewed in the text editor.
Of course, not all plugins are usable in text plugins. Therefore the default of thisattribute isFalse
. If your pluginis usable in a text plugin:
set this toTrue
make sure your plugin provides its ownicon_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()
.
Creates an item in the plugin / placeholder menu
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
The base class for a CMS plugin model. When defining a new custom plugin, you shouldstore plugin-instance specific information on a subclass of this class. (An example for thiswould be to store the number of pictures to display in a gallery.)
Two restrictions apply when subclassing this to use in your own models:
Subclasses of CMSPlugincannot be further subclassed
Subclasses of CMSPlugin cannot define a “text” field.
Handle copying of any relations attached to this plugin. Custom plugins haveto do this themselves.
See also:Handling Relations,post_copy()
.
old_instance (CMSPlugin
instance) – Source plugin instance
dict of action urls for edit, add, delete, copy, and move plugin.
This method replaces the set of legacy methodsget_add_url,``get_edit_url`,get_move_url,get_delete_url,get_copy_url.
Retrieve the list of ancestor plugins for the current plugin.
This method returns a list of ancestor plugins, starting from the rootancestor down to the immediate parent of the current plugin. If thecurrent plugin has no parent, an empty list is returned.
to the immediate parent of the current plugin.
Returns an instance of the plugin modelconfigured for this plugin type.
Get alt text for instance’s icon
Get src URL for instance’s icon
For a plugin instance (usually as a CMSPluginBase), this methodreturns the downcasted (i.e., correctly typed subclass of CMSPluginBase) instance and the plugin class
Tuple (instance, plugin)
instance: The instance AS THE APPROPRIATE SUBCLASS OF CMSPluginBase and not necessarily just ‘self’, which isoften just a CMSPluginBase,
plugin: the associated plugin class instance (subclass of CMSPlugin)
Method called when we auto add this plugin via default_plugins inCMS_PLACEHOLDER_CONF.
Some specific plugins may have some special stuff to do when they areauto added.
Method called when we auto add children to this plugin viadefault_plugins/<plugin>/children in CMS_PLACEHOLDER_CONF.
Some specific plugins may have some special stuff to do when we addchildren to them. ie : TextPlugin must update its content to add HTMLtags to be able to see his children in WYSIWYG.
Can (should) be overridden to handle the copying of plugins which contain children plugins after the originalparent has been copied.
E.g., TextPlugins use this to correct the references in the text to child plugins.copied
Reload field values from the database.
By default, the reloading happens from the database this instance wasloaded from, or by the read router if this instance wasn’t loaded fromany database. The using parameter will override the default.
Fields can be used to specify which fields to reload. The fieldsshould be an iterable of field attnames. If fields is None, thenall non-deferred fields are reloaded.
When accessing deferred fields of an instance, the deferred loadingof the field will call this method.
django:django.db.models.DateTimeField: Datetime the plugin was last changed
django:django.db.models.DateTimeField: Datetime the plugin was created
django.db.models.CharField
: Language of the plugin
django.db.models.ForeignKey
: Parent plugin orNone
for plugins at root level inthe placeholder
django.db.models.ForeignKey
: Placeholder the plugin belongs to
django:django.db.models.CharField: Plugin type (name of the class as string)
django.db.models.SmallIntegerField
: Position (unique for placeholder and language)starting with 1 for the first plugin in the placeholder
Check if the restrictions for a given plugin class can be cached globally.
This is the case if the plugin restrictions only depend on template and placeholder slot asdescribed by the CMS_PLACEHOLDER_CONF setting.
plugin_class (CMSPluginBase): The plugin class for which to check if restrictions can be cached globally.
bool: True if the restrictions can be cached globally, False otherwise.
Retrieve a plugin from the cache.
Retrieve the restrictions cache for a given plugin instance.
This method checks if the plugin class can be cached globally. This is the case if theplugin restrictions only depend on template and placeholder slot as described by theCMS_PLACEHOLDER_CONF setting.
If it can, it retrieves the appropriate restrictions cache based on the template and slotof the plugin instance’s placeholder. If not, it returns the (local) request cache which willbe recalculated for each request.
request_cache (dict): The current request cache.instance (CMSPluginBase): The plugin instance for which to retrieve the restrictions cache.page (Optional[Page]): The page associated with the plugin instance, if any.
dict: The restrictions cache for the given plugin instance - or the cache valid for the request.
Registers the given plugin(s).
Static sanity checks is also performed.
If a plugin is already registered, this will raise PluginAlreadyRegistered.
Unregisters the given plugin(s).
If a plugin isn’t already registered, this will raise PluginNotRegistered.
Plugins templates are validated at this stage
Fetch all plugins for the givenplaceholders
andcast them down to the concrete instances in one queryper type.
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 theplaceholders 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 thevalue 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
Copies an iterable of plugins to a placeholder
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:
Get bound plugins for each source plugin
Get the parent plugin (if it exists)
then get a copy of the source plugin instance
Set the id/pk to None to it the id of the generic plugin instance above;this will effectively change the generic plugin created aboveinto a concrete one
find the position in the new placeholder
save the concrete plugin (which creates a new plugin in the database)
trigger the copy relations
return the plugin ids
Downcasts the given list of plugins to their respective classes. Ignores any pluginsthat are not available.
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.
Generator that yields the downcasted plugins.
Generator[CMSPlugin, None, None]
Get the bound plugins by downcasting the plugins to their respective classes. Raises a KeyError if the plugin typeis 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.
plugins (List[CMSPlugin]) – List ofCMSPlugin
instances.
Generator that yields the downcasted plugins.
Generator[CMSPlugin, None, None]
Example:
plugins=[plugin_instance1,plugin_instance2]forbound_plugininget_bound_plugins(plugins):# Do something with the bound_pluginpass
Returns the plugin class for a given plugin_type (str)
Returns the plugin model class for a given plugin_type (str)
Get a list of plugins for a placeholder in a specified template. Respects the placeholder’s cache.
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.
list: A list of plugins for the specified placeholder in the template.
None.
Examples:
# Get plugins for a placeholder in a templateplugins=get_plugins(request,placeholder,template)# Get plugins for a placeholder in a template with specific languageplugins=get_plugins(request,placeholder,template,lang="en")
Given an iterable of plugins ordered by position,returns a deque of root plugins with their respectivechildren set in the child_plugin_instances attribute.
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.
CMSPluginBase
CMSPluginBase.get_render_template()
CMSPluginBase.model
CMSPluginBase.get_child_class_overrides()
CMSPluginBase.get_child_classes()
CMSPluginBase.get_child_plugin_candidates()
CMSPluginBase.get_empty_change_form_text()
CMSPluginBase.get_extra_placeholder_menu_items()
CMSPluginBase.get_extra_plugin_menu_items()
CMSPluginBase.get_cache_expiration()
CMSPluginBase.get_fieldsets()
CMSPluginBase.get_plugin_urls()
CMSPluginBase.get_vary_cache_on()
CMSPluginBase.icon_alt()
CMSPluginBase.icon_src()
CMSPluginBase.log_addition()
CMSPluginBase.log_change()
CMSPluginBase.log_deletion()
CMSPluginBase.render()
CMSPluginBase.render_change_form()
CMSPluginBase.render_close_frame()
CMSPluginBase.response_add()
CMSPluginBase.response_change()
CMSPluginBase.save_form()
CMSPluginBase.save_model()
CMSPluginBase.allow_children
CMSPluginBase.cache
CMSPluginBase.change_form_template
CMSPluginBase.child_classes
CMSPluginBase.disable_child_plugins
CMSPluginBase.disable_edit
CMSPluginBase.form
CMSPluginBase.is_local
CMSPluginBase.module
CMSPluginBase.name
CMSPluginBase.page_only
CMSPluginBase.parent_classes
CMSPluginBase.render_plugin
CMSPluginBase.render_template
CMSPluginBase.require_parent
CMSPluginBase.show_add_form
CMSPluginBase.text_enabled
PluginMenuItem
CMSPlugin
CMSPlugin.DoesNotExist
CMSPlugin.MultipleObjectsReturned
CMSPlugin.copy_relations()
CMSPlugin.get_action_urls()
CMSPlugin.get_ancestors()
CMSPlugin.get_bound_plugin()
CMSPlugin.get_instance_icon_alt()
CMSPlugin.get_instance_icon_src()
CMSPlugin.get_plugin_instance()
CMSPlugin.notify_on_autoadd()
CMSPlugin.notify_on_autoadd_children()
CMSPlugin.post_copy()
CMSPlugin.refresh_from_db()
CMSPlugin.changed_date
CMSPlugin.creation_date
CMSPlugin.language
CMSPlugin.parent
CMSPlugin.placeholder
CMSPlugin.plugin_type
CMSPlugin.position
PluginPool