models.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 bakerydemo.base.blocks import BaseStreamBlock
  14. from bakerydemo.base.models import Person
  15. class BlogPersonRelationship(Orderable, models.Model):
  16. """
  17. This defines the relationship between the `Person` 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 Person using
  20. the ParentalKey and ForeignKey
  21. """
  22. page = ParentalKey(
  23. "BlogPage", related_name="blog_person_relationship", on_delete=models.CASCADE
  24. )
  25. person = models.ForeignKey(
  26. "base.Person", related_name="person_blog_relationship", on_delete=models.CASCADE
  27. )
  28. panels = [FieldPanel("person")]
  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 Person object with an inline panel that references the
  42. ParentalKey's related_name in BlogPersonRelationship. More docs:
  43. https://docs.wagtail.org/en/stable/topics/pages.html#inline-models
  44. """
  45. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  46. image = models.ForeignKey(
  47. "wagtailimages.Image",
  48. null=True,
  49. blank=True,
  50. on_delete=models.SET_NULL,
  51. related_name="+",
  52. help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
  53. )
  54. body = StreamField(
  55. BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True
  56. )
  57. subtitle = models.CharField(blank=True, max_length=255)
  58. tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
  59. date_published = models.DateField("Date article published", blank=True, null=True)
  60. content_panels = Page.content_panels + [
  61. FieldPanel("subtitle"),
  62. FieldPanel("introduction"),
  63. FieldPanel("image"),
  64. FieldPanel("body"),
  65. FieldPanel("date_published"),
  66. InlinePanel(
  67. "blog_person_relationship",
  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. return Person.objects.filter(live=True, person_blog_relationship__page=self)
  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. base_url = self.get_parent().url
  96. for tag in tags:
  97. tag.url = f"{base_url}tags/{tag.slug}/"
  98. return tags
  99. # Specifies parent to BlogPage as being BlogIndexPages
  100. parent_page_types = ["BlogIndexPage"]
  101. # Specifies what content types can exist as children of BlogPage.
  102. # Empty list means that no child content types are allowed.
  103. subpage_types = []
  104. class BlogIndexPage(RoutablePageMixin, Page):
  105. """
  106. Index page for blogs.
  107. We need to alter the page model's context to return the child page objects,
  108. the BlogPage objects, so that it works as an index page
  109. RoutablePageMixin is used to allow for a custom sub-URL for the tag views
  110. defined above.
  111. """
  112. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  113. image = models.ForeignKey(
  114. "wagtailimages.Image",
  115. null=True,
  116. blank=True,
  117. on_delete=models.SET_NULL,
  118. related_name="+",
  119. help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
  120. )
  121. content_panels = Page.content_panels + [
  122. FieldPanel("introduction"),
  123. FieldPanel("image"),
  124. ]
  125. # Specifies that only BlogPage objects can live under this index page
  126. subpage_types = ["BlogPage"]
  127. # Defines a method to access the children of the page (e.g. BlogPage
  128. # objects). On the demo site we use this on the HomePage
  129. def children(self):
  130. return self.get_children().specific().live()
  131. # Overrides the context to list all child items, that are live, by the
  132. # date that they were published
  133. # https://docs.wagtail.org/en/stable/getting_started/tutorial.html#overriding-context
  134. def get_context(self, request):
  135. context = super(BlogIndexPage, self).get_context(request)
  136. context["posts"] = (
  137. BlogPage.objects.descendant_of(self).live().order_by("-date_published")
  138. )
  139. return context
  140. # This defines a Custom view that utilizes Tags. This view will return all
  141. # related BlogPages for a given Tag or redirect back to the BlogIndexPage.
  142. # More information on RoutablePages is at
  143. # https://docs.wagtail.org/en/stable/reference/contrib/routablepage.html
  144. @route(r"^tags/$", name="tag_archive")
  145. @route(r"^tags/([\w-]+)/$", name="tag_archive")
  146. def tag_archive(self, request, tag=None):
  147. try:
  148. tag = Tag.objects.get(slug=tag)
  149. except Tag.DoesNotExist:
  150. if tag:
  151. msg = 'There are no blog posts tagged with "{}"'.format(tag)
  152. messages.add_message(request, messages.INFO, msg)
  153. return redirect(self.url)
  154. posts = self.get_posts(tag=tag)
  155. context = {"tag": tag, "posts": posts}
  156. return render(request, "blog/blog_index_page.html", context)
  157. def serve_preview(self, request, mode_name):
  158. # Needed for previews to work
  159. return self.serve(request)
  160. # Returns the child BlogPage objects for this BlogPageIndex.
  161. # If a tag is used then it will filter the posts by tag.
  162. def get_posts(self, tag=None):
  163. posts = BlogPage.objects.live().descendant_of(self)
  164. if tag:
  165. posts = posts.filter(tags=tag)
  166. return posts
  167. # Returns the list of Tags for all child posts of this BlogPage.
  168. def get_child_tags(self):
  169. tags = []
  170. for post in self.get_posts():
  171. # Not tags.append() because we don't want a list of lists
  172. tags += post.get_tags
  173. tags = sorted(set(tags))
  174. return tags