Django: add filtering sidebar to a change list admin view
<p>I have a back-end module showing a quite long items listing that looks like this:</p>

<pre><code>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
</code></pre>

<p>What I want to do is quite simple: I want to add a "filter by" sidebox listing all available types, for example</p>

<pre><code>Available Types
Type A
Type B
Type C
Type D
</code></pre>

<p>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</p>

<pre><code>&lt;ul&gt;
&lt;li&gt;&lt;a href="?type=11"&gt;Type A&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="?type=12"&gt;Type B&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="?type=13"&gt;Type C&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="?type=14"&gt;Type D&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
</code></pre>

<p>How can I implement that? I'm quite confused right now...</p>

<p>Thanx a lot!</p>

<p>You can use <code>class based generic views</code></p>

<pre><code>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
</code></pre>

<p>You can refer to docs <a href="https://docs.djangoproject.com/en/1.10/ref/class-based-views/generic-display/#listview" rel="nofollow">here</a></p>

python django