2
0

forms.py 6.3 KB

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