models.py 7.9 KB

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