Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. import datetime
  2. from django.conf import settings
  3. from django.core.exceptions import ImproperlyConfigured
  4. from django.db import models
  5. from django.http import Http404
  6. from django.utils import timezone
  7. from django.utils.functional import cached_property
  8. from django.utils.translation import gettext as _
  9. from django.views.generic.base import View
  10. from django.views.generic.detail import (
  11. BaseDetailView,
  12. SingleObjectTemplateResponseMixin,
  13. )
  14. from django.views.generic.list import (
  15. MultipleObjectMixin,
  16. MultipleObjectTemplateResponseMixin,
  17. )
  18. class YearMixin:
  19. """Mixin for views manipulating year-based data."""
  20. year_format = "%Y"
  21. year = None
  22. def get_year_format(self):
  23. """
  24. Get a year format string in strptime syntax to be used to parse the
  25. year from url variables.
  26. """
  27. return self.year_format
  28. def get_year(self):
  29. """Return the year for which this view should display data."""
  30. year = self.year
  31. if year is None:
  32. try:
  33. year = self.kwargs["year"]
  34. except KeyError:
  35. try:
  36. year = self.request.GET["year"]
  37. except KeyError:
  38. raise Http404(_("No year specified"))
  39. return year
  40. def get_next_year(self, date):
  41. """Get the next valid year."""
  42. return _get_next_prev(self, date, is_previous=False, period="year")
  43. def get_previous_year(self, date):
  44. """Get the previous valid year."""
  45. return _get_next_prev(self, date, is_previous=True, period="year")
  46. def _get_next_year(self, date):
  47. """
  48. Return the start date of the next interval.
  49. The interval is defined by start date <= item date < next start date.
  50. """
  51. try:
  52. return date.replace(year=date.year + 1, month=1, day=1)
  53. except ValueError:
  54. raise Http404(_("Date out of range"))
  55. def _get_current_year(self, date):
  56. """Return the start date of the current interval."""
  57. return date.replace(month=1, day=1)
  58. class MonthMixin:
  59. """Mixin for views manipulating month-based data."""
  60. month_format = "%b"
  61. month = None
  62. def get_month_format(self):
  63. """
  64. Get a month format string in strptime syntax to be used to parse the
  65. month from url variables.
  66. """
  67. return self.month_format
  68. def get_month(self):
  69. """Return the month for which this view should display data."""
  70. month = self.month
  71. if month is None:
  72. try:
  73. month = self.kwargs["month"]
  74. except KeyError:
  75. try:
  76. month = self.request.GET["month"]
  77. except KeyError:
  78. raise Http404(_("No month specified"))
  79. return month
  80. def get_next_month(self, date):
  81. """Get the next valid month."""
  82. return _get_next_prev(self, date, is_previous=False, period="month")
  83. def get_previous_month(self, date):
  84. """Get the previous valid month."""
  85. return _get_next_prev(self, date, is_previous=True, period="month")
  86. def _get_next_month(self, date):
  87. """
  88. Return the start date of the next interval.
  89. The interval is defined by start date <= item date < next start date.
  90. """
  91. if date.month == 12:
  92. try:
  93. return date.replace(year=date.year + 1, month=1, day=1)
  94. except ValueError:
  95. raise Http404(_("Date out of range"))
  96. else:
  97. return date.replace(month=date.month + 1, day=1)
  98. def _get_current_month(self, date):
  99. """Return the start date of the previous interval."""
  100. return date.replace(day=1)
  101. class DayMixin:
  102. """Mixin for views manipulating day-based data."""
  103. day_format = "%d"
  104. day = None
  105. def get_day_format(self):
  106. """
  107. Get a day format string in strptime syntax to be used to parse the day
  108. from url variables.
  109. """
  110. return self.day_format
  111. def get_day(self):
  112. """Return the day for which this view should display data."""
  113. day = self.day
  114. if day is None:
  115. try:
  116. day = self.kwargs["day"]
  117. except KeyError:
  118. try:
  119. day = self.request.GET["day"]
  120. except KeyError:
  121. raise Http404(_("No day specified"))
  122. return day
  123. def get_next_day(self, date):
  124. """Get the next valid day."""
  125. return _get_next_prev(self, date, is_previous=False, period="day")
  126. def get_previous_day(self, date):
  127. """Get the previous valid day."""
  128. return _get_next_prev(self, date, is_previous=True, period="day")
  129. def _get_next_day(self, date):
  130. """
  131. Return the start date of the next interval.
  132. The interval is defined by start date <= item date < next start date.
  133. """
  134. return date + datetime.timedelta(days=1)
  135. def _get_current_day(self, date):
  136. """Return the start date of the current interval."""
  137. return date
  138. class WeekMixin:
  139. """Mixin for views manipulating week-based data."""
  140. week_format = "%U"
  141. week = None
  142. def get_week_format(self):
  143. """
  144. Get a week format string in strptime syntax to be used to parse the
  145. week from url variables.
  146. """
  147. return self.week_format
  148. def get_week(self):
  149. """Return the week for which this view should display data."""
  150. week = self.week
  151. if week is None:
  152. try:
  153. week = self.kwargs["week"]
  154. except KeyError:
  155. try:
  156. week = self.request.GET["week"]
  157. except KeyError:
  158. raise Http404(_("No week specified"))
  159. return week
  160. def get_next_week(self, date):
  161. """Get the next valid week."""
  162. return _get_next_prev(self, date, is_previous=False, period="week")
  163. def get_previous_week(self, date):
  164. """Get the previous valid week."""
  165. return _get_next_prev(self, date, is_previous=True, period="week")
  166. def _get_next_week(self, date):
  167. """
  168. Return the start date of the next interval.
  169. The interval is defined by start date <= item date < next start date.
  170. """
  171. try:
  172. return date + datetime.timedelta(days=7 - self._get_weekday(date))
  173. except OverflowError:
  174. raise Http404(_("Date out of range"))
  175. def _get_current_week(self, date):
  176. """Return the start date of the current interval."""
  177. return date - datetime.timedelta(self._get_weekday(date))
  178. def _get_weekday(self, date):
  179. """
  180. Return the weekday for a given date.
  181. The first day according to the week format is 0 and the last day is 6.
  182. """
  183. week_format = self.get_week_format()
  184. if week_format in {"%W", "%V"}: # week starts on Monday
  185. return date.weekday()
  186. elif week_format == "%U": # week starts on Sunday
  187. return (date.weekday() + 1) % 7
  188. else:
  189. raise ValueError("unknown week format: %s" % week_format)
  190. class DateMixin:
  191. """Mixin class for views manipulating date-based data."""
  192. date_field = None
  193. allow_future = False
  194. def get_date_field(self):
  195. """Get the name of the date field to be used to filter by."""
  196. if self.date_field is None:
  197. raise ImproperlyConfigured(
  198. "%s.date_field is required." % self.__class__.__name__
  199. )
  200. return self.date_field
  201. def get_allow_future(self):
  202. """
  203. Return `True` if the view should be allowed to display objects from
  204. the future.
  205. """
  206. return self.allow_future
  207. # Note: the following three methods only work in subclasses that also
  208. # inherit SingleObjectMixin or MultipleObjectMixin.
  209. @cached_property
  210. def uses_datetime_field(self):
  211. """
  212. Return `True` if the date field is a `DateTimeField` and `False`
  213. if it's a `DateField`.
  214. """
  215. model = self.get_queryset().model if self.model is None else self.model
  216. field = model._meta.get_field(self.get_date_field())
  217. return isinstance(field, models.DateTimeField)
  218. def _make_date_lookup_arg(self, value):
  219. """
  220. Convert a date into a datetime when the date field is a DateTimeField.
  221. When time zone support is enabled, `date` is assumed to be in the
  222. current time zone, so that displayed items are consistent with the URL.
  223. """
  224. if self.uses_datetime_field:
  225. value = datetime.datetime.combine(value, datetime.time.min)
  226. if settings.USE_TZ:
  227. value = timezone.make_aware(value)
  228. return value
  229. def _make_single_date_lookup(self, date):
  230. """
  231. Get the lookup kwargs for filtering on a single date.
  232. If the date field is a DateTimeField, we can't just filter on
  233. date_field=date because that doesn't take the time into account.
  234. """
  235. date_field = self.get_date_field()
  236. if self.uses_datetime_field:
  237. since = self._make_date_lookup_arg(date)
  238. until = self._make_date_lookup_arg(date + datetime.timedelta(days=1))
  239. return {
  240. "%s__gte" % date_field: since,
  241. "%s__lt" % date_field: until,
  242. }
  243. else:
  244. # Skip self._make_date_lookup_arg, it's a no-op in this branch.
  245. return {date_field: date}
  246. class BaseDateListView(MultipleObjectMixin, DateMixin, View):
  247. """Abstract base class for date-based views displaying a list of objects."""
  248. allow_empty = False
  249. date_list_period = "year"
  250. def get(self, request, *args, **kwargs):
  251. self.date_list, self.object_list, extra_context = self.get_dated_items()
  252. context = self.get_context_data(
  253. object_list=self.object_list, date_list=self.date_list, **extra_context
  254. )
  255. return self.render_to_response(context)
  256. def get_dated_items(self):
  257. """Obtain the list of dates and items."""
  258. raise NotImplementedError(
  259. "A DateView must provide an implementation of get_dated_items()"
  260. )
  261. def get_ordering(self):
  262. """
  263. Return the field or fields to use for ordering the queryset; use the
  264. date field by default.
  265. """
  266. return "-%s" % self.get_date_field() if self.ordering is None else self.ordering
  267. def get_dated_queryset(self, **lookup):
  268. """
  269. Get a queryset properly filtered according to `allow_future` and any
  270. extra lookup kwargs.
  271. """
  272. qs = self.get_queryset().filter(**lookup)
  273. date_field = self.get_date_field()
  274. allow_future = self.get_allow_future()
  275. allow_empty = self.get_allow_empty()
  276. paginate_by = self.get_paginate_by(qs)
  277. if not allow_future:
  278. now = timezone.now() if self.uses_datetime_field else timezone_today()
  279. qs = qs.filter(**{"%s__lte" % date_field: now})
  280. if not allow_empty:
  281. # When pagination is enabled, it's better to do a cheap query
  282. # than to load the unpaginated queryset in memory.
  283. is_empty = not qs if paginate_by is None else not qs.exists()
  284. if is_empty:
  285. raise Http404(
  286. _("No %(verbose_name_plural)s available")
  287. % {
  288. "verbose_name_plural": qs.model._meta.verbose_name_plural,
  289. }
  290. )
  291. return qs
  292. def get_date_list_period(self):
  293. """
  294. Get the aggregation period for the list of dates: 'year', 'month', or
  295. 'day'.
  296. """
  297. return self.date_list_period
  298. def get_date_list(self, queryset, date_type=None, ordering="ASC"):
  299. """
  300. Get a date list by calling `queryset.dates/datetimes()`, checking
  301. along the way for empty lists that aren't allowed.
  302. """
  303. date_field = self.get_date_field()
  304. allow_empty = self.get_allow_empty()
  305. if date_type is None:
  306. date_type = self.get_date_list_period()
  307. if self.uses_datetime_field:
  308. date_list = queryset.datetimes(date_field, date_type, ordering)
  309. else:
  310. date_list = queryset.dates(date_field, date_type, ordering)
  311. if date_list is not None and not date_list and not allow_empty:
  312. raise Http404(
  313. _("No %(verbose_name_plural)s available")
  314. % {
  315. "verbose_name_plural": queryset.model._meta.verbose_name_plural,
  316. }
  317. )
  318. return date_list
  319. class BaseArchiveIndexView(BaseDateListView):
  320. """
  321. Base class for archives of date-based items. Requires a response mixin.
  322. """
  323. context_object_name = "latest"
  324. def get_dated_items(self):
  325. """Return (date_list, items, extra_context) for this request."""
  326. qs = self.get_dated_queryset()
  327. date_list = self.get_date_list(qs, ordering="DESC")
  328. if not date_list:
  329. qs = qs.none()
  330. return (date_list, qs, {})
  331. class ArchiveIndexView(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView):
  332. """Top-level archive of date-based items."""
  333. template_name_suffix = "_archive"
  334. class BaseYearArchiveView(YearMixin, BaseDateListView):
  335. """List of objects published in a given year."""
  336. date_list_period = "month"
  337. make_object_list = False
  338. def get_dated_items(self):
  339. """Return (date_list, items, extra_context) for this request."""
  340. year = self.get_year()
  341. date_field = self.get_date_field()
  342. date = _date_from_string(year, self.get_year_format())
  343. since = self._make_date_lookup_arg(date)
  344. until = self._make_date_lookup_arg(self._get_next_year(date))
  345. lookup_kwargs = {
  346. "%s__gte" % date_field: since,
  347. "%s__lt" % date_field: until,
  348. }
  349. qs = self.get_dated_queryset(**lookup_kwargs)
  350. date_list = self.get_date_list(qs)
  351. if not self.get_make_object_list():
  352. # We need this to be a queryset since parent classes introspect it
  353. # to find information about the model.
  354. qs = qs.none()
  355. return (
  356. date_list,
  357. qs,
  358. {
  359. "year": date,
  360. "next_year": self.get_next_year(date),
  361. "previous_year": self.get_previous_year(date),
  362. },
  363. )
  364. def get_make_object_list(self):
  365. """
  366. Return `True` if this view should contain the full list of objects in
  367. the given year.
  368. """
  369. return self.make_object_list
  370. class YearArchiveView(MultipleObjectTemplateResponseMixin, BaseYearArchiveView):
  371. """List of objects published in a given year."""
  372. template_name_suffix = "_archive_year"
  373. class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView):
  374. """List of objects published in a given month."""
  375. date_list_period = "day"
  376. def get_dated_items(self):
  377. """Return (date_list, items, extra_context) for this request."""
  378. year = self.get_year()
  379. month = self.get_month()
  380. date_field = self.get_date_field()
  381. date = _date_from_string(
  382. year, self.get_year_format(), month, self.get_month_format()
  383. )
  384. since = self._make_date_lookup_arg(date)
  385. until = self._make_date_lookup_arg(self._get_next_month(date))
  386. lookup_kwargs = {
  387. "%s__gte" % date_field: since,
  388. "%s__lt" % date_field: until,
  389. }
  390. qs = self.get_dated_queryset(**lookup_kwargs)
  391. date_list = self.get_date_list(qs)
  392. return (
  393. date_list,
  394. qs,
  395. {
  396. "month": date,
  397. "next_month": self.get_next_month(date),
  398. "previous_month": self.get_previous_month(date),
  399. },
  400. )
  401. class MonthArchiveView(MultipleObjectTemplateResponseMixin, BaseMonthArchiveView):
  402. """List of objects published in a given month."""
  403. template_name_suffix = "_archive_month"
  404. class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView):
  405. """List of objects published in a given week."""
  406. def get_dated_items(self):
  407. """Return (date_list, items, extra_context) for this request."""
  408. year = self.get_year()
  409. week = self.get_week()
  410. date_field = self.get_date_field()
  411. week_format = self.get_week_format()
  412. week_choices = {"%W": "1", "%U": "0", "%V": "1"}
  413. try:
  414. week_start = week_choices[week_format]
  415. except KeyError:
  416. raise ValueError(
  417. "Unknown week format %r. Choices are: %s"
  418. % (
  419. week_format,
  420. ", ".join(sorted(week_choices)),
  421. )
  422. )
  423. year_format = self.get_year_format()
  424. if week_format == "%V" and year_format != "%G":
  425. raise ValueError(
  426. "ISO week directive '%s' is incompatible with the year "
  427. "directive '%s'. Use the ISO year '%%G' instead."
  428. % (
  429. week_format,
  430. year_format,
  431. )
  432. )
  433. date = _date_from_string(year, year_format, week_start, "%w", week, week_format)
  434. since = self._make_date_lookup_arg(date)
  435. until = self._make_date_lookup_arg(self._get_next_week(date))
  436. lookup_kwargs = {
  437. "%s__gte" % date_field: since,
  438. "%s__lt" % date_field: until,
  439. }
  440. qs = self.get_dated_queryset(**lookup_kwargs)
  441. return (
  442. None,
  443. qs,
  444. {
  445. "week": date,
  446. "next_week": self.get_next_week(date),
  447. "previous_week": self.get_previous_week(date),
  448. },
  449. )
  450. class WeekArchiveView(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView):
  451. """List of objects published in a given week."""
  452. template_name_suffix = "_archive_week"
  453. class BaseDayArchiveView(YearMixin, MonthMixin, DayMixin, BaseDateListView):
  454. """List of objects published on a given day."""
  455. def get_dated_items(self):
  456. """Return (date_list, items, extra_context) for this request."""
  457. year = self.get_year()
  458. month = self.get_month()
  459. day = self.get_day()
  460. date = _date_from_string(
  461. year,
  462. self.get_year_format(),
  463. month,
  464. self.get_month_format(),
  465. day,
  466. self.get_day_format(),
  467. )
  468. return self._get_dated_items(date)
  469. def _get_dated_items(self, date):
  470. """
  471. Do the actual heavy lifting of getting the dated items; this accepts a
  472. date object so that TodayArchiveView can be trivial.
  473. """
  474. lookup_kwargs = self._make_single_date_lookup(date)
  475. qs = self.get_dated_queryset(**lookup_kwargs)
  476. return (
  477. None,
  478. qs,
  479. {
  480. "day": date,
  481. "previous_day": self.get_previous_day(date),
  482. "next_day": self.get_next_day(date),
  483. "previous_month": self.get_previous_month(date),
  484. "next_month": self.get_next_month(date),
  485. },
  486. )
  487. class DayArchiveView(MultipleObjectTemplateResponseMixin, BaseDayArchiveView):
  488. """List of objects published on a given day."""
  489. template_name_suffix = "_archive_day"
  490. class BaseTodayArchiveView(BaseDayArchiveView):
  491. """List of objects published today."""
  492. def get_dated_items(self):
  493. """Return (date_list, items, extra_context) for this request."""
  494. return self._get_dated_items(datetime.date.today())
  495. class TodayArchiveView(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView):
  496. """List of objects published today."""
  497. template_name_suffix = "_archive_day"
  498. class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView):
  499. """
  500. Detail view of a single object on a single date; this differs from the
  501. standard DetailView by accepting a year/month/day in the URL.
  502. """
  503. def get_object(self, queryset=None):
  504. """Get the object this request displays."""
  505. year = self.get_year()
  506. month = self.get_month()
  507. day = self.get_day()
  508. date = _date_from_string(
  509. year,
  510. self.get_year_format(),
  511. month,
  512. self.get_month_format(),
  513. day,
  514. self.get_day_format(),
  515. )
  516. # Use a custom queryset if provided
  517. qs = self.get_queryset() if queryset is None else queryset
  518. if not self.get_allow_future() and date > datetime.date.today():
  519. raise Http404(
  520. _(
  521. "Future %(verbose_name_plural)s not available because "
  522. "%(class_name)s.allow_future is False."
  523. )
  524. % {
  525. "verbose_name_plural": qs.model._meta.verbose_name_plural,
  526. "class_name": self.__class__.__name__,
  527. }
  528. )
  529. # Filter down a queryset from self.queryset using the date from the
  530. # URL. This'll get passed as the queryset to DetailView.get_object,
  531. # which'll handle the 404
  532. lookup_kwargs = self._make_single_date_lookup(date)
  533. qs = qs.filter(**lookup_kwargs)
  534. return super().get_object(queryset=qs)
  535. class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView):
  536. """
  537. Detail view of a single object on a single date; this differs from the
  538. standard DetailView by accepting a year/month/day in the URL.
  539. """
  540. template_name_suffix = "_detail"
  541. def _date_from_string(
  542. year, year_format, month="", month_format="", day="", day_format="", delim="__"
  543. ):
  544. """
  545. Get a datetime.date object given a format string and a year, month, and day
  546. (only year is mandatory). Raise a 404 for an invalid date.
  547. """
  548. format = year_format + delim + month_format + delim + day_format
  549. datestr = str(year) + delim + str(month) + delim + str(day)
  550. try:
  551. return datetime.datetime.strptime(datestr, format).date()
  552. except ValueError:
  553. raise Http404(
  554. _("Invalid date string “%(datestr)s” given format “%(format)s”")
  555. % {
  556. "datestr": datestr,
  557. "format": format,
  558. }
  559. )
  560. def _get_next_prev(generic_view, date, is_previous, period):
  561. """
  562. Get the next or the previous valid date. The idea is to allow links on
  563. month/day views to never be 404s by never providing a date that'll be
  564. invalid for the given view.
  565. This is a bit complicated since it handles different intervals of time,
  566. hence the coupling to generic_view.
  567. However in essence the logic comes down to:
  568. * If allow_empty and allow_future are both true, this is easy: just
  569. return the naive result (just the next/previous day/week/month,
  570. regardless of object existence.)
  571. * If allow_empty is true, allow_future is false, and the naive result
  572. isn't in the future, then return it; otherwise return None.
  573. * If allow_empty is false and allow_future is true, return the next
  574. date *that contains a valid object*, even if it's in the future. If
  575. there are no next objects, return None.
  576. * If allow_empty is false and allow_future is false, return the next
  577. date that contains a valid object. If that date is in the future, or
  578. if there are no next objects, return None.
  579. """
  580. date_field = generic_view.get_date_field()
  581. allow_empty = generic_view.get_allow_empty()
  582. allow_future = generic_view.get_allow_future()
  583. get_current = getattr(generic_view, "_get_current_%s" % period)
  584. get_next = getattr(generic_view, "_get_next_%s" % period)
  585. # Bounds of the current interval
  586. start, end = get_current(date), get_next(date)
  587. # If allow_empty is True, the naive result will be valid
  588. if allow_empty:
  589. if is_previous:
  590. result = get_current(start - datetime.timedelta(days=1))
  591. else:
  592. result = end
  593. if allow_future or result <= timezone_today():
  594. return result
  595. else:
  596. return None
  597. # Otherwise, we'll need to go to the database to look for an object
  598. # whose date_field is at least (greater than/less than) the given
  599. # naive result
  600. else:
  601. # Construct a lookup and an ordering depending on whether we're doing
  602. # a previous date or a next date lookup.
  603. if is_previous:
  604. lookup = {"%s__lt" % date_field: generic_view._make_date_lookup_arg(start)}
  605. ordering = "-%s" % date_field
  606. else:
  607. lookup = {"%s__gte" % date_field: generic_view._make_date_lookup_arg(end)}
  608. ordering = date_field
  609. # Filter out objects in the future if appropriate.
  610. if not allow_future:
  611. # Fortunately, to match the implementation of allow_future,
  612. # we need __lte, which doesn't conflict with __lt above.
  613. if generic_view.uses_datetime_field:
  614. now = timezone.now()
  615. else:
  616. now = timezone_today()
  617. lookup["%s__lte" % date_field] = now
  618. qs = generic_view.get_queryset().filter(**lookup).order_by(ordering)
  619. # Snag the first object from the queryset; if it doesn't exist that
  620. # means there's no next/previous link available.
  621. try:
  622. result = getattr(qs[0], date_field)
  623. except IndexError:
  624. return None
  625. # Convert datetimes to dates in the current time zone.
  626. if generic_view.uses_datetime_field:
  627. if settings.USE_TZ:
  628. result = timezone.localtime(result)
  629. result = result.date()
  630. # Return the first day of the period.
  631. return get_current(result)
  632. def timezone_today():
  633. """Return the current date in the current time zone."""
  634. if settings.USE_TZ:
  635. return timezone.localdate()
  636. else:
  637. return datetime.date.today()