Skip to content
Aditya Bhalsod
← Web
WebIntermediate

Giving Every Database Row Its Own django CMS Page

How the ringtonefly-cms project turns each Ringtone row into a django CMS page through save() and plugins, and what patching a copy of the CMS to tag those pages costs.

  • #django
  • #django-cms
  • #python
  • #cms-plugins
Contents
  1. The model creates the page
  2. A plugin renders the record
  3. Tagging pages by patching the CMS
  4. ads.txt from the database
  5. The hosting side
  6. Where this fits

ringtonefly-cms is a ringtone site built on django CMS. A ringtone has an Android MP3, an iPhone M4R, a like counter and a download counter, and every ringtone gets its own page. The README is a single sentence, so everything below comes from the code.

This is an older project. requirements.txt pins Django 3.1.14 and django-cms 3.8.0, and the repo carries its own copy of django CMS in cms/ (its __init__.py says __version__ = '3.8.0'). I would not start a new site on those versions. The way the models are tied to CMS pages is still worth a look.

The model creates the page

Ringtone in config/models.py is a normal Django model. The audio is two nullable FileFields with FileExtensionValidator: mp3 for Android, m4r for iPhone. A ringtone can exist for one platform only.

The interesting part is save(). Nobody creates a CMS page by hand. The first save does it. This is the branch taken when the row has no Title yet:

Python
else:
    page = api.create_page(
        title=self.name,
        slug=self.slug,
        language="en",
        in_navigation=False,
        template=TEMPLATE_INHERITANCE_MAGIC,
        published=False,
        page_type=3 # Ringtone
    )
    self.title = Title.objects.get(page=page)
    self.page = page
    super().save(*args, **kwargs)
    data = {"ringtone": self}
    placeholder = page.placeholders.get(slot="content")
    add_plugin(placeholder, "SingleRingtone", "en", "first-child", **data)
    add_plugin(placeholder, "SingleFavorite", "en", "last-child")
    super().save(*args, **kwargs)

TEMPLATE_INHERITANCE_MAGIC is the CMS's 'INHERIT' constant, so no per-ringtone template is chosen. The row is saved before add_plugin runs because the plugin holds a foreign key to it. On later saves, the if self.title: branch copies the name and slug onto the existing Title. RingtoneAdmin sets exclude = ["title", "page"], so editors only ever see the ringtone form.

A plugin renders the record

A django CMS page is a set of plugins in placeholders, and the layout templates declare a content placeholder. The plugin class has a model that points at the record and a render that hands it to the template:

Python
class SingleRingtonePlugin(CMSPlugin):
    ringtone = models.ForeignKey(Ringtone, on_delete=models.CASCADE, null=True, blank=True)

@plugin_pool.register_plugin
class SingleRingtone(CMSPluginBase):
    model = SingleRingtonePlugin
    render_template = "single_ringtone.html"

    def render(self, context, instance, placeholder):
        context = super(SingleRingtone, self).render(context, instance, placeholder)
        context.update({"ringtone": instance.ringtone})
        return context

Category follows the same pattern with page_type=2. Its FetchRingtone plugin needs no foreign key, because the page slug is the join key:

Python
queryset = Ringtone.objects.filter(
    category__slug=context["request"].current_page.get_slug()
).order_by("-created_at")

Category.save() passes its own slug to create_page, so the page slug and category__slug match. That is cheap, and it breaks the day someone edits a slug on one side only.

Tagging pages by patching the CMS

I added a type column to django CMS's own Page model, with choices Page, Category and Ringtone, plus a migration (cms/migrations/0023_page_type.py). create_page in cms/api.py got a page_type argument, marked with TODO: Added page type comments. config/one_script.py holds a helper that back-fills pages that already existed:

Python
Page.objects.filter(id__in=category_page_ids).update(type=2)
Page.objects.filter(id__in=ringtone_page_ids).update(type=3)

I found nothing in config/ or templates/ that reads Page.type, so as far as the code goes it is only a marker.

ads.txt from the database

The small ads_txt app keeps ad-network lines in a Rule model: domain, account ID, account type (DIRECT or RESELLER) and an optional authority ID. A ListView renders them as text/plain, one line per rule, and config/urls.py mounts it with re_path(r"^ads\.txt", include("ads_txt.urls")). The view wraps itself in cache_page only when a timeout is set:

Python
def dispatch(self, request, *args, **kwargs):
    cache_timeout = self.get_cache_timeout()
    super_dispatch = super(RuleList, self).dispatch
    if not cache_timeout:
        return super_dispatch(request, *args, **kwargs)
    cache_decorator = cache_page(cache_timeout)
    return cache_decorator(super_dispatch)(request, *args, **kwargs)

settings.py sets ADSTXT_CACHE_TIMEOUT = 60*60*24, so a new rule can take up to a day to appear. The app's own settings.py replaces itself in sys.modules with a class that reads Django settings lazily. The Rule model also has a sites many-to-many, but the view does not filter by it, so every rule is served on every domain.

The hosting side

passenger_wsgi.py is one line, from config.wsgi import application. config/__init__.py calls pymysql.install_as_MySQLdb(), and DATABASES points at MySQL with placeholder credentials. A from .local import * at the bottom of settings.py lets an untracked config/local.py override them, and .gitignore excludes local.py.

Where this fits

One row, one page suits a catalogue where editors want the CMS toolbar, draft and publish, and URLs for free. It costs you two-way sync. The delete() overrides remove the Title and the Page but never call super().delete(). Both foreign keys use SET_NULL, so deleting the page does not delete the row.

Patching a vendored cms/ is the part I would not repeat. For a catalogue this size I would try an apphook with plain Django views first. I would also read DEBUG and the secret key from the environment: settings.py has DEBUG = True and a fallback key in the file.

Found this useful? Share it with your team.

Keep reading

More from Web and beyond