django custom admin list filter datetime range

Solutions on MaxInterview for django custom admin list filter datetime range by the best coders in the world

showing results for - "django custom admin list filter datetime range"
Azariah
21 Jan 2020
1import datetime
2
3from django.contrib import admin
4from django.contrib.admin.filters import DateFieldListFilter
5from django.utils.translation import gettext_lazy as _
6
7
8class MyDateTimeFilter(DateFieldListFilter):
9    def __init__(self, *args, **kwargs):
10        super(MyDateTimeFilter, self).__init__(*args, **kwargs)
11
12        now = timezone.now()
13        # When time zone support is enabled, convert "now" to the user's time
14        # zone so Django's definition of "Today" matches what the user expects.
15        if timezone.is_aware(now):
16            now = timezone.localtime(now)
17
18        today = now.date()
19
20        self.links += ((
21            (_('Next 7 days'), {
22                self.lookup_kwarg_since: str(today),
23                self.lookup_kwarg_until: str(today + datetime.timedelta(days=7)),
24            }),
25        ))
26
27class BookAdmin(admin.ModelAdmin):
28    list_filter = (
29        ('published_at', MyDateTimeFilter),
30    )