django-tables2 set of columns
Asked Answered
D

1

17

How to tell django-tables2 which columns I would like to have in table? I know there is this Column attribute 'visible', which can be set to False. However I have a model with many fields, and would like to display just some of them, so writing a complete list of all columns, just to tell that most of them will not be visible, does not seem the right approach.

What I am looking for is a way to provide list of column names to be displayed, if this is possible then maybe even give user the ability to select which columns he wants.

The other solution came to my mind - make that 'visible' attribute False by default, but since it is defined in Column class, I would still need to write a complete list.

Since I have not found any django-tables2 discussion forum, I ask here.

Delvecchio answered 24/7, 2012 at 11:38 Comment(3)
Do you mean show/hide columns dynamically or just configure which fields to display at runtime ?Swearingen
Primary goal is to determine which fields to display by providing a set of column names, dynamic part is optional. I don't actually see how the dynamic part could be achieved without my primary goal.Delvecchio
You should use Meta: fields: () or exclude: () in your tables.Table definition shouldn't you ?Swearingen
S
26

Example of specifying model fields

Your Model

class Product(model.Models):
    name = model.CharField(max_length=20)
    price = model.DecimalField(max_digit=9, decimal_places=2)

Your Table

class ProductTable(tables.Table):
    actions = ProductActions(orderable=False) # custom tables.Column()
    class Meta:
        model = Product
        fields = ('name', 'price', 'action') # fields to display

Also you can also use exclude

Related docs entry here

Swearingen answered 13/8, 2012 at 9:51 Comment(4)
Great, I also used 'sequence', since 'fields' option does not alter it, like it does with ModelForm.Delvecchio
Yes this django-tables2 is really a cool app and simplifies life a lot.Swearingen
I read that docs fifteen times and could not pick it up, but when I followed your link I saw it. FMLPace
somehow the pk field (created by django) is showing up as a column named ID by default and cannot be excluded with the exclude optionBobodioulasso

© 2022 - 2024 — McMap. All rights reserved.