Created
February 13, 2018 15:26
-
-
Save teror4uks/fe9b5e96ec836369846bb0377569a8fd to your computer and use it in GitHub Desktop.
Custom Input Text Filters (https://medium.com/@hakibenita/things-you-must-know-about-django-admin-as-your-app-gets-bigger-6be0b0ee9614)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib import 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 | |
class CategoryInputFilter(InputFilter): | |
parameter_name = 'category' | |
title = ('Категория') | |
def queryset(self, request, queryset): | |
category = None | |
if self.value() != '' and self.value() is not None: | |
category = self.value() | |
return queryset.filter(category__name__icontains=category) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% 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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment