2
0

models.py 7.7 KB

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