Django-tables2 send parameters to custom table template

扶醉桌前 提交于 2021-01-29 05:32:51

问题


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?


回答1:


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})



回答2:


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


来源:https://stackoverflow.com/questions/62679420/django-tables2-send-parameters-to-custom-table-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!