forms.py 23 KB

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