forms.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import csv
  2. import itertools
  3. import re
  4. from mptt.forms import TreeNodeMultipleChoiceField
  5. from django import forms
  6. from django.conf import settings
  7. from django.core.urlresolvers import reverse_lazy
  8. from django.core.validators import URLValidator
  9. from django.utils.encoding import force_text
  10. from django.utils.html import format_html
  11. from django.utils.safestring import mark_safe
  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 = '\[((?:\d+[?:,-])+\d+)\]'
  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()), 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 expand_ipaddress_pattern(string, family):
  72. """
  73. Expand an IP address pattern into a list of strings. Examples:
  74. '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']
  75. '2001:db8:0:[0,fd-ff]::/64' => ['2001:db8:0:0::/64', '2001:db8:0:fd::/64', ... '2001:db8:0:ff::/64']
  76. """
  77. if family not in [4, 6]:
  78. raise Exception("Invalid IP address family: {}".format(family))
  79. if family == 4:
  80. regex = IP4_EXPANSION_PATTERN
  81. base = 10
  82. else:
  83. regex = IP6_EXPANSION_PATTERN
  84. base = 16
  85. lead, pattern, remnant = re.split(regex, string, maxsplit=1)
  86. parsed_range = parse_numeric_range(pattern, base)
  87. for i in parsed_range:
  88. if re.search(regex, remnant):
  89. for string in expand_ipaddress_pattern(remnant, family):
  90. yield ''.join([lead, format(i, 'x' if family == 6 else 'd'), string])
  91. else:
  92. yield ''.join([lead, format(i, 'x' if family == 6 else 'd'), remnant])
  93. def add_blank_choice(choices):
  94. """
  95. Add a blank choice to the beginning of a choices list.
  96. """
  97. return ((None, '---------'),) + tuple(choices)
  98. #
  99. # Widgets
  100. #
  101. class SmallTextarea(forms.Textarea):
  102. pass
  103. class ColorSelect(forms.Select):
  104. def __init__(self, *args, **kwargs):
  105. kwargs['choices'] = COLOR_CHOICES
  106. super(ColorSelect, self).__init__(*args, **kwargs)
  107. def render_option(self, selected_choices, option_value, option_label):
  108. if option_value is None:
  109. option_value = ''
  110. option_value = force_text(option_value)
  111. if option_value in selected_choices:
  112. selected_html = mark_safe(' selected')
  113. if not self.allow_multiple_selected:
  114. # Only allow for a single selection.
  115. selected_choices.remove(option_value)
  116. else:
  117. selected_html = ''
  118. return format_html('<option value="{}"{} style="background-color: #{}">{}</option>',
  119. option_value, selected_html, option_value, force_text(option_label))
  120. class SelectWithDisabled(forms.Select):
  121. """
  122. Modified the stock Select widget to accept choices using a dict() for a label. The dict for each option must include
  123. 'label' (string) and 'disabled' (boolean).
  124. """
  125. def render_option(self, selected_choices, option_value, option_label):
  126. # Determine if option has been selected
  127. option_value = force_text(option_value)
  128. if option_value in selected_choices:
  129. selected_html = mark_safe(' selected="selected"')
  130. if not self.allow_multiple_selected:
  131. # Only allow for a single selection.
  132. selected_choices.remove(option_value)
  133. else:
  134. selected_html = ''
  135. # Determine if option has been disabled
  136. option_disabled = False
  137. exempt_value = force_text(self.attrs.get('exempt', None))
  138. if isinstance(option_label, dict):
  139. option_disabled = option_label['disabled'] if option_value != exempt_value else False
  140. option_label = option_label['label']
  141. disabled_html = ' disabled="disabled"' if option_disabled else ''
  142. return format_html(u'<option value="{}"{}{}>{}</option>',
  143. option_value,
  144. selected_html,
  145. disabled_html,
  146. force_text(option_label))
  147. class ArrayFieldSelectMultiple(SelectWithDisabled, forms.SelectMultiple):
  148. """
  149. MultiSelect widgets for a SimpleArrayField. Choices must be populated on the widget.
  150. """
  151. def __init__(self, *args, **kwargs):
  152. self.delimiter = kwargs.pop('delimiter', ',')
  153. super(ArrayFieldSelectMultiple, self).__init__(*args, **kwargs)
  154. def render_options(self, selected_choices):
  155. # Split the delimited string of values into a list
  156. if selected_choices:
  157. selected_choices = selected_choices.split(self.delimiter)
  158. return super(ArrayFieldSelectMultiple, self).render_options(selected_choices)
  159. def value_from_datadict(self, data, files, name):
  160. # Condense the list of selected choices into a delimited string
  161. data = super(ArrayFieldSelectMultiple, self).value_from_datadict(data, files, name)
  162. return self.delimiter.join(data)
  163. class APISelect(SelectWithDisabled):
  164. """
  165. A select widget populated via an API call
  166. :param api_url: API URL
  167. :param display_field: (Optional) Field to display for child in selection list. Defaults to `name`.
  168. :param disabled_indicator: (Optional) Mark option as disabled if this field equates true.
  169. """
  170. def __init__(self, api_url, display_field=None, disabled_indicator=None, *args, **kwargs):
  171. super(APISelect, self).__init__(*args, **kwargs)
  172. self.attrs['class'] = 'api-select'
  173. self.attrs['api-url'] = '/{}{}'.format(settings.BASE_PATH, api_url.lstrip('/')) # Inject BASE_PATH
  174. if display_field:
  175. self.attrs['display-field'] = display_field
  176. if disabled_indicator:
  177. self.attrs['disabled-indicator'] = disabled_indicator
  178. class Livesearch(forms.TextInput):
  179. """
  180. A text widget that carries a few extra bits of data for use in AJAX-powered autocomplete search
  181. :param query_key: The name of the parameter to query against
  182. :param query_url: The name of the API URL to query
  183. :param field_to_update: The name of the "real" form field whose value is being set
  184. :param obj_label: The field to use as the option label (optional)
  185. """
  186. def __init__(self, query_key, query_url, field_to_update, obj_label=None, *args, **kwargs):
  187. super(Livesearch, self).__init__(*args, **kwargs)
  188. self.attrs = {
  189. 'data-key': query_key,
  190. 'data-source': reverse_lazy(query_url),
  191. 'data-field': field_to_update,
  192. }
  193. if obj_label:
  194. self.attrs['data-label'] = obj_label
  195. #
  196. # Form fields
  197. #
  198. class CSVDataField(forms.CharField):
  199. """
  200. A field for comma-separated values (CSV). Values containing commas should be encased within double quotes. Example:
  201. '"New York, NY",new-york-ny,Other stuff' => ['New York, NY', 'new-york-ny', 'Other stuff']
  202. """
  203. csv_form = None
  204. widget = forms.Textarea
  205. def __init__(self, csv_form, *args, **kwargs):
  206. self.csv_form = csv_form
  207. self.columns = self.csv_form().fields.keys()
  208. super(CSVDataField, self).__init__(*args, **kwargs)
  209. self.strip = False
  210. if not self.label:
  211. self.label = 'CSV Data'
  212. if not self.help_text:
  213. self.help_text = 'Enter one line per record in CSV format.'
  214. def to_python(self, value):
  215. """
  216. Return a list of dictionaries, each representing an individual record
  217. """
  218. # Python 2's csv module has problems with Unicode
  219. if not isinstance(value, str):
  220. value = value.encode('utf-8')
  221. records = []
  222. reader = csv.reader(value.splitlines())
  223. for i, row in enumerate(reader, start=1):
  224. if row:
  225. if len(row) < len(self.columns):
  226. raise forms.ValidationError("Line {}: Field(s) missing (found {}; expected {})"
  227. .format(i, len(row), len(self.columns)))
  228. elif len(row) > len(self.columns):
  229. raise forms.ValidationError("Line {}: Too many fields (found {}; expected {})"
  230. .format(i, len(row), len(self.columns)))
  231. row = [col.strip() for col in row]
  232. record = dict(zip(self.columns, row))
  233. records.append(record)
  234. return records
  235. class ExpandableNameField(forms.CharField):
  236. """
  237. A field which allows for numeric range expansion
  238. Example: 'Gi0/[1-3]' => ['Gi0/1', 'Gi0/2', 'Gi0/3']
  239. """
  240. def __init__(self, *args, **kwargs):
  241. super(ExpandableNameField, self).__init__(*args, **kwargs)
  242. if not self.help_text:
  243. self.help_text = 'Numeric ranges are supported for bulk creation.<br />'\
  244. 'Example: <code>ge-0/0/[0-23,25,30]</code>'
  245. def to_python(self, value):
  246. if re.search(NUMERIC_EXPANSION_PATTERN, value):
  247. return list(expand_numeric_pattern(value))
  248. return [value]
  249. class ExpandableIPAddressField(forms.CharField):
  250. """
  251. A field which allows for expansion of IP address ranges
  252. 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']
  253. """
  254. def __init__(self, *args, **kwargs):
  255. super(ExpandableIPAddressField, self).__init__(*args, **kwargs)
  256. if not self.help_text:
  257. self.help_text = 'Specify a numeric range to create multiple IPs.<br />'\
  258. 'Example: <code>192.0.2.[1,5,100-254]/24</code>'
  259. def to_python(self, value):
  260. # Hackish address family detection but it's all we have to work with
  261. if '.' in value and re.search(IP4_EXPANSION_PATTERN, value):
  262. return list(expand_ipaddress_pattern(value, 4))
  263. elif ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
  264. return list(expand_ipaddress_pattern(value, 6))
  265. return [value]
  266. class CommentField(forms.CharField):
  267. """
  268. A textarea with support for GitHub-Flavored Markdown. Exists mostly just to add a standard help_text.
  269. """
  270. widget = forms.Textarea
  271. default_label = 'Comments'
  272. # TODO: Port GFM syntax cheat sheet to internal documentation
  273. default_helptext = '<i class="fa fa-info-circle"></i> '\
  274. '<a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank">'\
  275. 'GitHub-Flavored Markdown</a> syntax is supported'
  276. def __init__(self, *args, **kwargs):
  277. required = kwargs.pop('required', False)
  278. label = kwargs.pop('label', self.default_label)
  279. help_text = kwargs.pop('help_text', self.default_helptext)
  280. super(CommentField, self).__init__(required=required, label=label, help_text=help_text, *args, **kwargs)
  281. class FlexibleModelChoiceField(forms.ModelChoiceField):
  282. """
  283. Allow a model to be reference by either '{ID}' or the field specified by `to_field_name`.
  284. """
  285. def to_python(self, value):
  286. if value in self.empty_values:
  287. return None
  288. try:
  289. if not self.to_field_name:
  290. key = 'pk'
  291. elif re.match('^\{\d+\}$', value):
  292. key = 'pk'
  293. value = value.strip('{}')
  294. else:
  295. key = self.to_field_name
  296. value = self.queryset.get(**{key: value})
  297. except (ValueError, TypeError, self.queryset.model.DoesNotExist):
  298. raise forms.ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
  299. return value
  300. class SlugField(forms.SlugField):
  301. def __init__(self, slug_source='name', *args, **kwargs):
  302. label = kwargs.pop('label', "Slug")
  303. help_text = kwargs.pop('help_text', "URL-friendly unique shorthand")
  304. super(SlugField, self).__init__(label=label, help_text=help_text, *args, **kwargs)
  305. self.widget.attrs['slug-source'] = slug_source
  306. class FilterChoiceFieldMixin(object):
  307. iterator = forms.models.ModelChoiceIterator
  308. def __init__(self, null_option=None, *args, **kwargs):
  309. self.null_option = null_option
  310. if 'required' not in kwargs:
  311. kwargs['required'] = False
  312. if 'widget' not in kwargs:
  313. kwargs['widget'] = forms.SelectMultiple(attrs={'size': 6})
  314. super(FilterChoiceFieldMixin, self).__init__(*args, **kwargs)
  315. def label_from_instance(self, obj):
  316. label = super(FilterChoiceFieldMixin, self).label_from_instance(obj)
  317. if hasattr(obj, 'filter_count'):
  318. return u'{} ({})'.format(label, obj.filter_count)
  319. return label
  320. def _get_choices(self):
  321. if hasattr(self, '_choices'):
  322. return self._choices
  323. if self.null_option is not None:
  324. return itertools.chain([self.null_option], self.iterator(self))
  325. return self.iterator(self)
  326. choices = property(_get_choices, forms.ChoiceField._set_choices)
  327. class FilterChoiceField(FilterChoiceFieldMixin, forms.ModelMultipleChoiceField):
  328. pass
  329. class FilterTreeNodeMultipleChoiceField(FilterChoiceFieldMixin, TreeNodeMultipleChoiceField):
  330. pass
  331. class LaxURLField(forms.URLField):
  332. """
  333. Custom URLField which allows any valid URL scheme
  334. """
  335. class AnyURLScheme(object):
  336. # A fake URL list which "contains" all scheme names abiding by the syntax defined in RFC 3986 section 3.1
  337. def __contains__(self, item):
  338. if not item or not re.match('^[a-z][0-9a-z+\-.]*$', item.lower()):
  339. return False
  340. return True
  341. default_validators = [URLValidator(schemes=AnyURLScheme())]
  342. #
  343. # Forms
  344. #
  345. class BootstrapMixin(forms.BaseForm):
  346. def __init__(self, *args, **kwargs):
  347. super(BootstrapMixin, self).__init__(*args, **kwargs)
  348. for field_name, field in self.fields.items():
  349. if type(field.widget) not in [type(forms.CheckboxInput()), type(forms.RadioSelect())]:
  350. try:
  351. field.widget.attrs['class'] += ' form-control'
  352. except KeyError:
  353. field.widget.attrs['class'] = 'form-control'
  354. if field.required:
  355. field.widget.attrs['required'] = 'required'
  356. if 'placeholder' not in field.widget.attrs:
  357. field.widget.attrs['placeholder'] = field.label
  358. class ConfirmationForm(BootstrapMixin, forms.Form):
  359. """
  360. A generic confirmation form. The form is not valid unless the confirm field is checked. An optional return_url can
  361. be specified to direct the user to a specific URL after the action has been taken.
  362. """
  363. confirm = forms.BooleanField(required=True)
  364. return_url = forms.CharField(required=False, widget=forms.HiddenInput())
  365. class BulkEditForm(forms.Form):
  366. def __init__(self, model, *args, **kwargs):
  367. super(BulkEditForm, self).__init__(*args, **kwargs)
  368. self.model = model
  369. # Copy any nullable fields defined in Meta
  370. if hasattr(self.Meta, 'nullable_fields'):
  371. self.nullable_fields = [field for field in self.Meta.nullable_fields]
  372. else:
  373. self.nullable_fields = []
  374. class BulkImportForm(forms.Form):
  375. def clean(self):
  376. records = self.cleaned_data.get('csv')
  377. if not records:
  378. return
  379. obj_list = []
  380. for i, record in enumerate(records, start=1):
  381. obj_form = self.fields['csv'].csv_form(data=record)
  382. if obj_form.is_valid():
  383. obj = obj_form.save(commit=False)
  384. obj_list.append(obj)
  385. else:
  386. for field, errors in obj_form.errors.items():
  387. for e in errors:
  388. if field == '__all__':
  389. self.add_error('csv', "Record {}: {}".format(i, e))
  390. else:
  391. self.add_error('csv', "Record {} ({}): {}".format(i, field, e))
  392. self.cleaned_data['csv'] = obj_list