customfields.py 32 KB

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