django admin 筛选器:自定义筛选范围

本文介绍了一种自定义的数值范围过滤器实现方法,该过滤器用于在Django admin中提供更灵活的数值筛选功能。通过继承FieldListFilter并自定义NumberRangeFilterForm,可以实现对特定字段的最小值和最大值的输入框,允许用户设定数值范围来过滤数据。此外,还提供了一个自定义的HTML模板,以增强UI体验。
摘要由CSDN通过智能技术生成
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>

结果示例:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值