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

Add "Any" filter to ChoicesField #45

Closed
cvk77 opened this issue Mar 16, 2011 · 6 comments
Closed

Add "Any" filter to ChoicesField #45

cvk77 opened this issue Mar 16, 2011 · 6 comments

Comments

@cvk77
Copy link

cvk77 commented Mar 16, 2011

The ChoicesField currently doesn't provide an "Any" or "Unknown" filter entry, so as soon as a ChoiceField is added to a search form, the user has to always select an entry.

I currently workaround this by adding an empty filter in the Filter's constructor, but it would be great if there could be an easier way to achieve this:

class NicerFilterSet(django_filters.FilterSet):

def __init__(self, *args, **kwargs):
    super(NicerFilterSet, self).__init__(*args, **kwargs)

    for name, field in self.filters.iteritems():
        if isinstance(field, ChoiceFilter):
            # Add "Any" entry to choice fields.
            field.extra['choices'] = tuple([("", "Any"), ] + list(field.extra['choices']))`
@ngottlieb
Copy link

Nice -- thanks for the workaround. Agreed that it's a pretty common requirement for a search/filter form.

@apollo13
Copy link
Contributor

Could you guys rework that into a pull request with docs and tests? Thx!

@carltongibson
Copy link
Owner

@57even commented in #172. I'm closing that and pasting it here to keep everything in one place:

I think #45 is a great improvement but empty values gets the option "None" which is equivalent to no filter condition (instead of empty).

How could this be solved? I think the empty values should be completely ignored in AllValuesFilter.

@carltongibson
Copy link
Owner

Related to #36

@carltongibson
Copy link
Owner

Closing this in favour of #261

@paulhauner
Copy link

Here's a Python3 compatible version of the original work-around by @cvk77 (see top of thread)

class NicerFilterSet(django_filters.FilterSet):

def __init__(self, *args, **kwargs):
  super(NicerFilterSet, self).__init__(*args, **kwargs)

  for name, field in self.filters.items():
    if isinstance(field, ChoiceFilter):
      # Add "Any" entry to choice fields.
      field.extra['choices'] = tuple([("", "Any"), ] + list(field.extra['choices']))

Changes:
self.filters.iteritems() was changed to self.filters.items()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants