customfields.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. from collections import OrderedDict
  2. from django import forms
  3. from django.contrib.contenttypes.models import ContentType
  4. from django.contrib.postgres.fields import ArrayField
  5. from django.core.serializers.json import DjangoJSONEncoder
  6. from django.core.validators import RegexValidator, ValidationError
  7. from django.db import models
  8. from django.utils.safestring import mark_safe
  9. from utilities.forms import CSVChoiceField, DatePicker, LaxURLField, StaticSelect2, add_blank_choice
  10. from utilities.validators import validate_regex
  11. from extras.choices import *
  12. from extras.utils import FeatureQuery
  13. class CustomFieldModel(models.Model):
  14. """
  15. Abstract class for any model which may have custom fields associated with it.
  16. """
  17. custom_field_data = models.JSONField(
  18. encoder=DjangoJSONEncoder,
  19. blank=True,
  20. default=dict
  21. )
  22. class Meta:
  23. abstract = True
  24. @property
  25. def cf(self):
  26. """
  27. Convenience wrapper for custom field data.
  28. """
  29. return self.custom_field_data
  30. def get_custom_fields(self):
  31. """
  32. Return a dictionary of custom fields for a single object in the form {<field>: value}.
  33. """
  34. fields = CustomField.objects.get_for_model(self)
  35. return OrderedDict([
  36. (field, self.custom_field_data.get(field.name)) for field in fields
  37. ])
  38. class CustomFieldManager(models.Manager):
  39. use_in_migrations = True
  40. def get_for_model(self, model):
  41. """
  42. Return all CustomFields assigned to the given model.
  43. """
  44. content_type = ContentType.objects.get_for_model(model._meta.concrete_model)
  45. return self.get_queryset().filter(content_types=content_type)
  46. class CustomField(models.Model):
  47. content_types = models.ManyToManyField(
  48. to=ContentType,
  49. related_name='custom_fields',
  50. verbose_name='Object(s)',
  51. limit_choices_to=FeatureQuery('custom_fields'),
  52. help_text='The object(s) to which this field applies.'
  53. )
  54. type = models.CharField(
  55. max_length=50,
  56. choices=CustomFieldTypeChoices,
  57. default=CustomFieldTypeChoices.TYPE_TEXT
  58. )
  59. name = models.CharField(
  60. max_length=50,
  61. unique=True,
  62. help_text='Internal field name'
  63. )
  64. label = models.CharField(
  65. max_length=50,
  66. blank=True,
  67. help_text='Name of the field as displayed to users (if not provided, '
  68. 'the field\'s name will be used)'
  69. )
  70. description = models.CharField(
  71. max_length=200,
  72. blank=True
  73. )
  74. required = models.BooleanField(
  75. default=False,
  76. help_text='If true, this field is required when creating new objects '
  77. 'or editing an existing object.'
  78. )
  79. filter_logic = models.CharField(
  80. max_length=50,
  81. choices=CustomFieldFilterLogicChoices,
  82. default=CustomFieldFilterLogicChoices.FILTER_LOOSE,
  83. help_text='Loose matches any instance of a given string; exact '
  84. 'matches the entire field.'
  85. )
  86. default = models.CharField(
  87. max_length=100,
  88. blank=True,
  89. help_text='Default value for the field. Use "true" or "false" for booleans.'
  90. )
  91. weight = models.PositiveSmallIntegerField(
  92. default=100,
  93. help_text='Fields with higher weights appear lower in a form.'
  94. )
  95. validation_minimum = models.PositiveIntegerField(
  96. blank=True,
  97. null=True,
  98. verbose_name='Minimum value',
  99. help_text='Minimum allowed value (for numeric fields)'
  100. )
  101. validation_maximum = models.PositiveIntegerField(
  102. blank=True,
  103. null=True,
  104. verbose_name='Maximum value',
  105. help_text='Maximum allowed value (for numeric fields)'
  106. )
  107. validation_regex = models.CharField(
  108. blank=True,
  109. validators=[validate_regex],
  110. max_length=500,
  111. verbose_name='Validation regex',
  112. help_text='Regular expression to enforce on text field values. Use ^ and $ to force matching of entire string. '
  113. 'For example, <code>^[A-Z]{3}$</code> will limit values to exactly three uppercase letters.'
  114. )
  115. choices = ArrayField(
  116. base_field=models.CharField(max_length=100),
  117. blank=True,
  118. null=True,
  119. help_text='Comma-separated list of available choices (for selection fields)'
  120. )
  121. objects = CustomFieldManager()
  122. class Meta:
  123. ordering = ['weight', 'name']
  124. def __str__(self):
  125. return self.label or self.name.replace('_', ' ').capitalize()
  126. def remove_stale_data(self, content_types):
  127. """
  128. Delete custom field data which is no longer relevant (either because the CustomField is
  129. no longer assigned to a model, or because it has been deleted).
  130. """
  131. for ct in content_types:
  132. model = ct.model_class()
  133. for obj in model.objects.filter(**{f'custom_field_data__{self.name}__isnull': False}):
  134. del(obj.custom_field_data[self.name])
  135. obj.save()
  136. def clean(self):
  137. # Minimum/maximum values can be set only for numeric fields
  138. if self.validation_minimum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  139. raise ValidationError({
  140. 'validation_minimum': "A minimum value may be set only for numeric fields"
  141. })
  142. if self.validation_maximum is not None and self.type != CustomFieldTypeChoices.TYPE_INTEGER:
  143. raise ValidationError({
  144. 'validation_maximum': "A maximum value may be set only for numeric fields"
  145. })
  146. # Regex validation can be set only for text fields
  147. if self.validation_regex and self.type != CustomFieldTypeChoices.TYPE_TEXT:
  148. raise ValidationError({
  149. 'validation_regex': "Regular expression validation is supported only for text and URL fields"
  150. })
  151. # Choices can be set only on selection fields
  152. if self.choices and self.type != CustomFieldTypeChoices.TYPE_SELECT:
  153. raise ValidationError({
  154. 'choices': "Choices may be set only for custom selection fields."
  155. })
  156. # A selection field must have at least two choices defined
  157. if self.type == CustomFieldTypeChoices.TYPE_SELECT and len(self.choices) < 2:
  158. raise ValidationError({
  159. 'choices': "Selection fields must specify at least two choices."
  160. })
  161. # A selection field's default (if any) must be present in its available choices
  162. if self.type == CustomFieldTypeChoices.TYPE_SELECT and self.default and self.default not in self.choices:
  163. raise ValidationError({
  164. 'default': f"The specified default value ({self.default}) is not listed as an available choice."
  165. })
  166. def to_form_field(self, set_initial=True, enforce_required=True, for_csv_import=False):
  167. """
  168. Return a form field suitable for setting a CustomField's value for an object.
  169. set_initial: Set initial date for the field. This should be False when generating a field for bulk editing.
  170. enforce_required: Honor the value of CustomField.required. Set to False for filtering/bulk editing.
  171. for_csv_import: Return a form field suitable for bulk import of objects in CSV format.
  172. """
  173. initial = self.default if set_initial else None
  174. required = self.required if enforce_required else False
  175. # Integer
  176. if self.type == CustomFieldTypeChoices.TYPE_INTEGER:
  177. field = forms.IntegerField(
  178. required=required,
  179. initial=initial,
  180. min_value=self.validation_minimum,
  181. max_value=self.validation_maximum
  182. )
  183. # Boolean
  184. elif self.type == CustomFieldTypeChoices.TYPE_BOOLEAN:
  185. choices = (
  186. (None, '---------'),
  187. (True, 'True'),
  188. (False, 'False'),
  189. )
  190. if initial is not None:
  191. initial = bool(initial)
  192. field = forms.NullBooleanField(
  193. required=required, initial=initial, widget=StaticSelect2(choices=choices)
  194. )
  195. # Date
  196. elif self.type == CustomFieldTypeChoices.TYPE_DATE:
  197. field = forms.DateField(required=required, initial=initial, widget=DatePicker())
  198. # Select
  199. elif self.type == CustomFieldTypeChoices.TYPE_SELECT:
  200. choices = [(c, c) for c in self.choices]
  201. default_choice = self.default if self.default in self.choices else None
  202. if not required or default_choice is None:
  203. choices = add_blank_choice(choices)
  204. # Set the initial value to the first available choice (if any)
  205. if set_initial and default_choice:
  206. initial = default_choice
  207. field_class = CSVChoiceField if for_csv_import else forms.ChoiceField
  208. field = field_class(
  209. choices=choices, required=required, initial=initial, widget=StaticSelect2()
  210. )
  211. # URL
  212. elif self.type == CustomFieldTypeChoices.TYPE_URL:
  213. field = LaxURLField(required=required, initial=initial)
  214. # Text
  215. else:
  216. field = forms.CharField(max_length=255, required=required, initial=initial)
  217. if self.validation_regex:
  218. field.validators = [
  219. RegexValidator(
  220. regex=self.validation_regex,
  221. message=mark_safe(f"Values must match this regex: <code>{self.validation_regex}</code>")
  222. )
  223. ]
  224. field.model = self
  225. field.label = str(self)
  226. if self.description:
  227. field.help_text = self.description
  228. return field