Dexterity Types II: Growing Up – Mastering Plone 5 development

Dexterity Types II: Growing Up#

The existing talks are still lacking some functionality we want to use.

In this part we will:

  • add a marker interface to our talk type,

  • create custom catalog indexes,

  • query the catalog for them,

  • enable some more default features for our type.

Add a marker interface to the talk type#

Marker Interfaces#

The content type Talk is not yet a first class citizen because it does not implement its own interface. Interfaces are like nametags, telling other elements who and what you are and what you can do. A marker interface is like such a nametag. The talks actually have an auto-generated marker interface plone.dexterity.schema.generated.Plone_0_talk.

One problem is that the name of the Plone instance Plone is part of that interface name. If you now moved these types to a site with another name the code that uses these interfaces would no longer find the objects in question.

To create a real name tag we add a new Interface to

 1# -*- coding: utf-8 -*-
 2"""Module where all interfaces, events and exceptions live."""
 4from zope.publisher.interfaces.browser import IDefaultBrowserLayer
 5from zope.interface import Interface
 8class IPloneconfSiteLayer(IDefaultBrowserLayer):
 9    """Marker interface that defines a browser layer."""
12class ITalk(Interface):
13    """Marker interface for Talks"""

ITalk is a marker interface. We can bind Views and Viewlets to content that provide these interfaces. Lets see how we can provide this Interface.

There are two solutions for this.

  1. Let them be instances of a class that implements this Interface.

  2. Register this interface as a behavior and enable it on talks.

The first option has an important drawback: only new talks would be instances of the new class. We would either have to migrate the existing talks or delete them.

So let's register the interface as a behavior in behaviors/configure.zcml

    description="Marker interface for talks to be able to bind views to."

And enable it on the type in profiles/default/types/talk.xml

1<property name="behaviors">
2 <element value="plone.dublincore"/>
3 <element value="plone.namefromtitle"/>
4 <element value=""/>
5 <element value=""/>

Either reinstall the add-on, apply the behavior by hand or run an upgrade step (see below) and the interface will be there.

Then we can safely bind the talkview to the new marker interface.


Now the /talkview can only be used on objects that implement said interface. We can now also query the catalog for objects providing this interface catalog(object_provides="")(). The talklistview and the demoview do not get this constraint since they are not only used on talks.


Just for completeness sake, this is what would have to happen for the first option (associating the ITalk interface with a Talk class):

  • Create a new class that inherits from plone.dexterity.content.Container and implements the marker interface.

    from plone.dexterity.content import Container
    from import ITalk
    from zope.interface import implementer
    class Talk(Container):
        """Class for Talks"""
  • Modify the class for new talks in profiles/default/types/talk.xml

    2<property name="add_permission">cmf.AddPortalContent</property>
    3<property name="klass"></property>
    4<property name="behaviors">
  • Create an upgrade step that changes the class of the existing talks. A reuseable method to do such a thing is in

Upgrade steps#

When projects evolve you sometimes want to modify various things while the site is already up and brimming with content and users. Upgrade steps are pieces of code that run when upgrading from one version of an add-on to a newer one. They can do just about anything. We will use an upgrade step to enable the new behavior instead of reinstalling the add-on.

We will create an upgrade step that:

  • runs the typeinfo step (i.e. loads the GenericSetup configuration stored in profiles/default/types.xml and profiles/default/types/... so we don't have to reinstall the add-on to have our changes from above take effect) and

  • cleans up the talks that might be scattered around the site in the early stages of creating it. We will move all talks to a folder talks (unless they already are there).

Upgrade steps can be registered in their own ZCML file to prevent cluttering the main configure.zcml. The add-on you created already has a registration for the upgrades.zcml in our configure.zcml:

<include file="upgrades.zcml" />

You register the first upgrade-step in upgrades.zcml:

 2  xmlns=""
 3  xmlns:i18n=""
 4  xmlns:genericsetup=""
 5  i18n_domain="">
 7  <genericsetup:upgradeStep
 8      title="Update and cleanup talks"
 9      description="Update typeinfo and move talks to a folder 'talks'"
10      source="1000"
11      destination="1001"
12      handler=""
13      sortkey="1"
14      profile=""
15      />

The upgrade step bumps the version number of the GenericSetup profile of from 1000 to 1001. The version is stored in profiles/default/metadata.xml. Change it to


GenericSetup now expects the code as a method upgrade_site() in the file Let's create it.

 1# -*- coding: utf-8 -*-
 2from plone import api
 4import logging
 6default_profile = ''
 7logger = logging.getLogger(__name__)
10def upgrade_site(setup):
11    setup.runImportStepFromProfile(default_profile, 'typeinfo')
12    portal = api.portal.get()
13    # Create a folder 'The event' if needed
14    if 'the-event' not in portal:
15        event_folder = api.content.create(
16            container=portal,
17            type='Folder',
18            id='the-event',
19            title=u'The event')
20    else:
21        event_folder = portal['the-event']
23    # Create folder 'Talks' inside 'The event' if needed
24    if 'talks' not in event_folder:
25        talks_folder = api.content.create(
26            container=event_folder,
27            type='Folder',
28            id='talks',
29            title=u'Talks')
30    else:
31        talks_folder = event_folder['talks']
32    talks_url = talks_folder.absolute_url()
34    # Find all talks
35    brains = api.content.find(portal_type='talk')
36    for brain in brains:
37        if talks_url in brain.getURL():
38            # Skip if the talk is already somewhere inside the target folder
39            continue
40        obj = brain.getObject()
41'Moving {} to {}'.format(
42            obj.absolute_url(), talks_folder.absolute_url()))
43        # Move talk to the folder '/the-event/talks'
44        api.content.move(
45            source=obj,
46            target=talks_folder,
47            safe_id=True)


  • Upgrade steps get the tool portal_setup passed as their argument.

  • The portal_setup tool has a method runImportStepFromProfile()

  • We create the needed folder structure if it does not exists.

After restarting the site we can run the step:

On the console you should see logging messages like:

INFO Moving http://localhost:8080/Plone/old-talk1 to http://localhost:8080/Plone/the-event/talks

Alternatively you also select which upgrade steps to run like this:

  • In the ZMI go to portal_setup

  • Go to the tab Upgrades

  • Select from the dropdown and click Choose profile

  • Run the upgrade step.


Upgrading from an older version of Plone to a newer one also runs upgrade steps from the package You should be able to upgrade a clean site from 2.5 to 5.0 with one click.

Find the upgrade steps in plone/

Add a browserlayer#

A browserlayer is another such marker interface, but this time on the request. Browserlayers allow us to easily enable and disable views and other site functionality based on installed add-ons and themes.

Since we want the features we write only to be available when actually is installed we can bind them to a browserlayer.

Our package already has a browserlayer (added by bobtemplates.plone). See

 1# -*- coding: utf-8 -*-
 2"""Module where all interfaces, events and exceptions live."""
 4from zope.publisher.interfaces.browser import IDefaultBrowserLayer
 5from zope.interface import Interface
 8class IPloneconfSiteLayer(IDefaultBrowserLayer):
 9    """Marker interface that defines a browser layer."""
12class ITalk(Interface):
13    """Marker interface for Talks"""

It is enabled by GenericSetup when installing the package since it is registered in the profiles/default/browserlayer.xml

<?xml version="1.0" encoding="UTF-8"?>

We should bind all views to it. Here is an example using the talklistview.


Note the relative Python path interfaces.IPloneconfSiteLayer. It is equivalent to the absolute path


Do you need to bind the viewlet featured from the chapter Writing Viewlets to this new browser layer?


No, it would make no difference since the viewlet is already bound to the marker interface

Add catalog indexes#

In the talklistview we had to wake up all objects to access some of their attributes. That is OK if we don't have many objects and they are light dexterity objects. If we had thousands of objects this might not be a good idea.

Instead of loading them all into memory we will use catalog indexes to get the data we want to display.

Add a new file profiles/default/catalog.xml

 1<?xml version="1.0"?>
 2<object name="portal_catalog">
 3  <index name="type_of_talk" meta_type="FieldIndex">
 4    <indexed_attr value="type_of_talk"/>
 5  </index>
 6  <index name="speaker" meta_type="FieldIndex">
 7    <indexed_attr value="speaker"/>
 8  </index>
 9  <index name="audience" meta_type="KeywordIndex">
10    <indexed_attr value="audience"/>
11  </index>
12  <index name="room" meta_type="FieldIndex">
13    <indexed_attr value="room"/>
14  </index>
15  <index name="featured" meta_type="BooleanIndex">
16    <indexed_attr value="featured"/>
17  </index>
19  <column value="audience" />
20  <column value="type_of_talk" />
21  <column value="speaker" />
22  <column value="room" />
23  <column value="featured" />

This adds new indexes for the three fields we want to show in the listing. Note that audience is a KeywordIndex because the field is multi-valued, but we want a separate index entry for every value in an object.

The column .. entries allow us to display the values of these indexes in the tableview of collections.


The new indexes are still empty. We'll have to reindex them. To do so by hand go to http://localhost:8080/Plone/portal_catalog/manage_catalogIndexes, select the new indexes and click Reindex. We could also rebuild the whole catalog by going to the Advanced tab and clicking Clear and Rebuild. For large sites that can take a long time.

We could also write an upgrade step to enable the catalog indexes and reindex all talks:

def add_some_indexes(setup):
    setup.runImportStepFromProfile(default_profile, 'catalog')
    for brain in api.content.find(portal_type='talk'):
        obj = brain.getObject()

Query for custom indexes#

The new indexes behave like the ones that Plone has already built in:

>>> (Pdb) from Products.CMFCore.utils import getToolByName
>>> (Pdb) catalog = getToolByName(self.context, 'portal_catalog')
>>> (Pdb) catalog(type_of_talk='Keynote')
[<Products.ZCatalog.Catalog.mybrains object at 0x10737b9a8>, <Products.ZCatalog.Catalog.mybrains object at 0x10737b9a8>]
>>> (Pdb) catalog(audience=('Advanced', 'Professionals'))
[<Products.ZCatalog.Catalog.mybrains object at 0x10737b870>, <Products.ZCatalog.Catalog.mybrains object at 0x10737b940>, <Products.ZCatalog.Catalog.mybrains object at 0x10737b9a8>]
>>> (Pdb) brain = catalog(type_of_talk='Keynote')[0]
>>> (Pdb) brain.speaker
u'David Glick'

We now can use the new indexes to improve the talklistview so we don't have to wake up the objects anymore. Instead we use the brains' new attributes.

 1class TalkListView(BrowserView):
 2    """ A list of talks
 3    """
 5    def talks(self):
 6        results = []
 7        brains = api.content.find(context=self.context, portal_type='talk')
 8        for brain in brains:
 9            results.append({
10                'title': brain.Title,
11                'description': brain.Description,
12                'url': brain.getURL(),
13                'audience': ', '.join(brain.audience or []),
14                'type_of_talk': brain.type_of_talk,
15                'speaker': brain.speaker,
16                'room':,
17                'uuid': brain.UID,
18                })
19        return results

The template does not need to be changed and the result in the browser did not change either. But when listing a large number of objects the site will now be faster since all the data you use comes from the catalog and the objects do not have to be loaded into memory.

Exercise 1#

In fact we could now simplify the view even further by only returning the brains.

Modify TalkListView to return only brains and adapt the template to these changes. Remember to move ', '.join(brain.audience or []) into the template.


Here is the class:

1class TalkListView(BrowserView):
2    """ A list of talks
3    """
5    def talks(self):
6        return api.content.find(context=self.context, portal_type='talk')

Here is the template:

 1<html xmlns="" xml:lang="en" lang="en"
 2      metal:use-macro="context/main_template/macros/master"
 3      i18n:domain="">
 5  <metal:content-core fill-slot="content-core">
 7  <table class="listing"
 8         id="talks"
 9         tal:define="brains python:view.talks()">
10    <thead>
11      <tr>
12        <th>Title</th>
13        <th>Speaker</th>
14        <th>Audience</th>
15        <th>Room</th>
16      </tr>
17    </thead>
18    <tbody>
19      <tr tal:repeat="brain brains">
20        <td>
21          <a href=""
22             tal:attributes="href python:brain.getURL();
23                             title python:brain.Description"
24             tal:content="python:brain.Title">
25             The 7 sins of Plone development
26          </a>
27        </td>
28        <td tal:content="python:brain.speaker">
29            Philip Bauer
30        </td>
31        <td tal:content="python:', '.join(brain.audience or [])">
32            Advanced
33        </td>
34        <td tal:content="">
35            Room 101
36        </td>
37      </tr>
38      <tr tal:condition="not:brains">
39        <td colspan=4>
40            No talks so far :-(
41        </td>
42      </tr>
43    </tbody>
44  </table>
46  </metal:content-core>

Add collection criteria#

To be able to search content in collections using these new indexes we would have to register them as criteria for the querystring widget that collections use. As with all features make sure you only do this if you really need it!

Add a new file profiles/default/registry.xml

 2  <records interface=""
 3           prefix="">
 4    <value key="title">Audience</value>
 5    <value key="description">A custom speaker index</value>
 6    <value key="enabled">True</value>
 7    <value key="sortable">False</value>
 8    <value key="operations">
 9      <element></element>
10    </value>
11    <value key="group">Metadata</value>
12  </records>
13  <records interface=""
14           prefix="">
15    <value key="title">Type of Talk</value>
16    <value key="description">A custom index</value>
17    <value key="enabled">True</value>
18    <value key="sortable">False</value>
19    <value key="operations">
20      <element></element>
21    </value>
22    <value key="group">Metadata</value>
23  </records>
24  <records interface=""
25           prefix="">
26    <value key="title">Speaker</value>
27    <value key="description">A custom index</value>
28    <value key="enabled">True</value>
29    <value key="sortable">False</value>
30    <value key="operations">
31      <element></element>
32    </value>
33    <value key="group">Metadata</value>
34  </records>

Add versioning through GenericSetup#

Configure the versioning policy and a diff view for talks through GenericSetup.

Add new file profiles/default/repositorytool.xml

1<?xml version="1.0"?>
3  <policymap>
4    <type name="talk">
5      <policy name="at_edit_autoversion"/>
6      <policy name="version_on_revert"/>
7    </type>
8  </policymap>

Add new file profiles/default/diff_tool.xml

1<?xml version="1.0"?>
3  <difftypes>
4    <type portal_type="talk">
5      <field name="any" difftype="Compound Diff for Dexterity types"/>
6    </type>
7  </difftypes>

Finally you need to activate the versioning behavior on the content type. Edit profiles/default/types/talk.xml:

1<property name="behaviors">
2 <element value="plone.dublincore"/>
3 <element value="plone.namefromtitle"/>
4 <element value=""/>
5 <element value=""/>
6 <element value="plone.versioning" />


There is currently a bug that breaks showing diffs when multiple-choice fields were changed.


The talks are now grown up:

  • They provide a interface to which you can bind features like views

  • Some fields are indexed in the catalog making the listing faster

  • Talks are now versioned

  • You wrote your first upgrade step to move the talks around: yipee!