Skip to content

Commit

Permalink
Allow choices to contains optgroups in DateRangeFilter (#1621)
Browse files Browse the repository at this point in the history
  • Loading branch information
fle committed Nov 29, 2023
1 parent 83b314f commit d693a59
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
11 changes: 10 additions & 1 deletion django_filters/filters.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from collections import OrderedDict
from datetime import timedelta
from itertools import chain

from django import forms
from django.core.validators import MaxValueValidator
Expand Down Expand Up @@ -478,7 +479,15 @@ def __init__(self, choices=None, filters=None, *args, **kwargs):
if filters is not None:
self.filters = filters

unique = set([x[0] for x in self.choices]) ^ set(self.filters)
all_choices = list(
chain.from_iterable(
[subchoice[0] for subchoice in choice[1]]
if isinstance(choice[1], (list, tuple)) # This is an optgroup
else [choice[0]]
for choice in self.choices
)
)
unique = set(all_choices) ^ set(self.filters)
assert not unique, (
"Keys must be present in both 'choices' and 'filters'. Missing keys: "
"'%s'" % ", ".join(sorted(unique))
Expand Down
5 changes: 5 additions & 0 deletions tests/test_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -1100,6 +1100,11 @@ def test_choices_and_filters_mismatch(self):
with self.assertRaisesMessage(AssertionError, msg):
DateRangeFilter(choices=[("a", "a")], filters={"b": None})

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

def test_filtering_for_this_year(self):
qs = mock.Mock(spec=["filter"])
with mock.patch("django_filters.filters.now") as mock_now:
Expand Down

0 comments on commit d693a59

Please sign in to comment.