Expand admin’s interface filters usage to your front-end views — Django
Provide filters to views by simply reusing previously created admin classes
Django admin filters are pretty awesome and using the SimpleListFilter
expands on the basic filters over fields. Here’s a quick example just to remember how they work:
But did you know that we can do much more with them? How about using them in your views to provide filtering to your project outside of the Django admin interface?
A couple of simple changes are necessary for this to work properly.
Start with your SimpleListFilter
by moving your lookups
to class method because we’ll need to get them without an instance of your class.
This is related to a Form
we must have which will dynamically create its own fields based on the filters provided to it.
Now, the view we want to apply the filters to must use that form and inherit from a mixin that can grab the filters from GET
parameters and use them in a QuerySet
.
Finally, by adding the form to our template and setting the submit method to GET
, the form should be rendered properly and whenever it’s submitted, the results will be filtered according to the options chosen, like in the example below.
This is a really simple example of filters. Personally I’ve added filters for relations with ForeignKey
s, date ranges, years and months and more. I leave this challenge to you, but if you need any help leave a comment and I’ll try to answer it to my best knowledge 😄
All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.
🍋 🍋 🍋