如何更改view.py中django-tables2表的列标题? [英] How to change the column header of a django-tables2 table in the view.py?

查看:140
本文介绍了如何更改view.py中django-tables2表的列标题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的Django项目中使用了django-tables2,并且我想根据数据库查询来动态更改某些列的标题,这是在view.py中完成的。



我知道在tables.py中,可以更改每列的verbose_name属性,但我想指定一个模板变量{{headerxy}},以便动态更改。 / p>

或者有没有办法改变view.py中的verbose_name属性?



类似于:

  table.columns ['column1']。header = some_data 

谢谢

解决方案

在初始化Table类时将列名称作为参数,并在该类的 __ init __ 范围内使用它。例如:

Table类:

  class SomeTable(tables。表):
def __init __(self,* args,c1_name =,** kwargs):#将从该类的名称中获取c1_name。
super().__ init __(* args,** kwargs)
self.base_columns ['column1']。verbose_name = c1_name $ b $ class Meta:
model = SomeModel
字段=('column1')

查看:

  class SomeView(View):
def get(self,request):
context = {
'table':SomeTable(SomeModel。 objects.all(),c1_name ='some name')
}
return render(request,'table.html',{'context':context})


I'm using django-tables2 in my Django project and I would like to change dynamically the header of some columns according to a database query, which is done in view.py.

I know that in tables.py one can change the "verbose_name" attribute of each and every column but I would like to assign a template variable "{{ headerxy }}" for example so that it changes dynamically.

Or is there a way to change the "verbose_name" attribute in the view.py ?

Something like:

table.columns['column1'].header = some_data

Thanks

解决方案

Here what you have to do is to pass the column name as parameter when initialising the Table class and use it within __init__ scope of that class. For example:

Table Class:

class SomeTable(tables.Table):
    def __init__(self, *args, c1_name="",**kwargs):  #will get the c1_name from where the the class will be called.
        super().__init__(*args, **kwargs)
        self.base_columns['column1'].verbose_name = c1_name
    class Meta:
        model = SomeModel
        fields = ('column1')

View:

class SomeView(View):
  def get(self, request):
    context = {
      'table': SomeTable(SomeModel.objects.all(), c1_name='some name')
    }
    return render(request, 'table.html', {'context':context})

这篇关于如何更改view.py中django-tables2表的列标题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆