File: filtering.rst

package info (click to toggle)
django-tables 2.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,752 kB
  • sloc: python: 7,120; makefile: 132; sh: 74
file content (47 lines) | stat: -rw-r--r-- 1,564 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
.. _filtering:

Filtering data in your table
============================

When presenting a large amount of data, filtering is often a necessity.
Fortunately, filtering the data in your django-tables2 table is simple with
`django-filter <https://pypi.python.org/pypi/django-filter>`_.

The basis of a filtered table is a `SingleTableMixin` combined with a
`FilterView` from django-filter::

    from django_filters.views import FilterView
    from django_tables2.views import SingleTableMixin


    class FilteredPersonListView(SingleTableMixin, FilterView):
        table_class = PersonTable
        model = Person
        template_name = "template.html"

        filterset_class = PersonFilter

The ``PersonFilter`` is defined the following way::

    from django_filters import FilterSet
    from .models import Person

    class PersonFilter(FilterSet):
        class Meta:
            model = Person
            fields = {"name": ["exact", "contains"], "country": ["exact"]}

The ``FilterSet`` is added to the template context in a ``filter`` variable by
default. A basic template rendering the filter (using django-bootstrap3)[https://pypi.org/project/django-bootstrap3/] and
table looks like this::

    {% load render_table from django_tables2 %}
    {% load bootstrap3 %}

    {% if filter %}
        <form action="" method="get" class="form form-inline">
            {% bootstrap_form filter.form layout='inline' %}
            {% bootstrap_button 'filter' %}
        </form>
    {% endif %}
    {% render_table table 'django_tables2/bootstrap.html' %}