models.py 7.3 KB

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