OpenStack Dashboard (Horizon)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

formset.py 6.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  2. # not use this file except in compliance with the License. You may obtain
  3. # a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  9. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  10. # License for the specific language governing permissions and limitations
  11. # under the License.
  12. import collections
  13. import itertools
  14. import logging
  15. import sys
  16. import six
  17. from django import template
  18. from django.template import loader
  19. from horizon.tables import base as horizon_tables
  20. LOG = logging.getLogger(__name__)
  21. class FormsetCell(horizon_tables.Cell):
  22. """A DataTable cell that knows about its field from the formset."""
  23. def __init__(self, *args, **kwargs):
  24. super(FormsetCell, self).__init__(*args, **kwargs)
  25. try:
  26. self.field = (self.row.form or {})[self.column.name]
  27. except KeyError:
  28. self.field = None
  29. else:
  30. if self.field.errors:
  31. self.attrs['class'] = (self.attrs.get('class', '') +
  32. ' error form-group')
  33. self.attrs['title'] = ' '.join(
  34. six.text_type(error) for error in self.field.errors)
  35. class FormsetRow(horizon_tables.Row):
  36. """A DataTable row that knows about its form from the formset."""
  37. template_path = 'horizon/common/_formset_table_row.html'
  38. def __init__(self, column, datum, form):
  39. self.form = form
  40. super(FormsetRow, self).__init__(column, datum)
  41. if self.cells == []:
  42. # We need to be able to handle empty rows, because there may
  43. # be extra empty forms in a formset. The original DataTable breaks
  44. # on this, because it sets self.cells to [], but later expects a
  45. # OrderedDict. We just fill self.cells with empty Cells.
  46. cells = []
  47. for column in self.table.columns.values():
  48. cell = self.table._meta.cell_class(None, column, self)
  49. cells.append((column.name or column.auto, cell))
  50. self.cells = collections.OrderedDict(cells)
  51. def render(self):
  52. return loader.render_to_string(self.template_path,
  53. {"row": self, "form": self.form})
  54. class FormsetDataTableMixin(object):
  55. """A mixin for DataTable to support Django Formsets.
  56. This works the same as the ``FormsetDataTable`` below, but can be used
  57. to add to existing DataTable subclasses.
  58. """
  59. formset_class = None
  60. def __init__(self, *args, **kwargs):
  61. super(FormsetDataTableMixin, self).__init__(*args, **kwargs)
  62. self._formset = None
  63. # Override Meta settings, because we need custom Form and Cell classes,
  64. # and also our own template.
  65. self._meta.row_class = FormsetRow
  66. self._meta.cell_class = FormsetCell
  67. self._meta.template = 'horizon/common/_formset_table.html'
  68. def get_required_columns(self):
  69. """Lists names of columns that have required fields."""
  70. required_columns = []
  71. if self.formset_class:
  72. empty_form = self.get_formset().empty_form
  73. for column in self.columns.values():
  74. field = empty_form.fields.get(column.name)
  75. if field and field.required:
  76. required_columns.append(column.name)
  77. return required_columns
  78. def _get_formset_data(self):
  79. """Formats the self.filtered_data in a way suitable for a formset."""
  80. data = []
  81. for datum in self.filtered_data:
  82. form_data = {}
  83. for column in self.columns.values():
  84. value = column.get_data(datum)
  85. form_data[column.name] = value
  86. form_data['id'] = self.get_object_id(datum)
  87. data.append(form_data)
  88. return data
  89. def get_formset(self):
  90. """Provide the formset corresponding to this DataTable.
  91. Use this to validate the formset and to get the submitted data back.
  92. """
  93. if self._formset is None:
  94. self._formset = self.formset_class(
  95. self.request.POST or None,
  96. initial=self._get_formset_data(),
  97. prefix=self._meta.name)
  98. return self._formset
  99. def get_empty_row(self):
  100. """Return a row with no data, for adding at the end of the table."""
  101. return self._meta.row_class(self, None, self.get_formset().empty_form)
  102. def get_rows(self):
  103. """Return the row data for this table broken out by columns.
  104. The row objects get an additional ``form`` parameter, with the
  105. formset form corresponding to that row.
  106. """
  107. try:
  108. rows = []
  109. if self.formset_class is None:
  110. formset = []
  111. else:
  112. formset = self.get_formset()
  113. formset.is_valid()
  114. for datum, form in itertools.izip_longest(self.filtered_data,
  115. formset):
  116. row = self._meta.row_class(self, datum, form)
  117. if self.get_object_id(datum) == self.current_item_id:
  118. self.selected = True
  119. row.classes.append('current_selected')
  120. rows.append(row)
  121. except Exception:
  122. # Exceptions can be swallowed at the template level here,
  123. # re-raising as a TemplateSyntaxError makes them visible.
  124. LOG.exception("Error while rendering table rows.")
  125. exc_info = sys.exc_info()
  126. raise six.reraise(template.TemplateSyntaxError, exc_info[1],
  127. exc_info[2])
  128. return rows
  129. def get_object_id(self, datum):
  130. # We need to support ``None`` when there are more forms than data.
  131. if datum is None:
  132. return None
  133. return super(FormsetDataTableMixin, self).get_object_id(datum)
  134. class FormsetDataTable(FormsetDataTableMixin, horizon_tables.DataTable):
  135. """A DataTable with support for Django Formsets.
  136. Note that :attr:`horizon.tables.DataTableOptions.row_class` and
  137. :attr:`horizon.tables.DataTaleOptions.cell_class` are overwritten in this
  138. class, so setting them in ``Meta`` has no effect.
  139. .. attribute:: formset_class
  140. A class made with ``django.forms.formsets.formset_factory``
  141. containing the definition of the formset to use with this data table.
  142. The columns that are named the same as the formset fields will be
  143. replaced with form widgets in the table. Any hidden fields from the
  144. formset will also be included. The fields that are not hidden and
  145. don't correspond to any column will not be included in the form.
  146. """