customfields.py 29 KB

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