from project.common.blocks import build_stream_field from wagtail.admin.edit_handlers import StreamFieldPanel, FieldPanel from wagtail.search import index from project.common.models import Entity from django.db import models from wagtail.contrib.routable_page.models import RoutablePageMixin, route from modelcluster.fields import ParentalKey from modelcluster.contrib.taggit import ClusterTaggableManager from taggit.models import TaggedItemBase, Tag class BlogPageTag(TaggedItemBase): content_object = ParentalKey( 'BlogPage', related_name='tagged_items', on_delete=models.CASCADE ) class BlogPage(Entity): body = build_stream_field() tags = ClusterTaggableManager(through=BlogPageTag, blank=True) search_fields = Entity.search_fields + [ index.SearchField('body'), ] content_panels = Entity.content_panels + [ StreamFieldPanel('body'), FieldPanel('tags') ] class Meta: ordering = ('post_date',) def get_date_group(self): if self.post_date: return self.post_date.strftime("%Y-%m") class BlogIndexPage(RoutablePageMixin, Entity): body = build_stream_field() subpage_types = [BlogPage] content_panels = Entity.content_panels + [ StreamFieldPanel('body') ] @route(r'^tag/(\w+)/$') def tags(self, request, *args, **kwargs): self.tag_filter = args[0] return Entity.serve(self, request, *args, **kwargs) def get_context(self, request, *args, **kwargs): context = super().get_context(request) child_pages = self.get_children().specific().live().values_list('id', flat=True) context['blogs'] = BlogPage.objects.filter(id__in=child_pages) if hasattr(self, 'tag_filter'): context['tag'] = self.tag_filter context['blogs'] = context['blogs'].filter(tags__name=self.tag_filter) return context