models.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. from __future__ import unicode_literals
  2. from django.contrib import messages
  3. from django.db import models
  4. from django.shortcuts import redirect, render
  5. from modelcluster.contrib.taggit import ClusterTaggableManager
  6. from modelcluster.fields import ParentalKey
  7. from taggit.models import Tag, TaggedItemBase
  8. from wagtail.contrib.wagtailroutablepage.models import RoutablePageMixin, route
  9. from wagtail.wagtailadmin.edit_handlers import (
  10. FieldPanel, InlinePanel, StreamFieldPanel
  11. )
  12. from wagtail.wagtailcore.fields import StreamField
  13. from wagtail.wagtailcore.models import Page, Orderable
  14. from wagtail.wagtailsearch import index
  15. from wagtail.wagtailsnippets.edit_handlers import SnippetChooserPanel
  16. from bakerydemo.base.blocks import BaseStreamBlock
  17. from bakerydemo.base.models import BasePageFieldsMixin
  18. class BlogPeopleRelationship(Orderable, models.Model):
  19. """
  20. This defines the relationship between the `People` within the `base`
  21. app and the BlogPage below allowing us to add people to a BlogPage.
  22. """
  23. page = ParentalKey(
  24. 'BlogPage', related_name='blog_person_relationship'
  25. )
  26. people = models.ForeignKey(
  27. 'base.People', related_name='person_blog_relationship'
  28. )
  29. panels = [
  30. SnippetChooserPanel('people')
  31. ]
  32. class BlogPageTag(TaggedItemBase):
  33. content_object = ParentalKey('BlogPage', related_name='tagged_items')
  34. class BlogPage(BasePageFieldsMixin, Page):
  35. """
  36. A Blog Page (Post)
  37. """
  38. subtitle = models.CharField(blank=True, max_length=255)
  39. tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
  40. date_published = models.DateField("Date article published", blank=True, null=True)
  41. body = StreamField(
  42. BaseStreamBlock(), verbose_name="Blog post", blank=True
  43. )
  44. content_panels = BasePageFieldsMixin.content_panels + [
  45. StreamFieldPanel('body'),
  46. FieldPanel('date_published'),
  47. InlinePanel(
  48. 'blog_person_relationship', label="Author(s)",
  49. panels=None, min_num=1),
  50. FieldPanel('tags'),
  51. ]
  52. # Inject subtitle panel after title field
  53. title_index = next((i for i, panel in enumerate(content_panels) if panel.field_name == 'title'), -1) # noqa
  54. content_panels.insert(title_index + 1, FieldPanel('subtitle'))
  55. search_fields = Page.search_fields + [
  56. index.SearchField('title'),
  57. index.SearchField('body'),
  58. ]
  59. def authors(self):
  60. """
  61. Returns the BlogPage's related People
  62. """
  63. authors = [
  64. n.people for n in self.blog_person_relationship.all()
  65. ]
  66. return authors
  67. @property
  68. def get_tags(self):
  69. """
  70. Returns the BlogPage's related list of Tags.
  71. Each Tag is modified to include a url attribute
  72. """
  73. tags = self.tags.all()
  74. for tag in tags:
  75. tag.url = '/'+'/'.join(s.strip('/') for s in [
  76. self.get_parent().url,
  77. 'tags',
  78. tag.slug
  79. ])
  80. return tags
  81. parent_page_types = ['BlogIndexPage']
  82. # Define what content types can exist as children of BlogPage.
  83. # Empty list means that no child content types are allowed.
  84. subpage_types = []
  85. class BlogIndexPage(BasePageFieldsMixin, RoutablePageMixin, Page):
  86. """
  87. Index page for blogs.
  88. We need to alter the page model's context to return the child page objects - the
  89. BlogPage - so that it works as an index page
  90. RoutablePageMixin is used to allow for a custom sub-URL for tag views.
  91. """
  92. # What pages types can live under this page type?
  93. subpage_types = ['BlogPage']
  94. def children(self):
  95. return self.get_children().specific().live()
  96. def get_context(self, request):
  97. context = super(BlogIndexPage, self).get_context(request)
  98. context['posts'] = BlogPage.objects.descendant_of(
  99. self).live().order_by(
  100. '-date_published')
  101. return context
  102. @route('^tags/$', name='tag_archive')
  103. @route('^tags/(\w+)/$', name='tag_archive')
  104. def tag_archive(self, request, tag=None):
  105. """
  106. A Custom view that utilizes Tags.
  107. This view will return all related BlogPages for a given Tag or
  108. redirect back to the BlogIndexPage.
  109. """
  110. try:
  111. tag = Tag.objects.get(slug=tag)
  112. except Tag.DoesNotExist:
  113. if tag:
  114. msg = 'There are no blog posts tagged with "{}"'.format(tag)
  115. messages.add_message(request, messages.INFO, msg)
  116. return redirect(self.url)
  117. posts = self.get_posts(tag=tag)
  118. context = {
  119. 'tag': tag,
  120. 'posts': posts
  121. }
  122. return render(request, 'blog/blog_index_page.html', context)
  123. def get_posts(self, tag=None):
  124. """
  125. Return the child BlogPage objects for this BlogPageIndex.
  126. Optional filter by tag.
  127. """
  128. posts = BlogPage.objects.live().descendant_of(self)
  129. if tag:
  130. posts = posts.filter(tags=tag)
  131. return posts
  132. def get_child_tags(self):
  133. """
  134. Returns the list of Tags for all child posts of this BlogPage.
  135. """
  136. tags = []
  137. for post in self.get_posts():
  138. tags += post.get_tags # Not tags.append() because we don't want a list of lists
  139. tags = sorted(set(tags))
  140. return tags