How to change the column header of a django-tables

2019-08-13 01:01发布

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

2条回答
▲ chillily
2楼-- · 2019-08-13 01:46

One way of doing it would be:

1) render the table with custom template

{% render_table my_table "my_template.html" %}

2) create html template to display your custom table columns, and only extending specific template's block, in 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.

查看更多
聊天终结者
3楼-- · 2019-08-13 01:49

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})
查看更多
登录 后发表回答