使用文本输入过滤Django管理员列表

klsxnrf1  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(129)

基于django ModelAdmin文档的文件列表数据,在管理中存在一些类,使过滤器,如DateFieldListFilterChoicesFieldListFilter等,但dosent存在任何类的文本输入字段。
我需要在管理页面中使用多个文本输入字段来过滤我的模型列表数据。我该怎么办?

aij0ehis

aij0ehis1#

这里解释的东西会有帮助https://hakibenita.com/how-to-add-a-text-filter-to-django-admin

class InputFilter(admin.SimpleListFilter):
    template = "admin/input_filter.html"

    def lookups(self, request, model_admin):
        # Dummy, required to show the filter.
        return ((),)

    def choices(self, changelist):
        # Grab only the "all" option.
        all_choice = next(super().choices(changelist))
        all_choice["query_parts"] = (
            (k, v)
            for k, v in changelist.get_filters_params().items()
            if k != self.parameter_name
        )
        yield all_choice

字符串
你需要重写模板

<!-- templates/admin/input_filter.html -->

{% load i18n %}

<h3>{% blocktrans with filter_title=title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul>
  <li>
    <form method="GET" action="">
        <input
           type="text"
           value="{{ spec.value|default_if_none:'' }}"
           name="{{ spec.parameter_name }}"/>
    </form>
  </li>
</ul>

用法

class UIDFilter(InputFilter):
    parameter_name = 'uid'
    title = _('UID')

    def queryset(self, request, queryset):
        if self.value() is not None:
            uid = self.value()

            return queryset.filter(
                Q(uid=uid) |
                Q(payment__uid=uid) |
                Q(user__uid=uid)
            )


https://gist.githubusercontent.com/hakib/1491a848e71078dae81fca48c46cc258/raw/19934611bcdd6d806aabaf00f55f582cd40fffd8/input_filter.html
https://gist.githubusercontent.com/hakib/1491a848e71078dae81fca48c46cc258/raw/19934611bcdd6d806aabaf00f55f582cd40fffd8/admin.py
所有信贷的主人这篇文章

相关问题