forms.py 5.5 KB

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