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