forms.py 19 KB

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