Customizing the frontend rendering

As displayed in the Example plugin code page, a page type is made of two classes:

  • A model class in models.py.
  • A plugin class in page_type_plugins.py.

The plugin class renders the model instance using:

Simply stated, a plugin provides the “view” of the “page”.

Simple rendering

To quickly create plugins with little to no effort, only the render_template needs to be specified. The template code receives the model object via the instance variable.

To switch the template depending on the model, the get_render_template() method can be overwritten instead. For example:

@page_type.register
class MyPageType(PageTypePlugin):
    # ...

    def get_render_template(self, request, page, **kwargs):
        return page.template_name or self.render_template

To add more context data, overwrite the get_context method.

Custom rendering

Instead of only providing extra context data, the whole get_response() method can be overwritten as well.

The textfile and redirectnode page types use this for example:

def get_response(self, request, redirectnode, **kwargs):
    response = HttpResponseRedirect(redirectnode.new_url)
    response.status_code = redirectnode.redirect_type
    return response

The standard get_response() method basically does the following:

def get_response(self, request, page, **kwargs):
    render_template = self.get_render_template(request, page, **kwargs)
    context = self.get_context(request, page, **kwargs)
    return self.response_class(
        request = request,
        template = render_template,
        context = context,
    )

Note

The PageTypePlugin class is instantiated once, just like the ModelAdmin class. Unlike the Django class based views, it’s not possible to store state at the local instance.