【问题标题】:Django-tables2 does not sortDjango-tables2 不排序
【发布时间】:2012-06-12 07:20:45
【问题描述】:

我使用 django-tables2 显示一个数据库表。一切似乎都正常,但单击列标题不会按该列排序。标题是可点击的,但在它们的 html 中没有 url 文本,例如:

<div class="table-container">
<table class="paleblue"><thead><tr><th class="id orderable sortable"><a href="">ID</a>
</th><th class="orderable sortable system"><a href="">System</a></th> ...

我检查了 django-tables2 模板源,它是这样的:

... <a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}"> ...

我不明白。

我只能通过在 view.py 中设置 order_by 来进行排序:

class ResultsTable(tables.Table):
    class Meta:
        model = Performance
        attrs = {'class': 'paleblue'}
        order_by_field = True

def result(request, system):
    results = Performance.objects.filter(system__name=system)
    table = ResultsTable(results, order_by=('<any column name from Performance>',))
    RequestConfig(request).configure(table)
    return render_to_response('result.html', {'table': table})

但这显然只适用于一列,我想单击列以选择要排序的列。

我从docs 了解到,按列排序应该“开箱即用”,这是正确的,还是我做错了什么?

【问题讨论】:

  • order_by_field = True 此处无效。

标签: django django-tables2


【解决方案1】:

遇到了同样的问题,只是我错过了

django.core.context_processors.request

来自 settings.py 中的 TEMPLATE_CONTEXT_PROCESSORS

【讨论】:

  • 感谢您的参与。有同样的问题。这对我有帮助,连同接受的答案。
【解决方案2】:

在睡了一夜之后,我的代码与 django-tables2 文档中的示例进行了全新的外观和逐字比较,找到了我自己问题的答案。

对于我使用的结果函数:

return render_to_response('result.html', {'table': table})

如果我将其替换为:

return render(request, 'result.html', {'table': table})

排序按预期工作。 不要问我为什么……

【讨论】:

  • 谢谢布拉德利。顺便说一句,Django-tables2 非常好,正是我所需要的。
  • 布拉德利是对的。为了使您的第一个示例等效,您可以编写 return render_to_response('result.html', {'table': table}, RequestContext(request))
【解决方案3】:

此页面上的其他回复指出了正确的方向,但只是想包含在一个地方进行此工作所需的所有内容。在视图中:

  1. 定义您的查询集没有排序
  2. 将查询集传递到表实例中
  3. 在表 obj 上设置任何自定义项,例如默认排序
  4. 将其全部包含在 RequestConfig 中(必不可少 - 没有这个就无法订购!)
  5. 将完全配置的表传递到模板上下文中
# views.py
from django_tables2 import RequestConfig
...
data = MyModel.objects.all()
my_table = MySummariesTable(data)
my_table.order_by = "-name"
RequestConfig(request).configure(my_table)
ctx = {"my_table": my_table}

return render(request, "path/mytemplate.html", ctx)

如果您的任何列需要通过外键关系排序,请在表列定义中定义这些列,例如

col1 = tables.Column(verbose_name="Some Col", order_by="mycol.foobar.name")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多