models.py 6.6 KB

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