django - 如何将 django_tables2 与过滤器一起使用?

标签 django django-tables2

我正在网页上显示数据,我想迁移此代码以使用我在tables.py 中创建的表。我不知道如何在不破坏过滤器的情况下做到这一点。

View .py

def PlatListView(request):
    
    queryset = Plat.objects.all().values('id', 'description','status', 'phase__number','phase','schedule_found').annotate(lot_count=Sum('phase__lot_count')).order_by('description')

    f = PlatFilter(request.GET, queryset=queryset)
   
    return render(request, 'blog/filtertable2.html', {'filter': f})

过滤器.py

class PlatFilter(django_filters.FilterSet):
    community = ModelChoiceFilter(queryset=Community.objects.all())

表.py

import django_tables2 as tables

class PlatTable(tables.Table):  

    id = tables.Column()
    description = tables.Column()
    status = tables.Column()
    phase__number = tables.Column()
    lot_count = tables.Column()
    schedule_found = tables.Column()
    
    class Meta:
        ordering = 'description'
        #model = Plat

filtertable2.html

{% extends "blog/base.html" %}
{% block content %}

{% load bootstrap4 %}

<form method="get">
        {{ filter.form.as_p }}
        <input type="submit" />
    </form>

 <table>
  <tr>
    <th>Description</th>
    <th>Status</th>
  </tr>
 {% for obj in filter.qs %}
  <tr>
    
        <td> {{ obj.description }}</td>
        <td>{{ obj.status }}</td>
   
  </tr>
   {% endfor %}
</table>
   
{% endblock content %}

最佳答案

在您看来,您使用过滤器中的数据构建表格:

def PlatListView(request):
    queryset = Plat.objects.annotate(
        lot_count=Sum('phase__lot_count')
    ).order_by('description')

    f = PlatFilter(request.GET, queryset=queryset)
    table = <b>PlatTable(data=f.qs)</b>
    return render(request, 'blog/filtertable2.html', {'filter': f, <b>'table': table</b>})

然后您可以使用以下方式呈现表格:

{% extends "blog/base.html" %}
{% block content %}

{% load bootstrap4 %}
{% <b>load render_table from django_tables2</b> %}

<form method="get">
    {{ filter.form.as_p }}
    <input type="submit" />
</form>

{% <b>render_table table</b> %}
   
{% endblock content %}

关于django - 如何将 django_tables2 与过滤器一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65428522/

相关文章:

.net - Rosetta 类似于 ASP.NET MVC Web 应用程序的本地化?

django - 基于 ForeignKey 对象从模型中获取对象

python - 如何在 VSCode 中启动 django unittest?

python - MultiValueDictKeyError 在/addbook/

python - 在管理界面显示用户组?

python - 如何在 django-tables2 中使用基于类的 View 控制分页?

python - 将 django-tables 的列自定义为下拉列表

django - 从 django_tables2 获取行数

django - 默认禁用 django_tables2 表的排序

python - 使用 django_tables2 时,它告诉我 TemplateDoesNotExist