fields.py 13 KB

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