customfields.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 rename_object_data(self, old_name, new_name):
  111. """
  112. Called when a CustomField has been renamed. Updates all assigned object data.
  113. """
  114. for ct in self.content_types.all():
  115. model = ct.model_class()
  116. params = {f'custom_field_data__{old_name}__isnull': False}
  117. instances = model.objects.filter(**params)
  118. for instance in instances:
  119. instance.custom_field_data[new_name] = instance.custom_field_data.pop(old_name)
  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. for obj in model.objects.filter(**{f'custom_field_data__{self.name}__isnull': False}):
  129. del(obj.custom_field_data[self.name])
  130. obj.save()
  131. def clean(self):
  132. super().clean()
  133. # Validate the field's default value (if any)
  134. if self.default is not None:
  135. try:
  136. self.validate(self.default)
  137. except ValidationError as err:
  138. raise ValidationError({
  139. 'default': f'Invalid default value "{self.default}": {err.message}'
  140. })
  141. # Minimum/maximum values can be set only for numeric fields
  142. if self.validation_minimum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  143. raise ValidationError({
  144. 'validation_minimum': "A minimum value may be set only for numeric fields"
  145. })
  146. if self.validation_maximum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  147. raise ValidationError({
  148. 'validation_maximum': "A maximum value may be set only for numeric fields"
  149. })
  150. # Regex validation can be set only for text fields
  151. regex_types = (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_URL)
  152. if self.validation_regex and self.type not in regex_types:
  153. raise ValidationError({
  154. 'validation_regex': "Regular expression validation is supported only for text and URL fields"
  155. })
  156. # Choices can be set only on selection fields
  157. if self.choices and self.type not in (
  158. CustomFieldTypeChoices.TYPE_SELECT,
  159. CustomFieldTypeChoices.TYPE_MULTISELECT
  160. ):
  161. raise ValidationError({
  162. 'choices': "Choices may be set only for custom selection fields."
  163. })
  164. # A selection field must have at least two choices defined
  165. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.choices and len(self.choices) < 2:
  166. raise ValidationError({
  167. 'choices': "Selection fields must specify at least two choices."
  168. })
  169. # A selection field's default (if any) must be present in its available choices
  170. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.default and self.default not in self.choices:
  171. raise ValidationError({
  172. 'default': f"The specified default value ({self.default}) is not listed as an available choice."
  173. })
  174. def to_form_field(self, set_initial=True, enforce_required=True, for_csv_import=False):
  175. """
  176. Return a form field suitable for setting a CustomField's value for an object.
  177. set_initial: Set initial date for the field. This should be False when generating a field for bulk editing.
  178. enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
  179. for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
  180. """
  181. initial = self.default if set_initial else None
  182. required = self.required if enforce_required else False
  183. # Integer
  184. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  185. field = forms.IntegerField(
  186. required=required,
  187. initial=initial,
  188. min_value=self.validation_minimum,
  189. max_value=self.validation_maximum
  190. )
  191. # Boolean
  192. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  193. choices = (
  194. (None, '---------'),
  195. (True, 'True'),
  196. (False, 'False'),
  197. )
  198. field = forms.NullBooleanField(
  199. required=required, initial=initial, widget=StaticSelect2(choices=choices)
  200. )
  201. # Date
  202. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  203. field = forms.DateField(required=required, initial=initial, widget=DatePicker())
  204. # Select
  205. elif self.type in (CustomFieldTypeChoices.TYPE_SELECT, CustomFieldTypeChoices.TYPE_MULTISELECT):
  206. choices = [(c, c) for c in self.choices]
  207. default_choice = self.default if self.default in self.choices else None
  208. if not required or default_choice is None:
  209. choices = add_blank_choice(choices)
  210. # Set the initial value to the first available choice (if any)
  211. if set_initial and default_choice:
  212. initial = default_choice
  213. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  214. field_class = CSVChoiceField if for_csv_import else forms.ChoiceField
  215. field = field_class(
  216. choices=choices, required=required, initial=initial, widget=StaticSelect2()
  217. )
  218. else:
  219. field_class = CSVChoiceField if for_csv_import else forms.MultipleChoiceField
  220. field = field_class(
  221. choices=choices, required=required, initial=initial, widget=StaticSelect2Multiple()
  222. )
  223. # URL
  224. elif self.type == CustomFieldTypeChoices.TYPE_URL:
  225. field = LaxURLField(required=required, initial=initial)
  226. # Text
  227. else:
  228. field = forms.CharField(max_length=255, required=required, initial=initial)
  229. if self.validation_regex:
  230. field.validators = [
  231. RegexValidator(
  232. regex=self.validation_regex,
  233. message=mark_safe(f"Values must match this regex: <code>{self.validation_regex}</code>")
  234. )
  235. ]
  236. field.model = self
  237. field.label = str(self)
  238. if self.description:
  239. field.help_text = self.description
  240. return field
  241. def validate(self, value):
  242. """
  243. Validate a value according to the field's type validation rules.
  244. """
  245. if value not in [None, '']:
  246. # Validate text field
  247. if self.type == CustomFieldTypeChoices.TYPE_TEXT and self.validation_regex:
  248. if not re.match(self.validation_regex, value):
  249. raise ValidationError(f"Value must match regex '{self.validation_regex}'")
  250. # Validate integer
  251. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  252. try:
  253. int(value)
  254. except ValueError:
  255. raise ValidationError("Value must be an integer.")
  256. if self.validation_minimum is not None and value < self.validation_minimum:
  257. raise ValidationError(f"Value must be at least {self.validation_minimum}")
  258. if self.validation_maximum is not None and value > self.validation_maximum:
  259. raise ValidationError(f"Value must not exceed {self.validation_maximum}")
  260. # Validate boolean
  261. if self.type == CustomFieldTypeChoices.TYPE_BOOLEAN and value not in [True, False, 1, 0]:
  262. raise ValidationError("Value must be true or false.")
  263. # Validate date
  264. if self.type == CustomFieldTypeChoices.TYPE_DATE:
  265. if type(value) is not date:
  266. try:
  267. datetime.strptime(value, '%Y-%m-%d')
  268. except ValueError:
  269. raise ValidationError("Date values must be in the format YYYY-MM-DD.")
  270. # Validate selected choice
  271. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  272. if value not in self.choices:
  273. raise ValidationError(
  274. f"Invalid choice ({value}). Available choices are: {', '.join(self.choices)}"
  275. )
  276. # Validate all selected choices
  277. if self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  278. if not set(value).issubset(self.choices):
  279. raise ValidationError(
  280. f"Invalid choice(s) ({', '.join(value)}). Available choices are: {', '.join(self.choices)}"
  281. )
  282. elif self.required:
  283. raise ValidationError("Required field cannot be empty.")