forms.py 28 KB

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