Add 'yesterday' field to Django admin date list filter
Asked Answered
A

4

6

In my Django application, in the admin, for one of my models, I am allowing the option to filter by its 'create_date' field. Django by default gives me some options (Today, Past 7 Days, This Month, This Year). I want to simply add the option to choose 'Yesterday' as well. I looked at other Stack overflow questions regarding the same issue, but they were all looking for the ability to search by a date range, and I only want the one preloaded option. Is their a way in the admin class that configures this model to override some of their filter functionality ?

Admin Class

class User_LikeAdmin(admin.ModelAdmin):
    def fb_view_link(self, obj):
        if len(obj.user_facebook_link) > 2:
            return u"<a href='%s' target='_blank'>Facebook Page</a>" % obj.user_facebook_link
        else:
            return ""

    fb_view_link.short_description = ''
    fb_view_link.allow_tags = True


    list_display = ('vehicle', 'user', 'fb_view_link', 'dealer', 'create_date')
    list_filter = ('create_date', ('vehicle__dealer', custom_titled_filter('Dealer')))
    raw_id_fields = ('vehicle', 'user')

    actions = [export_csv]

    def dealer(self, obj):
        return obj.vehicle.dealer
Aurochs answered 31/8, 2017 at 14:54 Comment(0)
L
7

As an option, you can use custom filter class as mentioned in the documentation

class User_LikeAdmin(admin.ModelAdmin):
    list_filter = (('create_date', CustomDateFieldListFilter),)

You can extend DateFieldListFilter

from django.contrib.admin.filters import DateFieldListFilter

class CustomDateFieldListFilter(DateFieldListFilter):
    # Your tweaks here
Loma answered 31/8, 2017 at 15:25 Comment(0)
A
3
import datetime
from django.contrib.admin import DateFieldListFilter


class DateYesterdayFieldListFilter(DateFieldListFilter):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        today = datetime.date.today()
        yesterday = today - datetime.timedelta(days=1)

        self.links = list(self.links)
        self.links.insert(2, ('Yesterday', {
            self.lookup_kwarg_since: str(yesterday),
            self.lookup_kwarg_until: str(today),
        }))
Almallah answered 28/10, 2020 at 7:39 Comment(0)
P
1

Use the datetime, and create yesterday variable, and then get all records this way.

import datetime
yesterday = datetime.date.today() - datetime.timedelta(days=1)

data = Modelname.objects.filter(create_date=yesterday)
Phyllisphylloclade answered 31/8, 2017 at 15:11 Comment(0)
C
1

My version of @d2718nis answer:

class DateFilter(DateFieldListFilter):
    def __init__(self, field, request, params, model, model_admin, field_path):
        super().__init__(field, request, params, model, model_admin, field_path)

        now = timezone.now()
        if timezone.is_aware(now):
            now = timezone.localtime(now)

        if isinstance(field, models.DateTimeField):
            today = now.replace(hour=0, minute=0, second=0, microsecond=0)
        else:       # field is a models.DateField
            today = now.date()

        yesterday = today - datetime.timedelta(days=1)

        links_start = self.links[:2]  # anyday and today
        link_yesterday = (_('Yesterday'), {
                self.lookup_kwarg_since: str(yesterday),
                self.lookup_kwarg_until: str(today),
            })

        self.links = (*links_start, link_yesterday, *self.links[2:])
Cocainize answered 1/10, 2020 at 11:23 Comment(1)
it has some errors, for example there is no import for (_('Yesterday') and no import for timezoneEntoblast

© 2022 - 2024 — McMap. All rights reserved.