models.py 7.7 KB

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