Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I extend Django admin's DateFieldListFilter class ?

I am a newbie with Django and have a model with a DateTime field which is shown in the django admin.

In the list_filter option when I specify the fieldname I get the basic Django filter interface for date fields with 4 links (today, this month, past 7 days, etc.)

I now want to add a "next 7 days" option. This will require a minor tweak by extending the DateFieldListFilter class. However, Django throws the system check (admin.E114) The value of 'list_filter[0]' must not inherit from 'FieldListFilter'. when I try to extend it.

The only way it seems possible after a bit of search is by extending the SimpleListFilter class but it seems like a lot of work for such a small thing. (since I will have to duplicate functionality already taken care of in DateFieldListFilter)

Is there a simpler way of achieving this?

like image 325
uiboy Avatar asked Jun 09 '16 20:06

uiboy


1 Answers

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),
    )
like image 139
MrJaeger Avatar answered Sep 28 '22 02:09

MrJaeger