fields.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. import json
  2. from django import forms
  3. from django.conf import settings
  4. from django.db.models import BigIntegerField as BigIntegerModelField
  5. from django.db.models import Count
  6. from django.forms.fields import InvalidJSONInput
  7. from django.forms.fields import JSONField as _JSONField
  8. from django.templatetags.static import static
  9. from django.utils.text import format_lazy
  10. from django.utils.translation import gettext_lazy as _
  11. from netaddr import EUI, AddrFormatError
  12. from utilities.forms import widgets
  13. from utilities.validators import EnhancedURLValidator
  14. __all__ = (
  15. 'BigIntegerField',
  16. 'ColorField',
  17. 'CommentField',
  18. 'JSONField',
  19. 'LaxURLField',
  20. 'MACAddressField',
  21. 'PositiveBigIntegerField',
  22. 'QueryField',
  23. 'SlugField',
  24. 'TagFilterField',
  25. )
  26. class BigIntegerField(forms.IntegerField):
  27. """
  28. An IntegerField constrained to the range of a signed 64-bit integer.
  29. """
  30. def __init__(self, *args, **kwargs):
  31. kwargs.setdefault('min_value', -BigIntegerModelField.MAX_BIGINT - 1)
  32. kwargs.setdefault('max_value', BigIntegerModelField.MAX_BIGINT)
  33. super().__init__(*args, **kwargs)
  34. class PositiveBigIntegerField(BigIntegerField):
  35. """
  36. An IntegerField constrained to the range supported by Django's
  37. PositiveBigIntegerField model field.
  38. """
  39. def __init__(self, *args, **kwargs):
  40. kwargs.setdefault('min_value', 0)
  41. super().__init__(*args, **kwargs)
  42. class QueryField(forms.CharField):
  43. """
  44. A CharField subclass used for global search/query fields in filter forms.
  45. This field type signals to FilterModifierMixin to skip enhancement with lookup modifiers.
  46. """
  47. pass
  48. class CommentField(forms.CharField):
  49. """
  50. A textarea with support for Markdown rendering. Exists mostly just to add a standard `help_text`.
  51. """
  52. widget = widgets.MarkdownWidget
  53. label = _('Comments')
  54. # Keep the help text lazy so it uses the active language instead of the language at import time.
  55. help_text = format_lazy(
  56. _(
  57. '<i class="mdi mdi-information-outline" aria-hidden="true"></i> '
  58. '<a href="{url}" target="_blank" tabindex="-1">Markdown</a> syntax is supported'
  59. ),
  60. url=static('docs/reference/markdown/')
  61. )
  62. def __init__(self, *, label=label, help_text=help_text, required=False, **kwargs):
  63. super().__init__(label=label, help_text=help_text, required=required, **kwargs)
  64. class SlugField(forms.SlugField):
  65. """
  66. Extend Django's built-in SlugField to automatically populate from a field called `name` unless otherwise specified.
  67. Parameters:
  68. slug_source: Name of the form field from which the slug value will be derived
  69. """
  70. widget = widgets.SlugWidget
  71. label = _('Slug')
  72. help_text = _("URL-friendly unique shorthand")
  73. def __init__(self, *, slug_source='name', label=label, help_text=help_text, **kwargs):
  74. super().__init__(label=label, help_text=help_text, **kwargs)
  75. self.widget.attrs['slug-source'] = slug_source
  76. def get_bound_field(self, form, field_name):
  77. if prefix := form.prefix:
  78. slug_source = self.widget.attrs.get('slug-source')
  79. if slug_source and not slug_source.startswith(f'{prefix}-'):
  80. self.widget.attrs['slug-source'] = f"{prefix}-{slug_source}"
  81. return super().get_bound_field(form, field_name)
  82. class ColorField(forms.CharField):
  83. """
  84. A field which represents a color value in hexadecimal `RRGGBB` format. Utilizes NetBox's `ColorSelect` widget to
  85. render choices.
  86. """
  87. widget = widgets.ColorSelect
  88. class TagFilterField(forms.MultipleChoiceField):
  89. """
  90. A filter field for the tags of a model. Only the tags used by a model are displayed.
  91. :param model: The model of the filter
  92. """
  93. def __init__(self, model, *args, **kwargs):
  94. def get_choices():
  95. tags = model.tags.annotate(
  96. count=Count('extras_taggeditem_items')
  97. ).order_by('name')
  98. return [
  99. (settings.FILTERS_NULL_CHOICE_VALUE, settings.FILTERS_NULL_CHOICE_LABEL), # "None" option
  100. *[(str(tag.slug), f'{tag.name} ({tag.count})') for tag in tags]
  101. ]
  102. # Choices are fetched each time the form is initialized
  103. super().__init__(label=_('Tags'), choices=get_choices, required=False, *args, **kwargs)
  104. class LaxURLField(forms.URLField):
  105. """
  106. Modifies Django's built-in URLField to remove the requirement for fully-qualified domain names
  107. (e.g. http://myserver/ is valid)
  108. """
  109. default_validators = [EnhancedURLValidator()]
  110. class JSONField(_JSONField):
  111. """
  112. Custom wrapper around Django's built-in JSONField to avoid presenting "null" as the default text.
  113. """
  114. empty_values = [None, '', ()]
  115. def __init__(self, *args, **kwargs):
  116. super().__init__(*args, **kwargs)
  117. self.widget.attrs['placeholder'] = ''
  118. self.widget.attrs['class'] = 'font-monospace'
  119. if not self.help_text:
  120. self.help_text = _('Enter context data in <a href="https://json.org/">JSON</a> format.')
  121. def prepare_value(self, value):
  122. if isinstance(value, InvalidJSONInput):
  123. return value
  124. if value in ('', None):
  125. return ''
  126. if type(value) is str:
  127. try:
  128. value = json.loads(value, cls=self.decoder)
  129. except json.decoder.JSONDecodeError:
  130. return f'"{value}"'
  131. return json.dumps(value, sort_keys=True, indent=4, ensure_ascii=False, cls=self.encoder)
  132. class MACAddressField(forms.Field):
  133. """
  134. Validates a 48-bit MAC address.
  135. """
  136. widget = forms.CharField
  137. default_error_messages = {
  138. 'invalid': _('MAC address must be in EUI-48 format'),
  139. }
  140. def to_python(self, value):
  141. value = super().to_python(value)
  142. # Validate MAC address format
  143. try:
  144. value = EUI(value.strip())
  145. except AddrFormatError:
  146. raise forms.ValidationError(self.error_messages['invalid'], code='invalid')
  147. return value