validators.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. """
  2. We perform uniqueness checks explicitly on the serializer class, rather
  3. the using Django's `.full_clean()`.
  4. This gives us better separation of concerns, allows us to use single-step
  5. object creation, and makes it possible to switch between using the implicit
  6. `ModelSerializer` class and an equivalent explicit `Serializer` class.
  7. """
  8. from django.db import DataError
  9. from django.utils.translation import gettext_lazy as _
  10. from rest_framework.exceptions import ValidationError
  11. from rest_framework.utils.representation import smart_repr
  12. # Robust filter and exist implementations. Ensures that queryset.exists() for
  13. # an invalid value returns `False`, rather than raising an error.
  14. # Refs https://github.com/encode/django-rest-framework/issues/3381
  15. def qs_exists(queryset):
  16. try:
  17. return queryset.exists()
  18. except (TypeError, ValueError, DataError):
  19. return False
  20. def qs_filter(queryset, **kwargs):
  21. try:
  22. return queryset.filter(**kwargs)
  23. except (TypeError, ValueError, DataError):
  24. return queryset.none()
  25. class UniqueValidator:
  26. """
  27. Validator that corresponds to `unique=True` on a model field.
  28. Should be applied to an individual field on the serializer.
  29. """
  30. message = _('This field must be unique.')
  31. requires_context = True
  32. def __init__(self, queryset, message=None, lookup='exact'):
  33. self.queryset = queryset
  34. self.message = message or self.message
  35. self.lookup = lookup
  36. def filter_queryset(self, value, queryset, field_name):
  37. """
  38. Filter the queryset to all instances matching the given attribute.
  39. """
  40. filter_kwargs = {'%s__%s' % (field_name, self.lookup): value}
  41. return qs_filter(queryset, **filter_kwargs)
  42. def exclude_current_instance(self, queryset, instance):
  43. """
  44. If an instance is being updated, then do not include
  45. that instance itself as a uniqueness conflict.
  46. """
  47. if instance is not None:
  48. return queryset.exclude(pk=instance.pk)
  49. return queryset
  50. def __call__(self, value, serializer_field):
  51. # Determine the underlying model field name. This may not be the
  52. # same as the serializer field name if `source=<>` is set.
  53. field_name = serializer_field.source_attrs[-1]
  54. # Determine the existing instance, if this is an update operation.
  55. instance = getattr(serializer_field.parent, 'instance', None)
  56. queryset = self.queryset
  57. queryset = self.filter_queryset(value, queryset, field_name)
  58. queryset = self.exclude_current_instance(queryset, instance)
  59. if qs_exists(queryset):
  60. raise ValidationError(self.message, code='unique')
  61. def __repr__(self):
  62. return '<%s(queryset=%s)>' % (
  63. self.__class__.__name__,
  64. smart_repr(self.queryset)
  65. )
  66. class UniqueTogetherValidator:
  67. """
  68. Validator that corresponds to `unique_together = (...)` on a model class.
  69. Should be applied to the serializer class, not to an individual field.
  70. """
  71. message = _('The fields {field_names} must make a unique set.')
  72. missing_message = _('This field is required.')
  73. requires_context = True
  74. def __init__(self, queryset, fields, message=None):
  75. self.queryset = queryset
  76. self.fields = fields
  77. self.message = message or self.message
  78. def enforce_required_fields(self, attrs, serializer):
  79. """
  80. The `UniqueTogetherValidator` always forces an implied 'required'
  81. state on the fields it applies to.
  82. """
  83. if serializer.instance is not None:
  84. return
  85. missing_items = {
  86. field_name: self.missing_message
  87. for field_name in self.fields
  88. if serializer.fields[field_name].source not in attrs
  89. }
  90. if missing_items:
  91. raise ValidationError(missing_items, code='required')
  92. def filter_queryset(self, attrs, queryset, serializer):
  93. """
  94. Filter the queryset to all instances matching the given attributes.
  95. """
  96. # field names => field sources
  97. sources = [
  98. serializer.fields[field_name].source
  99. for field_name in self.fields
  100. ]
  101. # If this is an update, then any unprovided field should
  102. # have it's value set based on the existing instance attribute.
  103. if serializer.instance is not None:
  104. for source in sources:
  105. if source not in attrs:
  106. attrs[source] = getattr(serializer.instance, source)
  107. # Determine the filter keyword arguments and filter the queryset.
  108. filter_kwargs = {
  109. source: attrs[source]
  110. for source in sources
  111. }
  112. return qs_filter(queryset, **filter_kwargs)
  113. def exclude_current_instance(self, attrs, queryset, instance):
  114. """
  115. If an instance is being updated, then do not include
  116. that instance itself as a uniqueness conflict.
  117. """
  118. if instance is not None:
  119. return queryset.exclude(pk=instance.pk)
  120. return queryset
  121. def __call__(self, attrs, serializer):
  122. self.enforce_required_fields(attrs, serializer)
  123. queryset = self.queryset
  124. queryset = self.filter_queryset(attrs, queryset, serializer)
  125. queryset = self.exclude_current_instance(attrs, queryset, serializer.instance)
  126. # Ignore validation if any field is None
  127. checked_values = [
  128. value for field, value in attrs.items() if field in self.fields
  129. ]
  130. if None not in checked_values and qs_exists(queryset):
  131. field_names = ', '.join(self.fields)
  132. message = self.message.format(field_names=field_names)
  133. raise ValidationError(message, code='unique')
  134. def __repr__(self):
  135. return '<%s(queryset=%s, fields=%s)>' % (
  136. self.__class__.__name__,
  137. smart_repr(self.queryset),
  138. smart_repr(self.fields)
  139. )
  140. class ProhibitSurrogateCharactersValidator:
  141. message = _('Surrogate characters are not allowed: U+{code_point:X}.')
  142. code = 'surrogate_characters_not_allowed'
  143. def __call__(self, value):
  144. for surrogate_character in (ch for ch in str(value)
  145. if 0xD800 <= ord(ch) <= 0xDFFF):
  146. message = self.message.format(code_point=ord(surrogate_character))
  147. raise ValidationError(message, code=self.code)
  148. class BaseUniqueForValidator:
  149. message = None
  150. missing_message = _('This field is required.')
  151. requires_context = True
  152. def __init__(self, queryset, field, date_field, message=None):
  153. self.queryset = queryset
  154. self.field = field
  155. self.date_field = date_field
  156. self.message = message or self.message
  157. def enforce_required_fields(self, attrs):
  158. """
  159. The `UniqueFor<Range>Validator` classes always force an implied
  160. 'required' state on the fields they are applied to.
  161. """
  162. missing_items = {
  163. field_name: self.missing_message
  164. for field_name in [self.field, self.date_field]
  165. if field_name not in attrs
  166. }
  167. if missing_items:
  168. raise ValidationError(missing_items, code='required')
  169. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  170. raise NotImplementedError('`filter_queryset` must be implemented.')
  171. def exclude_current_instance(self, attrs, queryset, instance):
  172. """
  173. If an instance is being updated, then do not include
  174. that instance itself as a uniqueness conflict.
  175. """
  176. if instance is not None:
  177. return queryset.exclude(pk=instance.pk)
  178. return queryset
  179. def __call__(self, attrs, serializer):
  180. # Determine the underlying model field names. These may not be the
  181. # same as the serializer field names if `source=<>` is set.
  182. field_name = serializer.fields[self.field].source_attrs[-1]
  183. date_field_name = serializer.fields[self.date_field].source_attrs[-1]
  184. self.enforce_required_fields(attrs)
  185. queryset = self.queryset
  186. queryset = self.filter_queryset(attrs, queryset, field_name, date_field_name)
  187. queryset = self.exclude_current_instance(attrs, queryset, serializer.instance)
  188. if qs_exists(queryset):
  189. message = self.message.format(date_field=self.date_field)
  190. raise ValidationError({
  191. self.field: message
  192. }, code='unique')
  193. def __repr__(self):
  194. return '<%s(queryset=%s, field=%s, date_field=%s)>' % (
  195. self.__class__.__name__,
  196. smart_repr(self.queryset),
  197. smart_repr(self.field),
  198. smart_repr(self.date_field)
  199. )
  200. class UniqueForDateValidator(BaseUniqueForValidator):
  201. message = _('This field must be unique for the "{date_field}" date.')
  202. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  203. value = attrs[self.field]
  204. date = attrs[self.date_field]
  205. filter_kwargs = {}
  206. filter_kwargs[field_name] = value
  207. filter_kwargs['%s__day' % date_field_name] = date.day
  208. filter_kwargs['%s__month' % date_field_name] = date.month
  209. filter_kwargs['%s__year' % date_field_name] = date.year
  210. return qs_filter(queryset, **filter_kwargs)
  211. class UniqueForMonthValidator(BaseUniqueForValidator):
  212. message = _('This field must be unique for the "{date_field}" month.')
  213. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  214. value = attrs[self.field]
  215. date = attrs[self.date_field]
  216. filter_kwargs = {}
  217. filter_kwargs[field_name] = value
  218. filter_kwargs['%s__month' % date_field_name] = date.month
  219. return qs_filter(queryset, **filter_kwargs)
  220. class UniqueForYearValidator(BaseUniqueForValidator):
  221. message = _('This field must be unique for the "{date_field}" year.')
  222. def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  223. value = attrs[self.field]
  224. date = attrs[self.date_field]
  225. filter_kwargs = {}
  226. filter_kwargs[field_name] = value
  227. filter_kwargs['%s__year' % date_field_name] = date.year
  228. return qs_filter(queryset, **filter_kwargs)