我使用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按列排序应该“开箱即用”,这是正确的,还是我做错了什么?
答案 0 :(得分:5)
遇到同样的问题,只有我错过了
django.core.context_processors.request
来自settings.py中的TEMPLATE_CONTEXT_PROCESSORS
答案 1 :(得分:1)
在经过一夜的睡眠和新鲜的表情以及我的代码与django-tables2文档中的示例的逐字比较后,找到了我自己的问题的答案。
对于我使用的结果函数:
return render_to_response('result.html', {'table': table})
如果我将其替换为:
return render(request, 'result.html', {'table': table})
排序按预期工作。 不要问我为什么......
答案 2 :(得分:1)
此页面上的其他回答都指向正确的方向,但只是想包含使此功能在一个地方工作所需的一切。在视图中:
RequestConfig
中(必不可少-没有此功能,订购将不起作用!)# 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")