Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add #528 - Define and use get_table_data in MultiTableMixin #538

Merged
merged 3 commits into from
Feb 15, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 13 additions & 5 deletions django_tables2/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,13 +137,14 @@ class SingleTableView(SingleTableMixin, ListView):

class MultiTableMixin(TableMixinBase):
'''
Adds a Table object to the context. Typically used with
Add a list with multiple Table object's to the context. Typically used with
`.TemplateResponseMixin`.

the `tables` attribute must be either a list of `.Table` instances or
classes extended from `.Table` which are not already instantiated. In that
case, tables_data must be defined, having an entry containing the data for
each table in `tables`.
case, `get_tables_data` must be able to return the tables data, either by
having an entry containing the data for each table in `tables`, or by
overriding this method in order to return this data.

Attributes:
tables: list of `.Table` instances or list of `.Table` child objects.
Expand Down Expand Up @@ -175,13 +176,20 @@ def get_tables(self):

return self.tables

def get_tables_data(self):
'''
Return an array of table_data that should be used to populate each table
'''
return self.tables_data

def get_context_data(self, **kwargs):
context = super(MultiTableMixin, self).get_context_data(**kwargs)
data = self.get_tables_data()

if self.tables_data is None:
if data is None:
tables = self.get_tables()

else:
data = self.tables_data
if len(data) != len(self.get_tables()):
klass = type(self).__name__
raise ImproperlyConfigured(
Expand Down
16 changes: 16 additions & 0 deletions tests/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,3 +340,19 @@ class View(DispatchHookMixin, tables.MultiTableMixin, TemplateView):

assert tableA.page.number == 1
assert tableB.page.number == 3

def test_get_tables_data(self):
class View(tables.MultiTableMixin, TemplateView):
tables = (TableA, TableB)
template_name = 'multiple.html'

def get_tables_data(self):
return [Person.objects.all(), Region.objects.all()]

response = View.as_view()(build_request('/'))
response.render()

html = response.rendered_content

assert '<td class="first_name">Jan Pieter</td>' in html
assert '<td class="name">Zuid-Holland</td>' in html