Sep 10, 2018 · Updated: Jul 12, 2021 · 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 /jobs/?city=London
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 FilterView
.
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 toFalse
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.
Hey, if you've found this useful, please share the post to help other folks find it: