models.py 5.2 KB

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