customfields.py 35 KB

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