2
0

models.py 6.1 KB

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