models.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  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.admin.panels import FieldPanel, InlinePanel
  9. from wagtail.contrib.routable_page.models import RoutablePageMixin, route
  10. from wagtail.fields import StreamField
  11. from wagtail.models import Orderable, Page
  12. from wagtail.search import index
  13. from wagtail_editable_help.models import HelpText
  14. from bakerydemo.base.blocks import BaseStreamBlock
  15. class BlogPeopleRelationship(Orderable, models.Model):
  16. """
  17. This defines the relationship between the `People` within the `base`
  18. app and the BlogPage below. This allows People to be added to a BlogPage.
  19. We have created a two way relationship between BlogPage and People using
  20. the ParentalKey and ForeignKey
  21. """
  22. page = ParentalKey(
  23. "BlogPage", related_name="blog_person_relationship", on_delete=models.CASCADE
  24. )
  25. people = models.ForeignKey(
  26. "base.People", related_name="person_blog_relationship", on_delete=models.CASCADE
  27. )
  28. panels = [FieldPanel("people")]
  29. class BlogPageTag(TaggedItemBase):
  30. """
  31. This model allows us to create a many-to-many relationship between
  32. the BlogPage object and tags. There's a longer guide on using it at
  33. https://docs.wagtail.org/en/stable/reference/pages/model_recipes.html#tagging
  34. """
  35. content_object = ParentalKey(
  36. "BlogPage", related_name="tagged_items", on_delete=models.CASCADE
  37. )
  38. class BlogPage(Page):
  39. """
  40. A Blog Page
  41. We access the People object with an inline panel that references the
  42. ParentalKey's related_name in BlogPeopleRelationship. More docs:
  43. https://docs.wagtail.org/en/stable/topics/pages.html#inline-models
  44. """
  45. introduction = models.TextField(
  46. help_text=HelpText("Blog page introduction", default="Text to describe the page"),
  47. blank=True,
  48. )
  49. image = models.ForeignKey(
  50. "wagtailimages.Image",
  51. null=True,
  52. blank=True,
  53. on_delete=models.SET_NULL,
  54. related_name="+",
  55. help_text=HelpText("Hero image", default="Landscape mode only; horizontal width between 1000px and 3000px."),
  56. )
  57. body = StreamField(
  58. BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True
  59. )
  60. subtitle = models.CharField(blank=True, max_length=255)
  61. tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
  62. date_published = models.DateField("Date article published", blank=True, null=True)
  63. content_panels = Page.content_panels + [
  64. FieldPanel("subtitle", classname="full"),
  65. FieldPanel("introduction", classname="full"),
  66. FieldPanel("image"),
  67. FieldPanel("body"),
  68. FieldPanel("date_published"),
  69. InlinePanel(
  70. "blog_person_relationship", label="Author(s)", panels=None, min_num=1
  71. ),
  72. FieldPanel("tags"),
  73. ]
  74. search_fields = Page.search_fields + [
  75. index.SearchField("body"),
  76. ]
  77. def authors(self):
  78. """
  79. Returns the BlogPage's related People. Again note that we are using
  80. the ParentalKey's related_name from the BlogPeopleRelationship model
  81. to access these objects. This allows us to access the People objects
  82. with a loop on the template. If we tried to access the blog_person_
  83. relationship directly we'd print `blog.BlogPeopleRelationship.None`
  84. """
  85. authors = [n.people for n in self.blog_person_relationship.all()]
  86. return authors
  87. @property
  88. def get_tags(self):
  89. """
  90. Similar to the authors function above we're returning all the tags that
  91. are related to the blog post into a list we can access on the template.
  92. We're additionally adding a URL to access BlogPage objects with that tag
  93. """
  94. tags = self.tags.all()
  95. for tag in tags:
  96. tag.url = "/" + "/".join(
  97. s.strip("/") for s in [self.get_parent().url, "tags", tag.slug]
  98. )
  99. return tags
  100. # Specifies parent to BlogPage as being BlogIndexPages
  101. parent_page_types = ["BlogIndexPage"]
  102. # Specifies what content types can exist as children of BlogPage.
  103. # Empty list means that no child content types are allowed.
  104. subpage_types = []
  105. class BlogIndexPage(RoutablePageMixin, Page):
  106. """
  107. Index page for blogs.
  108. We need to alter the page model's context to return the child page objects,
  109. the BlogPage objects, so that it works as an index page
  110. RoutablePageMixin is used to allow for a custom sub-URL for the tag views
  111. defined above.
  112. """
  113. introduction = models.TextField(
  114. help_text=HelpText("Blog index page introduction", default="Text to describe the page"),
  115. blank=True
  116. )
  117. image = models.ForeignKey(
  118. "wagtailimages.Image",
  119. null=True,
  120. blank=True,
  121. on_delete=models.SET_NULL,
  122. related_name="+",
  123. help_text=HelpText("Hero image", default="Landscape mode only; horizontal width between 1000px and 3000px."),
  124. )
  125. content_panels = Page.content_panels + [
  126. FieldPanel("introduction", classname="full"),
  127. FieldPanel("image"),
  128. ]
  129. # Speficies that only BlogPage objects can live under this index page
  130. subpage_types = ["BlogPage"]
  131. # Defines a method to access the children of the page (e.g. BlogPage
  132. # objects). On the demo site we use this on the HomePage
  133. def children(self):
  134. return self.get_children().specific().live()
  135. # Overrides the context to list all child items, that are live, by the
  136. # date that they were published
  137. # https://docs.wagtail.org/en/stable/getting_started/tutorial.html#overriding-context
  138. def get_context(self, request):
  139. context = super(BlogIndexPage, self).get_context(request)
  140. context["posts"] = (
  141. BlogPage.objects.descendant_of(self).live().order_by("-date_published")
  142. )
  143. return context
  144. # This defines a Custom view that utilizes Tags. This view will return all
  145. # related BlogPages for a given Tag or redirect back to the BlogIndexPage.
  146. # More information on RoutablePages is at
  147. # https://docs.wagtail.org/en/stable/reference/contrib/routablepage.html
  148. @route(r"^tags/$", name="tag_archive")
  149. @route(r"^tags/([\w-]+)/$", name="tag_archive")
  150. def tag_archive(self, request, tag=None):
  151. try:
  152. tag = Tag.objects.get(slug=tag)
  153. except Tag.DoesNotExist:
  154. if tag:
  155. msg = 'There are no blog posts tagged with "{}"'.format(tag)
  156. messages.add_message(request, messages.INFO, msg)
  157. return redirect(self.url)
  158. posts = self.get_posts(tag=tag)
  159. context = {"tag": tag, "posts": posts}
  160. return render(request, "blog/blog_index_page.html", context)
  161. def serve_preview(self, request, mode_name):
  162. # Needed for previews to work
  163. return self.serve(request)
  164. # Returns the child BlogPage objects for this BlogPageIndex.
  165. # If a tag is used then it will filter the posts by tag.
  166. def get_posts(self, tag=None):
  167. posts = BlogPage.objects.live().descendant_of(self)
  168. if tag:
  169. posts = posts.filter(tags=tag)
  170. return posts
  171. # Returns the list of Tags for all child posts of this BlogPage.
  172. def get_child_tags(self):
  173. tags = []
  174. for post in self.get_posts():
  175. # Not tags.append() because we don't want a list of lists
  176. tags += post.get_tags
  177. tags = sorted(set(tags))
  178. return tags