[Solved]-How do I extend Django admin's DateFieldListFilter class ?

9👍

Assume we have a model called Book with a published_at field which is a DateTimeField. You could then achieve this type of filtering by doing something like this (code is based on DateFieldListFilter as seen in https://github.com/django/django/blob/4ad2f862844d35404e4798b3227517625210a72e/django/contrib/admin/filters.py):

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()
        # When time zone support is enabled, convert "now" to the user's time
        # zone so Django's definition of "Today" matches what the user expects.
        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),
    )

Leave a comment