Reputation: 244
I have a back-end module showing a quite long items listing that looks like this:
ID Label Type
1 Label 1 Type A
2 Label 2 Type B
3 Label 3 Type A
4 Label 4 Type D
5 Label 5 Type C
6 Label 6 Type D
7 Label 7 Type C
What I want to do is quite simple: I want to add a "filter by" sidebox listing all available types, for example
Available Types
Type A
Type B
Type C
Type D
If clicked they should enable filtering by single type. For example, if I click on "Type A" only items belonging to that type will be shown. Sidebar's HTML should look like this
<ul>
<li><a href="?type=11">Type A</a></li>
<li><a href="?type=12">Type B</a></li>
<li><a href="?type=13">Type C</a></li>
<li><a href="?type=14">Type D</a></li>
</ul>
How can I implement that? I'm quite confused right now...
Thanx a lot!
Upvotes: 0
Views: 712
Reputation: 739
You can use class based generic views
from django.views import generic
class MyListView(generic.ListView):
model = MyModel
template_name = 'my_list.html'
def get_queryset(self):
queryset = super(MyListView, self).get_queryset()
# get query value of query parameter 'type'
type = self.request.GET.get('type', None)
if type:
# if type is given then filter
return queryset.filter(type__exact=type)
# if type is not give then return all
return queryset
You can refer to docs here
Upvotes: 1