forms.py 25 KB

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