Skip to content

Instantly share code, notes, and snippets.

@haplo
Created May 14, 2012 18:52
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 haplo/2695675 to your computer and use it in GitHub Desktop.
Save haplo/2695675 to your computer and use it in GitHub Desktop.
Blank admin filter for Django 1.4+.
from django.contrib import admin
class BlankFilter(admin.SimpleListFilter):
"""Abstract base class for filtering blank fields.
To use define a subclass that defines title and parameter_name fields:
class ConcreteBlankFilter(BlankFilter):
title = "some title"
parameter_name = "model_field_name"
This has been inspired (read "almost an exact copy of") this solution
at StackOverflow: http://stackoverflow.com/a/9593302/519510
"""
title = ''
parameter_name = ''
def lookups(self, request, model_admin):
return (
('1', _('Has value'), ),
('0', _('Empty value'), ),
)
def queryset(self, request, queryset):
kwargs = {
unicode(self.parameter_name): '',
}
if self.value() == '0':
return queryset.filter(**kwargs)
if self.value() == '1':
return queryset.exclude(**kwargs)
return queryset
class ConcreteBlankFilter(BlankFilter):
title = "this filter is usable in "
parameter_name = "model_field_name" # model_field_name should correspond to
# a field with blank=True
class SomeModelAdmin(admin.ModelAdmin):
list_filter = [ConcreteBlankFilter]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment