models.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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'
  25. )
  26. people = models.ForeignKey(
  27. 'base.People', related_name='person_blog_relationship'
  28. )
  29. panels = [
  30. SnippetChooserPanel('people')
  31. ]
  32. class BlogPageTag(TaggedItemBase):
  33. """
  34. This model allows us to creates 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/v1.9/reference/pages/model_recipes.html#tagging
  37. """
  38. content_object = ParentalKey('BlogPage', related_name='tagged_items')
  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/v1.9/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('title'),
  78. index.SearchField('body'),
  79. ]
  80. def authors(self):
  81. """
  82. Returns the BlogPage's related People. Again note that we are using
  83. the ParentalKey's related_name from the BlogPeopleRelationship model
  84. to access these objects. This allows us to access the People objects
  85. with a loop on the template. If we tried to access the blog_person_
  86. relationship directly we'd print `blog.BlogPeopleRelationship.None`
  87. """
  88. authors = [
  89. n.people for n in self.blog_person_relationship.all()
  90. ]
  91. return authors
  92. @property
  93. def get_tags(self):
  94. """
  95. Similar to the authors function above we're returning all the tags that
  96. are related to the blog post into a list we can access on the template.
  97. We're additionally adding a URL to access BlogPage objects with that tag
  98. """
  99. tags = self.tags.all()
  100. for tag in tags:
  101. tag.url = '/'+'/'.join(s.strip('/') for s in [
  102. self.get_parent().url,
  103. 'tags',
  104. tag.slug
  105. ])
  106. return tags
  107. # Defines parent to BlogPage as being BlogIndexPages
  108. parent_page_types = ['BlogIndexPage']
  109. # Defines what content types can exist as children of BlogPage.
  110. # Empty list means that no child content types are allowed.
  111. subpage_types = []
  112. class BlogIndexPage(RoutablePageMixin, Page):
  113. """
  114. Index page for blogs.
  115. We need to alter the page model's context to return the child page objects,
  116. the BlogPage objects, so that it works as an index page
  117. RoutablePageMixin is used to allow for a custom sub-URL for the tag views
  118. defined above.
  119. """
  120. introduction = models.TextField(
  121. help_text='Text to describe the page',
  122. blank=True)
  123. image = models.ForeignKey(
  124. 'wagtailimages.Image',
  125. null=True,
  126. blank=True,
  127. on_delete=models.SET_NULL,
  128. related_name='+',
  129. help_text='Landscape mode only; horizontal width between 1000px and 3000px.'
  130. )
  131. content_panels = Page.content_panels + [
  132. FieldPanel('introduction', classname="full"),
  133. ImageChooserPanel('image'),
  134. ]
  135. # Defines that only BlogPage objects can live under this index page
  136. subpage_types = ['BlogPage']
  137. # Defines a function to access the children of the page (e.g. BlogPage
  138. # objects). On the demo site we use this on the HomePage
  139. def children(self):
  140. return self.get_children().specific().live()
  141. # Overrides the context to list all child items, that are live, by the
  142. # date that they were published
  143. # http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html#overriding-context
  144. def get_context(self, request):
  145. context = super(BlogIndexPage, self).get_context(request)
  146. context['posts'] = BlogPage.objects.descendant_of(
  147. self).live().order_by(
  148. '-date_published')
  149. return context
  150. # This defines a Custom view that utilizes Tags. This view will return all
  151. # related BlogPages for a given Tag or redirect back to the BlogIndexPage.
  152. # More information on RoutablePages is at
  153. # http://docs.wagtail.io/en/v1.9/reference/contrib/routablepage.html
  154. @route('^tags/$', name='tag_archive')
  155. @route('^tags/(\w+)/$', name='tag_archive')
  156. def tag_archive(self, request, tag=None):
  157. try:
  158. tag = Tag.objects.get(slug=tag)
  159. except Tag.DoesNotExist:
  160. if tag:
  161. msg = 'There are no blog posts tagged with "{}"'.format(tag)
  162. messages.add_message(request, messages.INFO, msg)
  163. return redirect(self.url)
  164. posts = self.get_posts(tag=tag)
  165. context = {
  166. 'tag': tag,
  167. 'posts': posts
  168. }
  169. return render(request, 'blog/blog_index_page.html', context)
  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