models.py 7.5 KB

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