Created
May 14, 2012 18:52
-
-
Save haplo/2695675 to your computer and use it in GitHub Desktop.
Blank admin filter for Django 1.4+.
This file contains hidden or 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
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