[Fixed]-Django SimpleListFilter

16👍

Try the below code. It will provide you to filter with the valid/invalid customers list.

class ExpiryDateFilter(admin.SimpleListFilter):

    title = _('Title name')

    parameter_name = 'exp_date'

   def lookups(self, request, model_admin):
       """
           List of values to allow admin to select
       """
       return (
          ('valid', _('All Valid')),
          ('invalid', _('All Invalid')),
       )

  def queryset(self, request, queryset):
     """
         Return the filtered queryset
     """

    if self.value() == 'valid':
        return queryset.filter(exp_date__gt=datatime.datatime.now())
    elif self.value() == 'invalid':
        return queryset.filter(exp_date__lt=datatime.datatime.now())
    else:
        return queryset

In the admin class add a list filter like the following.

class youModelAdminClass(admin.ModelAdmin):

     list_filter = [ExpiryDateFilter]
     list_display = ['CustomerValidity']

and then register the model admin with you Django model.

admin.site.register(ModelClassName, youModelAdminClass)

Hope this will help.

Leave a comment