forms.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779
  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. self.attrs['class'] = 'netbox-select2-color-picker'
  149. class BulkEditNullBooleanSelect(forms.NullBooleanSelect):
  150. """
  151. A Select widget for NullBooleanFields
  152. """
  153. def __init__(self, *args, **kwargs):
  154. super().__init__(*args, **kwargs)
  155. # Override the built-in choice labels
  156. self.choices = (
  157. ('1', '---------'),
  158. ('2', 'Yes'),
  159. ('3', 'No'),
  160. )
  161. self.attrs['class'] = 'netbox-select2-static'
  162. class SelectWithDisabled(forms.Select):
  163. """
  164. Modified the stock Select widget to accept choices using a dict() for a label. The dict for each option must include
  165. 'label' (string) and 'disabled' (boolean).
  166. """
  167. option_template_name = 'widgets/selectwithdisabled_option.html'
  168. class StaticSelect2(SelectWithDisabled):
  169. """
  170. A static content using the Select2 widget
  171. :param filter_for: (Optional) A dict of chained form fields for which this field is a filter. The key is the
  172. name of the filter-for field (child field) and the value is the name of the query param filter.
  173. """
  174. def __init__(self, filter_for=None, *args, **kwargs):
  175. super().__init__(*args, **kwargs)
  176. self.attrs['class'] = 'netbox-select2-static'
  177. if filter_for:
  178. for key, value in filter_for.items():
  179. self.add_filter_for(key, value)
  180. def add_filter_for(self, name, value):
  181. """
  182. Add details for an additional query param in the form of a data-filter-for-* attribute.
  183. :param name: The name of the query param
  184. :param value: The value of the query param
  185. """
  186. self.attrs['data-filter-for-{}'.format(name)] = value
  187. class StaticSelect2Multiple(StaticSelect2, forms.SelectMultiple):
  188. def __init__(self, *args, **kwargs):
  189. super().__init__(*args, **kwargs)
  190. self.attrs['data-multiple'] = 1
  191. class SelectWithPK(StaticSelect2):
  192. """
  193. Include the primary key of each option in the option label (e.g. "Router7 (4721)").
  194. """
  195. option_template_name = 'widgets/select_option_with_pk.html'
  196. class ContentTypeSelect(forms.Select):
  197. """
  198. Appends an `api-value` attribute equal to the slugified model name for each ContentType. For example:
  199. <option value="37" api-value="console-server-port">console server port</option>
  200. This attribute can be used to reference the relevant API endpoint for a particular ContentType.
  201. """
  202. option_template_name = 'widgets/select_contenttype.html'
  203. class ArrayFieldSelectMultiple(SelectWithDisabled, forms.SelectMultiple):
  204. """
  205. MultiSelect widget for a SimpleArrayField. Choices must be populated on the widget.
  206. """
  207. def __init__(self, *args, **kwargs):
  208. self.delimiter = kwargs.pop('delimiter', ',')
  209. super().__init__(*args, **kwargs)
  210. def optgroups(self, name, value, attrs=None):
  211. # Split the delimited string of values into a list
  212. if value:
  213. value = value[0].split(self.delimiter)
  214. return super().optgroups(name, value, attrs)
  215. def value_from_datadict(self, data, files, name):
  216. # Condense the list of selected choices into a delimited string
  217. data = super().value_from_datadict(data, files, name)
  218. return self.delimiter.join(data)
  219. class APISelect(SelectWithDisabled):
  220. """
  221. A select widget populated via an API call
  222. :param api_url: API URL
  223. :param display_field: (Optional) Field to display for child in selection list. Defaults to `name`.
  224. :param value_field: (Optional) Field to use for the option value in selection list. Defaults to `id`.
  225. :param disabled_indicator: (Optional) Mark option as disabled if this field equates true.
  226. :param filter_for: (Optional) A dict of chained form fields for which this field is a filter. The key is the
  227. name of the filter-for field (child field) and the value is the name of the query param filter.
  228. :param conditional_query_params: (Optional) A dict of URL query params to append to the URL if the
  229. condition is met. The condition is the dict key and is specified in the form `<field_name>__<field_value>`.
  230. If the provided field value is selected for the given field, the URL query param will be appended to
  231. the rendered URL. The value is the in the from `<param_name>=<param_value>`. This is useful in cases where
  232. a particular field value dictates an additional API filter.
  233. :param additional_query_params: Optional) A dict of query params to append to the API request. The key is the
  234. name of the query param and the value if the query param's value.
  235. :param null_option: If true, include the static null option in the selection list.
  236. """
  237. def __init__(
  238. self,
  239. api_url,
  240. display_field=None,
  241. value_field=None,
  242. disabled_indicator=None,
  243. filter_for=None,
  244. conditional_query_params=None,
  245. additional_query_params=None,
  246. null_option=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 display_field:
  254. self.attrs['display-field'] = display_field
  255. if value_field:
  256. self.attrs['value-field'] = value_field
  257. if disabled_indicator:
  258. self.attrs['disabled-indicator'] = disabled_indicator
  259. if filter_for:
  260. for key, value in filter_for.items():
  261. self.add_filter_for(key, value)
  262. if conditional_query_params:
  263. for key, value in conditional_query_params.items():
  264. self.add_conditional_query_param(key, value)
  265. if additional_query_params:
  266. for key, value in additional_query_params.items():
  267. self.add_additional_query_param(key, value)
  268. if null_option:
  269. self.attrs['data-null-option'] = 1
  270. def add_filter_for(self, name, value):
  271. """
  272. Add details for an additional query param in the form of a data-filter-for-* attribute.
  273. :param name: The name of the query param
  274. :param value: The value of the query param
  275. """
  276. self.attrs['data-filter-for-{}'.format(name)] = value
  277. def add_additional_query_param(self, name, value):
  278. """
  279. Add details for an additional query param in the form of a data-* attribute.
  280. :param name: The name of the query param
  281. :param value: The value of the query param
  282. """
  283. self.attrs['data-additional-query-param-{}'.format(name)] = value
  284. def add_conditional_query_param(self, condition, value):
  285. """
  286. Add details for a URL query strings to append to the URL if the condition is met.
  287. The condition is specified in the form `<field_name>__<field_value>`.
  288. :param condition: The condition for the query param
  289. :param value: The value of the query param
  290. """
  291. self.attrs['data-conditional-query-param-{}'.format(condition)] = value
  292. class APISelectMultiple(APISelect, forms.SelectMultiple):
  293. def __init__(self, *args, **kwargs):
  294. super().__init__(*args, **kwargs)
  295. self.attrs['data-multiple'] = 1
  296. class Livesearch(forms.TextInput):
  297. """
  298. A text widget that carries a few extra bits of data for use in AJAX-powered autocomplete search
  299. :param query_key: The name of the parameter to query against
  300. :param query_url: The name of the API URL to query
  301. :param field_to_update: The name of the "real" form field whose value is being set
  302. :param obj_label: The field to use as the option label (optional)
  303. """
  304. def __init__(self, query_key, query_url, field_to_update, obj_label=None, *args, **kwargs):
  305. super().__init__(*args, **kwargs)
  306. self.attrs = {
  307. 'data-key': query_key,
  308. 'data-source': reverse_lazy(query_url),
  309. 'data-field': field_to_update,
  310. }
  311. if obj_label:
  312. self.attrs['data-label'] = obj_label
  313. #
  314. # Form fields
  315. #
  316. class CSVDataField(forms.CharField):
  317. """
  318. A CharField (rendered as a Textarea) which accepts CSV-formatted data. It returns a list of dictionaries mapping
  319. column headers to values. Each dictionary represents an individual record.
  320. """
  321. widget = forms.Textarea
  322. def __init__(self, fields, required_fields=[], *args, **kwargs):
  323. self.fields = fields
  324. self.required_fields = required_fields
  325. super().__init__(*args, **kwargs)
  326. self.strip = False
  327. if not self.label:
  328. self.label = 'CSV Data'
  329. if not self.initial:
  330. self.initial = ','.join(required_fields) + '\n'
  331. if not self.help_text:
  332. self.help_text = 'Enter the list of column headers followed by one line per record to be imported, using ' \
  333. 'commas to separate values. Multi-line data and values containing commas may be wrapped ' \
  334. 'in double quotes.'
  335. def to_python(self, value):
  336. records = []
  337. reader = csv.reader(StringIO(value))
  338. # Consume and validate the first line of CSV data as column headers
  339. headers = next(reader)
  340. for f in self.required_fields:
  341. if f not in headers:
  342. raise forms.ValidationError('Required column header "{}" not found.'.format(f))
  343. for f in headers:
  344. if f not in self.fields:
  345. raise forms.ValidationError('Unexpected column header "{}" found.'.format(f))
  346. # Parse CSV data
  347. for i, row in enumerate(reader, start=1):
  348. if row:
  349. if len(row) != len(headers):
  350. raise forms.ValidationError(
  351. "Row {}: Expected {} columns but found {}".format(i, len(headers), len(row))
  352. )
  353. row = [col.strip() for col in row]
  354. record = dict(zip(headers, row))
  355. records.append(record)
  356. return records
  357. class CSVChoiceField(forms.ChoiceField):
  358. """
  359. Invert the provided set of choices to take the human-friendly label as input, and return the database value.
  360. """
  361. def __init__(self, choices, *args, **kwargs):
  362. super().__init__(choices=choices, *args, **kwargs)
  363. self.choices = [(label, label) for value, label in unpack_grouped_choices(choices)]
  364. self.choice_values = {label: value for value, label in unpack_grouped_choices(choices)}
  365. def clean(self, value):
  366. value = super().clean(value)
  367. if not value:
  368. return None
  369. if value not in self.choice_values:
  370. raise forms.ValidationError("Invalid choice: {}".format(value))
  371. return self.choice_values[value]
  372. class ExpandableNameField(forms.CharField):
  373. """
  374. A field which allows for numeric range expansion
  375. Example: 'Gi0/[1-3]' => ['Gi0/1', 'Gi0/2', 'Gi0/3']
  376. """
  377. def __init__(self, *args, **kwargs):
  378. super().__init__(*args, **kwargs)
  379. if not self.help_text:
  380. self.help_text = 'Alphanumeric ranges are supported for bulk creation.<br />' \
  381. 'Mixed cases and types within a single range are not supported.<br />' \
  382. 'Examples:<ul><li><code>ge-0/0/[0-23,25,30]</code></li>' \
  383. '<li><code>e[0-3][a-d,f]</code></li>' \
  384. '<li><code>e[0-3,a-d,f]</code></li></ul>'
  385. def to_python(self, value):
  386. if re.search(ALPHANUMERIC_EXPANSION_PATTERN, value):
  387. return list(expand_alphanumeric_pattern(value))
  388. return [value]
  389. class ExpandableIPAddressField(forms.CharField):
  390. """
  391. A field which allows for expansion of IP address ranges
  392. 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']
  393. """
  394. def __init__(self, *args, **kwargs):
  395. super().__init__(*args, **kwargs)
  396. if not self.help_text:
  397. self.help_text = 'Specify a numeric range to create multiple IPs.<br />'\
  398. 'Example: <code>192.0.2.[1,5,100-254]/24</code>'
  399. def to_python(self, value):
  400. # Hackish address family detection but it's all we have to work with
  401. if '.' in value and re.search(IP4_EXPANSION_PATTERN, value):
  402. return list(expand_ipaddress_pattern(value, 4))
  403. elif ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
  404. return list(expand_ipaddress_pattern(value, 6))
  405. return [value]
  406. class CommentField(forms.CharField):
  407. """
  408. A textarea with support for GitHub-Flavored Markdown. Exists mostly just to add a standard help_text.
  409. """
  410. widget = forms.Textarea
  411. default_label = 'Comments'
  412. # TODO: Port GFM syntax cheat sheet to internal documentation
  413. default_helptext = '<i class="fa fa-info-circle"></i> '\
  414. '<a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank">'\
  415. 'GitHub-Flavored Markdown</a> syntax is supported'
  416. def __init__(self, *args, **kwargs):
  417. required = kwargs.pop('required', False)
  418. label = kwargs.pop('label', self.default_label)
  419. help_text = kwargs.pop('help_text', self.default_helptext)
  420. super().__init__(required=required, label=label, help_text=help_text, *args, **kwargs)
  421. class FlexibleModelChoiceField(forms.ModelChoiceField):
  422. """
  423. Allow a model to be reference by either '{ID}' or the field specified by `to_field_name`.
  424. """
  425. def to_python(self, value):
  426. if value in self.empty_values:
  427. return None
  428. try:
  429. if not self.to_field_name:
  430. key = 'pk'
  431. elif re.match(r'^\{\d+\}$', value):
  432. key = 'pk'
  433. value = value.strip('{}')
  434. else:
  435. key = self.to_field_name
  436. value = self.queryset.get(**{key: value})
  437. except (ValueError, TypeError, self.queryset.model.DoesNotExist):
  438. raise forms.ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
  439. return value
  440. class ChainedModelChoiceField(forms.ModelChoiceField):
  441. """
  442. A ModelChoiceField which is initialized based on the values of other fields within a form. `chains` is a dictionary
  443. mapping of model fields to peer fields within the form. For example:
  444. country1 = forms.ModelChoiceField(queryset=Country.objects.all())
  445. city1 = ChainedModelChoiceField(queryset=City.objects.all(), chains={'country': 'country1'}
  446. The queryset of the `city1` field will be modified as
  447. .filter(country=<value>)
  448. where <value> is the value of the `country1` field. (Note: The form must inherit from ChainedFieldsMixin.)
  449. """
  450. def __init__(self, chains=None, *args, **kwargs):
  451. self.chains = chains
  452. super().__init__(*args, **kwargs)
  453. class ChainedModelMultipleChoiceField(forms.ModelMultipleChoiceField):
  454. """
  455. See ChainedModelChoiceField
  456. """
  457. def __init__(self, chains=None, *args, **kwargs):
  458. self.chains = chains
  459. super().__init__(*args, **kwargs)
  460. class SlugField(forms.SlugField):
  461. """
  462. Extend the built-in SlugField to automatically populate from a field called `name` unless otherwise specified.
  463. """
  464. def __init__(self, slug_source='name', *args, **kwargs):
  465. label = kwargs.pop('label', "Slug")
  466. help_text = kwargs.pop('help_text', "URL-friendly unique shorthand")
  467. super().__init__(label=label, help_text=help_text, *args, **kwargs)
  468. self.widget.attrs['slug-source'] = slug_source
  469. class FilterChoiceIterator(forms.models.ModelChoiceIterator):
  470. def __iter__(self):
  471. # Filter on "empty" choice using FILTERS_NULL_CHOICE_VALUE (instead of an empty string)
  472. if self.field.null_label is not None:
  473. yield (settings.FILTERS_NULL_CHOICE_VALUE, self.field.null_label)
  474. queryset = self.queryset.all()
  475. # Can't use iterator() when queryset uses prefetch_related()
  476. if not queryset._prefetch_related_lookups:
  477. queryset = queryset.iterator()
  478. for obj in queryset:
  479. yield self.choice(obj)
  480. class FilterChoiceFieldMixin(object):
  481. iterator = FilterChoiceIterator
  482. def __init__(self, null_label=None, count_attr='filter_count', *args, **kwargs):
  483. self.null_label = null_label
  484. self.count_attr = count_attr
  485. if 'required' not in kwargs:
  486. kwargs['required'] = False
  487. if 'widget' not in kwargs:
  488. kwargs['widget'] = forms.SelectMultiple(attrs={'size': 6})
  489. super().__init__(*args, **kwargs)
  490. def label_from_instance(self, obj):
  491. label = super().label_from_instance(obj)
  492. obj_count = getattr(obj, self.count_attr, None)
  493. if obj_count is not None:
  494. return '{} ({})'.format(label, obj_count)
  495. return label
  496. class FilterChoiceField(FilterChoiceFieldMixin, forms.ModelMultipleChoiceField):
  497. pass
  498. class FilterTreeNodeMultipleChoiceField(FilterChoiceFieldMixin, TreeNodeMultipleChoiceField):
  499. pass
  500. class AnnotatedMultipleChoiceField(forms.MultipleChoiceField):
  501. """
  502. Render a set of static choices with each choice annotated to include a count of related objects. For example, this
  503. field can be used to display a list of all available device statuses along with the number of devices currently
  504. assigned to each status.
  505. """
  506. def annotate_choices(self):
  507. queryset = self.annotate.values(
  508. self.annotate_field
  509. ).annotate(
  510. count=Count(self.annotate_field)
  511. ).order_by(
  512. self.annotate_field
  513. )
  514. choice_counts = {
  515. c[self.annotate_field]: c['count'] for c in queryset
  516. }
  517. annotated_choices = [
  518. (c[0], '{} ({})'.format(c[1], choice_counts.get(c[0], 0))) for c in self.static_choices
  519. ]
  520. return annotated_choices
  521. def __init__(self, choices, annotate, annotate_field, *args, **kwargs):
  522. self.annotate = annotate
  523. self.annotate_field = annotate_field
  524. self.static_choices = unpack_grouped_choices(choices)
  525. super().__init__(choices=self.annotate_choices, *args, **kwargs)
  526. class LaxURLField(forms.URLField):
  527. """
  528. Modifies Django's built-in URLField in two ways:
  529. 1) Allow any valid scheme per RFC 3986 section 3.1
  530. 2) Remove the requirement for fully-qualified domain names (e.g. http://myserver/ is valid)
  531. """
  532. default_validators = [EnhancedURLValidator()]
  533. class JSONField(_JSONField):
  534. """
  535. Custom wrapper around Django's built-in JSONField to avoid presenting "null" as the default text.
  536. """
  537. def __init__(self, *args, **kwargs):
  538. super().__init__(*args, **kwargs)
  539. if not self.help_text:
  540. self.help_text = 'Enter context data in <a href="https://json.org/">JSON</a> format.'
  541. self.widget.attrs['placeholder'] = ''
  542. def prepare_value(self, value):
  543. if isinstance(value, InvalidJSONInput):
  544. return value
  545. if value is None:
  546. return ''
  547. return json.dumps(value, sort_keys=True, indent=4)
  548. #
  549. # Forms
  550. #
  551. class BootstrapMixin(forms.BaseForm):
  552. """
  553. Add the base Bootstrap CSS classes to form elements.
  554. """
  555. def __init__(self, *args, **kwargs):
  556. super().__init__(*args, **kwargs)
  557. exempt_widgets = [
  558. forms.CheckboxInput, forms.ClearableFileInput, forms.FileInput, forms.RadioSelect
  559. ]
  560. for field_name, field in self.fields.items():
  561. if field.widget.__class__ not in exempt_widgets:
  562. css = field.widget.attrs.get('class', '')
  563. field.widget.attrs['class'] = ' '.join([css, 'form-control']).strip()
  564. if field.required and not isinstance(field.widget, forms.FileInput):
  565. field.widget.attrs['required'] = 'required'
  566. if 'placeholder' not in field.widget.attrs:
  567. field.widget.attrs['placeholder'] = field.label
  568. class ChainedFieldsMixin(forms.BaseForm):
  569. """
  570. Iterate through all ChainedModelChoiceFields in the form and modify their querysets based on chained fields.
  571. """
  572. def __init__(self, *args, **kwargs):
  573. super().__init__(*args, **kwargs)
  574. for field_name, field in self.fields.items():
  575. if isinstance(field, ChainedModelChoiceField):
  576. filters_dict = {}
  577. for (db_field, parent_field) in field.chains:
  578. if self.is_bound and parent_field in self.data:
  579. filters_dict[db_field] = self.data[parent_field] or None
  580. elif self.initial.get(parent_field):
  581. filters_dict[db_field] = self.initial[parent_field]
  582. elif self.fields[parent_field].widget.attrs.get('nullable'):
  583. filters_dict[db_field] = None
  584. else:
  585. break
  586. if filters_dict:
  587. field.queryset = field.queryset.filter(**filters_dict)
  588. elif not self.is_bound and getattr(self, 'instance', None) and hasattr(self.instance, field_name):
  589. obj = getattr(self.instance, field_name)
  590. if obj is not None:
  591. field.queryset = field.queryset.filter(pk=obj.pk)
  592. else:
  593. field.queryset = field.queryset.none()
  594. elif not self.is_bound:
  595. field.queryset = field.queryset.none()
  596. class ReturnURLForm(forms.Form):
  597. """
  598. Provides a hidden return URL field to control where the user is directed after the form is submitted.
  599. """
  600. return_url = forms.CharField(required=False, widget=forms.HiddenInput())
  601. class ConfirmationForm(BootstrapMixin, ReturnURLForm):
  602. """
  603. A generic confirmation form. The form is not valid unless the confirm field is checked.
  604. """
  605. confirm = forms.BooleanField(required=True, widget=forms.HiddenInput(), initial=True)
  606. class ComponentForm(BootstrapMixin, forms.Form):
  607. """
  608. Allow inclusion of the parent Device/VirtualMachine as context for limiting field choices.
  609. """
  610. def __init__(self, parent, *args, **kwargs):
  611. self.parent = parent
  612. super().__init__(*args, **kwargs)
  613. def get_iterative_data(self, iteration):
  614. return {}
  615. class BulkEditForm(forms.Form):
  616. """
  617. Base form for editing multiple objects in bulk
  618. """
  619. def __init__(self, model, parent_obj=None, *args, **kwargs):
  620. super().__init__(*args, **kwargs)
  621. self.model = model
  622. self.parent_obj = parent_obj
  623. self.nullable_fields = []
  624. # Copy any nullable fields defined in Meta
  625. if hasattr(self.Meta, 'nullable_fields'):
  626. self.nullable_fields = self.Meta.nullable_fields