johnnymondo
johnnymondo

Reputation: 79

Django-tables2 send parameters to custom table template

I'm trying to use a custom table template to embed the django-filter fields on my table. So I copied the django-tables2 bootstrap.html template in a new file custom_table.html. Then I added it the following code in the thead section:

     {% if filter %}
       <tr>
          {% for filter_field in filter.form.fields %}
              <td>
                 {{ filter_field }}
              </td>
          {% endfor %}
          <td>
             <button class="login100-form-btn" type="submit">Filter</button>
          </td>
       </tr>
    {% endif %}

So the problem is : how can I send the filter to the table template?

Upvotes: 0

Views: 1163

Answers (2)

johnnymondo
johnnymondo

Reputation: 79

I resolved this issue. I have overridden the get_context_data function of my view:

    def get_context_data(self, **kwargs):
   
         context = super().get_context_data(**kwargs)
         table = self.get_table(**self.get_table_kwargs())
         table.filter = self.filterset
         context[self.get_context_table_name(table)] = table
         return context

In this way, I can use the filter in my custom table template by the following code:

               {% if table.filter %}

                <tr>
                    <form action="" method="get" class="form-inline">
                        {% csrf_token %}
                        {% for field_form in table.filter.form %}
                        <th>
                            {{field_form}}
                        </th>
                        {% endfor %}
                        <th>
                            <button class="btn" type="submit">Filter</button>
                        </th>
                    </form>
                </tr>
                {% endif %}

Upvotes: 2

minglyu
minglyu

Reputation: 3327

You can send the query paramters to the server, and construct the table using filtered_queryset. For example:

#views.py
def your_view(request):
    filter = ModelFilter(request.GET, queryset=Model.objects.all())

    filtered_queryset = filter.qs
    # pass filtered_queryset to your table
    table = SimpleTable(filtered_queryset)
    return render(request, 'table.html', {'table': table})

Upvotes: 0

Related Questions