models.py 6.4 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.wagtailcore.fields import StreamField
  7. from wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel, StreamFieldPanel
  8. from wagtail.wagtailcore.models import Orderable, Page
  9. from wagtail.wagtailsearch import index
  10. from wagtail.wagtailimages.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.opening_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. )
  71. class LocationsIndexPage(Page):
  72. """
  73. A Page model that creates an index page (a listview)
  74. """
  75. introduction = models.TextField(
  76. help_text='Text to describe the page',
  77. blank=True)
  78. image = models.ForeignKey(
  79. 'wagtailimages.Image',
  80. null=True,
  81. blank=True,
  82. on_delete=models.SET_NULL,
  83. related_name='+',
  84. help_text='Landscape mode only; horizontal width between 1000px and 3000px.'
  85. )
  86. # Only LocationPage objects can be added underneath this index page
  87. subpage_types = ['LocationPage']
  88. # Allows children of this indexpage to be accessible via the indexpage
  89. # object on templates. We use this on the homepage to show featured
  90. # sections of the site and their child pages
  91. def children(self):
  92. return self.get_children().specific().live()
  93. # Overrides the context to list all child
  94. # items, that are live, by the date that they were published
  95. # http://docs.wagtail.io/en/v1.9/getting_started/tutorial.html#overriding-context
  96. def get_context(self, request):
  97. context = super(LocationsIndexPage, self).get_context(request)
  98. context['locations'] = LocationPage.objects.descendant_of(
  99. self).live().order_by(
  100. 'title')
  101. return context
  102. content_panels = Page.content_panels + [
  103. FieldPanel('introduction', classname="full"),
  104. ImageChooserPanel('image'),
  105. ]
  106. class LocationPage(Page):
  107. """
  108. Detail for a specific bakery location.
  109. """
  110. introduction = models.TextField(
  111. help_text='Text to describe the page',
  112. blank=True)
  113. image = models.ForeignKey(
  114. 'wagtailimages.Image',
  115. null=True,
  116. blank=True,
  117. on_delete=models.SET_NULL,
  118. related_name='+',
  119. help_text='Landscape mode only; horizontal width between 1000px and 3000px.'
  120. )
  121. body = StreamField(
  122. BaseStreamBlock(), verbose_name="Page body", blank=True
  123. )
  124. address = models.TextField()
  125. lat_long = models.CharField(
  126. max_length=36,
  127. help_text="Comma separated lat/long. (Ex. 64.144367, -21.939182) \
  128. Right click Google Maps and select 'What\'s Here'",
  129. validators=[
  130. RegexValidator(
  131. regex='^(\-?\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. ImageChooserPanel('image'),
  147. StreamFieldPanel('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']