forms.py 18 KB

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