Request Object Passed to Django-Tables2 Tables Class

試著忘記壹切 提交于 2019-12-20 06:24:36

问题


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


来源:https://stackoverflow.com/questions/55836417/request-object-passed-to-django-tables2-tables-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!