2
0

forms.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import json
  2. import re
  3. import yaml
  4. from django import forms
  5. from .widgets import APISelect, APISelectMultiple, ClearableFileInput, StaticSelect
  6. __all__ = (
  7. 'BootstrapMixin',
  8. 'BulkEditForm',
  9. 'BulkRenameForm',
  10. 'ConfirmationForm',
  11. 'CSVModelForm',
  12. 'FilterForm',
  13. 'ImportForm',
  14. 'ReturnURLForm',
  15. 'TableConfigForm',
  16. )
  17. #
  18. # Mixins
  19. #
  20. class BootstrapMixin:
  21. """
  22. Add the base Bootstrap CSS classes to form elements.
  23. """
  24. def __init__(self, *args, **kwargs):
  25. super().__init__(*args, **kwargs)
  26. exempt_widgets = [
  27. forms.CheckboxInput,
  28. forms.FileInput,
  29. forms.RadioSelect,
  30. forms.Select,
  31. APISelect,
  32. APISelectMultiple,
  33. ClearableFileInput,
  34. StaticSelect,
  35. ]
  36. for field_name, field in self.fields.items():
  37. if field.widget.__class__ not in exempt_widgets:
  38. css = field.widget.attrs.get('class', '')
  39. field.widget.attrs['class'] = ' '.join([css, 'form-control']).strip()
  40. if field.required and not isinstance(field.widget, forms.FileInput):
  41. field.widget.attrs['required'] = 'required'
  42. if 'placeholder' not in field.widget.attrs and field.label is not None:
  43. field.widget.attrs['placeholder'] = field.label
  44. if field.widget.__class__ == forms.CheckboxInput:
  45. css = field.widget.attrs.get('class', '')
  46. field.widget.attrs['class'] = ' '.join((css, 'form-check-input')).strip()
  47. if field.widget.__class__ == forms.Select:
  48. css = field.widget.attrs.get('class', '')
  49. field.widget.attrs['class'] = ' '.join((css, 'form-select')).strip()
  50. #
  51. # Form classes
  52. #
  53. class ReturnURLForm(forms.Form):
  54. """
  55. Provides a hidden return URL field to control where the user is directed after the form is submitted.
  56. """
  57. return_url = forms.CharField(required=False, widget=forms.HiddenInput())
  58. class ConfirmationForm(BootstrapMixin, ReturnURLForm):
  59. """
  60. A generic confirmation form. The form is not valid unless the confirm field is checked.
  61. """
  62. confirm = forms.BooleanField(required=True, widget=forms.HiddenInput(), initial=True)
  63. class BulkEditForm(BootstrapMixin, forms.Form):
  64. """
  65. Provides bulk edit support for objects.
  66. """
  67. nullable_fields = ()
  68. class BulkRenameForm(BootstrapMixin, forms.Form):
  69. """
  70. An extendable form to be used for renaming objects in bulk.
  71. """
  72. find = forms.CharField()
  73. replace = forms.CharField(
  74. required=False
  75. )
  76. use_regex = forms.BooleanField(
  77. required=False,
  78. initial=True,
  79. label='Use regular expressions'
  80. )
  81. def clean(self):
  82. super().clean()
  83. # Validate regular expression in "find" field
  84. if self.cleaned_data['use_regex']:
  85. try:
  86. re.compile(self.cleaned_data['find'])
  87. except re.error:
  88. raise forms.ValidationError({
  89. 'find': "Invalid regular expression"
  90. })
  91. class CSVModelForm(forms.ModelForm):
  92. """
  93. ModelForm used for the import of objects in CSV format.
  94. """
  95. def __init__(self, *args, headers=None, **kwargs):
  96. super().__init__(*args, **kwargs)
  97. # Modify the model form to accommodate any customized to_field_name properties
  98. if headers:
  99. for field, to_field in headers.items():
  100. if to_field is not None:
  101. self.fields[field].to_field_name = to_field
  102. class ImportForm(BootstrapMixin, forms.Form):
  103. """
  104. Generic form for creating an object from JSON/YAML data
  105. """
  106. data = forms.CharField(
  107. widget=forms.Textarea(attrs={'class': 'font-monospace'}),
  108. help_text="Enter object data in JSON or YAML format. Note: Only a single object/document is supported."
  109. )
  110. format = forms.ChoiceField(
  111. choices=(
  112. ('json', 'JSON'),
  113. ('yaml', 'YAML')
  114. ),
  115. initial='yaml'
  116. )
  117. def clean(self):
  118. super().clean()
  119. data = self.cleaned_data['data']
  120. format = self.cleaned_data['format']
  121. # Process JSON/YAML data
  122. if format == 'json':
  123. try:
  124. self.cleaned_data['data'] = json.loads(data)
  125. # Check for multiple JSON objects
  126. if type(self.cleaned_data['data']) is not dict:
  127. raise forms.ValidationError({
  128. 'data': "Import is limited to one object at a time."
  129. })
  130. except json.decoder.JSONDecodeError as err:
  131. raise forms.ValidationError({
  132. 'data': "Invalid JSON data: {}".format(err)
  133. })
  134. else:
  135. # Check for multiple YAML documents
  136. if '\n---' in data:
  137. raise forms.ValidationError({
  138. 'data': "Import is limited to one object at a time."
  139. })
  140. try:
  141. self.cleaned_data['data'] = yaml.load(data, Loader=yaml.SafeLoader)
  142. except yaml.error.YAMLError as err:
  143. raise forms.ValidationError({
  144. 'data': "Invalid YAML data: {}".format(err)
  145. })
  146. class FilterForm(BootstrapMixin, forms.Form):
  147. """
  148. Base Form class for FilterSet forms.
  149. """
  150. q = forms.CharField(
  151. required=False,
  152. label='Search'
  153. )
  154. class TableConfigForm(BootstrapMixin, forms.Form):
  155. """
  156. Form for configuring user's table preferences.
  157. """
  158. available_columns = forms.MultipleChoiceField(
  159. choices=[],
  160. required=False,
  161. widget=forms.SelectMultiple(
  162. attrs={'size': 10, 'class': 'form-select'}
  163. ),
  164. label='Available Columns'
  165. )
  166. columns = forms.MultipleChoiceField(
  167. choices=[],
  168. required=False,
  169. widget=forms.SelectMultiple(
  170. attrs={'size': 10, 'class': 'form-select'}
  171. ),
  172. label='Selected Columns'
  173. )
  174. def __init__(self, table, *args, **kwargs):
  175. self.table = table
  176. super().__init__(*args, **kwargs)
  177. # Initialize columns field based on table attributes
  178. self.fields['available_columns'].choices = table.available_columns
  179. self.fields['columns'].choices = table.selected_columns
  180. @property
  181. def table_name(self):
  182. return self.table.__class__.__name__