django admin date range code example
Example: django custom admin list_filter datetime range
import datetime
from django.contrib import admin
from django.contrib.admin.filters import DateFieldListFilter
from django.utils.translation import gettext_lazy as _
class MyDateTimeFilter(DateFieldListFilter):
def __init__(self, *args, **kwargs):
super(MyDateTimeFilter, self).__init__(*args, **kwargs)
now = timezone.now()
if timezone.is_aware(now):
now = timezone.localtime(now)
today = now.date()
self.links += ((
(_('Next 7 days'), {
self.lookup_kwarg_since: str(today),
self.lookup_kwarg_until: str(today + datetime.timedelta(days=7)),
}),
))
class BookAdmin(admin.ModelAdmin):
list_filter = (
('published_at', MyDateTimeFilter),
)