customfields.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. import decimal
  2. import json
  3. import re
  4. from datetime import datetime, date
  5. import django_filters
  6. from django import forms
  7. from django.conf import settings
  8. from django.contrib.postgres.fields import ArrayField
  9. from django.core.validators import RegexValidator, ValidationError
  10. from django.db import models
  11. from django.urls import reverse
  12. from django.utils.html import escape
  13. from django.utils.safestring import mark_safe
  14. from django.utils.translation import gettext_lazy as _
  15. from core.models import ObjectType
  16. from extras.choices import *
  17. from extras.data import CHOICE_SETS
  18. from netbox.models import ChangeLoggedModel
  19. from netbox.models.features import CloningMixin, ExportTemplatesMixin
  20. from netbox.search import FieldTypes
  21. from utilities import filters
  22. from utilities.forms.fields import (
  23. CSVChoiceField, CSVModelChoiceField, CSVModelMultipleChoiceField, CSVMultipleChoiceField, DynamicChoiceField,
  24. DynamicModelChoiceField, DynamicModelMultipleChoiceField, DynamicMultipleChoiceField, JSONField, LaxURLField,
  25. )
  26. from utilities.forms.utils import add_blank_choice
  27. from utilities.forms.widgets import APISelect, APISelectMultiple, DatePicker, DateTimePicker
  28. from utilities.querysets import RestrictedQuerySet
  29. from utilities.templatetags.builtins.filters import render_markdown
  30. from utilities.validators import validate_regex
  31. __all__ = (
  32. 'CustomField',
  33. 'CustomFieldChoiceSet',
  34. 'CustomFieldManager',
  35. )
  36. SEARCH_TYPES = {
  37. CustomFieldTypeChoices.TYPE_TEXT: FieldTypes.STRING,
  38. CustomFieldTypeChoices.TYPE_LONGTEXT: FieldTypes.STRING,
  39. CustomFieldTypeChoices.TYPE_INTEGER: FieldTypes.INTEGER,
  40. CustomFieldTypeChoices.TYPE_DECIMAL: FieldTypes.FLOAT,
  41. CustomFieldTypeChoices.TYPE_DATE: FieldTypes.STRING,
  42. CustomFieldTypeChoices.TYPE_URL: FieldTypes.STRING,
  43. }
  44. class CustomFieldManager(models.Manager.from_queryset(RestrictedQuerySet)):
  45. use_in_migrations = True
  46. def get_for_model(self, model):
  47. """
  48. Return all CustomFields assigned to the given model.
  49. """
  50. content_type = ObjectType.objects.get_for_model(model._meta.concrete_model)
  51. return self.get_queryset().filter(object_types=content_type)
  52. def get_defaults_for_model(self, model):
  53. """
  54. Return a dictionary of serialized default values for all CustomFields applicable to the given model.
  55. """
  56. custom_fields = self.get_for_model(model).filter(default__isnull=False)
  57. return {
  58. cf.name: cf.default for cf in custom_fields
  59. }
  60. class CustomField(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  61. object_types = models.ManyToManyField(
  62. to='core.ObjectType',
  63. related_name='custom_fields',
  64. help_text=_('The object(s) to which this field applies.')
  65. )
  66. type = models.CharField(
  67. verbose_name=_('type'),
  68. max_length=50,
  69. choices=CustomFieldTypeChoices,
  70. default=CustomFieldTypeChoices.TYPE_TEXT,
  71. help_text=_('The type of data this custom field holds')
  72. )
  73. related_object_type = models.ForeignKey(
  74. to='core.ObjectType',
  75. on_delete=models.PROTECT,
  76. blank=True,
  77. null=True,
  78. help_text=_('The type of NetBox object this field maps to (for object fields)')
  79. )
  80. name = models.CharField(
  81. verbose_name=_('name'),
  82. max_length=50,
  83. unique=True,
  84. help_text=_('Internal field name'),
  85. validators=(
  86. RegexValidator(
  87. regex=r'^[a-z0-9_]+$',
  88. message=_("Only alphanumeric characters and underscores are allowed."),
  89. flags=re.IGNORECASE
  90. ),
  91. RegexValidator(
  92. regex=r'__',
  93. message=_("Double underscores are not permitted in custom field names."),
  94. flags=re.IGNORECASE,
  95. inverse_match=True
  96. ),
  97. )
  98. )
  99. label = models.CharField(
  100. verbose_name=_('label'),
  101. max_length=50,
  102. blank=True,
  103. help_text=_(
  104. "Name of the field as displayed to users (if not provided, 'the field's name will be used)"
  105. )
  106. )
  107. group_name = models.CharField(
  108. verbose_name=_('group name'),
  109. max_length=50,
  110. blank=True,
  111. help_text=_("Custom fields within the same group will be displayed together")
  112. )
  113. description = models.CharField(
  114. verbose_name=_('description'),
  115. max_length=200,
  116. blank=True
  117. )
  118. required = models.BooleanField(
  119. verbose_name=_('required'),
  120. default=False,
  121. help_text=_("If true, this field is required when creating new objects or editing an existing object.")
  122. )
  123. search_weight = models.PositiveSmallIntegerField(
  124. verbose_name=_('search weight'),
  125. default=1000,
  126. help_text=_(
  127. "Weighting for search. Lower values are considered more important. Fields with a search weight of zero "
  128. "will be ignored."
  129. )
  130. )
  131. filter_logic = models.CharField(
  132. verbose_name=_('filter logic'),
  133. max_length=50,
  134. choices=CustomFieldFilterLogicChoices,
  135. default=CustomFieldFilterLogicChoices.FILTER_LOOSE,
  136. help_text=_("Loose matches any instance of a given string; exact matches the entire field.")
  137. )
  138. default = models.JSONField(
  139. verbose_name=_('default'),
  140. blank=True,
  141. null=True,
  142. help_text=_(
  143. 'Default value for the field (must be a JSON value). Encapsulate strings with double quotes (e.g. "Foo").'
  144. )
  145. )
  146. weight = models.PositiveSmallIntegerField(
  147. default=100,
  148. verbose_name=_('display weight'),
  149. help_text=_('Fields with higher weights appear lower in a form.')
  150. )
  151. validation_minimum = models.BigIntegerField(
  152. blank=True,
  153. null=True,
  154. verbose_name=_('minimum value'),
  155. help_text=_('Minimum allowed value (for numeric fields)')
  156. )
  157. validation_maximum = models.BigIntegerField(
  158. blank=True,
  159. null=True,
  160. verbose_name=_('maximum value'),
  161. help_text=_('Maximum allowed value (for numeric fields)')
  162. )
  163. validation_regex = models.CharField(
  164. blank=True,
  165. validators=[validate_regex],
  166. max_length=500,
  167. verbose_name=_('validation regex'),
  168. help_text=_(
  169. 'Regular expression to enforce on text field values. Use ^ and $ to force matching of entire string. For '
  170. 'example, <code>^[A-Z]{3}$</code> will limit values to exactly three uppercase letters.'
  171. )
  172. )
  173. choice_set = models.ForeignKey(
  174. to='CustomFieldChoiceSet',
  175. on_delete=models.PROTECT,
  176. related_name='choices_for',
  177. verbose_name=_('choice set'),
  178. blank=True,
  179. null=True
  180. )
  181. ui_visible = models.CharField(
  182. max_length=50,
  183. choices=CustomFieldUIVisibleChoices,
  184. default=CustomFieldUIVisibleChoices.ALWAYS,
  185. verbose_name=_('UI visible'),
  186. help_text=_('Specifies whether the custom field is displayed in the UI')
  187. )
  188. ui_editable = models.CharField(
  189. max_length=50,
  190. choices=CustomFieldUIEditableChoices,
  191. default=CustomFieldUIEditableChoices.YES,
  192. verbose_name=_('UI editable'),
  193. help_text=_('Specifies whether the custom field value can be edited in the UI')
  194. )
  195. is_cloneable = models.BooleanField(
  196. default=False,
  197. verbose_name=_('is cloneable'),
  198. help_text=_('Replicate this value when cloning objects')
  199. )
  200. comments = models.TextField(
  201. verbose_name=_('comments'),
  202. blank=True
  203. )
  204. objects = CustomFieldManager()
  205. clone_fields = (
  206. 'object_types', 'type', 'related_object_type', 'group_name', 'description', 'required', 'search_weight',
  207. 'filter_logic', 'default', 'weight', 'validation_minimum', 'validation_maximum', 'validation_regex',
  208. 'choice_set', 'ui_visible', 'ui_editable', 'is_cloneable',
  209. )
  210. class Meta:
  211. ordering = ['group_name', 'weight', 'name']
  212. verbose_name = _('custom field')
  213. verbose_name_plural = _('custom fields')
  214. def __str__(self):
  215. return self.label or self.name.replace('_', ' ').capitalize()
  216. def get_absolute_url(self):
  217. return reverse('extras:customfield', args=[self.pk])
  218. @property
  219. def docs_url(self):
  220. return f'{settings.STATIC_URL}docs/models/extras/customfield/'
  221. def __init__(self, *args, **kwargs):
  222. super().__init__(*args, **kwargs)
  223. # Cache instance's original name so we can check later whether it has changed
  224. self._name = self.__dict__.get('name')
  225. @property
  226. def search_type(self):
  227. return SEARCH_TYPES.get(self.type)
  228. @property
  229. def choices(self):
  230. if self.choice_set:
  231. return self.choice_set.choices
  232. return []
  233. def get_ui_visible_color(self):
  234. return CustomFieldUIVisibleChoices.colors.get(self.ui_visible)
  235. def get_ui_editable_color(self):
  236. return CustomFieldUIEditableChoices.colors.get(self.ui_editable)
  237. def get_choice_label(self, value):
  238. if not hasattr(self, '_choice_map'):
  239. self._choice_map = dict(self.choices)
  240. return self._choice_map.get(value, value)
  241. def populate_initial_data(self, content_types):
  242. """
  243. Populate initial custom field data upon either a) the creation of a new CustomField, or
  244. b) the assignment of an existing CustomField to new object types.
  245. """
  246. for ct in content_types:
  247. model = ct.model_class()
  248. instances = model.objects.exclude(**{f'custom_field_data__contains': self.name})
  249. for instance in instances:
  250. instance.custom_field_data[self.name] = self.default
  251. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  252. def remove_stale_data(self, content_types):
  253. """
  254. Delete custom field data which is no longer relevant (either because the CustomField is
  255. no longer assigned to a model, or because it has been deleted).
  256. """
  257. for ct in content_types:
  258. model = ct.model_class()
  259. instances = model.objects.filter(custom_field_data__has_key=self.name)
  260. for instance in instances:
  261. del instance.custom_field_data[self.name]
  262. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  263. def rename_object_data(self, old_name, new_name):
  264. """
  265. Called when a CustomField has been renamed. Updates all assigned object data.
  266. """
  267. for ct in self.object_types.all():
  268. model = ct.model_class()
  269. params = {f'custom_field_data__{old_name}__isnull': False}
  270. instances = model.objects.filter(**params)
  271. for instance in instances:
  272. instance.custom_field_data[new_name] = instance.custom_field_data.pop(old_name)
  273. model.objects.bulk_update(instances, ['custom_field_data'], batch_size=100)
  274. def clean(self):
  275. super().clean()
  276. # Validate the field's default value (if any)
  277. if self.default is not None:
  278. try:
  279. if self.type in (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_LONGTEXT):
  280. default_value = str(self.default)
  281. else:
  282. default_value = self.default
  283. self.validate(default_value)
  284. except ValidationError as err:
  285. raise ValidationError({
  286. 'default': _(
  287. 'Invalid default value "{value}": {error}'
  288. ).format(value=self.default, error=err.message)
  289. })
  290. # Minimum/maximum values can be set only for numeric fields
  291. if self.type not in (CustomFieldTypeChoices.TYPE_INTEGER, CustomFieldTypeChoices.TYPE_DECIMAL):
  292. if self.validation_minimum:
  293. raise ValidationError({'validation_minimum': _("A minimum value may be set only for numeric fields")})
  294. if self.validation_maximum:
  295. raise ValidationError({'validation_maximum': _("A maximum value may be set only for numeric fields")})
  296. # Regex validation can be set only for text fields
  297. regex_types = (
  298. CustomFieldTypeChoices.TYPE_TEXT,
  299. CustomFieldTypeChoices.TYPE_LONGTEXT,
  300. CustomFieldTypeChoices.TYPE_URL,
  301. )
  302. if self.validation_regex and self.type not in regex_types:
  303. raise ValidationError({
  304. 'validation_regex': _("Regular expression validation is supported only for text and URL fields")
  305. })
  306. # Choice set must be set on selection fields, and *only* on selection fields
  307. if self.type in (
  308. CustomFieldTypeChoices.TYPE_SELECT,
  309. CustomFieldTypeChoices.TYPE_MULTISELECT
  310. ):
  311. if not self.choice_set:
  312. raise ValidationError({
  313. 'choice_set': _("Selection fields must specify a set of choices.")
  314. })
  315. elif self.choice_set:
  316. raise ValidationError({
  317. 'choice_set': _("Choices may be set only on selection fields.")
  318. })
  319. # Object fields must define an object_type; other fields must not
  320. if self.type in (CustomFieldTypeChoices.TYPE_OBJECT, CustomFieldTypeChoices.TYPE_MULTIOBJECT):
  321. if not self.related_object_type:
  322. raise ValidationError({
  323. 'object_type': _("Object fields must define an object type.")
  324. })
  325. elif self.related_object_type:
  326. raise ValidationError({
  327. 'object_type': _(
  328. "{type} fields may not define an object type.")
  329. .format(type=self.get_type_display())
  330. })
  331. def serialize(self, value):
  332. """
  333. Prepare a value for storage as JSON data.
  334. """
  335. if value is None:
  336. return value
  337. if self.type == CustomFieldTypeChoices.TYPE_DATE and type(value) is date:
  338. return value.isoformat()
  339. if self.type == CustomFieldTypeChoices.TYPE_DATETIME and type(value) is datetime:
  340. return value.isoformat()
  341. if self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  342. return value.pk
  343. if self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  344. return [obj.pk for obj in value] or None
  345. return value
  346. def deserialize(self, value):
  347. """
  348. Convert JSON data to a Python object suitable for the field type.
  349. """
  350. if value is None:
  351. return value
  352. if self.type == CustomFieldTypeChoices.TYPE_DATE:
  353. try:
  354. return date.fromisoformat(value)
  355. except ValueError:
  356. return value
  357. if self.type == CustomFieldTypeChoices.TYPE_DATETIME:
  358. try:
  359. return datetime.fromisoformat(value)
  360. except ValueError:
  361. return value
  362. if self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  363. model = self.related_object_type.model_class()
  364. return model.objects.filter(pk=value).first()
  365. if self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  366. model = self.related_object_type.model_class()
  367. return model.objects.filter(pk__in=value)
  368. return value
  369. def to_form_field(self, set_initial=True, enforce_required=True, enforce_visibility=True, for_csv_import=False):
  370. """
  371. Return a form field suitable for setting a CustomField's value for an object.
  372. set_initial: Set initial data for the field. This should be False when generating a field for bulk editing.
  373. enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
  374. enforce_visibility: Honor the value of CustomField.ui_visible. Set to False for filtering.
  375. for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
  376. """
  377. initial = self.default if set_initial else None
  378. required = self.required if enforce_required else False
  379. # Integer
  380. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  381. field = forms.IntegerField(
  382. required=required,
  383. initial=initial,
  384. min_value=self.validation_minimum,
  385. max_value=self.validation_maximum
  386. )
  387. # Decimal
  388. elif self.type == CustomFieldTypeChoices.TYPE_DECIMAL:
  389. field = forms.DecimalField(
  390. required=required,
  391. initial=initial,
  392. max_digits=12,
  393. decimal_places=4,
  394. min_value=self.validation_minimum,
  395. max_value=self.validation_maximum
  396. )
  397. # Boolean
  398. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  399. choices = (
  400. (None, '---------'),
  401. (True, _('True')),
  402. (False, _('False')),
  403. )
  404. field = forms.NullBooleanField(
  405. required=required, initial=initial, widget=forms.Select(choices=choices)
  406. )
  407. # Date
  408. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  409. field = forms.DateField(required=required, initial=initial, widget=DatePicker())
  410. # Date & time
  411. elif self.type == CustomFieldTypeChoices.TYPE_DATETIME:
  412. field = forms.DateTimeField(required=required, initial=initial, widget=DateTimePicker())
  413. # Select
  414. elif self.type in (CustomFieldTypeChoices.TYPE_SELECT, CustomFieldTypeChoices.TYPE_MULTISELECT):
  415. choices = self.choice_set.choices
  416. default_choice = self.default if self.default in self.choices else None
  417. if not required or default_choice is None:
  418. choices = add_blank_choice(choices)
  419. # Set the initial value to the first available choice (if any)
  420. if set_initial and default_choice:
  421. initial = default_choice
  422. if for_csv_import:
  423. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  424. field_class = CSVChoiceField
  425. else:
  426. field_class = CSVMultipleChoiceField
  427. field = field_class(choices=choices, required=required, initial=initial)
  428. else:
  429. if self.type == CustomFieldTypeChoices.TYPE_SELECT:
  430. field_class = DynamicChoiceField
  431. widget_class = APISelect
  432. else:
  433. field_class = DynamicMultipleChoiceField
  434. widget_class = APISelectMultiple
  435. field = field_class(
  436. choices=choices,
  437. required=required,
  438. initial=initial,
  439. widget=widget_class(api_url=f'/api/extras/custom-field-choice-sets/{self.choice_set.pk}/choices/')
  440. )
  441. # URL
  442. elif self.type == CustomFieldTypeChoices.TYPE_URL:
  443. field = LaxURLField(required=required, initial=initial)
  444. # JSON
  445. elif self.type == CustomFieldTypeChoices.TYPE_JSON:
  446. field = JSONField(required=required, initial=json.dumps(initial) if initial else None)
  447. # Object
  448. elif self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  449. model = self.related_object_type.model_class()
  450. field_class = CSVModelChoiceField if for_csv_import else DynamicModelChoiceField
  451. field = field_class(
  452. queryset=model.objects.all(),
  453. required=required,
  454. initial=initial
  455. )
  456. # Multiple objects
  457. elif self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  458. model = self.related_object_type.model_class()
  459. field_class = CSVModelMultipleChoiceField if for_csv_import else DynamicModelMultipleChoiceField
  460. field = field_class(
  461. queryset=model.objects.all(),
  462. required=required,
  463. initial=initial,
  464. )
  465. # Text
  466. else:
  467. widget = forms.Textarea if self.type == CustomFieldTypeChoices.TYPE_LONGTEXT else None
  468. field = forms.CharField(required=required, initial=initial, widget=widget)
  469. if self.validation_regex:
  470. field.validators = [
  471. RegexValidator(
  472. regex=self.validation_regex,
  473. message=mark_safe(_("Values must match this regex: <code>{regex}</code>").format(
  474. regex=escape(self.validation_regex)
  475. ))
  476. )
  477. ]
  478. field.model = self
  479. field.label = str(self)
  480. if self.description:
  481. field.help_text = render_markdown(self.description)
  482. # Annotate read-only fields
  483. if enforce_visibility and self.ui_editable != CustomFieldUIEditableChoices.YES:
  484. field.disabled = True
  485. return field
  486. def to_filter(self, lookup_expr=None):
  487. """
  488. Return a django_filters Filter instance suitable for this field type.
  489. :param lookup_expr: Custom lookup expression (optional)
  490. """
  491. kwargs = {
  492. 'field_name': f'custom_field_data__{self.name}'
  493. }
  494. if lookup_expr is not None:
  495. kwargs['lookup_expr'] = lookup_expr
  496. # Text/URL
  497. if self.type in (
  498. CustomFieldTypeChoices.TYPE_TEXT,
  499. CustomFieldTypeChoices.TYPE_LONGTEXT,
  500. CustomFieldTypeChoices.TYPE_URL,
  501. ):
  502. filter_class = filters.MultiValueCharFilter
  503. if self.filter_logic == CustomFieldFilterLogicChoices.FILTER_LOOSE:
  504. kwargs['lookup_expr'] = 'icontains'
  505. # Integer
  506. elif self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  507. filter_class = filters.MultiValueNumberFilter
  508. # Decimal
  509. elif self.type == CustomFieldTypeChoices.TYPE_DECIMAL:
  510. filter_class = filters.MultiValueDecimalFilter
  511. # Boolean
  512. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  513. filter_class = django_filters.BooleanFilter
  514. # Date
  515. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  516. filter_class = filters.MultiValueDateFilter
  517. # Date & time
  518. elif self.type == CustomFieldTypeChoices.TYPE_DATETIME:
  519. filter_class = filters.MultiValueDateTimeFilter
  520. # Select
  521. elif self.type == CustomFieldTypeChoices.TYPE_SELECT:
  522. filter_class = filters.MultiValueCharFilter
  523. # Multiselect
  524. elif self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  525. filter_class = filters.MultiValueArrayFilter
  526. # Object
  527. elif self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  528. filter_class = filters.MultiValueNumberFilter
  529. # Multi-object
  530. elif self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  531. filter_class = filters.MultiValueNumberFilter
  532. kwargs['lookup_expr'] = 'contains'
  533. # Unsupported custom field type
  534. else:
  535. return None
  536. filter_instance = filter_class(**kwargs)
  537. filter_instance.custom_field = self
  538. return filter_instance
  539. def validate(self, value):
  540. """
  541. Validate a value according to the field's type validation rules.
  542. """
  543. if value not in [None, '']:
  544. # Validate text field
  545. if self.type in (CustomFieldTypeChoices.TYPE_TEXT, CustomFieldTypeChoices.TYPE_LONGTEXT):
  546. if type(value) is not str:
  547. raise ValidationError(_("Value must be a string."))
  548. if self.validation_regex and not re.match(self.validation_regex, value):
  549. raise ValidationError(_("Value must match regex '{regex}'").format(regex=self.validation_regex))
  550. # Validate integer
  551. elif self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  552. if type(value) is not int:
  553. raise ValidationError(_("Value must be an integer."))
  554. if self.validation_minimum is not None and value < self.validation_minimum:
  555. raise ValidationError(
  556. _("Value must be at least {minimum}").format(minimum=self.validation_maximum)
  557. )
  558. if self.validation_maximum is not None and value > self.validation_maximum:
  559. raise ValidationError(
  560. _("Value must not exceed {maximum}").format(maximum=self.validation_maximum)
  561. )
  562. # Validate decimal
  563. elif self.type == CustomFieldTypeChoices.TYPE_DECIMAL:
  564. try:
  565. decimal.Decimal(value)
  566. except decimal.InvalidOperation:
  567. raise ValidationError(_("Value must be a decimal."))
  568. if self.validation_minimum is not None and value < self.validation_minimum:
  569. raise ValidationError(
  570. _("Value must be at least {minimum}").format(minimum=self.validation_minimum)
  571. )
  572. if self.validation_maximum is not None and value > self.validation_maximum:
  573. raise ValidationError(
  574. _("Value must not exceed {maximum}").format(maximum=self.validation_maximum)
  575. )
  576. # Validate boolean
  577. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN and value not in [True, False, 1, 0]:
  578. raise ValidationError(_("Value must be true or false."))
  579. # Validate date
  580. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  581. if type(value) is not date:
  582. try:
  583. date.fromisoformat(value)
  584. except ValueError:
  585. raise ValidationError(_("Date values must be in ISO 8601 format (YYYY-MM-DD)."))
  586. # Validate date & time
  587. elif self.type == CustomFieldTypeChoices.TYPE_DATETIME:
  588. if type(value) is not datetime:
  589. # Work around UTC issue for Python < 3.11; see
  590. # https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat
  591. if type(value) is str and value.endswith('Z'):
  592. value = f'{value[:-1]}+00:00'
  593. try:
  594. datetime.fromisoformat(value)
  595. except ValueError:
  596. raise ValidationError(
  597. _("Date and time values must be in ISO 8601 format (YYYY-MM-DD HH:MM:SS).")
  598. )
  599. # Validate selected choice
  600. elif self.type == CustomFieldTypeChoices.TYPE_SELECT:
  601. if value not in self.choice_set.values:
  602. raise ValidationError(
  603. _("Invalid choice ({value}) for choice set {choiceset}.").format(
  604. value=value,
  605. choiceset=self.choice_set
  606. )
  607. )
  608. # Validate all selected choices
  609. elif self.type == CustomFieldTypeChoices.TYPE_MULTISELECT:
  610. if not set(value).issubset(self.choice_set.values):
  611. raise ValidationError(
  612. _("Invalid choice(s) ({value}) for choice set {choiceset}.").format(
  613. value=value,
  614. choiceset=self.choice_set
  615. )
  616. )
  617. # Validate selected object
  618. elif self.type == CustomFieldTypeChoices.TYPE_OBJECT:
  619. if type(value) is not int:
  620. raise ValidationError(_("Value must be an object ID, not {type}").format(type=type(value).__name__))
  621. # Validate selected objects
  622. elif self.type == CustomFieldTypeChoices.TYPE_MULTIOBJECT:
  623. if type(value) is not list:
  624. raise ValidationError(
  625. _("Value must be a list of object IDs, not {type}").format(type=type(value).__name__)
  626. )
  627. for id in value:
  628. if type(id) is not int:
  629. raise ValidationError(_("Found invalid object ID: {id}").format(id=id))
  630. elif self.required:
  631. raise ValidationError(_("Required field cannot be empty."))
  632. class CustomFieldChoiceSet(CloningMixin, ExportTemplatesMixin, ChangeLoggedModel):
  633. """
  634. Represents a set of choices available for choice and multi-choice custom fields.
  635. """
  636. name = models.CharField(
  637. max_length=100,
  638. unique=True
  639. )
  640. description = models.CharField(
  641. max_length=200,
  642. blank=True
  643. )
  644. base_choices = models.CharField(
  645. max_length=50,
  646. choices=CustomFieldChoiceSetBaseChoices,
  647. blank=True,
  648. help_text=_('Base set of predefined choices (optional)')
  649. )
  650. extra_choices = ArrayField(
  651. ArrayField(
  652. base_field=models.CharField(max_length=100),
  653. size=2
  654. ),
  655. blank=True,
  656. null=True
  657. )
  658. order_alphabetically = models.BooleanField(
  659. default=False,
  660. help_text=_('Choices are automatically ordered alphabetically')
  661. )
  662. clone_fields = ('extra_choices', 'order_alphabetically')
  663. class Meta:
  664. ordering = ('name',)
  665. verbose_name = _('custom field choice set')
  666. verbose_name_plural = _('custom field choice sets')
  667. def __str__(self):
  668. return self.name
  669. def get_absolute_url(self):
  670. return reverse('extras:customfieldchoiceset', args=[self.pk])
  671. @property
  672. def choices(self):
  673. """
  674. Returns a concatenation of the base and extra choices.
  675. """
  676. if not hasattr(self, '_choices'):
  677. self._choices = []
  678. if self.base_choices:
  679. self._choices.extend(CHOICE_SETS.get(self.base_choices))
  680. if self.extra_choices:
  681. self._choices.extend(self.extra_choices)
  682. if self.order_alphabetically:
  683. self._choices = sorted(self._choices, key=lambda x: x[0])
  684. return self._choices
  685. @property
  686. def choices_count(self):
  687. return len(self.choices)
  688. @property
  689. def values(self):
  690. """
  691. Returns an iterator of the valid choice values.
  692. """
  693. return (x[0] for x in self.choices)
  694. def clean(self):
  695. if not self.base_choices and not self.extra_choices:
  696. raise ValidationError(_("Must define base or extra choices."))
  697. def save(self, *args, **kwargs):
  698. # Sort choices if alphabetical ordering is enforced
  699. if self.order_alphabetically:
  700. self.extra_choices = sorted(self.extra_choices, key=lambda x: x[0])
  701. return super().save(*args, **kwargs)