diff --git a/django_tables2/tables.py b/django_tables2/tables.py index 28a160b..bd9e2b2 100644 --- a/django_tables2/tables.py +++ b/django_tables2/tables.py @@ -35,22 +35,15 @@ class TableData(object): self.queryset = data # otherwise it must be convertable to a list else: - try: + # do some light validation + if hasattr(data, '__iter__') or (hasattr(data, '__len__') and hasattr(data, '__getitem__')): self.list = list(data) - except Exception as ex: - if six.PY3: - raise ValueError( - 'data must be QuerySet-like (have count and ' - 'order_by) or support list(data) -- %s has ' - 'neither' % type(data).__name__ - ) - else: - # really horrible, but this syntax is not supported on PY3 and would not work otherwise - exec("""raise ValueError, ( - 'data must be QuerySet-like (have count and ' - 'order_by) or support list(data) -- %s has ' - 'neither. Original exception: %s' % (type(data).__name__, ex) - ), sys.exc_info()[2]""") + else: + raise ValueError( + 'data must be QuerySet-like (have count and ' + 'order_by) or support list(data) -- %s has ' + 'neither' % type(data).__name__ + ) def __len__(self): if not hasattr(self, "_length"): diff --git a/tests/core.py b/tests/core.py index eb29fc0..0c8cbb4 100644 --- a/tests/core.py +++ b/tests/core.py @@ -165,7 +165,30 @@ def should_support_haystack_data_source(): table = PersonTable(SearchQuerySet().all()) table.as_html() + + +@core.test +def data_validation(): + with raises(ValueError): + table = OrderedTable(None) + + class Bad: + def __len__(self): + pass + + with raises(ValueError): + table = OrderedTable(Bad()) + class Ok: + def __len__(self): + return 1 + def __getitem__(self, pos): + if pos != 0: + raise IndexError() + return {'a': 1} + + table = OrderedTable(Ok()) + assert len(table.rows) == 1 @core.test def ordering():