Change Column Headers in Django Tables 2

Change Column Headers in Django Tables 2
Photo by Jana Sabeth on Unsplash

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

Model class

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.

Last updated: May 22, 2024

← Previous
Dynamically construct filters based on string input using SQLAlchemy

Building a filter which takes model class/query & conditions as input, return a filtered query.

Next →
Make a Blog using Django Part 1

This post is now deprecated. Please follow the official tutorial for creating your first django …

Share Your Thoughts
M↓ Markdown