Created
February 10, 2021 19:01
-
-
Save ahmedshahriar/4240f0451261c4bb8364dd5341c7cf59 to your computer and use it in GitHub Desktop.
Alphabet filter in Django admin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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