customfields.py 30 KB

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