Movatterモバイル変換


[0]ホーム

URL:


ContentsMenuExpandLight modeDark modeAuto light/dark, in light modeAuto light/dark, in dark modeSkip to content
django cms 5.1.0dev1 documentation
django cms 5.1.0dev1 documentation
Back to top

Plugins

classcms.plugin_base.CMSPluginBase(model=None,admin_site=None)

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.

get_render_template(self,context,instance,placeholder)

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()

model

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

classmethodget_child_class_overrides(slot:str,page:Page|None=None,instance:CMSPlugin|None=None)

Returns a list of plugin types that are allowedas children of this plugin.

classmethodget_child_classes(slot,page:Page|None=None,instance:CMSPlugin|None=None,only_uncached:bool=False)list

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

classmethodget_child_plugin_candidates(slot:str,page:Page|None=None)list

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

classmethodget_empty_change_form_text(obj=None)

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

classmethodget_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 whenin structure mode, override this method in a related plugin to return a list ofcms.plugin_base.PluginMenuItem instances.

classmethodget_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 instructure mode, override this method in a related plugin to return a list ofcms.plugin_base.PluginMenuItem instances.

get_cache_expiration(request,instance,placeholder)

Provides hints to the placeholder, and in turn to the page fordetermining the appropriate Cache-Control headers to add to theHTTPResponse object.

Parameters:
  • request – RelevantHTTPRequest instance.

  • instance – TheCMSPlugin instance that is being rendered.

Return type:

None ordatetime ortime_delta orint

Must return one of:

None:

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

Datetime:

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.

Datetime.timedelta:

A timedelta instance indicating how long, relative tothe 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 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_TTLwill 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.

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 placeholderand 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 cacheto 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 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.

icon_alt(instance)

Overwrite this if necessary iftext_enabled=TrueReturn the ‘alt’ text to be used for an icon representingthe plugin object in a text editor.

Parameters:

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().

icon_src(instance)

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.

Parameters:

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_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 becalled 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 templatespecified inrender_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 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
render_change_form(request,context,add=False,change=False,form_url='',obj=None)

We just need the popup interface here

render_close_frame(request:HttpRequest,obj:CMSPlugin|None,action:str|None='edit',extra_data:Context|None=None,extra_context:Context|None=None)HttpResponse

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.

Args:

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”.

extra_data (Optional[Context]): Additional data to include in

the data bridge to the frontend. Defaults to None.

extra_context (Optional[Context]): Additional context to include in

the rendering. Defaults to None.

Returns:

HttpResponse: The rendered confirmation form as an HTTP response.

Raises:
ObjectDoesNotExist: If the parent plugin is a ghost plugin and the

plugin tree cannot be fetched.

Notes:
  • 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.

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 ifthe 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 objThis has to be made, because if the object is newly created, it must knowwhere it lives.

allow_children=False

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.

cache=True

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.

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

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.

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

Disablesdragging of child plugins in structure mode.

disable_edit=False

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.

form=None

Custom form class to be used to edit this plugin.

is_local=True

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.

module='Generic'

Modules collect plugins of similar type

name=''

Name of the plugin needs to be set in child classes

page_only=False

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.

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 toFalse, this plugin will not be rendered at all. IfTrue,render_template() must alsobe defined. See also:render_template,get_render_template().

render_template=None

The path to the template used to render the template. Ifrender_plugin isTrue either this orget_render_templatemust 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 oneattached to a page. See also:child_classes,parent_classes.

show_add_form=True

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.

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 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:

  1. set this toTrue

  2. 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().

classcms.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

classcms.models.pluginmodel.CMSPlugin(*args,**kwargs)

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:

  1. Subclasses of CMSPlugincannot be further subclassed

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

exceptionDoesNotExist
exceptionMultipleObjectsReturned
copy_relations(old_instance)

Handle copying of any relations attached to this plugin. Custom plugins haveto 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 methodsget_add_url,``get_edit_url`,get_move_url,get_delete_url,get_copy_url.

get_ancestors()list[CMSPlugin]

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.

Returns:
list: A list of ancestor plugins, ordered from the root ancestor

to the immediate parent of the current plugin.

get_bound_plugin()

Returns an instance of the plugin modelconfigured 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 methodreturns 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 isoften 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 inCMS_PLACEHOLDER_CONF.

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

notify_on_autoadd_children(request,conf,children)

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.

post_copy(old_instance,new_old_ziplist)

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

refresh_from_db(*args,**kwargs)

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.

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 orNone for plugins at root level inthe 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

classcms.plugin_pool.PluginPool
can_cache_globally(plugin_class:CMSPluginBase)bool

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.

Args:

plugin_class (CMSPluginBase): The plugin class for which to check if restrictions can be cached globally.

Returns:

bool: True if the restrictions can be cached globally, False otherwise.

get_plugin(name)type[CMSPluginBase]

Retrieve a plugin from the cache.

get_restrictions_cache(request_cache:dict,instance:CMSPluginBase,page:Page|None=None)

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.

Args:

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.

Returns:

dict: The restrictions cache for the given plugin instance - or the cache valid for the request.

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 givenplaceholders andcast them down to the concrete instances in one queryper 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 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

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 aboveinto 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:Iterable[CMSPlugin],placeholders:list|None=None,select_placeholder:bool=False,request:HttpRequest|None=None)Iterable[CMSPlugin]

Downcasts the given list of plugins to their respective classes. Ignores any pluginsthat 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 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.

Parameters:

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

Returns:

Generator that yields the downcasted plugins.

Return type:

Generator[CMSPlugin, None, None]

Example:

plugins=[plugin_instance1,plugin_instance2]forbound_plugininget_bound_plugins(plugins):# Do something with the bound_pluginpass
cms.utils.plugins.get_plugin_class(plugin_type:str)type[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 templateplugins=get_plugins(request,placeholder,template)# Get plugins for a placeholder in a template with specific languageplugins=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 respectivechildren 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.

On this page

[8]ページ先頭

©2009-2025 Movatter.jp