Request Object Passed to Django-Tables2 Tables Cla

2020-05-01 06:53发布

问题:

Lets say that we have two models: ModelA and ModelB.

I will use Django-Tables2 to create a table out of these models.

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'

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.

回答1:

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