Change Column Header Dynamically in Django Tables2

Django Tables2 is a package which displays table directly from queryset. It shows column header based on object's attribute's name. But if someone wants to override it, how can he/she do that? Here is a easy solution.

Suppose we have a model class like this:

class SomeModel(models.Model):
   somevalue = models.CharField()

And we want to show table column somevalue to overridenvalue

Table Class:

class SomeTable(tables.Table):
    def __init__(self, *args, _overriden_value="",**kwargs):
        super().__init__(*args, **kwargs)

        self.base_columns['somevalue'].verbose_name = _overriden_value
    class Meta:
         model = models.SomeModel
             fields = '__all__'

And the Class Based View:

View Class

class SomeView(ListView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['sometable'] = SomeTable(SomeModel.objects.all(), _overriden_value="overriden value")
        return context

And template should render that table like this:

{% load render_table from django_tables2 %}
{% render_table sometable %}

Thats it, we shall be able to see our override table column header.

comments powered by Disqus