Reputation: 555
I have a long list of elements (50 elements) and I wanted to use that as a list_filter in django admin panel. But when I use this list, on very right side where FILTER panel appears I can see only 20 items and it is not scrollable so rest of 30 is hidden. How can I get those 30 items in FILTER section or How scrolling will be possible so that all 50 items can be viewed.
Upvotes: 0
Views: 832
Reputation: 447
I suggest you to use this cool third-party.
It's easy to use and user-friendly in case of your problem.
For example look at this. models.py
from django.db import models
class Artist(models.Model):
name = models.CharField(max_length=128)
class Album(models.Model):
name = models.CharField(max_length=64)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE)
cover = models.CharField(max_length=256, null=True, default=None)
admin.py
from django.contrib import admin
from admin_auto_filters.filters import AutocompleteFilter
class ArtistFilter(AutocompleteFilter):
title = 'Artist' # display title
field_name = 'artist' # name of the foreign key field
class ArtistAdmin(admin.ModelAdmin):
search_fields = ['name'] # this is required for django's autocomplete functionality
# ...
class AlbumAdmin(admin.ModelAdmin):
list_filter = [ArtistFilter]
"""
defining this class is required for AutocompleteFilter
it's a bug and I am working on it.
"""
class Media:
pass
# ...
Upvotes: 0
Reputation: 321
You can create a custom filter for your field and use a dropdown as selector. I strongly recommend using https://github.com/mrts/django-admin-list-filter-dropdown which already provide a couple of filters.
If you want to create your own:
admin.py
from django.contrib.admin.filters import RelatedOnlyFieldListFilter
class RelatedOnlyDropdownFilter(RelatedOnlyFieldListFilter):
template = 'filters/related_filter.html'
@admin.register(ModelName)
class YourModelAdmin(admin.ModelAdmin):
list_filter = (
('field', RelatedOnlyDropdownFilter),
)
related_filter.html
{% load i18n %}
<script type="text/javascript">var filter_by_select = function(opt) { window.location = window.location.pathname + opt };</script>
<h3>{% blocktrans with title as filter_title %} By {{ filter_title }} {% endblocktrans %}</h3>
<ul class="admin-filter-{{ title|cut:' ' }}">
{% if choices|slice:"4:" %}
<li>
<select class="form-control"
onchange="filter_by_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>
Upvotes: 3