2
0

models.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. from datetime import datetime
  2. from django.conf import settings
  3. from django.core.validators import RegexValidator
  4. from django.db import models
  5. from modelcluster.fields import ParentalKey
  6. from wagtail.admin.panels import FieldPanel, InlinePanel
  7. from wagtail.api import APIField
  8. from wagtail.fields import StreamField
  9. from wagtail.models import Orderable, Page
  10. from wagtail.search import index
  11. from bakerydemo.base.blocks import BaseStreamBlock
  12. from bakerydemo.headless import CustomHeadlessMixin
  13. from bakerydemo.locations.choices import DAY_CHOICES
  14. class OperatingHours(models.Model):
  15. """
  16. A Django model to capture operating hours for a Location
  17. """
  18. day = models.CharField(max_length=3, choices=DAY_CHOICES, default="MON")
  19. opening_time = models.TimeField(blank=True, null=True)
  20. closing_time = models.TimeField(blank=True, null=True)
  21. closed = models.BooleanField(
  22. "Closed?", blank=True, help_text="Tick if location is closed on this day"
  23. )
  24. api_fields = [
  25. APIField("day"),
  26. APIField("get_day_display"),
  27. APIField("opening_time"),
  28. APIField("closing_time"),
  29. APIField("closed"),
  30. ]
  31. panels = [
  32. FieldPanel("day"),
  33. FieldPanel("opening_time"),
  34. FieldPanel("closing_time"),
  35. FieldPanel("closed"),
  36. ]
  37. class Meta:
  38. abstract = True
  39. def __str__(self):
  40. if self.opening_time:
  41. opening = self.opening_time.strftime("%H:%M")
  42. else:
  43. opening = "--"
  44. if self.closing_time:
  45. closed = self.closing_time.strftime("%H:%M")
  46. else:
  47. closed = "--"
  48. return "{}: {} - {} {}".format(self.day, opening, closed, settings.TIME_ZONE)
  49. class LocationOperatingHours(Orderable, OperatingHours):
  50. """
  51. A model creating a relationship between the OperatingHours and Location
  52. Note that unlike BlogPersonRelationship we don't include a ForeignKey to
  53. OperatingHours as we don't need that relationship (e.g. any Location open
  54. a certain day of the week). The ParentalKey is the minimum required to
  55. relate the two objects to one another. We use the ParentalKey's related_
  56. name to access it from the LocationPage admin
  57. """
  58. location = ParentalKey(
  59. "LocationPage", related_name="hours_of_operation", on_delete=models.CASCADE
  60. )
  61. class LocationsIndexPage(CustomHeadlessMixin, Page):
  62. """
  63. A Page model that creates an index page (a listview)
  64. """
  65. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  66. image = models.ForeignKey(
  67. "wagtailimages.Image",
  68. null=True,
  69. blank=True,
  70. on_delete=models.SET_NULL,
  71. related_name="+",
  72. help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
  73. )
  74. # Only LocationPage objects can be added underneath this index page
  75. subpage_types = ["LocationPage"]
  76. # Allows children of this indexpage to be accessible via the indexpage
  77. # object on templates. We use this on the homepage to show featured
  78. # sections of the site and their child pages
  79. def children(self):
  80. return self.get_children().specific().live()
  81. # Overrides the context to list all child
  82. # items, that are live, by the title alphabetical order.
  83. # https://docs.wagtail.org/en/stable/getting_started/tutorial.html#overriding-context
  84. def get_context(self, request):
  85. context = super(LocationsIndexPage, self).get_context(request)
  86. context["locations"] = (
  87. LocationPage.objects.descendant_of(self).live().order_by("title")
  88. )
  89. return context
  90. content_panels = Page.content_panels + [
  91. FieldPanel("introduction"),
  92. FieldPanel("image"),
  93. ]
  94. api_fields = [
  95. APIField("introduction"),
  96. APIField("image"),
  97. ]
  98. class LocationPage(CustomHeadlessMixin, Page):
  99. """
  100. Detail for a specific bakery location.
  101. """
  102. introduction = models.TextField(help_text="Text to describe the page", blank=True)
  103. image = models.ForeignKey(
  104. "wagtailimages.Image",
  105. null=True,
  106. blank=True,
  107. on_delete=models.SET_NULL,
  108. related_name="+",
  109. help_text="Landscape mode only; horizontal width between 1000px and 3000px.",
  110. )
  111. body = StreamField(
  112. BaseStreamBlock(), verbose_name="Page body", blank=True, use_json_field=True
  113. )
  114. address = models.TextField()
  115. lat_long = models.CharField(
  116. max_length=36,
  117. help_text="Comma separated lat/long. (Ex. 64.144367, -21.939182) \
  118. Right click Google Maps and select 'What's Here'",
  119. validators=[
  120. RegexValidator(
  121. regex=r"^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$",
  122. message="Lat Long must be a comma-separated numeric lat and long",
  123. code="invalid_lat_long",
  124. ),
  125. ],
  126. )
  127. # Search index configuration
  128. search_fields = Page.search_fields + [
  129. index.SearchField("address"),
  130. index.SearchField("body"),
  131. ]
  132. # Fields to show to the editor in the admin view
  133. content_panels = [
  134. FieldPanel("title"),
  135. FieldPanel("introduction"),
  136. FieldPanel("image"),
  137. FieldPanel("body"),
  138. FieldPanel("address"),
  139. FieldPanel("lat_long"),
  140. InlinePanel("hours_of_operation", heading="Hours of Operation", label="Slot"),
  141. ]
  142. api_fields = [
  143. APIField("introduction"),
  144. APIField("image"),
  145. APIField("body"),
  146. APIField("address"),
  147. APIField("lat_long"),
  148. APIField("is_open"),
  149. APIField("hours_of_operation"),
  150. ]
  151. def __str__(self):
  152. return self.title
  153. @property
  154. def operating_hours(self):
  155. hours = self.hours_of_operation.all()
  156. return hours
  157. # Determines if the location is currently open. It is timezone naive
  158. def is_open(self):
  159. now = datetime.now()
  160. current_time = now.time()
  161. current_day = now.strftime("%a").upper()
  162. try:
  163. self.operating_hours.get(
  164. day=current_day,
  165. opening_time__lte=current_time,
  166. closing_time__gte=current_time,
  167. )
  168. return True
  169. except LocationOperatingHours.DoesNotExist:
  170. return False
  171. # Makes additional context available to the template so that we can access
  172. # the latitude, longitude and map API key to render the map
  173. def get_context(self, request):
  174. context = super(LocationPage, self).get_context(request)
  175. context["lat"] = self.lat_long.split(",")[0]
  176. context["long"] = self.lat_long.split(",")[1]
  177. context["google_map_api_key"] = settings.GOOGLE_MAP_API_KEY
  178. return context
  179. # Can only be placed under a LocationsIndexPage object
  180. parent_page_types = ["LocationsIndexPage"]