customfields.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. import re
  2. from datetime import datetime, date
  3. from django import forms
  4. from django.contrib.contenttypes.models import ContentType
  5. from django.contrib.postgres.fields import ArrayField
  6. from django.core.validators import RegexValidator, ValidationError
  7. from django.db import models
  8. from django.utils.safestring import mark_safe
  9. from extras.choices import *
  10. from extras.utils import FeatureQuery
  11. from netbox.models import BigIDModel
  12. from utilities.forms import (
  13. CSVChoiceField, DatePicker, LaxURLField, StaticSelect2Multiple, StaticSelect2, add_blank_choice,
  14. )
  15. from utilities.querysets import RestrictedQuerySet
  16. from utilities.validators import validate_regex
  17. class CustomFieldManager(models.Manager.from_queryset(RestrictedQuerySet)):
  18. use_in_migrations = True
  19. def get_for_model(self, model):
  20. """
  21. Return all CustomFields assigned to the given model.
  22. """
  23. content_type = ContentType.objects.get_for_model(model._meta.concrete_model)
  24. return self.get_queryset().filter(content_types=content_type)
  25. class CustomField(BigIDModel):
  26. content_types = models.ManyToManyField(
  27. to=ContentType,
  28. related_name='custom_fields',
  29. verbose_name='Object(s)',
  30. limit_choices_to=FeatureQuery('custom_fields'),
  31. help_text='The object(s) to which this field applies.'
  32. )
  33. type = models.CharField(
  34. max_length=50,
  35. choices=CustomFieldTypeChoices,
  36. default=CustomFieldTypeChoices.TYPE_TEXT
  37. )
  38. name = models.CharField(
  39. max_length=50,
  40. unique=True,
  41. help_text='Internal field name'
  42. )
  43. label = models.CharField(
  44. max_length=50,
  45. blank=True,
  46. help_text='Name of the field as displayed to users (if not provided, '
  47. 'the field\'s name will be used)'
  48. )
  49. description = models.CharField(
  50. max_length=200,
  51. blank=True
  52. )
  53. required = models.BooleanField(
  54. default=False,
  55. help_text='If true, this field is required when creating new objects '
  56. 'or editing an existing object.'
  57. )
  58. filter_logic = models.CharField(
  59. max_length=50,
  60. choices=CustomFieldFilterLogicChoices,
  61. default=CustomFieldFilterLogicChoices.FILTER_LOOSE,
  62. help_text='Loose matches any instance of a given string; exact '
  63. 'matches the entire field.'
  64. )
  65. default = models.JSONField(
  66. blank=True,
  67. null=True,
  68. help_text='Default value for the field (must be a JSON value). Encapsulate '
  69. 'strings with double quotes (e.g. "Foo").'
  70. )
  71. weight = models.PositiveSmallIntegerField(
  72. default=100,
  73. help_text='Fields with higher weights appear lower in a form.'
  74. )
  75. validation_minimum = models.PositiveIntegerField(
  76. blank=True,
  77. null=True,
  78. verbose_name='Minimum value',
  79. help_text='Minimum allowed value (for numeric fields)'
  80. )
  81. validation_maximum = models.PositiveIntegerField(
  82. blank=True,
  83. null=True,
  84. verbose_name='Maximum value',
  85. help_text='Maximum allowed value (for numeric fields)'
  86. )
  87. validation_regex = models.CharField(
  88. blank=True,
  89. validators=[validate_regex],
  90. max_length=500,
  91. verbose_name='Validation regex',
  92. help_text='Regular expression to enforce on text field values. Use ^ and $ to force matching of entire string. '
  93. 'For example, <code>^[A-Z]{3}$</code> will limit values to exactly three uppercase letters.'
  94. )
  95. choices = ArrayField(
  96. base_field=models.CharField(max_length=100),
  97. blank=True,
  98. null=True,
  99. help_text='Comma-separated list of available choices (for selection fields)'
  100. )
  101. objects = CustomFieldManager()
  102. class Meta:
  103. ordering = ['weight', 'name']
  104. def __str__(self):
  105. return self.label or self.name.replace('_', ' ').capitalize()
  106. def __init__(self, *args, **kwargs):
  107. super().__init__(*args, **kwargs)
  108. # Cache instance's original name so we can check later whether it has changed
  109. self._name = self.name
  110. def populate_initial_data(self, content_types):
  111. """
  112. Populate initial custom field data upon either a) the creation of a new CustomField, or
  113. b) the assignment of an existing CustomField to new object types.
  114. """
  115. for ct in content_types:
  116. model = ct.model_class()
  117. instances = model.objects.exclude(**{f'custom_field_data__contains': self.name})
  118. for instance in instances:
  119. instance.custom_field_data[self.name] = self.default
  120. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  121. def remove_stale_data(self, content_types):
  122. """
  123. Delete custom field data which is no longer relevant (either because the CustomField is
  124. no longer assigned to a model, or because it has been deleted).
  125. """
  126. for ct in content_types:
  127. model = ct.model_class()
  128. instances = model.objects.filter(**{f'custom_field_data__{self.name}__isnull': False})
  129. for instance in instances:
  130. del(instance.custom_field_data[self.name])
  131. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  132. def rename_object_data(self, old_name, new_name):
  133. """
  134. Called when a CustomField has been renamed. Updates all assigned object data.
  135. """
  136. for ct in self.content_types.all():
  137. model = ct.model_class()
  138. params = {f'custom_field_data__{old_name}__isnull': False}
  139. instances = model.objects.filter(**params)
  140. for instance in instances:
  141. instance.custom_field_data[new_name] = instance.custom_field_data.pop(old_name)
  142. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  143. def clean(self):
  144. super().clean()
  145. # Validate the field's default value (if any)
  146. if self.default is not None:
  147. try:
  148. default_value = str(self.default) if self.type == CustomFieldTypeChoices.TYPE_TEXT else self.default
  149. self.validate(default_value)
  150. except ValidationError as err:
  151. raise ValidationError({
  152. 'default': f'Invalid default value "{self.default}": {err.message}'
  153. })
  154. # Minimum/maximum values can be set only for numeric fields
  155. if self.validation_minimum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  156. raise ValidationError({
  157. 'validation_minimum': "A minimum value may be set only for numeric fields"
  158. })
  159. if self.validation_maximum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  160. raise ValidationError({
  161. 'validation_maximum': "A maximum value may be set only for numeric fields"
  162. })
  163. # Regex validation can be set only for text fields
  164. regex_types = (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_URL)
  165. if self.validation_regex and self.type not in regex_types:
  166. raise ValidationError({
  167. 'validation_regex': "Regular expression validation is supported only for text and URL fields"
  168. })
  169. # Choices can be set only on selection fields
  170. if self.choices and self.type not in (
  171. CustomFieldTypeChoices.TYPE_SELECT,
  172. CustomFieldTypeChoices.TYPE_MULTISELECT
  173. ):
  174. raise ValidationError({
  175. 'choices': "Choices may be set only for custom selection fields."
  176. })
  177. # A selection field must have at least two choices defined
  178. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.choices and len(self.choices) < 2:
  179. raise ValidationError({
  180. 'choices': "Selection fields must specify at least two choices."
  181. })
  182. # A selection field's default (if any) must be present in its available choices
  183. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.default and self.default not in self.choices:
  184. raise ValidationError({
  185. 'default': f"The specified default value ({self.default}) is not listed as an available choice."
  186. })
  187. def to_form_field(self, set_initial=True, enforce_required=True, for_csv_import=False):
  188. """
  189. Return a form field suitable for setting a CustomField's value for an object.
  190. set_initial: Set initial date for the field. This should be False when generating a field for bulk editing.
  191. enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
  192. for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
  193. """
  194. initial = self.default if set_initial else None
  195. required = self.required if enforce_required else False
  196. # Integer
  197. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  198. field = forms.IntegerField(
  199. required=required,
  200. initial=initial,
  201. min_value=self.validation_minimum,
  202. max_value=self.validation_maximum
  203. )
  204. # Boolean
  205. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  206. choices = (
  207. (None, '---------'),
  208. (True, 'True'),
  209. (False, 'False'),
  210. )
  211. field = forms.NullBooleanField(
  212. required=required, initial=initial, widget=StaticSelect2(choices=choices)
  213. )
  214. # Date
  215. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  216. field = forms.DateField(required=required, initial=initial, widget=DatePicker())
  217. # Select
  218. elif self.type in (CustomFieldTypeChoices.TYPE_SELECT, CustomFieldTypeChoices.TYPE_MULTISELECT):
  219. choices = [(c, c) for c in self.choices]
  220. default_choice = self.default if self.default in self.choices else None
  221. if not required or default_choice is None:
  222. choices = add_blank_choice(choices)
  223. # Set the initial value to the first available choice (if any)
  224. if set_initial and default_choice:
  225. initial = default_choice
  226. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  227. field_class = CSVChoiceField if for_csv_import else forms.ChoiceField
  228. field = field_class(
  229. choices=choices, required=required, initial=initial, widget=StaticSelect2()
  230. )
  231. else:
  232. field_class = CSVChoiceField if for_csv_import else forms.MultipleChoiceField
  233. field = field_class(
  234. choices=choices, required=required, initial=initial, widget=StaticSelect2Multiple()
  235. )
  236. # URL
  237. elif self.type == CustomFieldTypeChoices.TYPE_URL:
  238. field = LaxURLField(required=required, initial=initial)
  239. # Text
  240. else:
  241. field = forms.CharField(max_length=255, required=required, initial=initial)
  242. if self.validation_regex:
  243. field.validators = [
  244. RegexValidator(
  245. regex=self.validation_regex,
  246. message=mark_safe(f"Values must match this regex: <code>{self.validation_regex}</code>")
  247. )
  248. ]
  249. field.model = self
  250. field.label = str(self)
  251. if self.description:
  252. field.help_text = self.description
  253. return field
  254. def validate(self, value):
  255. """
  256. Validate a value according to the field's type validation rules.
  257. """
  258. if value not in [None, '']:
  259. # Validate text field
  260. if self.type == CustomFieldTypeChoices.TYPE_TEXT:
  261. if type(value) is not str:
  262. raise ValidationError(f"Value must be a string.")
  263. if self.validation_regex and not re.match(self.validation_regex, value):
  264. raise ValidationError(f"Value must match regex '{self.validation_regex}'")
  265. # Validate integer
  266. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  267. if type(value) is not int:
  268. raise ValidationError("Value must be an integer.")
  269. if self.validation_minimum is not None and value < self.validation_minimum:
  270. raise ValidationError(f"Value must be at least {self.validation_minimum}")
  271. if self.validation_maximum is not None and value > self.validation_maximum:
  272. raise ValidationError(f"Value must not exceed {self.validation_maximum}")
  273. # Validate boolean
  274. if self.type == CustomFieldTypeChoices.TYPE_BOOLEAN and value not in [True, False, 1, 0]:
  275. raise ValidationError("Value must be true or false.")
  276. # Validate date
  277. if self.type == CustomFieldTypeChoices.TYPE_DATE:
  278. if type(value) is not date:
  279. try:
  280. datetime.strptime(value, '%Y-%m-%d')
  281. except ValueError:
  282. raise ValidationError("Date values must be in the format YYYY-MM-DD.")
  283. # Validate selected choice
  284. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  285. if value not in self.choices:
  286. raise ValidationError(
  287. f"Invalid choice ({value}). Available choices are: {', '.join(self.choices)}"
  288. )
  289. # Validate all selected choices
  290. if self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  291. if not set(value).issubset(self.choices):
  292. raise ValidationError(
  293. f"Invalid choice(s) ({', '.join(value)}). Available choices are: {', '.join(self.choices)}"
  294. )
  295. elif self.required:
  296. raise ValidationError("Required field cannot be empty.")