fields.py 17 KB

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