Skip to content

Instantly share code, notes, and snippets.

@ahmedshahriar
Created February 10, 2021 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedshahriar/4240f0451261c4bb8364dd5341c7cf59 to your computer and use it in GitHub Desktop.
Save ahmedshahriar/4240f0451261c4bb8364dd5341c7cf59 to your computer and use it in GitHub Desktop.
Alphabet filter in Django admin
"""
Suppose you have a django model in models.py:
class Animal(models.Model):
animal_name = models.CharField(u'name', max_length=255)
to create an alphabetfilter in django admin panel you need to create a class which inherits
admin.SimpleListFilter in admin.py
here is the code snippet below for admin.py file
"""
import string
from django.contrib import admin
class AlphabetFilter(admin.SimpleListFilter):
title = 'alphabet'
parameter_name = 'alphabet'
def lookups(self, request, model_admin):
abc = list(string.ascii_lowercase)
return ((c.upper(), c.upper()) for c in abc)
def queryset(self, request, queryset):
if self.value():
# filter specific attr of the model
return queryset.filter(animal_name__startswith=self.value())
class AnimalAdmin(admin.ModelAdmin):
list_display = ['name',]
list_filter = (AlphabetFilter,)
admin.site.register(Animal, AnimalAdmin)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment