carltongibson / django-filter

A generic system for filtering Django QuerySets based on user selections

Home Page:https://django-filter.readthedocs.io/en/main/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Usage of optgroups in DateRangeFilter.choices raises an AssertionError

fle opened this issue · comments

Context

Django allows to use optgroups in the choices of a ChoiceField with this syntaxe:

class MyChoiceField(ChoiceField):

    choices = [
        (
            "group1",
            (
                ("choice1", "Label 1"),
                ("choice2", "Label 2"),
            )
        )
    ]

Problem

Unfortunately, DateRangeFilter does not allow to do the same kind of things because of the assert that checks that the list of choices matches the list of filters.

class MyDateRangeFilter(DateRangeFilter):

    choices = [
        (
            "group1",
            (
                ("choice1", "Label 1"),
                ("choice2", "Label 2"),
            )
        )
    ]

    filters = {
        "choice1": None,
        "choice2": None
    }

>>> MyDateRangeFilter()
Traceback (most recent call last):
  File "/home/florent/dev/django-filter/django_filters/filters.py", line 491, in __init__
    assert not unique, (
AssertionError: Keys must be present in both 'choices' and 'filters'. Missing keys: 'group1, choice1, choice2'

Suggested solution

One could simply detect optgroups in choices as django do so.