【问题标题】:Request Object Passed to Django-Tables2 Tables Class传递给 Django-Tables2 表类的请求对象
【发布时间】: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


【解决方案1】:

我认为您正在寻找table_factory。这将为您返回一个可以使用的 Table 类。 (另请注意,django.apps.apps.get_model 是一种比使用全局变量更好的查找模型的方法。)

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})

【讨论】:

    猜你喜欢
    • 2020-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-01
    • 2020-01-10
    • 2012-05-17
    • 1970-01-01
    相关资源
    最近更新 更多