models.py 7.9 KB

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