models.py 7.5 KB

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