Skip to content

Instantly share code, notes, and snippets.

@sunfkny
Forked from hakib/admin.py
Last active November 15, 2023 02:19
Show Gist options
  • Save sunfkny/20170b4d4634c94cabeb2b692cd5d3b2 to your computer and use it in GitHub Desktop.
Save sunfkny/20170b4d4634c94cabeb2b692cd5d3b2 to your computer and use it in GitHub Desktop.
Django Admin InputFilter
# common/admin.py
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>
{% with choices.0 as all_choice %}
<form method="GET" action="">
{% for k, v in all_choice.query_parts %}
<input type="hidden" name="{{ k }}" value="{{ v }}" />
{% endfor %}
<input type="text"
value="{{ spec.value|default_if_none:'' }}"
name="{{ spec.parameter_name }}"/>
{% if not all_choice.selected %}
<strong><a href="{{ all_choice.query_string }}">x {% trans 'Remove' %}</a></strong>
{% endif %}
</form>
{% endwith %}
</li>
</ul>
@sunfkny
Copy link
Author

sunfkny commented May 16, 2023

@sunfkny
Copy link
Author

sunfkny commented May 16, 2023

from django.db.models import Q

class UserFilter(InputFilter):
    parameter_name = 'user'
    title = _('User')

    def queryset(self, request, queryset):
        term = self.value()

        if term is None:
            return

        any_name = Q()
        for bit in term.split():
            any_name &= (
                Q(user__first_name__icontains=bit) |
                Q(user__last_name__icontains=bit)
            )

        return queryset.filter(any_name)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment