models.py 6.7 KB

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