class NumberRangeFilterForm(Form):
def __init__(self, *args, **kwargs):
self.field_name = kwargs.pop('field_name')
super(NumberRangeFilterForm, self).__init__(*args, **kwargs)
self.fields['%s__gte' % self.field_name] = DecimalField()
self.fields['%s__lte' % self.field_name] = DecimalField()
class NumberRangeFilter(admin.filters.FieldListFilter):
template = 'admin/NumberRangeFilter.html'
def __init__(self, *args, **kwargs):
field_path = kwargs['field_path']
self.lookup_kwarg_since = '%s__gte' % field_path
self.lookup_kwarg_upto = '%s__lte' % field_path
super(NumberRangeFilter, self).__init__(*args, **kwargs)
self.form = NumberRangeFilterForm(data=self.used_parameters, field_name=field_path)
def expected_parameters(self):
return [self.lookup_kwarg_since, self.lookup_kwarg_upto]
# no predefined choices
def choices(self, cl):
return []
def queryset(self, request, queryset):
if self.form.is_valid():
filter_params = {
p: self.form.cleaned_data.get(p) for p in self.expected_parameters()
if self.form.cleaned_data.get(p) is not None
}
return queryset.filter(**filter_params)
else:
return queryset
自定义模板 template = 'admin/NumberRangeFilter.html'
{% load i18n %}
<span class="range_filter_label">HK$</span><input type="number" class="filter_amount" name="{{ field_name }}__gte" placeholder="Min. amount" min=0>
<span class="range_filter_center">—</span>
<span class="range_filter_label">HK$</span><input type="number" class="filter_amount" name="{{ field_name }}__lte" placeholder="Max. amount" min=0>
结果示例: