forms.py 26 KB

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