tables.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import django_tables2 as tables
  2. from django.utils.safestring import mark_safe
  3. class BaseTable(tables.Table):
  4. """
  5. Default table for object lists
  6. """
  7. def __init__(self, *args, **kwargs):
  8. super(BaseTable, self).__init__(*args, **kwargs)
  9. # Set default empty_text if none was provided
  10. if self.empty_text is None:
  11. self.empty_text = 'No {} found'.format(self._meta.model._meta.verbose_name_plural)
  12. class Meta:
  13. attrs = {
  14. 'class': 'table table-hover table-headings',
  15. }
  16. class ToggleColumn(tables.CheckBoxColumn):
  17. """
  18. Extend CheckBoxColumn to add a "toggle all" checkbox in the column header.
  19. """
  20. def __init__(self, *args, **kwargs):
  21. default = kwargs.pop('default', '')
  22. visible = kwargs.pop('visible', False)
  23. super(ToggleColumn, self).__init__(*args, default=default, visible=visible, **kwargs)
  24. @property
  25. def header(self):
  26. return mark_safe('<input type="checkbox" class="toggle" title="Toggle all" />')
  27. class BooleanColumn(tables.Column):
  28. """
  29. Custom implementation of BooleanColumn to render a nicely-formatted checkmark or X icon instead of a Unicode
  30. character.
  31. """
  32. def render(self, value):
  33. if value is True:
  34. rendered = '<span class="text-success"><i class="fa fa-check"></i></span>'
  35. elif value is False:
  36. rendered = '<span class="text-danger"><i class="fa fa-close"></i></span>'
  37. else:
  38. rendered = '<span class="text-muted">&mdash;</span>'
  39. return mark_safe(rendered)
  40. class ColorColumn(tables.Column):
  41. """
  42. Display a color (#RRGGBB).
  43. """
  44. def render(self, value):
  45. return mark_safe(
  46. '<span class="label color-block" style="background-color: #{}">&nbsp;</span>'.format(value)
  47. )