Change Column Headers in Django Tables 2
Sep 17, 2015 · 1 Min Read · 0 Like · 2 CommentsDjango 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: Jul 13, 2024
I won't spam you. Unsubscribe at any time.