Wagtail defaults to serving Page-derived models by passing a reference to the page object to a Django HTML template matching the model’s name, but suppose you wanted to serve something other than HTML? You can override the serve() method provided by the Page class and handle the Django request and response more directly.

Consider this example from the Wagtail demo site’s models.py, which serves an EventPage object as an iCal file if the format variable is set in the request:

serve() takes a Django request object and returns a Django response object. Wagtail returns a TemplateResponse object with the template and context which it generates, which allows middleware to function as intended, so keep in mind that a simpler response object like a HttpResponse will not receive these benefits.

With this strategy, you could use Django or Python utilities to render your model in JSON or XML or any other format you’d like.

A much simpler way of adding more endpoints to pages is provided by the routable_page module.

Wagtail routes requests by iterating over the path components (separated with a forward slash /), finding matching objects based on their slug, and delegating further routing to that object’s model class. The Wagtail source is very instructive in figuring out what’s happening. This is the default route() method of the Page class:

classPage(...):...defroute(self,request,path_components):ifpath_components:# request is for a child of this pagechild_slug=path_components[0]remaining_components=path_components[1:]# find a matching child or 404try:subpage=self.get_children().get(slug=child_slug)exceptPage.DoesNotExist:raiseHttp404# delegate further routingreturnsubpage.specific.route(request,remaining_components)else:# request is for this very pageifself.live:# Return a RouteResult that will tell Wagtail to call# this page's serve() methodreturnRouteResult(self)else:# the page matches the request, but isn't published, so 404raiseHttp404

route() takes the current object (self), the request object, and a list of the remaining path_components from the request URL. It either continues delegating routing by calling route() again on one of its children in the Wagtail tree, or ends the routing process by returning a RouteResult object or raising a 404 error.

The RouteResult object (defined in wagtail.core.url_routing) encapsulates all the information Wagtail needs to call a page’s serve() method and return a final response: this information consists of the page object, and any additional args/kwargs to be passed to serve().

By overriding the route() method, we could create custom endpoints for each object in the Wagtail tree. One use case might be using an alternate template when encountering the print/ endpoint in the path. Another might be a REST API which interacts with the current object. Just to see what’s involved, lets make a simple model which prints out all of its child path components.

First, models.py:

fromdjango.shortcutsimportrenderfromwagtail.core.url_routingimportRouteResultfromdjango.http.responseimportHttp404fromwagtail.core.modelsimportPage...classEchoer(Page):defroute(self,request,path_components):ifpath_components:# tell Wagtail to call self.serve() with an additional 'path_components' kwargreturnRouteResult(self,kwargs={'path_components':path_components})else:ifself.live:# tell Wagtail to call self.serve() with no further argsreturnRouteResult(self)else:raiseHttp404defserve(self,path_components=[]):returnrender(request,self.template,{'page':self,'echo':' '.join(path_components),})

This model, Echoer, doesn’t define any properties, but does subclass Page so objects will be able to have a custom title and slug. The template just has to display our {{echo}} property.

Now, once creating a new Echoer page in the Wagtail admin titled “Echo Base,” requests such as:

http://127.0.0.1:8000/echo-base/tauntaun/kennel/bed/and/breakfast/

Will return:

tauntaunkennelbedandbreakfast

Be careful if you’re introducing new required arguments to the serve() method - Wagtail still needs to be able to display a default view of the page for previewing and moderation, and by default will attempt to do this by calling serve() with a request object and no further arguments. If your serve() method does not accept that as a method signature, you will need to override the page’s serve_preview() method to call serve() with suitable arguments:

Wagtail provides tagging capabilities through the combination of two Django modules, django-taggit (which provides a general-purpose tagging implementation) and django-modelcluster (which extends django-taggit’s TaggableManager to allow tag relations to be managed in memory without writing to the database - necessary for handling previews and revisions). To add tagging to a page model, you’ll need to define a ‘through’ model inheriting from TaggedItemBase to set up the many-to-many relationship between django-taggit’s Tag model and your page model, and add a ClusterTaggableManager accessor to your page model to present this relation as a single tag field.

In this example, we set up tagging on BlogPage through a BlogPageTag model:

We can now make use of the many-to-many tag relationship in our views and templates. For example, we can set up the blog’s index page to accept a ?tag=... query parameter to filter the BlogPage listing by tag:

Here, blog_entries.filter(tags__name=tag) follows the tags relation on BlogPage, to filter the listing to only those pages with a matching tag name before passing this to the template for rendering. We can now update the blog_page.html template to show a list of tags associated with the page, with links back to the filtered index page:

Iterating through page.tags.all will display each tag associated with page, while the links back to the index make use of the filter option added to the BlogIndexPage model. A Django query could also use the tagged_items related name field to get BlogPage objects associated with a tag.

The same approach can be used to add tagging to non-page models managed through Snippets and ModelAdmin. In this case, the model must inherit from modelcluster.models.ClusterableModel to be compatible with ClusterTaggableManager.

In the above example, any newly-created tags will be added to django-taggit’s default Tag model, which will be shared by all other models using the same recipe as well as Wagtail’s image and document models. In particular, this means that the autocompletion suggestions on tag fields will include tags previously added to other models. To avoid this, you can set up a custom tag model inheriting from TagBase, along with a ‘through’ model inheriting from ItemBase, which will provide an independent pool of tags for that page model.

By default, tag fields work on a “free tagging” basis: editors can enter anything into the field, and upon saving, any tag text not recognised as an existing tag will be created automatically. To disable this behaviour, and only allow editors to enter tags that already exist in the database, custom tag models accept a free_tagging=False option:

Here we have registered BlogTag as a snippet, to provide an interface for administrators (and other users with the appropriate permissions) to manage the allowed set of tags. With the free_tagging=False option set, editors can no longer enter arbitrary text into the tag field, and must instead select existing tags from the autocomplete dropdown.

You may want redirects created automatically when a url gets changed in the admin so as to avoid broken links. You can add something like the following block to a wagtail_hooks.py file within one of your project’s apps.