forms.py 24 KB

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