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.

dates.py 25KB

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