Вы можете попробовать что-то вроде этого.
Примечание. Оригинал сообщения от Gedas здесь
- Создайте новый шаблон с именем
custom_filter.html
- Скопируйте следующий код в
custom_filter.html
,Я включаю две разные версии - одна с одним выбором, а другая с множественным выбором.
custom_filter_single.html
{% load i18n %}
<script type="text/javascript">
var go_from_select = function(opt)
{ window.location = window.location.pathname + opt };
</script>
<h3>{{ title }}</h3>
<ul class="admin-filter-{{ title|cut:' ' }}">
{% if choices|slice:"4:" %}
<li>
<select style="width: 95%;"
onchange="go_from_select(this.options[this.selectedIndex].value)">
{% for choice in choices %}
<option{% if choice.selected %} selected="selected"{% endif %}
value="{{ choice.query_string|iriencode }}">{{ choice.display }}
</option>
{% endfor %}
</select>
</li>
{% else %}
{% for choice in choices %}
<li{% if choice.selected %} class="selected"{% endif %}>
<a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a>
</li>
{% endfor %}
{% endif %}
</ul>
custom_filter_multiple.html
использует select2 lib,ниже может быть оптимизировано
{% load i18n %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-
rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-
rc.0/js/select2.min.js"></script>
<script>
$(document).ready(function() {
$("#personnel").select2();
$("#personnel").change(function() {
var selected_vals = $('#personnel').val();
var selections = selected_vals.join().replace(/\?/g, '').replace(/\,/g,
'&');
window.location = window.location.pathname + "?" +selections;
});
});
</script>
<h3>{{ title }}</h3>
<ul class="admin-filter-{{ title|cut:' ' }}">
{% if choices|slice:"4:" %}
<li>
<select style="width: 95%;" class="js-example-basic-multiple"
multiple="multiple" id="personnel">
{% for choice in choices %}
<option
value="{{ choice.query_string|iriencode }}">{{ choice.display }}
</option>
{% endfor %}
</select>
</li>
{% else %}
{% for choice in choices %}
<li{% if choice.selected %} class="selected"{% endif %}>
<a href="{{ choice.query_string|iriencode }}">{{ choice.display }}</a>
</li>
{% endfor %}
{% endif %}
</ul>
Создайте новый класс фильтра в filters.py с именем CustomFilter
из django.contrib.admin.filters import AllValuesFieldListFilter
класс CustomFilter (AllValuesFieldListFilter): template = 'admin / custom_filter_single.html '#use подходящий шаблон
Теперь используйте приведенный выше класс фильтра в admin.py
, например,
class SomeAdmin(admin.ModelAdmin):
list_filter = (('personnel_type', CustomDropDownFilter),)
#TIP: for custom filter labels, you can add verbose_name in
#models.py like this.
personnel_type = models.CharField(max_length=32, blank=True,
verbose_name="By Personnel Type")
Некоторыескриншоты.