Django ListView – Form to filter and sort

You don’t need post. Pass the filter value and order_by in the url for example:

.../update/list/?filter=filter-val&orderby=order-val

and get the filter and orderby in the get_queryset like:

class MyView(ListView):
    model = Update
    template_name = "updates/update.html"
    paginate_by = 10

    def get_queryset(self):
        filter_val = self.request.GET.get('filter', 'give-default-value')
        order = self.request.GET.get('orderby', 'give-default-value')
        new_context = Update.objects.filter(
            state=filter_val,
        ).order_by(order)
        return new_context

    def get_context_data(self, **kwargs):
        context = super(MyView, self).get_context_data(**kwargs)
        context['filter'] = self.request.GET.get('filter', 'give-default-value')
        context['orderby'] = self.request.GET.get('orderby', 'give-default-value')
        return context

Make sure you give proper default value to filter and orderby

Example form (you can modify this to your need):

<form method="get" action="{% url 'update-list' %}">
    <p>Filter: <input type="text" value={{filter}} name="filter"/></p>
    <p>order_by: <input type="text" value={{orderby}} name="orderby"/></p>
    <p><input type="submit" name="submit" value="submit"/></p>
</form>

Leave a Comment

tech