Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ckrybus/1c597830ed6d0dead642fd4cb31f3b7e to your computer and use it in GitHub Desktop.
Save ckrybus/1c597830ed6d0dead642fd4cb31f3b7e to your computer and use it in GitHub Desktop.
How to integrate django-crispy-forms, django-tables2 and django-filter in order to display a paginated table with filter functionality.
import django_filters
from myapp.models import ModelName
class ModelNameFilter(django_filters.FilterSet):
class Meta:
model = ModelName
fields = ['status']
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit
class ModelNameFilterFormHelper(FormHelper):
form_method = 'GET'
layout = Layout(
'status',
Submit('submit', 'Apply Filter'),
)
{% load render_table from django_tables2 %}
{% load crispy_forms_tags %}
<!-- display the filter -->
{% crispy filter.form filter.form.helper %}
<!-- display the table -->
{% render_table table %}
from django_tables2 import Column, Table
from myapp.models import ModelName
class ModelNameTable(Table):
status = Column(accessor='status', verbose_name='Status')
class Meta:
model = ModelName
from django_filters.views import FilterView
from django_tables2 import SingleTableMixin
class FilteredSingleTableView(SingleTableMixin, FilterView):
formhelper_class = None
def get_filterset(self, filterset_class):
kwargs = self.get_filterset_kwargs(filterset_class)
filterset = filterset_class(**kwargs)
filterset.form.helper = self.formhelper_class()
return filterset
class ModelNameView(FilteredSingleTableView):
template_name = 'modelname.html'
table_class = ModelNameTable
paginate_by = 25
filterset_class = ModelNameFilter
formhelper_class = ModelNameFilterFormHelper
@marcuoli
Copy link

Excelent !!!

Tried to follow but I stumbled in a 'Customer() got unexpected keyword arguments: 'data'' error.... any tip for me ?

Thanks !

@alexander-jacob
Copy link

Great! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment