models.py 6.5 KB

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