Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix grouped choices as dict #1668

Merged
merged 4 commits into from
Aug 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions django_filters/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@
)
from .utils import get_model_field, label_for_filter

try:
from django.utils.choices import BaseChoiceIterator, normalize_choices
except ImportError:
DJANGO_50 = False
else:
DJANGO_50 = True


__all__ = [
"AllValuesFilter",
"AllValuesMultipleFilter",
Expand Down Expand Up @@ -479,6 +487,12 @@ def __init__(self, choices=None, filters=None, *args, **kwargs):
if filters is not None:
self.filters = filters

if isinstance(self.choices, dict):
if DJANGO_50:
self.choices = normalize_choices(self.choices)
else:
assert not DJANGO_50, "Django 5.0 or later is required for dict choices"

all_choices = list(
chain.from_iterable(
[subchoice[0] for subchoice in choice[1]]
Expand Down
5 changes: 5 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1105,6 +1105,11 @@ def test_choices_with_optgroups_dont_mistmatch(self):
choices=[("group", ("a", "a")), ("b", "b")], filters={"a": None, "b": None}
)

def test_grouped_choices_as_dictionary(self):
DateRangeFilter(
choices={"group": {"a": "a", "b": "b"}}, filters={"a": None, "b": None}
)

saevarom marked this conversation as resolved.
Show resolved Hide resolved
def test_filtering_for_this_year(self):
qs = mock.Mock(spec=["filter"])
with mock.patch("django_filters.filters.now") as mock_now:
Expand Down
Loading