fields.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. import csv
  2. import json
  3. import re
  4. from io import StringIO
  5. import django_filters
  6. from django import forms
  7. from django.conf import settings
  8. from django.forms.fields import JSONField as _JSONField, InvalidJSONInput
  9. from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist
  10. from django.db.models import Count
  11. from django.forms import BoundField
  12. from django.urls import reverse
  13. from utilities.choices import unpack_grouped_choices
  14. from utilities.utils import content_type_name
  15. from utilities.validators import EnhancedURLValidator
  16. from . import widgets
  17. from .constants import *
  18. from .utils import expand_alphanumeric_pattern, expand_ipaddress_pattern
  19. __all__ = (
  20. 'CommentField',
  21. 'ContentTypeChoiceField',
  22. 'ContentTypeMultipleChoiceField',
  23. 'CSVChoiceField',
  24. 'CSVContentTypeField',
  25. 'CSVDataField',
  26. 'CSVFileField',
  27. 'CSVModelChoiceField',
  28. 'CSVTypedChoiceField',
  29. 'DynamicModelChoiceField',
  30. 'DynamicModelMultipleChoiceField',
  31. 'ExpandableIPAddressField',
  32. 'ExpandableNameField',
  33. 'JSONField',
  34. 'LaxURLField',
  35. 'SlugField',
  36. 'TagFilterField',
  37. )
  38. class CommentField(forms.CharField):
  39. """
  40. A textarea with support for Markdown rendering. Exists mostly just to add a standard help_text.
  41. """
  42. widget = forms.Textarea
  43. default_label = ''
  44. # TODO: Port Markdown cheat sheet to internal documentation
  45. default_helptext = '<i class="mdi mdi-information-outline"></i> '\
  46. '<a href="https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet" target="_blank" tabindex="-1">'\
  47. 'Markdown</a> syntax is supported'
  48. def __init__(self, *args, **kwargs):
  49. required = kwargs.pop('required', False)
  50. label = kwargs.pop('label', self.default_label)
  51. help_text = kwargs.pop('help_text', self.default_helptext)
  52. super().__init__(required=required, label=label, help_text=help_text, *args, **kwargs)
  53. class SlugField(forms.SlugField):
  54. """
  55. Extend the built-in SlugField to automatically populate from a field called `name` unless otherwise specified.
  56. """
  57. def __init__(self, slug_source='name', *args, **kwargs):
  58. label = kwargs.pop('label', "Slug")
  59. help_text = kwargs.pop('help_text', "URL-friendly unique shorthand")
  60. widget = kwargs.pop('widget', widgets.SlugWidget)
  61. super().__init__(label=label, help_text=help_text, widget=widget, *args, **kwargs)
  62. self.widget.attrs['slug-source'] = slug_source
  63. class TagFilterField(forms.MultipleChoiceField):
  64. """
  65. A filter field for the tags of a model. Only the tags used by a model are displayed.
  66. :param model: The model of the filter
  67. """
  68. widget = widgets.StaticSelect2Multiple
  69. def __init__(self, model, *args, **kwargs):
  70. def get_choices():
  71. tags = model.tags.annotate(
  72. count=Count('extras_taggeditem_items')
  73. ).order_by('name')
  74. return [
  75. (str(tag.slug), '{} ({})'.format(tag.name, tag.count)) for tag in tags
  76. ]
  77. # Choices are fetched each time the form is initialized
  78. super().__init__(label='Tags', choices=get_choices, required=False, *args, **kwargs)
  79. class LaxURLField(forms.URLField):
  80. """
  81. Modifies Django's built-in URLField to remove the requirement for fully-qualified domain names
  82. (e.g. http://myserver/ is valid)
  83. """
  84. default_validators = [EnhancedURLValidator()]
  85. class JSONField(_JSONField):
  86. """
  87. Custom wrapper around Django's built-in JSONField to avoid presenting "null" as the default text.
  88. """
  89. def __init__(self, *args, **kwargs):
  90. super().__init__(*args, **kwargs)
  91. if not self.help_text:
  92. self.help_text = 'Enter context data in <a href="https://json.org/">JSON</a> format.'
  93. self.widget.attrs['placeholder'] = ''
  94. def prepare_value(self, value):
  95. if isinstance(value, InvalidJSONInput):
  96. return value
  97. if value is None:
  98. return ''
  99. return json.dumps(value, sort_keys=True, indent=4)
  100. class ContentTypeChoiceMixin:
  101. def __init__(self, queryset, *args, **kwargs):
  102. # Order ContentTypes by app_label
  103. queryset = queryset.order_by('app_label', 'model')
  104. super().__init__(queryset, *args, **kwargs)
  105. def label_from_instance(self, obj):
  106. try:
  107. return content_type_name(obj)
  108. except AttributeError:
  109. return super().label_from_instance(obj)
  110. class ContentTypeChoiceField(ContentTypeChoiceMixin, forms.ModelChoiceField):
  111. pass
  112. class ContentTypeMultipleChoiceField(ContentTypeChoiceMixin, forms.ModelMultipleChoiceField):
  113. pass
  114. #
  115. # CSV fields
  116. #
  117. class CSVDataField(forms.CharField):
  118. """
  119. A CharField (rendered as a Textarea) which accepts CSV-formatted data. It returns data as a two-tuple: The first
  120. item is a dictionary of column headers, mapping field names to the attribute by which they match a related object
  121. (where applicable). The second item is a list of dictionaries, each representing a discrete row of CSV data.
  122. :param from_form: The form from which the field derives its validation rules.
  123. """
  124. widget = forms.Textarea
  125. def __init__(self, from_form, *args, **kwargs):
  126. form = from_form()
  127. self.model = form.Meta.model
  128. self.fields = form.fields
  129. self.required_fields = [
  130. name for name, field in form.fields.items() if field.required
  131. ]
  132. super().__init__(*args, **kwargs)
  133. self.strip = False
  134. if not self.label:
  135. self.label = ''
  136. if not self.initial:
  137. self.initial = ','.join(self.required_fields) + '\n'
  138. if not self.help_text:
  139. self.help_text = 'Enter the list of column headers followed by one line per record to be imported, using ' \
  140. 'commas to separate values. Multi-line data and values containing commas may be wrapped ' \
  141. 'in double quotes.'
  142. def to_python(self, value):
  143. records = []
  144. reader = csv.reader(StringIO(value.strip()))
  145. # Consume the first line of CSV data as column headers. Create a dictionary mapping each header to an optional
  146. # "to" field specifying how the related object is being referenced. For example, importing a Device might use a
  147. # `site.slug` header, to indicate the related site is being referenced by its slug.
  148. headers = {}
  149. for header in next(reader):
  150. if '.' in header:
  151. field, to_field = header.split('.', 1)
  152. headers[field] = to_field
  153. else:
  154. headers[header] = None
  155. # Parse CSV rows into a list of dictionaries mapped from the column headers.
  156. for i, row in enumerate(reader, start=1):
  157. if len(row) != len(headers):
  158. raise forms.ValidationError(
  159. f"Row {i}: Expected {len(headers)} columns but found {len(row)}"
  160. )
  161. row = [col.strip() for col in row]
  162. record = dict(zip(headers.keys(), row))
  163. records.append(record)
  164. return headers, records
  165. def validate(self, value):
  166. headers, records = value
  167. # Validate provided column headers
  168. for field, to_field in headers.items():
  169. if field not in self.fields:
  170. raise forms.ValidationError(f'Unexpected column header "{field}" found.')
  171. if to_field and not hasattr(self.fields[field], 'to_field_name'):
  172. raise forms.ValidationError(f'Column "{field}" is not a related object; cannot use dots')
  173. if to_field and not hasattr(self.fields[field].queryset.model, to_field):
  174. raise forms.ValidationError(f'Invalid related object attribute for column "{field}": {to_field}')
  175. # Validate required fields
  176. for f in self.required_fields:
  177. if f not in headers:
  178. raise forms.ValidationError(f'Required column header "{f}" not found.')
  179. return value
  180. class CSVFileField(forms.FileField):
  181. """
  182. A FileField (rendered as a file input button) which accepts a file containing CSV-formatted data. It returns
  183. data as a two-tuple: The first item is a dictionary of column headers, mapping field names to the attribute
  184. by which they match a related object (where applicable). The second item is a list of dictionaries, each
  185. representing a discrete row of CSV data.
  186. :param from_form: The form from which the field derives its validation rules.
  187. """
  188. def __init__(self, from_form, *args, **kwargs):
  189. form = from_form()
  190. self.model = form.Meta.model
  191. self.fields = form.fields
  192. self.required_fields = [
  193. name for name, field in form.fields.items() if field.required
  194. ]
  195. super().__init__(*args, **kwargs)
  196. def to_python(self, file):
  197. records = []
  198. csv_str = file.read().decode('utf-8')
  199. reader = csv.reader(csv_str.splitlines())
  200. # Consume the first line of CSV data as column headers. Create a dictionary mapping each header to an optional
  201. # "to" field specifying how the related object is being referenced. For example, importing a Device might use a
  202. # `site.slug` header, to indicate the related site is being referenced by its slug.
  203. headers = {}
  204. for header in next(reader):
  205. if '.' in header:
  206. field, to_field = header.split('.', 1)
  207. headers[field] = to_field
  208. else:
  209. headers[header] = None
  210. # Parse CSV rows into a list of dictionaries mapped from the column headers.
  211. for i, row in enumerate(reader, start=1):
  212. if len(row) != len(headers):
  213. raise forms.ValidationError(
  214. f"Row {i}: Expected {len(headers)} columns but found {len(row)}"
  215. )
  216. row = [col.strip() for col in row]
  217. record = dict(zip(headers.keys(), row))
  218. records.append(record)
  219. return headers, records
  220. def validate(self, value):
  221. headers, records = value
  222. # Validate provided column headers
  223. for field, to_field in headers.items():
  224. if field not in self.fields:
  225. raise forms.ValidationError(f'Unexpected column header "{field}" found.')
  226. if to_field and not hasattr(self.fields[field], 'to_field_name'):
  227. raise forms.ValidationError(f'Column "{field}" is not a related object; cannot use dots')
  228. if to_field and not hasattr(self.fields[field].queryset.model, to_field):
  229. raise forms.ValidationError(f'Invalid related object attribute for column "{field}": {to_field}')
  230. # Validate required fields
  231. for f in self.required_fields:
  232. if f not in headers:
  233. raise forms.ValidationError(f'Required column header "{f}" not found.')
  234. return value
  235. class CSVChoiceField(forms.ChoiceField):
  236. """
  237. Invert the provided set of choices to take the human-friendly label as input, and return the database value.
  238. """
  239. STATIC_CHOICES = True
  240. def __init__(self, *, choices=(), **kwargs):
  241. super().__init__(choices=choices, **kwargs)
  242. self.choices = unpack_grouped_choices(choices)
  243. class CSVTypedChoiceField(forms.TypedChoiceField):
  244. STATIC_CHOICES = True
  245. class CSVModelChoiceField(forms.ModelChoiceField):
  246. """
  247. Provides additional validation for model choices entered as CSV data.
  248. """
  249. default_error_messages = {
  250. 'invalid_choice': 'Object not found.',
  251. }
  252. def to_python(self, value):
  253. try:
  254. return super().to_python(value)
  255. except MultipleObjectsReturned:
  256. raise forms.ValidationError(
  257. f'"{value}" is not a unique value for this field; multiple objects were found'
  258. )
  259. class CSVContentTypeField(CSVModelChoiceField):
  260. """
  261. Reference a ContentType in the form <app>.<model>
  262. """
  263. STATIC_CHOICES = True
  264. def prepare_value(self, value):
  265. return f'{value.app_label}.{value.model}'
  266. def to_python(self, value):
  267. try:
  268. app_label, model = value.split('.')
  269. except ValueError:
  270. raise forms.ValidationError(f'Object type must be specified as "<app>.<model>"')
  271. try:
  272. return self.queryset.get(app_label=app_label, model=model)
  273. except ObjectDoesNotExist:
  274. raise forms.ValidationError(f'Invalid object type')
  275. #
  276. # Expansion fields
  277. #
  278. class ExpandableNameField(forms.CharField):
  279. """
  280. A field which allows for numeric range expansion
  281. Example: 'Gi0/[1-3]' => ['Gi0/1', 'Gi0/2', 'Gi0/3']
  282. """
  283. def __init__(self, *args, **kwargs):
  284. super().__init__(*args, **kwargs)
  285. if not self.help_text:
  286. self.help_text = """
  287. Alphanumeric ranges are supported for bulk creation. Mixed cases and types within a single range
  288. are not supported. Examples:
  289. <ul>
  290. <li><code>[ge,xe]-0/0/[0-9]</code></li>
  291. <li><code>e[0-3][a-d,f]</code></li>
  292. </ul>
  293. """
  294. def to_python(self, value):
  295. if not value:
  296. return ''
  297. if re.search(ALPHANUMERIC_EXPANSION_PATTERN, value):
  298. return list(expand_alphanumeric_pattern(value))
  299. return [value]
  300. class ExpandableIPAddressField(forms.CharField):
  301. """
  302. A field which allows for expansion of IP address ranges
  303. 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']
  304. """
  305. def __init__(self, *args, **kwargs):
  306. super().__init__(*args, **kwargs)
  307. if not self.help_text:
  308. self.help_text = 'Specify a numeric range to create multiple IPs.<br />'\
  309. 'Example: <code>192.0.2.[1,5,100-254]/24</code>'
  310. def to_python(self, value):
  311. # Hackish address family detection but it's all we have to work with
  312. if '.' in value and re.search(IP4_EXPANSION_PATTERN, value):
  313. return list(expand_ipaddress_pattern(value, 4))
  314. elif ':' in value and re.search(IP6_EXPANSION_PATTERN, value):
  315. return list(expand_ipaddress_pattern(value, 6))
  316. return [value]
  317. #
  318. # Dynamic fields
  319. #
  320. class DynamicModelChoiceMixin:
  321. """
  322. :param display_field: The name of the attribute of an API response object to display in the selection list
  323. :param query_params: A dictionary of additional key/value pairs to attach to the API request
  324. :param initial_params: A dictionary of child field references to use for selecting a parent field's initial value
  325. :param null_option: The string used to represent a null selection (if any)
  326. :param disabled_indicator: The name of the field which, if populated, will disable selection of the
  327. choice (optional)
  328. """
  329. filter = django_filters.ModelChoiceFilter
  330. widget = widgets.APISelect
  331. # TODO: Remove display_field in v3.0
  332. def __init__(self, display_field='display', query_params=None, initial_params=None, null_option=None,
  333. disabled_indicator=None, *args, **kwargs):
  334. self.display_field = display_field
  335. self.query_params = query_params or {}
  336. self.initial_params = initial_params or {}
  337. self.null_option = null_option
  338. self.disabled_indicator = disabled_indicator
  339. # to_field_name is set by ModelChoiceField.__init__(), but we need to set it early for reference
  340. # by widget_attrs()
  341. self.to_field_name = kwargs.get('to_field_name')
  342. super().__init__(*args, **kwargs)
  343. def widget_attrs(self, widget):
  344. attrs = {
  345. 'display-field': self.display_field,
  346. }
  347. # Set value-field attribute if the field specifies to_field_name
  348. if self.to_field_name:
  349. attrs['value-field'] = self.to_field_name
  350. # Set the string used to represent a null option
  351. if self.null_option is not None:
  352. attrs['data-null-option'] = self.null_option
  353. # Set the disabled indicator, if any
  354. if self.disabled_indicator is not None:
  355. attrs['disabled-indicator'] = self.disabled_indicator
  356. # Attach any static query parameters
  357. for key, value in self.query_params.items():
  358. widget.add_query_param(key, value)
  359. return attrs
  360. def get_bound_field(self, form, field_name):
  361. bound_field = BoundField(form, self, field_name)
  362. # Set initial value based on prescribed child fields (if not already set)
  363. if not self.initial and self.initial_params:
  364. filter_kwargs = {}
  365. for kwarg, child_field in self.initial_params.items():
  366. value = form.initial.get(child_field.lstrip('$'))
  367. if value:
  368. filter_kwargs[kwarg] = value
  369. if filter_kwargs:
  370. self.initial = self.queryset.filter(**filter_kwargs).first()
  371. # Modify the QuerySet of the field before we return it. Limit choices to any data already bound: Options
  372. # will be populated on-demand via the APISelect widget.
  373. data = bound_field.value()
  374. if data:
  375. field_name = getattr(self, 'to_field_name') or 'pk'
  376. filter = self.filter(field_name=field_name)
  377. try:
  378. self.queryset = filter.filter(self.queryset, data)
  379. except TypeError:
  380. # Catch any error caused by invalid initial data passed from the user
  381. self.queryset = self.queryset.none()
  382. else:
  383. self.queryset = self.queryset.none()
  384. # Set the data URL on the APISelect widget (if not already set)
  385. widget = bound_field.field.widget
  386. if not widget.attrs.get('data-url'):
  387. app_label = self.queryset.model._meta.app_label
  388. model_name = self.queryset.model._meta.model_name
  389. data_url = reverse('{}-api:{}-list'.format(app_label, model_name))
  390. widget.attrs['data-url'] = data_url
  391. return bound_field
  392. class DynamicModelChoiceField(DynamicModelChoiceMixin, forms.ModelChoiceField):
  393. """
  394. Override get_bound_field() to avoid pre-populating field choices with a SQL query. The field will be
  395. rendered only with choices set via bound data. Choices are populated on-demand via the APISelect widget.
  396. """
  397. def clean(self, value):
  398. """
  399. When null option is enabled and "None" is sent as part of a form to be submitted, it is sent as the
  400. string 'null'. This will check for that condition and gracefully handle the conversion to a NoneType.
  401. """
  402. if self.null_option is not None and value == settings.FILTERS_NULL_CHOICE_VALUE:
  403. return None
  404. return super().clean(value)
  405. class DynamicModelMultipleChoiceField(DynamicModelChoiceMixin, forms.ModelMultipleChoiceField):
  406. """
  407. A multiple-choice version of DynamicModelChoiceField.
  408. """
  409. filter = django_filters.ModelMultipleChoiceFilter
  410. widget = widgets.APISelectMultiple