【问题标题】:How to change the column header of a django-tables2 table in the view.py?如何更改 view.py 中 django-tables2 表的列标题?
【发布时间】:2015-01-22 12:21:18
【问题描述】:
我在我的 Django 项目中使用 django-tables2,我想根据数据库查询动态更改某些列的标题,这是在 view.py 中完成的。
我知道在 tables.py 中可以更改每一列的“verbose_name”属性,但我想分配一个模板变量“{{ headerxy }}”,以便它动态更改。
或者有没有办法改变view.py中的“verbose_name”属性?
类似:
table.columns['column1'].header = some_data
谢谢
【问题讨论】:
标签:
python
django
view
header
django-tables2
【解决方案1】:
这里你要做的是在初始化 Table 类时将列名作为参数传递,并在该类的__init__ 范围内使用它。例如:
表类:
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')
查看:
class SomeView(View):
def get(self, request):
context = {
'table': SomeTable(SomeModel.objects.all(), c1_name='some name')
}
return render(request, 'table.html', {'context':context})
【解决方案2】:
一种方法是:
1) 使用自定义模板渲染表格
{% render_table my_table "my_template.html" %}
2) 创建 html 模板以显示您的自定义表格列,并且只扩展特定模板的块,在 my_template.html:
{% extends "django_tables2/table.html" %}
{% block table.thead %}
<thread>
<tr>
{% for column in table.columns %}
{% if my_condition == 2 %}
<th {{ column.attrs.th.as_html }}>{{ my_variable }}</th>
{% elif other_condition|length > 108 %}
<th {{ column.attrs.th.as_html }}><span class="red">{{ other_variable }}</span></th>
{% else %}
<th {{ column.attrs.th.as_html }}>{{ column.header }}</th>
{% endif %}
{% endfor %}
</tr>
</thread>
{% endblock table.thead %}
HTH。