2

I'm using SingleTableMixin and FilterView in Django to render a filter form and table. On the basic level it works very well.

Now, the table has as many columns as the model has fields (as it should), but I would like to render ONLY the columns for which a user has provided input in the filter form and exclude the others columns dynamically.

I'm trying to achieve this by using def get_table_kwargs(self): Here is my code:

class FactListView(SingleTableMixin, FilterView):
    table_class = FactTable
    filterset_class = FactFilter
    template_name = 'main/table.html'

    def get_table_kwargs(self):
        filtered = self.filterset.form.data()

        columns = {}
        fact_fields = [
            "field_name1",
            "field_name2",
            "field_name3",
            "other fields",
            "...",

        ]

        for field, value in filtered():
            if value is not None:
                columns.update({field: value})

        fact_fields[:] = [x for x in fact_fields if x not in columns]
        return {
            'exclude': fact_fields
        }

I'm currently getting an error saying: "TypeError at /table/ 'dict' object is not callable" That's because I'm a noob. So I would be very grateful for comments on this particular error, which results from filtered = self.filterset.form.data(), as well as on the general logic.

Many thanks in advance!

Oleksandr K
  • 119
  • 1
  • 10
  • This is not really related to your question, however when I have "long" tables (with many columns) for which I want to allow configuration for each user I use https://github.com/djk2/django-tables2-column-shifter which lets each user select which columns he wants to display. Try it it may help you. – Serafeim Oct 09 '18 at 06:33

1 Answers1

1

I was able to find the solution on my own. So, in case there is someone else who also combines django-tables2 with django-filter and would like to have dynamic column rendering, depending on wether the user has filtered the corresponding field.

My mistake was trying to access the filterset.form.data to get the user input, when I had to go for the request:

...
for field in fact_fields:
filtered = self.request.GET.get(field)
    if filtered is None:
    ...   
Oleksandr K
  • 119
  • 1
  • 10