Context: I'm creating a custom input filter in Django using the SimpleListFilter class. I've followed the steps in here https://hakibenita.com/how-to-add-a-text-filter-to-django-admin, but I'm encountering a ValueError when trying to use the filter. Here is my code:
filters.py:
from django.contrib import admin
from django.db.models import Q
class InputFilter(admin.SimpleListFilter):
title = 'Language'
parameter_name = 'language'
template = 'admin/input_filter.html'
def lookups(self, request, model_admin):
# Dummy, required to show the filter.
return ((),)
def queryset(self, request, queryset):
if self.value():
return queryset.filter(Q(language__icontains=self.value()))
def choices(self, changelist):
all_choices = super().choices(changelist)
query_params = changelist.get_filters_params()
if not self.lookup_choices:
return []
for lookup, title in self.lookup_choices:
query_parts = changelist.get_query_string({self.parameter_name: lookup}).split('&')
if query_parts and len(query_parts) >= 2:
query = '&'.join([f'{k}={v}' for k, v in query_parts])
choice = {
'query_string': f'?{query}&{query_params}',
'display': title,
'selected': self.value() == lookup,
}
all_choices.append(choice)
return all_choices
I get the following error when accessing the admin page:
ValueError at /repoman/admin/aws_storage/raw_file/ not enough values to unpack (expected 2, got 0)
I'm not sure what is causing this error or how to fix it. Any help would be appreciated!
Traceback:
File "/usr/local/lib/python3.7/site-packages/django/contrib/admin/templatetags/admin_list.py",
line 440, in admin_list_filter
'choices': list(spec.choices(cl)),
File "/app/repoman/aws_storage/filters.py", line 26, in choices
for lookup, title in self.lookup_choices:
ValueError: not enough values to unpack (expected 2, got 0)
Your lookup is empty. So when it checks with the parameter it gets empty Value. So you should fill up your lookup list.
def lookups(self, request, model_admin):
return [
('en', 'English'),
('fr', 'French'),
('es', 'Spanish'),
]