Search code examples
djangodjango-tables2

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?


Solution

  • 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 %}