forms.py 15 KB

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