customfields.py 30 KB

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