[英]How to display multiple tables in one view using django-tables2?
使用djt2 v0.15 / dj1.6 / pyth2.6.6
多個表的djt2 doc示例視圖文件:
def people_listing(request) :
config = RequestConfig(request)
table1 = PeopleTable(Person.objects.all(), prefix="1-")
table2 = PeopleTable(Person.objects.all(), prefix="2-")
config.configure(table1)
config.configure(table2)
return render(request, "people_listing.html",
{"table1": table1, "table2": table2})
首先,此示例對於引用的“ table1”,“ table2”參數似乎是不正確的。 我的測試表明,至少在單個表上的引號中需要使用定義名稱“ people_list”。 此外,為什么有人要兩次顯示同一張表? 這是一個不好的例子嗎? 這是我的應用嘗試使用此結構:
def AvLabVw(request):
config = RequestConfig(request)
cmutbl = CmuTable(CmuVersion.objects.all(), prefix="1-")
simtbl = SimTable(Simulator.objects.all(), prefix="2-")
config.configure(cmutbl)
config.configure(simtbl)
return render(request, "AvRelInfo.html", {"AvLabVw":cmutbl, "AvLabVw":simtbl})
url文件在AvLabVw上獲取,並且html模板使用render_table。
{% render_table AvLabVw %}
此代碼會發生什么,就是僅顯示一個表,以返回渲染行上的最后一個表為准。
在文檔的其他地方,它說需要使用具有get_context_data的SingleTableView,但我還沒有弄清楚...
我嘗試過這種樣式的實現,我認為它需要一個表對象和一個列表對象嗎?
from django_tables2 import views from django_tables2 import SingleTableView from django_tables2 import SingleTableMixin from django.shortcuts import render from django_tables2 import RequestConfig def SimVers_lst(request): return render(request, 'AvRelInfo.html', {'SimVers_lst' : Simulator.objects.all()}) def AvLabVw(request): config = RequestConfig(request) simlst = SimVers_lst(Simulator.objects.all()) table = CmuTable(CmuVersion.objects.all(), prefix="1-") Stv = views.SingleTableView() multitbl = Stv.get_context_data() config.configure(multitbl) return render(request, "AvRelInfo.html", { "AvLabVw" : multitbl })
html模板中{% render_table AvLabVw %}
處的{% render_table AvLabVw %}
,具有通常的全部"ValueError at /AvCtlapp/ Expected table or queryset, not 'str'."
...得到一些垃圾...如果可以設置測試,我想我可以嘗試看看它在外殼中得到了什么...
謝謝你的幫助...
喬
PS:是否需要自定義渲染,外觀如何?
您的第一個代碼示例(它是從django-tables2文檔中復制的)旨在在一個頁面中呈現兩個表。 這不是一個壞例子(我認為),因為它展示了如何使用相同的查詢集(具有不同的前綴)呈現來自同一表類的2個表。
最后一個代碼示例是您使用SingleTableView時出錯的。 它的意思是在模板中呈現一個表,並且基本上是一個基於類的視圖。 嘗試這樣:
class AvLabVw(SingleTableView):
model = Simulator
template_name = 'AvRelInfo.html'
table_class = SimulatorTable
模板就像:
{% load render_table from django_tables2 %}
{% render_table table %}
現在,如果要呈現多個表,請從此視圖覆蓋get_context_data()
方法,如下所示:
class AvLabVw(SingleTableView):
model = Simulator
template_name = 'AvRelInfo.html'
table_class = SimulatorTable
def get_context_data(self, **kwargs):
context = super(AvLabVw, self).get_context_data(**kwargs)
context['table_cmu'] = CmuTable(CmuVersion.objects.all(), prefix="1-")
return context
和模板,如:
{% load render_table from django_tables2 %}
{% render_table table %}
{% render_table table_cmu %}
和網址:
url(r'^something/$', AvLabVw.as_view(), name='avlabvw'),
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.