Complex apphook configuration

In Apphooks we discuss some basic points of using apphooks. In this document we will cover some more complex implementation possibilities.

Attaching an application multiple times

Define a namespace at class-level

If you want to attach an application multiple times to different pages, then the class defining the apphook must have an app_name attribute:

  1. class MyApphook(CMSApp):
  2. name = _("My Apphook")
  3. urls = ["myapp.urls"]
  4. app_name = "myapp"

The app_name does three key things:

  • It provides the fallback namespace for views and templates that reverse URLs.
  • It exposes the Application instance name field in the page admin when applying an apphook.
  • It sets the default apphook instance name (which you’ll see in the Application instance name field).

We’ll explain these with an example. Let’s suppose that your application’s views or templates use reverse('myapp:index') or {% url 'myapp:index' %}.

In this case the namespace of any apphooks you apply must match myapp. If they don’t, your pages using them will throw up a NoReverseMatch error.

You can set the namespace for the instance of the apphook in the Application instance name field. However, you’ll need to set that to something different if an instance with that value already exists. In this case, as long as app_name = "myapp" it doesn’t matter; even if the system doesn’t find a match with the name of the instance it will fall back to the one hard-wired into the class.

In other words setting app_name correctly guarantees that URL-reversing will work, because it sets the fallback namespace approppriately.

Set a namespace at instance-level

On the other hand, the Application instance name will override the app_name if a match is found.

This arrangement allows you to use multiple application instances and namespaces if that flexibility is required, while guaranteeing a simple way to make it work when it’s not.

Django’s Reversing namespaced URLs documentation provides more information on how this works, but the simplified version is:

  1. First, it’ll try to find a match for the Application instance name.
  2. If it fails, it will try to find a match for the app_name.

Apphook configurations

Namespacing your apphooks also makes it possible to manage additional database-stored aphook configuration, on an instance-by-instance basis.

Basic concepts

To capture the configuration that different instances of an apphook can take, a Django model needs to be created - each apphook instance will be an instance of that model, and administered through the Django admin in the usual way.

Once set up, an apphook configuration can be applied to to an apphook instance, in the Advanced settings of the page the apphook instance belongs to:

selecting an apphook configuration application

The configuration is then loaded in the application’s views for that namespace, and will be used to determined how it behaves.

Creating an application configuration in fact creates an apphook instance namespace. Once created, the namespace of a configuration cannot be changed - if a different namespace is required, a new configuration will also need to be created.

An example apphook configuration

In order to illustrate how this all works, we’ll create a new FAQ application, that provides a simple list of questions and answers, together with an apphook class and an apphook configuration model that allows it to exist in multiple places on the site in multiple configurations.

We’ll assume that you have a working django CMS project running already.

Using helper applications

We’ll use a couple of simple helper applications for this example, just to make our work easier.

Aldryn Apphooks Config

Aldryn Apphooks Config is a helper application that makes it easier to develop configurable apphooks. For example, it provides an AppHookConfig for you to subclass, and other useful components to save you time.

In this example, we’ll use Aldryn Apphooks Config, as we recommend it. However, you don’t have to use it in your own projects; if you prefer to can build the code you require by hand.

Use pip install aldryn-apphooks-config to install it.

Aldryn Apphooks Config in turn installs Django AppData, which provides an elegant way for an application to extend another; we’ll make use of this too.

Create the new FAQ application

  1. python manage.py startapp faq

Create the FAQ Entry model

models.py:

  1. from aldryn_apphooks_config.fields import AppHookConfigField
  2. from aldryn_apphooks_config.managers import AppHookConfigManager
  3. from django.db import models
  4. from faq.cms_appconfig import FaqConfig
  5. class Entry(models.Model):
  6. app_config = AppHookConfigField(FaqConfig)
  7. question = models.TextField(blank=True, default='')
  8. answer = models.TextField()
  9. objects = AppHookConfigManager()
  10. def __str__(self): # use __unicode__() if you are using Python 2
  11. return self.question
  12. class Meta:
  13. verbose_name_plural = 'entries'

The app_config field is a ForeignKey to an apphook configuration model; we’ll create it in a moment. This model will hold the specific namespace configuration, and makes it possible to assign each FAQ Entry to a namespace.

The custom AppHookConfigManager is there to make it easy to filter the queryset of Entries using a convenient shortcut: Entry.objects.namespace('foobar').

Define the AppHookConfig subclass

In a new file cms_appconfig.py in the FAQ application:

  1. from aldryn_apphooks_config.models import AppHookConfig
  2. from aldryn_apphooks_config.utils import setup_config
  3. from app_data import AppDataForm
  4. from django.db import models
  5. from django import forms
  6. from django.utils.translation import ugettext_lazy as _
  7. class FaqConfig(AppHookConfig):
  8. paginate_by = models.PositiveIntegerField(
  9. _('Paginate size'),
  10. blank=False,
  11. default=5,
  12. )
  13. class FaqConfigForm(AppDataForm):
  14. title = forms.CharField()
  15. setup_config(FaqConfigForm, FaqConfig)

The implementation can be left completely empty, as the minimal schema is already defined in the abstract parent model provided by Aldryn Apphooks Config.

Here though we’re defining an extra field on model, paginate_by. We’ll use it later to control how many entries should be displayed per page.

We also set up a FaqConfigForm, which uses AppDataForm to add a field to FaqConfig without actually touching its model.

The title field could also just be a model field, like paginate_by. But we’re using the AppDataForm to demonstrate this capability.

Define its admin properties

In admin.py we need to define all fields we’d like to display:

  1. from django.contrib import admin
  2. from .cms_appconfig import FaqConfig
  3. from .models import Entry
  4. from aldryn_apphooks_config.admin import ModelAppHookConfig, BaseAppHookConfig
  5. class EntryAdmin(ModelAppHookConfig, admin.ModelAdmin):
  6. list_display = (
  7. 'question',
  8. 'answer',
  9. 'app_config',
  10. )
  11. list_filter = (
  12. 'app_config',
  13. )
  14. admin.site.register(Entry, EntryAdmin)
  15. class FaqConfigAdmin(BaseAppHookConfig, admin.ModelAdmin):
  16. def get_config_fields(self):
  17. return (
  18. 'paginate_by',
  19. 'config.title',
  20. )
  21. admin.site.register(FaqConfig, FaqConfigAdmin)

get_config_fields defines the fields that should be displayed. Any fields using the AppData forms need to be prefixed by config..

Define the apphook itself

Now let’s create the apphook, and set it up with support for multiple instances. In cms_apps.py:

  1. from aldryn_apphooks_config.app_base import CMSConfigApp
  2. from cms.apphook_pool import apphook_pool
  3. from django.utils.translation import ugettext_lazy as _
  4. from .cms_appconfig import FaqConfig
  5. class FaqApp(CMSConfigApp):
  6. name = _("Faq App")
  7. urls = ["faq.urls"]
  8. app_name = "faq"
  9. app_config = FaqConfig
  10. apphook_pool.register(FaqApp)

Define a list view for FAQ entries

We have all the basics in place. Now we’ll add a list view for the FAQ entries that only displays entries for the currently used namespace. In views.py:

  1. from aldryn_apphooks_config.mixins import AppConfigMixin
  2. from django.views import generic
  3. from .models import Entry
  4. class IndexView(AppConfigMixin, generic.ListView):
  5. model = Entry
  6. template_name = 'faq/index.html'
  7. def get_queryset(self):
  8. qs = super(IndexView, self).get_queryset()
  9. return qs.namespace(self.namespace)
  10. def get_paginate_by(self, queryset):
  11. try:
  12. return self.config.paginate_by
  13. except AttributeError:
  14. return 10

AppConfigMixin saves you the work of setting any attributes in your view - it automatically sets, for the view class instance:

  • current namespace in self.namespace
  • namespace configuration (the instance of FaqConfig) in self.config
  • current application in the current_app parameter passed to the Response class

In this case we’re filtering to only show entries assigned to the current namespace in get_queryset. qs.namespace, thanks to the model manager we defined earlier, is the equivalent of qs.filter(app_config__namespace=self.namespace).

In get_paginate_by we use the value from our appconfig model.

Define a template

In faq/templates/faq/index.html:

  1. {% extends 'base.html' %}
  2. {% block content %}
  3. <h1>{{ view.config.title }}</h1>
  4. <p>Namespace: {{ view.namespace }}</p>
  5. <dl>
  6. {% for entry in object_list %}
  7. <dt>{{ entry.question }}</dt>
  8. <dd>{{ entry.answer }}</dd>
  9. {% endfor %}
  10. </dl>
  11. {% if is_paginated %}
  12. <div class="pagination">
  13. <span class="step-links">
  14. {% if page_obj.has_previous %}
  15. <a href="?page={{ page_obj.previous_page_number }}">previous</a>
  16. {% else %}
  17. previous
  18. {% endif %}
  19. <span class="current">
  20. Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
  21. </span>
  22. {% if page_obj.has_next %}
  23. <a href="?page={{ page_obj.next_page_number }}">next</a>
  24. {% else %}
  25. next
  26. {% endif %}
  27. </span>
  28. </div>
  29. {% endif %}
  30. {% endblock %}
URLconf

urls.py:

  1. from django.conf.urls import url
  2. from . import views
  3. urlpatterns = [
  4. url(r'^$', views.IndexView.as_view(), name='index'),
  5. ]

Put it all together

Finally, we add faq to INSTALLED_APPS, then create and run migrations:

  1. python manage.py makemigrations faq
  2. python manage.py migrate faq

Now we should be all set.

Create two pages with the faq apphook (don’t forget to publish them), with different namespaces and different configurations. Also create some entries assigned to the two namespaces.

You can experiment with the different configured behaviours (in this case, only pagination is available), and the way that different Entry instances can be associated with a specific apphook.