forms.py 29 KB

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