[Django]-Extending Django-admin's DateFieldListFilter for custom "Upcoming" filter

8👍

Without jumping straight into this one, I have done exactly what you needed for a previous project:

In filters.py:

import datetime

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 += ((
            (_('Upcoming'), {
                self.lookup_kwarg_since: str(today),
                self.lookup_kwarg_until: str(today + datetime.timedelta(days=7)),
            }),
        ))

You want to add a few declarations to be used later (e.g., today = now.date()) and then you want to use the self.lookup_kwarg_until keyword argument, and have some time range as your lookup until date (for ease, I have used today + datetime.timedelta(days=7), but you could quite easily configure this to whatever timespan you need.

Then you’d need something like this in admin.py:

from django.contrib import admin

from filters import MyDateTimeFilter

class PostAdmin(admin.ModelAdmin):
    list_filter = (
        ('published_at', MyDateTimeFilter()),
    )

Disclaimer: this worked on Python 3.7, Django 2.0*. Fingers crossed this works for you!

0👍

Thank you for your answer, it definitely pointed me in the right direction.

I was missing the _ in my syntax and I was trying to create my custom filter directly in the admin.py and not filters.py. Since I was not sure if you were refering to the Django source file django.contrib.admin.filters.py or a new created model.filters.py file, I tried both method, adding a custom filter and then importing did not work for some reason I had the following error code:

  TypeError: __init__() missing 6 required positional arguments: 'field', 'request', 'params', 'model', 'model_admin', and 'field_path'

It is like my init declaration is incomplete.

However, given I found Django filters’s original source file, I was able to adjust Django’s original code (which is probably not recommended, but harmless in my case) and it worked great. I was not able to extend the original filter, but to override it.

Leave a comment