Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add 'yesterday' field to Django admin date list filter

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
like image 284
TJB Avatar asked Aug 31 '17 14:08

TJB


People also ask

What is list filter in Django admin?

Django allows the user of the admin site to filter the instances of a Model by adding the list_filter attribute to your ModelAdmin objects. You can find more information about the Django's filtering utilities in the official documentation, in the Django Admin Site section.

What is Fieldsets in Django admin?

It's just a way for you to be able to group the fields on a Model Admin Page. Just implement the example in the documentation and it should become apparent for you.


1 Answers

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
like image 102
d2718nis Avatar answered Sep 19 '22 19:09

d2718nis