forms.py 23 KB

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