fields.py 16 KB

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