2013-05-22 41 views
7

W moim projekcie Django potrzebuję tabel, które są kolumnami dynamicznymi i zależą od tego, co jest w bazie danych. Więc znalazłem rozwiązanie w here i działa, ale z małym problemem. Tutaj jest klasa z tabeli Mam rozciągającej się dynamicznie:Django-tables2 - dynamiczne dodawanie kolumn do tabeli - nie dodawanie attrs do tagu tabeli w html

class ClientsTable(tables.Table): 
    class Meta: 
     model = Client 
     attrs = {"class": "paleblue", "orderable":"True", "width":"100%"} 
     fields = ('name',) 

    def __init__(self, *args, **kwargs): 
     super(ClientsTable, self).__init__(*args, **kwargs) 
     self.counter = itertools.count() 

    def render_row_number(self): 
     return '%d' % next(self.counter) 

    def render_id(self, value): 
     return '%s' % value 

I tu jest metoda, która rozszerza klasę:

def define_table(roles): 
    attrs = dict((r.name, tables.Column() for r in roles) 
    klass = type('DynamicTable', (ClientsTable,), attrs) 
    return klass 

Kiedy tworzę tabelę w views.py tak:

table = define_table(roles)(queryset) 

tabela przedstawia kolumny jak chciałem, ale w kodzie html widzę, że zignorował attrs:

{"class": "paleblue", "orderable":"True", "width":"100%"} 

Nie ma więc stylu css dla paleblue, co jest dla mnie ważne. Czuję, że może to być coś z klasy Meta, ale pola i model działają, więc nie mam pojęcia, dlaczego attrs nie są.

Odpowiedz

6

Po pierwsze, meta options are not inherited w django-tables2. Możesz więc sprawdzić obejścia omówione w tym wydaniu, aby sprawdzić, czy coś pasuje, lub możesz dodać klasę Meta do tabeli dynamicznej. Aby to zrobić, możesz swoją define_table metoda tak:

 
def define_table(roles): 
    attrs = dict((r.name, tables.Column() for r in roles) 
    attrs['Meta'] = type('Meta',(), dict(attrs={"class":"paleblue", "orderable":"True", "width":"100%"})) 
    return klass 

Ups po ponad dwóch lat zauważyłem, że wystąpił błąd w kodzie - Zapomniałam zawierać linię klass = type('DynamicTable', (ClientsTable,), attrs) przed return klass powyżej. Jestem, dodając go teraz do kompletności.

+0

ładne rzeczy! Niezupełnie odpowiadając na mój problem, ale mogłem zmodyfikować twój fragment kodu, aby rozwiązać mój problem i nauczyłem się dużo o Pythonie typu "typ" i meta klasy działania. Thx a bunch! – schwobaseggl

+0

Cieszę się, że pomogłem! Napisałem też różne posty robiące rzeczy typu na moim blogu: http://spapas.github.io/category/django.html – Serafeim

3

Dla każdego, kto szuka tego teraz, z django-tables2 1.10 dynamicznie dodajesz kolumny do tabeli, przekazując extra_columns do konstruktora Table.

powinna być listą krotek, definiującą nazwę kolumny i obiekt Column, np.

class MyTable(Table): 
    static_column = Column() 

mytable = MyTable(extra_columns=[('dynamic_column', Column())] 

Zobacz dokumentację API pod adresem: http://django-tables2.readthedocs.io/en/latest/pages/api-reference.html#django_tables2.tables.Table