models.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. from django import forms
  2. from django.contrib.contenttypes.fields import GenericRelation
  3. from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
  4. from django.db import models
  5. from modelcluster.fields import ParentalManyToManyField
  6. from wagtail.admin.panels import FieldPanel, MultiFieldPanel
  7. from wagtail.fields import StreamField
  8. from wagtail.models import DraftStateMixin, Page, RevisionMixin
  9. from wagtail.search import index
  10. from bakerydemo.base.blocks import BaseStreamBlock
  11. class Country(models.Model):
  12. """
  13. A Django model to store set of countries of origin.
  14. It is made accessible in the Wagtail admin interface through the CountrySnippetViewSet
  15. class in wagtail_hooks.py. This allows us to customize the admin interface for this snippet.
  16. In the BreadPage model you'll see we use a ForeignKey to create the relationship between
  17. Country and BreadPage. This allows a single relationship (e.g only one
  18. Country can be added) that is one-way (e.g. Country will have no way to
  19. access related BreadPage objects).
  20. """
  21. title = models.CharField(max_length=100)
  22. def __str__(self):
  23. return self.title
  24. class Meta:
  25. verbose_name = "country of origin"
  26. verbose_name_plural = "countries of origin"
  27. class BreadIngredient(DraftStateMixin, RevisionMixin, models.Model):
  28. """
  29. A Django model to store a single ingredient.
  30. It is made accessible in the Wagtail admin interface through the BreadIngredientSnippetViewSet
  31. class in wagtail_hooks.py. This allows us to customize the admin interface for this snippet.
  32. We use a piece of functionality available to Wagtail called the ParentalManyToManyField on the BreadPage
  33. model to display this. The Wagtail Docs give a slightly more detailed example
  34. https://docs.wagtail.org/en/stable/getting_started/tutorial.html#categories
  35. """
  36. name = models.CharField(max_length=255)
  37. revisions = GenericRelation(
  38. "wagtailcore.Revision",
  39. content_type_field="base_content_type",
  40. object_id_field="object_id",
  41. related_query_name="bread_ingredient",
  42. for_concrete_model=False,
  43. )
  44. panels = [
  45. FieldPanel("name"),
  46. ]
  47. def __str__(self):
  48. return self.name
  49. class Meta:
  50. verbose_name = "bread ingredient"
  51. verbose_name_plural = "bread ingredients"
  52. class BreadType(RevisionMixin, models.Model):
  53. """
  54. A Django model to define the bread type
  55. It is made accessible in the Wagtail admin interface through the BreadTypeSnippetViewSet
  56. class in wagtail_hooks.py. This allows us to customize the admin interface for this snippet.
  57. In the BreadPage model you'll see we use a ForeignKey
  58. to create the relationship between BreadType and BreadPage. This allows a
  59. single relationship (e.g only one BreadType can be added) that is one-way
  60. (e.g. BreadType will have no way to access related BreadPage objects)
  61. """
  62. title = models.CharField(max_length=255)
  63. revisions = GenericRelation(
  64. "wagtailcore.Revision",
  65. content_type_field="base_content_type",
  66. object_id_field="object_id",
  67. related_query_name="bread_type",
  68. for_concrete_model=False,
  69. )
  70. panels = [
  71. FieldPanel("title"),
  72. ]
  73. def __str__(self):
  74. return self.title
  75. class Meta:
  76. verbose_name = "bread type"
  77. verbose_name_plural = "bread types"
  78. class BreadPage(Page):
  79. """
  80. Detail view for a specific bread
  81. """
  82. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  83. image = models.ForeignKey(
  84. "wagtailimages.Image",
  85. null=True,
  86. blank=True,
  87. on_delete=models.SET_NULL,
  88. related_name="+",
  89. help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
  90. )
  91. body = StreamField(
  92. BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True
  93. )
  94. origin = models.ForeignKey(
  95. Country,
  96. on_delete=models.SET_NULL,
  97. null=True,
  98. blank=True,
  99. )
  100. # We include related_name='+' to avoid name collisions on relationships.
  101. # e.g. there are two FooPage models in two different apps,
  102. # and they both have a FK to bread_type, they'll both try to create a
  103. # relationship called `foopage_objects` that will throw a valueError on
  104. # collision.
  105. bread_type = models.ForeignKey(
  106. "breads.BreadType",
  107. null=True,
  108. blank=True,
  109. on_delete=models.SET_NULL,
  110. related_name="+",
  111. )
  112. ingredients = ParentalManyToManyField("BreadIngredient", blank=True)
  113. content_panels = Page.content_panels + [
  114. FieldPanel("introduction"),
  115. FieldPanel("image"),
  116. FieldPanel("body"),
  117. FieldPanel("origin"),
  118. FieldPanel("bread_type"),
  119. MultiFieldPanel(
  120. [
  121. FieldPanel(
  122. "ingredients",
  123. widget=forms.CheckboxSelectMultiple,
  124. ),
  125. ],
  126. heading="Additional Metadata",
  127. classname="collapsed",
  128. ),
  129. ]
  130. search_fields = Page.search_fields + [
  131. index.SearchField("body"),
  132. ]
  133. parent_page_types = ["BreadsIndexPage"]
  134. class BreadsIndexPage(Page):
  135. """
  136. Index page for breads.
  137. This is more complex than other index pages on the bakery demo site as we've
  138. included pagination. We've separated the different aspects of the index page
  139. to be discrete functions to make it easier to follow
  140. """
  141. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  142. image = models.ForeignKey(
  143. "wagtailimages.Image",
  144. null=True,
  145. blank=True,
  146. on_delete=models.SET_NULL,
  147. related_name="+",
  148. help_text="Landscape mode only; horizontal width between 1000px and " "3000px.",
  149. )
  150. content_panels = Page.content_panels + [
  151. FieldPanel("introduction"),
  152. FieldPanel("image"),
  153. ]
  154. # Can only have BreadPage children
  155. subpage_types = ["BreadPage"]
  156. # Returns a queryset of BreadPage objects that are live, that are direct
  157. # descendants of this index page with most recent first
  158. def get_breads(self):
  159. return (
  160. BreadPage.objects.live().descendant_of(self).order_by("-first_published_at")
  161. )
  162. # Allows child objects (e.g. BreadPage objects) to be accessible via the
  163. # template. We use this on the HomePage to display child items of featured
  164. # content
  165. def children(self):
  166. return self.get_children().specific().live()
  167. # Pagination for the index page. We use the `django.core.paginator` as any
  168. # standard Django app would, but the difference here being we have it as a
  169. # method on the model rather than within a view function
  170. def paginate(self, request, *args):
  171. page = request.GET.get("page")
  172. paginator = Paginator(self.get_breads(), 12)
  173. try:
  174. pages = paginator.page(page)
  175. except PageNotAnInteger:
  176. pages = paginator.page(1)
  177. except EmptyPage:
  178. pages = paginator.page(paginator.num_pages)
  179. return pages
  180. # Returns the above to the get_context method that is used to populate the
  181. # template
  182. def get_context(self, request):
  183. context = super(BreadsIndexPage, self).get_context(request)
  184. # BreadPage objects (get_breads) are passed through pagination
  185. breads = self.paginate(request, self.get_breads())
  186. context["breads"] = breads
  187. return context