【发布时间】:2019-04-24 18:26:52
【问题描述】:
假设我们有两个模型:ModelA 和 ModelB。
我将使用 Django-Tables2 从这些模型中创建一个表。
在 tables.py 中,您可以有两个单独的表类(如下)。
from .models import ModelA, ModelB
import django_tables2 as tables
class ModelATable(tables.Table):
class Meta:
#some basic parameters
model = ModelA
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
class ModelBTable(tables.Table):
class Meta:
#some basic parameters
model = ModelB
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
这意味着每个模型都有一个表格。但是我认为更有效的编码解决方案如下。
class MasterTable(tables.Table, request):
#where request is the HTML request
letter = request.user.letter
class Meta:
#getting the correct model by doing some variable formatting
temp_model = globals()[f'Model{letter}']
#some basic parameters
model = temp_model
#the template we want to use
template_name = 'django_tables2/bootstrap.html'
问题涉及从views.py 传递表定义中的请求对象。它看起来像:
def test_view(request):
#table decleration with the request object passed through...
table = MasterTable(ModelOutput.objects.all(), request)
RequestConfig(request).configure(table)
return render(request, 'some_html.html', {'table': table})
我不知道如何将变量(在本例中为请求对象)传递给类,以便进行变量格式化。
【问题讨论】:
-
这根本没有任何意义。类不能从当前请求继承。
-
好的,我如何传递一个变量而不是请求对象?
标签: python django django-tables2