Filter django admin list with text input

754 Views Asked by At

Based on django ModelAdmin document for filterize list data, exist some class in admin that making filters, like DateFieldListFilter, ChoicesFieldListFilter and etc, But dosent exist any class for text input field.

I need to use several text input fields for filter my model list data in admin page. What can i do?

1

There are 1 best solutions below

0
kuhajeyan On

Something explained here would be helpful 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

and you need to override template

<!-- 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>

usage

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


all credits to owner of this post