forms.py 5.9 KB

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