forms.py 21 KB

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