Django Filters Problem: How To Display All Results When The Filter Is Not SetSep 10, 2018 · by Tim Kamanin
If a view extends django-filter's
FilterView it may look similar to this:
from django_filters.views import FilterView from .filters import JobFilter class JobList(FilterView): model = Job paginate_by = 20 filterset_class = JobFilter
JobFilter has a single filter field
city that filters jobs by city and generate URL like
Everything is good and filter works, BUT, if you go to /jobs/ without any filter parameters set you'll see NOTHING!
That's the default behavior served us by
But what if we want to list all jobs when the parameters are not set (which is the obvious wish I think)?
It turns out it's as easy as setting the
strict variable to
False in the View class.
So let's change our code to:
from django_filters.views import FilterView from .filters import JobFilter class JobList(FilterView): model = Job paginate_by = 20 filterset_class = JobFilter # We set strict mode to False strict = False
And we're good to go!
Unfortunately, it isn't described in the docs, so I spent some time figuring this one out. I hope I've saved you some time, let me know if that's the case.