django-filter with django-tables2

2,806 views
Skip to first unread message

Andy Warburton

unread,
Mar 20, 2013, 6:40:21 AM3/20/13
to django...@googlegroups.com
Has anyone managed to use django-filter with django-tables2?

In using django-filter I've created a Filter class in models.py:

class MyFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_type='startswith')
...etc

and then instantiated this in a view and passed the results to a template:

myfilterdata = MyFilter(data, queryset=Event.objects.all().filter(data_source__exact=1).order_by(*sort))
return render(request, 'xgenca/list.html', {'events': myfilterdata })

However to customise django-tables2, you need a Table class which is instantiated and passed to the template:

# tutorial/tables.py
import django_tables2 as tables
from tutorial.models import Person

class PersonTable(tables.Table):
    class Meta:
        model = Person
        # add class="paleblue" to <table> tag
        attrs = {"class": "paleblue"}

You’ll then need to instantiate and configure the table in the view, before adding it to the context.

# tutorial/views.py
from django.shortcuts import render
from django_tables2   import RequestConfig
from tutorial.models  import Person
from tutorial.tables  import PersonTable

def people(request):
    table = PersonTable(Person.objects.all())
    RequestConfig(request).configure(table)
    return render(request, 'people.html', {'table': table})


I'm trying to work out how I could combine both of these.  Any ideas would be appreciated.

Marwen Hammami

unread,
Sep 25, 2013, 7:30:06 AM9/25/13
to django...@googlegroups.com
 I tried your solution but it doesn't work, so i displayed the filter as a form but i don't know how to pass the results to the django-table2 in the template

Le mercredi 5 juin 2013 02:30:03 UTC+2, Scott O'Brien a écrit :
Yes, I've got it to work pretty easily.

in my example I was using my Filter to populate items in django-tables2

queryset = Fitzroyfalls.objects.select_related().all()
f = FitzroyfallsFilter(request.GET, queryset=queryset)
table = FitsroyFallsTable(f.qs)
table.paginate(page=request.GET.get('page', 1), per_page=25)
RequestConfig(request).configure(table)
return render(request, 'query.html', {'table': table})
Reply all
Reply to author
Forward
0 new messages