Объект запроса передан в класс таблиц Django-Tables2 - PullRequest
0 голосов
/ 24 апреля 2019

Допустим, у нас есть две модели: 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})

Я не знаю, как передать переменную, в данном случае объект запроса, в класс, чтобы можно было выполнить форматирование переменной.

1 Ответ

1 голос
/ 24 апреля 2019

Я думаю, что вы ищете 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})
...