Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple example of how to use a class based view and django-filter?

The example in the documentation, https://django-filter.readthedocs.org/en/latest/usage.html, is I think for a function based view. I am currently researching how to do this with a class based view.

def product_list(request):
    f = ProductFilter(request.GET, queryset=Product.objects.all())
    return render_to_response('my_app/template.html', {'filter': f})
like image 292
hum3 Avatar asked Jun 19 '14 11:06

hum3


2 Answers

A bit more digging and I have managed to answer it. I have used the code from here https://github.com/rasca/django-enhanced-cbv.

I added the contents of list.py into my main app as main_app/filter_mixin.py

Then in the app I was adding a search to the list view I added the file filter.py like this (identical to documentation)

from django_filters import FilterSet
from .models import Contact


class ContactFilter(FilterSet):
    class Meta:
        model = Contact
        fields = ['name_first', 'name_last']

Now the view.py becomes:

from vanilla import ListView

from .filter import ContactFilter
from galleria.filter_mixin import ListFilteredMixin


class ContactList(ListFilteredMixin, ListView):
    filter_set = ContactFilter
like image 191
hum3 Avatar answered Oct 31 '22 20:10

hum3


Here's an example with just overwriting the queryset to allow filtering and context to embed the filters in the template.

class ObjFilter(django_filters.FilterSet):
    class Meta:
        model = Obj
        fields = ["field1", "field2"]


class ObjView(ListView):
    template_name = "template.html"
    model = Obj
    paginate_by = 10
    ordering = ["-id"]

    def get_queryset(self):
        queryset = super().get_queryset()
        filter = ObjFilter(self.request.GET, queryset)
        return filter.qs

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        queryset = self.get_queryset()
        filter = ObjFilter(self.request.GET, queryset)
        context["filter"] = filter
        return context
like image 3
marcinowski Avatar answered Oct 31 '22 20:10

marcinowski