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