March 11, 2017  
In Articles by Iunary

Using categories or tags is a common thing in almost all web applications, especially content management systems and i will write a quick simple consuming article over that.

Wagtail is shipped with a tagging capability through the famous module taggit combaned with modelcluster, we are going to use it as our pages filter. To make a seo friendly urls we are going to use a very interesting mixin provided by wagtail named RoutablePageMixin and it can be useful for many use cases.

First let's write our models, considering that we are working in the home application that is created when we create our wagtail project:

from wagtail.wagtailcore.models import Page
from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase
from wagtail.wagtailadmin.edit_handlers import FieldPanel

class PostTag(TaggedItemBase):
    content_object = ParentalKey('home.PostPage', related_name='tagged_items')

class PostPage(Page):
    body = RichTextField()
    tags = ClusterTaggableManager(through=PostTag, blank=True)

    content_panels = [
            FieldPanel('title', classname="full title"),
            FieldPanel('description', classname="full"),

This is it for our tags and post page, now we are going to use the Home page model as the parent of the Post page model and we will make it inherites from the RoutablePageMixin beside the Page model, so the code will looks like that:

from wagtail.contrib.wagtailroutablepage.models import RoutablePageMixin, route
from django.template.response import TemplateResponse

class Home(Page):
    subpage_types = ['home.PostPage']

    def posts(self):
        posts = PostPage.objects.live().descendant_of(self)
        posts = posts.order_by('-latest_revision_created_at')
        return posts

    @route(r'^tag/([\w-]+)/$', name='slug')
    def tag(self, request, slug):
        posts = self.posts.filter(tags__slug=slug)

        return TemplateResponse(request,
                                {'posts': posts}

for the route decorator you can use any url pattern same as you use in django urls and that's it. Hopefully this simple post will be useful for you.

Usefull links:



There are currently no comments. You can be first!

Sign in