Reference¶
API reference automatically generated from source code.
CMSConfig options¶
Declare a CMSConfig inner class on a content model to opt into CMS
integration. All options are read at app startup and default to off.
Option |
Default |
Effect |
|---|---|---|
|
|
Register the content model with djangocms-versioning (which must be
installed). If the model has a |
|
|
Make the content frontend-editable (double-click editing via the CMS
toolbar). The grouper admin should mix in |
|
|
Register a CMS app hook exposing a detail view. The URL uses the model’s
|
|
|
Add a shortcut to the grouper changelist in the toolbar’s admin (site) menu. Entries are sorted alphabetically above the Administration break and are only shown to users with view permission on the grouper. |
Whether a content model participates as a grouper/content pair is inferred from
its foreign key to an AbstractCustomGrouper;
a content model without such a foreign key is treated as a plain model (no
versioning, apphook or grouper admin).
Related setting:
CMS_SETTINGS_SHORTCUT(defaultTrue) — show the settings-cog button for the current grouper in the toolbar.
Special field names¶
Two field names on a content model are read by the framework and change its behaviour. Both are optional; name a field one of these only when you mean it.
slug¶
Present, and the generated app hook routes on it —
<slug:slug>/ instead of <int:pk>/ — and the injected
get_absolute_url() builds the URL from it. Absent, and the detail URL uses
the primary key.
Because a detail URL has to identify a single object, a slug may be repeated only
within one grouper — across its versions and, if the model also has a
language field, across its translations:
slug = models.SlugField(_("Slug")) # not unique=True
Warning
Do not declare unique=True on a versioned content model. Every version
is a row of its own and they all carry the same slug, so a database-level
unique constraint makes it impossible to create a second version.
Uniqueness across objects is validated instead of constrained.
validate_unique()
rejects a slug another object already uses — counting every version, not just
the current one, so a slug held by an archived version stays reserved and
reverting that version can never introduce an ambiguous URL. The grouper admin
repeats the check on its own form, where it can attach the error to the field the
editor typed in.
Should a duplicate reach the database anyway (an import, a data migration, a
QuerySet.update()), the detail view does not raise: it serves the first match
and logs an error naming the model, the slug and the pk it chose.
language¶
Present on a content model that has a grouper, and the content is treated as translatable:
languagebecomes an extra grouping field, so version history is kept per language rather than per object;the grouper admin grows language tabs and a language column;
the detail view filters by the active language, so a slug shared by an object’s own translations resolves to the right one.
Add it as a plain character field — the framework reads the field, not a particular type:
language = models.CharField(_("Language"), max_length=8)
Without this field a grouper has exactly one content object per version, which is
the simpler shape; contrib.people and contrib.services are built that way,
contrib.blog has the field.
Models¶
The abstract models are the normal entry point. They combine the framework
mixins with django.db.models.Model and, for content, install the required
managers.
Using the mixins with another model base¶
Use the mixins directly when a model already has to inherit from another Django
model base. The mixins deliberately do not inherit from models.Model;
the other base must do so. Put the framework mixin first so its cooperative
super() calls continue through the existing model:
from django.db import models
from djangocms_custom_content.models import (
ContentAdminManager,
CustomContentManager,
CustomContentMixin,
CustomGrouperMixin,
)
class ExistingGrouperBase(models.Model):
external_id = models.UUIDField()
class Meta:
abstract = True
class ExistingContentBase(models.Model):
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Article(CustomGrouperMixin, ExistingGrouperBase):
pass
class ArticleContent(CustomContentMixin, ExistingContentBase):
# Plain Python mixins cannot contribute Django managers, so mixin-only
# content models declare the same managers as AbstractCustomContent.
objects = CustomContentManager()
admin_manager = ContentAdminManager()
article = models.ForeignKey(Article, on_delete=models.CASCADE)
language = models.CharField(max_length=8)
title = models.CharField(max_length=200)
class CMSConfig:
enable_versioning = True
enable_frontend_editing = True
Mixin-only models are discovered and configured exactly like subclasses of the
abstract models. When django CMS starts, the fallback admin_manager is
replaced by django CMS’s manager and the placeholder relation is added. Without
django CMS, both models remain ordinary usable Django models.
Do not combine a mixin with its corresponding abstract model: the abstract model already includes it.
- class djangocms_custom_content.models.AbstractCustomGrouper(*args, **kwargs)¶
Bases:
CustomGrouperMixin,ModelReady-to-use abstract Django model with grouper behavior.
- class djangocms_custom_content.models.AbstractCustomContent(*args, **kwargs)¶
Bases:
CustomContentMixin,ModelDjango model layer for
CustomContentMixin.When django CMS is installed,
cms_config.pyadds its placeholder relation and CMS-aware admin manager to concrete subclasses.- objects¶
- admin_manager¶
- class djangocms_custom_content.models.CustomGrouperMixin(*args, **kwargs)¶
Bases:
objectMixin providing grouper functionality without inheriting
models.Model.A grouper is a container that organizes multiple language versions of content. Put this mixin before an existing Django model base when
AbstractCustomGroupercannot be used directly.The grouper automatically discovers its related content model and provides methods to access content by language.
Example:
class Article(AbstractCustomGrouper): '''Groups all language versions of an article.''' pass class ArticleContent(AbstractCustomContent): article = ForeignKey(Article, on_delete=CASCADE) title = CharField(max_length=200) language = CharField(max_length=5)
- Attributes:
_content_accessor_name: Name of the reverse accessor to the content model _has_language_field: Whether the content model has a language field _content_cache: Cache for retrieved content instances _is_admin_cache: Flag for admin-specific caching
- get_content(language=None)¶
Retrieve content for this grouper in a specific language.
Uses the current language by default if no language is specified. Implements caching for performance.
- Args:
language: The language code to retrieve. Defaults to current language.- Returns:
The content model instance for the specified language, or None if not found
Example:
article = Article.objects.first() english_content = article.get_content(language='en') german_content = article.get_content(language='de')
- Parameters:
language (str | None)
- Return type:
Model | None
- get_admin_content(language=None)¶
Retrieve content for admin interface with prefetch optimization.
This method is optimized for admin display and uses prefetched data when available. It retrieves the latest published content.
- Args:
language: The language code to retrieve. Defaults to current language.- Returns:
The latest content model instance for the specified language, or None if not found
- Notes:
This method is primarily used by the Django admin interface.
- Parameters:
language (str | None)
- Return type:
Model | None
- class djangocms_custom_content.models.CustomContentMixin¶
Bases:
objectMixin providing base content model functionality.
This mixin is inherited by
AbstractCustomContentto provide content model functionality and serves as a marker class for identifying content models in the framework.When combining it with another Django model base, put this mixin first and declare
objectsandadmin_managerusing the manager classes in this module. The final model must inheritmodels.Modelthrough that other base.To relate content groupers to one another, declare a
RelationFieldon the grouper model. Seedjangocms_custom_content.relations.- template_name_suffix = '_detail'¶
- classmethod find_slug_conflicts(slug, language=None, grouper_id=None)¶
Content of other objects that already uses
slug.A detail URL has to identify a single object, so a slug may be repeated only within one grouper – across its versions and, where the content has a
languagefield, across its translations.Deliberately checks every version rather than only the current one: a slug held by an archived version of another object comes back the moment that version is reverted, and an ambiguous URL is worse than a rejected one.
- validate_unique(exclude=None)¶
Reject a slug that another object already uses.
- Return type:
None
- class djangocms_custom_content.models.CustomContentManager(*args, **kwargs)¶
Bases:
WithUserMixin,ManagerManager for custom content models.
Provides the
with_userAPI without importing django CMS.
Relations¶
- class djangocms_custom_content.relations.RelationField(target, *, related_name=None, ordered=False, through_name=None)¶
Bases:
objectDeclarative grouper-to-grouper relation, à la
ManyToManyField.targetmay be a model class or an"app_label.Model"string naming either a grouper or its content model (resolved to the grouper). The forward accessor is installed immediately; the reverse accessor named byrelated_nameis installed on the target once the app registry is ready.- contribute_to_class(cls, name)¶
- class djangocms_custom_content.relations.RelationManager(instance, through, target_model, *, ordered)¶
Bases:
objectForward accessor
owner.<field>→ a queryset of target groupers.throughrows are filtered bysource=owner; the target groupers are returned as a genuine queryset so all queryset methods are available. When the through is ordered, results are ordered by the through’sorder.- Parameters:
- get_queryset()¶
- Return type:
QuerySet
- all()¶
- Return type:
QuerySet
- add(*objs)¶
- Parameters:
objs (Model)
- Return type:
None
- remove(*objs)¶
- Parameters:
objs (Model)
- Return type:
None
- clear()¶
- Return type:
None
- class djangocms_custom_content.relations.ReverseRelationManager(instance, through, source_model)¶
Bases:
objectReverse accessor
target.<related_name>→ queryset of source groupers.- get_queryset()¶
- Return type:
QuerySet
- all()¶
- Return type:
QuerySet
- add(*objs)¶
- Parameters:
objs (Model)
- Return type:
None
- remove(*objs)¶
- Parameters:
objs (Model)
- Return type:
None
- clear()¶
- Return type:
None
- djangocms_custom_content.relations.relation_through_factory(owner_model, *, ordered=False, name=None, module=None)¶
Build a concrete through model linking
owner_modelto any grouper.The returned model has a concrete
sourceFK toowner_model, the inherited generictarget, a uniqueness constraint preventing duplicate edges and an index on the generic columns for fast reverse lookups.
- djangocms_custom_content.relations.grouper_model_of(model)¶
Return the grouper model for a content model, else
modelunchanged.Relations always target the grouper so they survive version copies. A declaration may name either the grouper or its content model; both resolve here to the grouper (“if there is one”).
CMS Toolbars¶
- class djangocms_custom_content.cms_toolbars.CustomContentToolbar(request, toolbar, is_current_app, app_path)¶
Bases:
CMSToolbarToolbar for djangocms-custom-content.
Adds a settings icon button to the right toolbar.
- content = None¶
The content object currently shown, set by
populate().
- classmethod get_insert_position(admin_menu, item_name)¶
Return the position for a custom content shortcut in the admin (site) menu.
Entries are grouped directly above the
ADMINISTRATION_BREAKand ordered alphabetically among themselves, following the convention used by djangocms-stories and djangocms-alias. The first menu item (the current site entry) is always kept in place.Note that django CMS core adds the
SHORTCUTS_BREAKbelow theADMINISTRATION_BREAK(near the “Logout” entry), so it cannot be used as an upper anchor for the shortcut region – theADMINISTRATION_BREAKis the only reliable boundary.- Args:
admin_menu: The CMS admin menu instance to inspect and modify.item_name: The menu item name used for alphabetical ordering.- Returns:
The integer position where the item should be inserted.
- add_shortcut_links()¶
Add admin-menu shortcut links for content that opted in.
A model is included when its content sets
admin_menu = Trueon itsCMSConfig. The linked changelist is the grouper’s for grouper-backed content, or the content model’s own for plain (grouper-less) content such asFlatCategory(seeadmin_menu_modelsin the app config).
- get_settings_url()¶
Return the grouper change URL for the content object currently shown.
The grouper change view edits the latest content object unless a specific one is requested by primary key. Without that parameter the settings modal would always open the draft, even while a published (read-only) version is being viewed – the form would then wrongly offer its fields for editing.
- Return type:
Add menu entries for the current grouper instance.
- populate()¶
Populate the toolbar with custom content entries.
- property media¶
Admin¶
- class djangocms_custom_content.admin.CustomGrouperAdminMixin¶
Bases:
RelationAdminMixinAdmin mixin to redirect content endpoints for grouper admins.
Provides a breadcrumb redirect compatible with django CMS versioning, and (via
RelationAdminMixin) renders anyRelationFieldon the model as an autocomplete multi-select — sortable when the relation is ordered.Prefetching of the latest related content (
_admin_prefetch_cache) is handled bycms.admin.utils.GrouperModelAdmin.get_queryset, which the concrete admin classes inherit from, so this mixin does not overrideget_queryset.- get_form(request, obj=None, **kwargs)¶
Add slug-uniqueness validation to the grouper change form.
Injected into the base form rather than wrapped around the finished one: subclassing a built form re-runs
ModelFormMetaclass, which rebuildsbase_fieldsand would discard the autocomplete widgetsRelationAdminMixinhas already applied.
- get_urls()¶
Register breadcrumb redirect URLs for grouper admin views.
- breadcrumb_redir(request, *args, **kwargs)¶
Redirect versioning breadcrumb URLs to the grouper admin.
djangocms-versioning uses content admin URLs for breadcrumbs, but this project uses grouper admin classes and must redirect accordingly.
- class djangocms_custom_content.relation_admin.RelationAdminMixin¶
Bases:
objectRenders the model’s relation fields (declared by
RelationModelForm) with autocomplete widgets — sortable when the relation is ordered.Field creation, initial values and saving live in
RelationModelForm; this mixin only ensures that form is in use, swaps in the autocomplete widgets, and serves the autocomplete endpoint. Setrelation_autocomplete = Falseto opt out.- relation_autocomplete = True¶
- get_urls()¶
- relation_autocomplete_view(request)¶
- get_form(request, obj=None, **kwargs)¶
App hooks¶
- class djangocms_custom_content.apphooks.AppHookConfig(detail_view=None, list_view=None, extra_urls=(), slug_field=None, namespace_field=None, app_name=None, name=None)¶
Bases:
objectWhat to generate for a content model’s app hook.
- Args:
detail_view: View class for a single object. Defaults to the generatedDetailView. A class is expected, not the result ofas_view().list_view: View class for the app hook root. Defaults toNone–see the module docstring for why.
extra_urls: Extra URL patterns, registered before the detail route soa literal path can win over the slug pattern.
slug_field: Field the detail URL routes on. Defaults to"slug"whenthe content model has one, otherwise the primary key.
namespace_field: Field on the grouper naming the app hook instancethis object belongs to. Set it to support more than one app hook page; leaving it unset keeps the current single-instance behaviour.
app_name: Application namespace. Defaults to the grouper model name,lowercased.
name: Human-readable name shown in the page’s Application dropdown.Defaults to the grouper model name.
- Parameters:
- classmethod coerce(value)¶
Normalise a
CMSConfig.apphookdeclaration.Truebecomes a default config,False/Nonemeans no app hook, and a config is returned unchanged.- Parameters:
value (Any)
- Return type:
AppHookConfig | None
Helpers¶
- djangocms_custom_content.helpers.get_custom_config(model)¶
Return the custom content configuration tuple for the given model.
Looks up the model in the
custom_content_groupersregistry and returns a tuple of(content_model, grouper_field_name, enable_versioning). If the model is not registered, returns(None, None, False).