请求对象传递给Django-Tables2 Tables类 [英] Request Object Passed to Django-Tables2 Tables Class
问题描述
让我们说我们有两个模型:ModelA和ModelB。
Lets say that we have two models: ModelA and ModelB.
我将使用Django-Tables2从这些模型中创建一个表。
I will use Django-Tables2 to create a table out of these models.
在tables.py中,您可以有两个单独的表类(如下)。
In tables.py you could have two separate table classes (below).
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'
这意味着每个模型都有一个表格。但是,我认为更有效的编码解决方案将是针对以下内容。
This means there will be a table for each model. However I think a more efficient coding solution would be to something as follows.
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'
此问题涉及从视图传递表定义中的请求对象。 py。看起来像这样:
The issue involves passing the request object in the table definition from views.py. It would look something like:
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})
我不知道如何传递变量,在这种情况下,请求对象是该类的对象,以便可以进行变量格式化。
I do not know how to pass through a variable, in this case the request object, to the class so that variable formatting can be done.
推荐答案
我认为您正在寻找 table_factory
。这将为您返回一个Table类,您可以使用它。 (还请注意,与使用全局变量相比, django.apps.apps.get_model
是查找模型的更好方法。)
I think you are looking for table_factory
. This returns a Table class for you which you can use. (Also note, django.apps.apps.get_model
is a better way of looking up a model than using globals.)
from django_tables2 import tables
from django.apps import apps
class BaseTable(tables.Table):
class Meta:
template_name = 'django_tables2/bootstrap.html'
def test_view(request):
temp_model = apps.get_model('myapp', f'Model{request.user.letter}')
MasterTable = tables.table_factory(temp_model, table=BaseTable)
table = MasterTable(ModelOutput.objects.all())
RequestConfig(request).configure(table)
return render(request, 'some_html.html', {'table': table})
这篇关于请求对象传递给Django-Tables2 Tables类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!