forms.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  1. import csv
  2. import json
  3. import re
  4. from io import StringIO
  5. import django_filters
  6. import yaml
  7. from django import forms
  8. from django.conf import settings
  9. from django.contrib.postgres.forms.jsonb import JSONField as _JSONField, InvalidJSONInput
  10. from django.db.models import Count
  11. from django.forms import BoundField
  12. from django.urls import reverse
  13. from .choices import unpack_grouped_choices
  14. from .constants import *
  15. from .validators import EnhancedURLValidator
  16. NUMERIC_EXPANSION_PATTERN = r'\[((?:\d+[?:,-])+\d+)\]'
  17. ALPHANUMERIC_EXPANSION_PATTERN = r'\[((?:[a-zA-Z0-9]+[?:,-])+[a-zA-Z0-9]+)\]'
  18. IP4_EXPANSION_PATTERN = r'\[((?:[0-9]{1,3}[?:,-])+[0-9]{1,3})\]'
  19. IP6_EXPANSION_PATTERN = r'\[((?:[0-9a-f]{1,4}[?:,-])+[0-9a-f]{1,4})\]'
  20. BOOLEAN_WITH_BLANK_CHOICES = (
  21. ('', '---------'),
  22. ('True', 'Yes'),
  23. ('False', 'No'),
  24. )
  25. def parse_numeric_range(string, base=10):
  26. """
  27. Expand a numeric range (continuous or not) into a decimal or
  28. hexadecimal list, as specified by the base parameter
  29. '0-3,5' => [0, 1, 2, 3, 5]
  30. '2,8-b,d,f' => [2, 8, 9, a, b, d, f]
  31. """
  32. values = list()
  33. for dash_range in string.split(','):
  34. try:
  35. begin, end = dash_range.split('-')
  36. except ValueError:
  37. begin, end = dash_range, dash_range
  38. begin, end = int(begin.strip(), base=base), int(end.strip(), base=base) + 1
  39. values.extend(range(begin, end))
  40. return list(set(values))
  41. def parse_alphanumeric_range(string):
  42. """
  43. Expand an alphanumeric range (continuous or not) into a list.
  44. 'a-d,f' => [a, b, c, d, f]
  45. '0-3,a-d' => [0, 1, 2, 3, a, b, c, d]
  46. """
  47. values = []
  48. for dash_range in string.split(','):
  49. try:
  50. begin, end = dash_range.split('-')
  51. vals = begin + end
  52. # Break out of loop if there's an invalid pattern to return an error
  53. if (not (vals.isdigit() or vals.isalpha())) or (vals.isalpha() and not (vals.isupper() or vals.islower())):
  54. return []
  55. except ValueError:
  56. begin, end = dash_range, dash_range
  57. if begin.isdigit() and end.isdigit():
  58. for n in list(range(int(begin), int(end) + 1)):
  59. values.append(n)
  60. else:
  61. # Value-based
  62. if begin == end:
  63. values.append(begin)
  64. # Range-based
  65. else:
  66. # Not a valid range (more than a single character)
  67. if not len(begin) == len(end) == 1:
  68. raise forms.ValidationError('Range "{}" is invalid.'.format(dash_range))
  69. for n in list(range(ord(begin), ord(end) + 1)):
  70. values.append(chr(n))
  71. return values
  72. def expand_alphanumeric_pattern(string):
  73. """
  74. Expand an alphabetic pattern into a list of strings.
  75. """
  76. lead, pattern, remnant = re.split(ALPHANUMERIC_EXPANSION_PATTERN, string, maxsplit=1)
  77. parsed_range = parse_alphanumeric_range(pattern)
  78. for i in parsed_range:
  79. if re.search(ALPHANUMERIC_EXPANSION_PATTERN, remnant):
  80. for string in expand_alphanumeric_pattern(remnant):
  81. yield "{}{}{}".format(lead, i, string)
  82. else:
  83. yield "{}{}{}".format(lead, i, remnant)
  84. def expand_ipaddress_pattern(string, family):
  85. """
  86. Expand an IP address pattern into a list of strings. Examples:
  87. '192.0.2.[1,2,100-250]/24' => ['192.0.2.1/24', '192.0.2.2/24', '192.0.2.100/24' ... '192.0.2.250/24']
  88. '2001:db8:0:[0,fd-ff]::/64' => ['2001:db8:0:0::/64', '2001:db8:0:fd::/64', ... '2001:db8:0:ff::/64']
  89. """
  90. if family not in [4, 6]:
  91. raise Exception("Invalid IP address family: {}".format(family))
  92. if family == 4:
  93. regex = IP4_EXPANSION_PATTERN
  94. base = 10
  95. else:
  96. regex = IP6_EXPANSION_PATTERN
  97. base = 16
  98. lead, pattern, remnant = re.split(regex, string, maxsplit=1)
  99. parsed_range = parse_numeric_range(pattern, base)
  100. for i in parsed_range:
  101. if re.search(regex, remnant):
  102. for string in expand_ipaddress_pattern(remnant, family):
  103. yield ''.join([lead, format(i, 'x' if family == 6 else 'd'), string])
  104. else:
  105. yield ''.join([lead, format(i, 'x' if family == 6 else 'd'), remnant])
  106. def add_blank_choice(choices):
  107. """
  108. Add a blank choice to the beginning of a choices list.
  109. """
  110. return ((None, '---------'),) + tuple(choices)
  111. #
  112. # Widgets
  113. #
  114. class SmallTextarea(forms.Textarea):
  115. """
  116. Subclass used for rendering a smaller textarea element.
  117. """
  118. pass
  119. class SlugWidget(forms.TextInput):
  120. """
  121. Subclass TextInput and add a slug regeneration button next to the form field.
  122. """
  123. template_name = 'widgets/sluginput.html'
  124. class ColorSelect(forms.Select):
  125. """
  126. Extends the built-in Select widget to colorize each <option>.
  127. """
  128. option_template_name = 'widgets/colorselect_option.html'
  129. def __init__(self, *args, **kwargs):
  130. kwargs['choices'] = add_blank_choice(COLOR_CHOICES)
  131. super().__init__(*args, **kwargs)
  132. self.attrs['class'] = 'netbox-select2-color-picker'
  133. class BulkEditNullBooleanSelect(forms.NullBooleanSelect):
  134. """
  135. A Select widget for NullBooleanFields
  136. """
  137. def __init__(self, *args, **kwargs):
  138. super().__init__(*args, **kwargs)
  139. # Override the built-in choice labels
  140. self.choices = (
  141. ('1', '---------'),
  142. ('2', 'Yes'),
  143. ('3', 'No'),
  144. )
  145. self.attrs['class'] = 'netbox-select2-static'
  146. class SelectWithDisabled(forms.Select):
  147. """
  148. Modified the stock Select widget to accept choices using a dict() for a label. The dict for each option must include
  149. 'label' (string) and 'disabled' (boolean).
  150. """
  151. option_template_name = 'widgets/selectwithdisabled_option.html'
  152. class StaticSelect2(SelectWithDisabled):
  153. """
  154. A static content using the Select2 widget
  155. :param filter_for: (Optional) A dict of chained form fields for which this field is a filter. The key is the
  156. name of the filter-for field (child field) and the value is the name of the query param filter.
  157. """
  158. def __init__(self, filter_for=None, *args, **kwargs):
  159. super().__init__(*args, **kwargs)
  160. self.attrs['class'] = 'netbox-select2-static'
  161. if filter_for:
  162. for key, value in filter_for.items():
  163. self.add_filter_for(key, value)
  164. def add_filter_for(self, name, value):
  165. """
  166. Add details for an additional query param in the form of a data-filter-for-* attribute.
  167. :param name: The name of the query param
  168. :param value: The value of the query param
  169. """
  170. self.attrs['data-filter-for-{}'.format(name)] = value
  171. class StaticSelect2Multiple(StaticSelect2, forms.SelectMultiple):
  172. def __init__(self, *args, **kwargs):
  173. super().__init__(*args, **kwargs)
  174. self.attrs['data-multiple'] = 1
  175. class SelectWithPK(StaticSelect2):
  176. """
  177. Include the primary key of each option in the option label (e.g. "Router7 (4721)").
  178. """
  179. option_template_name = 'widgets/select_option_with_pk.html'
  180. class ContentTypeSelect(StaticSelect2):
  181. """
  182. Appends an `api-value` attribute equal to the slugified model name for each ContentType. For example:
  183. <option value="37" api-value="console-server-port">console server port</option>
  184. This attribute can be used to reference the relevant API endpoint for a particular ContentType.
  185. """
  186. option_template_name = 'widgets/select_contenttype.html'
  187. class ArrayFieldSelectMultiple(SelectWithDisabled, forms.SelectMultiple):
  188. """
  189. MultiSelect widget for a SimpleArrayField. Choices must be populated on the widget.
  190. """
  191. def __init__(self, *args, **kwargs):
  192. self.delimiter = kwargs.pop('delimiter', ',')
  193. super().__init__(*args, **kwargs)
  194. def optgroups(self, name, value, attrs=None):
  195. # Split the delimited string of values into a list
  196. if value:
  197. value = value[0].split(self.delimiter)
  198. return super().optgroups(name, value, attrs)
  199. def value_from_datadict(self, data, files, name):
  200. # Condense the list of selected choices into a delimited string
  201. data = super().value_from_datadict(data, files, name)
  202. return self.delimiter.join(data)
  203. class APISelect(SelectWithDisabled):
  204. """
  205. A select widget populated via an API call
  206. :param api_url: API endpoint URL. Required if not set automatically by the parent field.
  207. :param display_field: (Optional) Field to display for child in selection list. Defaults to `name`.
  208. :param value_field: (Optional) Field to use for the option value in selection list. Defaults to `id`.
  209. :param disabled_indicator: (Optional) Mark option as disabled if this field equates true.
  210. :param filter_for: (Optional) A dict of chained form fields for which this field is a filter. The key is the
  211. name of the filter-for field (child field) and the value is the name of the query param filter.
  212. :param conditional_query_params: (Optional) A dict of URL query params to append to the URL if the
  213. condition is met. The condition is the dict key and is specified in the form `<field_name>__<field_value>`.
  214. If the provided field value is selected for the given field, the URL query param will be appended to
  215. the rendered URL. The value is the in the from `<param_name>=<param_value>`. This is useful in cases where
  216. a particular field value dictates an additional API filter.
  217. :param additional_query_params: Optional) A dict of query params to append to the API request. The key is the
  218. name of the query param and the value if the query param's value.
  219. :param null_option: If true, include the static null option in the selection list.
  220. """
  221. def __init__(
  222. self,
  223. api_url=None,
  224. display_field=None,
  225. value_field=None,
  226. disabled_indicator=None,
  227. filter_for=None,
  228. conditional_query_params=None,
  229. additional_query_params=None,
  230. null_option=False,
  231. full=False,
  232. *args,
  233. **kwargs
  234. ):
  235. super().__init__(*args, **kwargs)
  236. self.attrs['class'] = 'netbox-select2-api'
  237. if api_url:
  238. self.attrs['data-url'] = '/{}{}'.format(settings.BASE_PATH, api_url.lstrip('/')) # Inject BASE_PATH
  239. if full:
  240. self.attrs['data-full'] = full
  241. if display_field:
  242. self.attrs['display-field'] = display_field
  243. if value_field:
  244. self.attrs['value-field'] = value_field
  245. if disabled_indicator:
  246. self.attrs['disabled-indicator'] = disabled_indicator
  247. if filter_for:
  248. for key, value in filter_for.items():
  249. self.add_filter_for(key, value)
  250. if conditional_query_params:
  251. for key, value in conditional_query_params.items():
  252. self.add_conditional_query_param(key, value)
  253. if additional_query_params:
  254. for key, value in additional_query_params.items():
  255. self.add_additional_query_param(key, value)
  256. if null_option:
  257. self.attrs['data-null-option'] = 1
  258. def add_filter_for(self, name, value):
  259. """
  260. Add details for an additional query param in the form of a data-filter-for-* attribute.
  261. :param name: The name of the query param
  262. :param value: The value of the query param
  263. """
  264. self.attrs['data-filter-for-{}'.format(name)] = value
  265. def add_additional_query_param(self, name, value):
  266. """
  267. Add details for an additional query param in the form of a data-* JSON-encoded list attribute.
  268. :param name: The name of the query param
  269. :param value: The value of the query param
  270. """
  271. key = 'data-additional-query-param-{}'.format(name)
  272. values = json.loads(self.attrs.get(key, '[]'))
  273. values.append(value)
  274. self.attrs[key] = json.dumps(values)
  275. def add_conditional_query_param(self, condition, value):
  276. """
  277. Add details for a URL query strings to append to the URL if the condition is met.
  278. The condition is specified in the form `<field_name>__<field_value>`.
  279. :param condition: The condition for the query param
  280. :param value: The value of the query param
  281. """
  282. self.attrs['data-conditional-query-param-{}'.format(condition)] = value
  283. class APISelectMultiple(APISelect, forms.SelectMultiple):
  284. def __init__(self, *args, **kwargs):
  285. super().__init__(*args, **kwargs)
  286. self.attrs['data-multiple'] = 1
  287. class DatePicker(forms.TextInput):
  288. """
  289. Date picker using Flatpickr.
  290. """
  291. def __init__(self, *args, **kwargs):
  292. super().__init__(*args, **kwargs)
  293. self.attrs['class'] = 'date-picker'
  294. self.attrs['placeholder'] = 'YYYY-MM-DD'
  295. class DateTimePicker(forms.TextInput):
  296. """
  297. DateTime picker using Flatpickr.
  298. """
  299. def __init__(self, *args, **kwargs):
  300. super().__init__(*args, **kwargs)
  301. self.attrs['class'] = 'datetime-picker'
  302. self.attrs['placeholder'] = 'YYYY-MM-DD hh:mm:ss'
  303. class TimePicker(forms.TextInput):
  304. """
  305. Time picker using Flatpickr.
  306. """
  307. def __init__(self, *args, **kwargs):
  308. super().__init__(*args, **kwargs)
  309. self.attrs['class'] = 'time-picker'
  310. self.attrs['placeholder'] = 'hh:mm:ss'
  311. #
  312. # Form fields
  313. #
  314. class CSVDataField(forms.CharField):
  315. """
  316. A CharField (rendered as a Textarea) which accepts CSV-formatted data. It returns a list of dictionaries mapping
  317. column headers to values. Each dictionary represents an individual record.
  318. """
  319. widget = forms.Textarea
  320. def __init__(self, fields, required_fields=[], *args, **kwargs):
  321. self.fields = fields
  322. self.required_fields = required_fields
  323. super().__init__(*args, **kwargs)
  324. self.strip = False
  325. if not self.label:
  326. self.label = ''
  327. if not self.initial:
  328. self.initial = ','.join(required_fields) + '\n'
  329. if not self.help_text:
  330. self.help_text = 'Enter the list of column headers followed by one line per record to be imported, using ' \
  331. 'commas to separate values. Multi-line data and values containing commas may be wrapped ' \
  332. 'in double quotes.'
  333. def to_python(self, value):
  334. records = []
  335. reader = csv.reader(StringIO(value))
  336. # Consume and validate the first line of CSV data as column headers
  337. headers = next(reader)
  338. for f in self.required_fields:
  339. if f not in headers:
  340. raise forms.ValidationError('Required column header "{}" not found.'.format(f))
  341. for f in headers:
  342. if f not in self.fields:
  343. raise forms.ValidationError('Unexpected column header "{}" found.'.format(f))
  344. # Parse CSV data
  345. for i, row in enumerate(reader, start=1):
  346. if row:
  347. if len(row) != len(headers):
  348. raise forms.ValidationError(
  349. "Row {}: Expected {} columns but found {}".format(i, len(headers), len(row))
  350. )
  351. row = [col.strip() for col in row]
  352. record = dict(zip(headers, row))
  353. records.append(record)
  354. return records
  355. class CSVChoiceField(forms.ChoiceField):
  356. """
  357. Invert the provided set of choices to take the human-friendly label as input, and return the database value.
  358. """
  359. def __init__(self, choices, *args, **kwargs):
  360. super().__init__(choices=choices, *args, **kwargs)
  361. self.choices = [(label, label) for value, label in unpack_grouped_choices(choices)]
  362. self.choice_values = {label: value for value, label in unpack_grouped_choices(choices)}
  363. def clean(self, value):
  364. value = super().clean(value)
  365. if not value:
  366. return ''
  367. if value not in self.choice_values:
  368. raise forms.ValidationError("Invalid choice: {}".format(value))
  369. return self.choice_values[value]
  370. class ExpandableNameField(forms.CharField):
  371. """
  372. A field which allows for numeric range expansion
  373. Example: 'Gi0/[1-3]' => ['Gi0/1', 'Gi0/2', 'Gi0/3']
  374. """
  375. def __init__(self, *args, **kwargs):
  376. super().__init__(*args, **kwargs)
  377. if not self.help_text:
  378. self.help_text = """
  379. Alphanumeric ranges are supported for bulk creation. Mixed cases and types within a single range
  380. are not supported. Examples:
  381. <ul>
  382. <li><code>[ge,xe]-0/0/[0-9]</code></li>
  383. <li><code>e[0-3][a-d,f]</code></li>
  384. </ul>
  385. """
  386. def to_python(self, value):
  387. if re.search(ALPHANUMERIC_EXPANSION_PATTERN, value):
  388. return list(expand_alphanumeric_pattern(value))
  389. return [value]
  390. class ExpandableIPAddressField(forms.CharField):
  391. """
  392. A field which allows for expansion of IP address ranges
  393. Example: '192.0.2.[1-254]/24' => ['192.0.2.1/24', '192.0.2.2/24', '192.0.2.3/24' ... '192.0.2.254/24']
  394. """
  395. def __init__(self, *args, **kwargs):
  396. super().__init__(*args, **kwargs)
  397. if not self.help_text:
  398. self.help_text = 'Specify a numeric range to create multiple IPs.<br />'\
  399. 'Example: <code>192.0.2.[1,5,100-254]/24</code>'
  400. def to_python(self, value):
  401. # Hackish address family detection but it's all we have to work with
  402. if '.' in value and re.search(IP4_EXPANSION_PATTERN, value):
  403. return list(expand_ipaddress_pattern(value, 4))
  404. elif ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
  405. return list(expand_ipaddress_pattern(value, 6))
  406. return [value]
  407. class CommentField(forms.CharField):
  408. """
  409. A textarea with support for Markdown rendering. Exists mostly just to add a standard help_text.
  410. """
  411. widget = forms.Textarea
  412. default_label = ''
  413. # TODO: Port Markdown cheat sheet to internal documentation
  414. default_helptext = '<i class="fa fa-info-circle"></i> '\
  415. '<a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank">'\
  416. 'Markdown</a> syntax is supported'
  417. def __init__(self, *args, **kwargs):
  418. required = kwargs.pop('required', False)
  419. label = kwargs.pop('label', self.default_label)
  420. help_text = kwargs.pop('help_text', self.default_helptext)
  421. super().__init__(required=required, label=label, help_text=help_text, *args, **kwargs)
  422. class FlexibleModelChoiceField(forms.ModelChoiceField):
  423. """
  424. Allow a model to be reference by either '{ID}' or the field specified by `to_field_name`.
  425. """
  426. def to_python(self, value):
  427. if value in self.empty_values:
  428. return None
  429. try:
  430. if not self.to_field_name:
  431. key = 'pk'
  432. elif re.match(r'^\{\d+\}$', value):
  433. key = 'pk'
  434. value = value.strip('{}')
  435. else:
  436. key = self.to_field_name
  437. value = self.queryset.get(**{key: value})
  438. except (ValueError, TypeError, self.queryset.model.DoesNotExist):
  439. raise forms.ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
  440. return value
  441. class SlugField(forms.SlugField):
  442. """
  443. Extend the built-in SlugField to automatically populate from a field called `name` unless otherwise specified.
  444. """
  445. def __init__(self, slug_source='name', *args, **kwargs):
  446. label = kwargs.pop('label', "Slug")
  447. help_text = kwargs.pop('help_text', "URL-friendly unique shorthand")
  448. widget = kwargs.pop('widget', SlugWidget)
  449. super().__init__(label=label, help_text=help_text, widget=widget, *args, **kwargs)
  450. self.widget.attrs['slug-source'] = slug_source
  451. class TagFilterField(forms.MultipleChoiceField):
  452. """
  453. A filter field for the tags of a model. Only the tags used by a model are displayed.
  454. :param model: The model of the filter
  455. """
  456. widget = StaticSelect2Multiple
  457. def __init__(self, model, *args, **kwargs):
  458. def get_choices():
  459. tags = model.tags.annotate(count=Count('extras_taggeditem_items')).order_by('name')
  460. return [(str(tag.slug), '{} ({})'.format(tag.name, tag.count)) for tag in tags]
  461. # Choices are fetched each time the form is initialized
  462. super().__init__(label='Tags', choices=get_choices, required=False, *args, **kwargs)
  463. class DynamicModelChoiceMixin:
  464. filter = django_filters.ModelChoiceFilter
  465. widget = APISelect
  466. def __init__(self, *args, **kwargs):
  467. super().__init__(*args, **kwargs)
  468. def get_bound_field(self, form, field_name):
  469. bound_field = BoundField(form, self, field_name)
  470. # Modify the QuerySet of the field before we return it. Limit choices to any data already bound: Options
  471. # will be populated on-demand via the APISelect widget.
  472. data = self.prepare_value(bound_field.data or bound_field.initial)
  473. if data:
  474. filter = self.filter(field_name=self.to_field_name or 'pk', queryset=self.queryset)
  475. self.queryset = filter.filter(self.queryset, data)
  476. else:
  477. self.queryset = self.queryset.none()
  478. # Set the data URL on the APISelect widget (if not already set)
  479. widget = bound_field.field.widget
  480. if not widget.attrs.get('data-url'):
  481. app_label = self.queryset.model._meta.app_label
  482. model_name = self.queryset.model._meta.model_name
  483. data_url = reverse('{}-api:{}-list'.format(app_label, model_name))
  484. widget.attrs['data-url'] = data_url
  485. return bound_field
  486. class DynamicModelChoiceField(DynamicModelChoiceMixin, forms.ModelChoiceField):
  487. """
  488. Override get_bound_field() to avoid pre-populating field choices with a SQL query. The field will be
  489. rendered only with choices set via bound data. Choices are populated on-demand via the APISelect widget.
  490. """
  491. pass
  492. class DynamicModelMultipleChoiceField(DynamicModelChoiceMixin, forms.ModelMultipleChoiceField):
  493. """
  494. A multiple-choice version of DynamicModelChoiceField.
  495. """
  496. filter = django_filters.ModelMultipleChoiceFilter
  497. widget = APISelectMultiple
  498. class LaxURLField(forms.URLField):
  499. """
  500. Modifies Django's built-in URLField in two ways:
  501. 1) Allow any valid scheme per RFC 3986 section 3.1
  502. 2) Remove the requirement for fully-qualified domain names (e.g. http://myserver/ is valid)
  503. """
  504. default_validators = [EnhancedURLValidator()]
  505. class JSONField(_JSONField):
  506. """
  507. Custom wrapper around Django's built-in JSONField to avoid presenting "null" as the default text.
  508. """
  509. def __init__(self, *args, **kwargs):
  510. super().__init__(*args, **kwargs)
  511. if not self.help_text:
  512. self.help_text = 'Enter context data in <a href="https://json.org/">JSON</a> format.'
  513. self.widget.attrs['placeholder'] = ''
  514. def prepare_value(self, value):
  515. if isinstance(value, InvalidJSONInput):
  516. return value
  517. if value is None:
  518. return ''
  519. return json.dumps(value, sort_keys=True, indent=4)
  520. #
  521. # Forms
  522. #
  523. class BootstrapMixin(forms.BaseForm):
  524. """
  525. Add the base Bootstrap CSS classes to form elements.
  526. """
  527. def __init__(self, *args, **kwargs):
  528. super().__init__(*args, **kwargs)
  529. exempt_widgets = [
  530. forms.CheckboxInput, forms.ClearableFileInput, forms.FileInput, forms.RadioSelect
  531. ]
  532. for field_name, field in self.fields.items():
  533. if field.widget.__class__ not in exempt_widgets:
  534. css = field.widget.attrs.get('class', '')
  535. field.widget.attrs['class'] = ' '.join([css, 'form-control']).strip()
  536. if field.required and not isinstance(field.widget, forms.FileInput):
  537. field.widget.attrs['required'] = 'required'
  538. if 'placeholder' not in field.widget.attrs:
  539. field.widget.attrs['placeholder'] = field.label
  540. class ReturnURLForm(forms.Form):
  541. """
  542. Provides a hidden return URL field to control where the user is directed after the form is submitted.
  543. """
  544. return_url = forms.CharField(required=False, widget=forms.HiddenInput())
  545. class ConfirmationForm(BootstrapMixin, ReturnURLForm):
  546. """
  547. A generic confirmation form. The form is not valid unless the confirm field is checked.
  548. """
  549. confirm = forms.BooleanField(required=True, widget=forms.HiddenInput(), initial=True)
  550. class BulkEditForm(forms.Form):
  551. """
  552. Base form for editing multiple objects in bulk
  553. """
  554. def __init__(self, model, *args, **kwargs):
  555. super().__init__(*args, **kwargs)
  556. self.model = model
  557. self.nullable_fields = []
  558. # Copy any nullable fields defined in Meta
  559. if hasattr(self.Meta, 'nullable_fields'):
  560. self.nullable_fields = self.Meta.nullable_fields
  561. class ImportForm(BootstrapMixin, forms.Form):
  562. """
  563. Generic form for creating an object from JSON/YAML data
  564. """
  565. data = forms.CharField(
  566. widget=forms.Textarea,
  567. help_text="Enter object data in JSON or YAML format. Note: Only a single object/document is supported."
  568. )
  569. format = forms.ChoiceField(
  570. choices=(
  571. ('json', 'JSON'),
  572. ('yaml', 'YAML')
  573. ),
  574. initial='yaml'
  575. )
  576. def clean(self):
  577. data = self.cleaned_data['data']
  578. format = self.cleaned_data['format']
  579. # Process JSON/YAML data
  580. if format == 'json':
  581. try:
  582. self.cleaned_data['data'] = json.loads(data)
  583. # Check for multiple JSON objects
  584. if type(self.cleaned_data['data']) is not dict:
  585. raise forms.ValidationError({
  586. 'data': "Import is limited to one object at a time."
  587. })
  588. except json.decoder.JSONDecodeError as err:
  589. raise forms.ValidationError({
  590. 'data': "Invalid JSON data: {}".format(err)
  591. })
  592. else:
  593. # Check for multiple YAML documents
  594. if '\n---' in data:
  595. raise forms.ValidationError({
  596. 'data': "Import is limited to one object at a time."
  597. })
  598. try:
  599. self.cleaned_data['data'] = yaml.load(data, Loader=yaml.SafeLoader)
  600. except yaml.error.YAMLError as err:
  601. raise forms.ValidationError({
  602. 'data': "Invalid YAML data: {}".format(err)
  603. })