fields.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945
  1. import copy
  2. import datetime
  3. import decimal
  4. import functools
  5. import inspect
  6. import re
  7. import uuid
  8. import warnings
  9. from collections import OrderedDict
  10. from collections.abc import Mapping
  11. from django.conf import settings
  12. from django.core.exceptions import ObjectDoesNotExist
  13. from django.core.exceptions import ValidationError as DjangoValidationError
  14. from django.core.validators import (
  15. EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator,
  16. MinValueValidator, RegexValidator, URLValidator, ip_address_validators
  17. )
  18. from django.forms import FilePathField as DjangoFilePathField
  19. from django.forms import ImageField as DjangoImageField
  20. from django.utils import timezone
  21. from django.utils.dateparse import (
  22. parse_date, parse_datetime, parse_duration, parse_time
  23. )
  24. from django.utils.duration import duration_string
  25. from django.utils.encoding import is_protected_type, smart_str
  26. from django.utils.formats import localize_input, sanitize_separators
  27. from django.utils.ipv6 import clean_ipv6_address
  28. from django.utils.timezone import utc
  29. from django.utils.translation import gettext_lazy as _
  30. from pytz.exceptions import InvalidTimeError
  31. from rest_framework import ISO_8601, RemovedInDRF313Warning
  32. from rest_framework.compat import ProhibitNullCharactersValidator
  33. from rest_framework.exceptions import ErrorDetail, ValidationError
  34. from rest_framework.settings import api_settings
  35. from rest_framework.utils import html, humanize_datetime, json, representation
  36. from rest_framework.utils.formatting import lazy_format
  37. class empty:
  38. """
  39. This class is used to represent no data being provided for a given input
  40. or output value.
  41. It is required because `None` may be a valid input or output value.
  42. """
  43. pass
  44. class BuiltinSignatureError(Exception):
  45. """
  46. Built-in function signatures are not inspectable. This exception is raised
  47. so the serializer can raise a helpful error message.
  48. """
  49. pass
  50. def is_simple_callable(obj):
  51. """
  52. True if the object is a callable that takes no arguments.
  53. """
  54. # Bail early since we cannot inspect built-in function signatures.
  55. if inspect.isbuiltin(obj):
  56. raise BuiltinSignatureError(
  57. 'Built-in function signatures are not inspectable. '
  58. 'Wrap the function call in a simple, pure Python function.')
  59. if not (inspect.isfunction(obj) or inspect.ismethod(obj) or isinstance(obj, functools.partial)):
  60. return False
  61. sig = inspect.signature(obj)
  62. params = sig.parameters.values()
  63. return all(
  64. param.kind == param.VAR_POSITIONAL or
  65. param.kind == param.VAR_KEYWORD or
  66. param.default != param.empty
  67. for param in params
  68. )
  69. def get_attribute(instance, attrs):
  70. """
  71. Similar to Python's built in `getattr(instance, attr)`,
  72. but takes a list of nested attributes, instead of a single attribute.
  73. Also accepts either attribute lookup on objects or dictionary lookups.
  74. """
  75. for attr in attrs:
  76. try:
  77. if isinstance(instance, Mapping):
  78. instance = instance[attr]
  79. else:
  80. instance = getattr(instance, attr)
  81. except ObjectDoesNotExist:
  82. return None
  83. if is_simple_callable(instance):
  84. try:
  85. instance = instance()
  86. except (AttributeError, KeyError) as exc:
  87. # If we raised an Attribute or KeyError here it'd get treated
  88. # as an omitted field in `Field.get_attribute()`. Instead we
  89. # raise a ValueError to ensure the exception is not masked.
  90. raise ValueError('Exception raised in callable attribute "{}"; original exception was: {}'.format(attr, exc))
  91. return instance
  92. def set_value(dictionary, keys, value):
  93. """
  94. Similar to Python's built in `dictionary[key] = value`,
  95. but takes a list of nested keys instead of a single key.
  96. set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
  97. set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
  98. set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}}
  99. """
  100. if not keys:
  101. dictionary.update(value)
  102. return
  103. for key in keys[:-1]:
  104. if key not in dictionary:
  105. dictionary[key] = {}
  106. dictionary = dictionary[key]
  107. dictionary[keys[-1]] = value
  108. def to_choices_dict(choices):
  109. """
  110. Convert choices into key/value dicts.
  111. to_choices_dict([1]) -> {1: 1}
  112. to_choices_dict([(1, '1st'), (2, '2nd')]) -> {1: '1st', 2: '2nd'}
  113. to_choices_dict([('Group', ((1, '1st'), 2))]) -> {'Group': {1: '1st', 2: '2'}}
  114. """
  115. # Allow single, paired or grouped choices style:
  116. # choices = [1, 2, 3]
  117. # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')]
  118. # choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')]
  119. ret = OrderedDict()
  120. for choice in choices:
  121. if not isinstance(choice, (list, tuple)):
  122. # single choice
  123. ret[choice] = choice
  124. else:
  125. key, value = choice
  126. if isinstance(value, (list, tuple)):
  127. # grouped choices (category, sub choices)
  128. ret[key] = to_choices_dict(value)
  129. else:
  130. # paired choice (key, display value)
  131. ret[key] = value
  132. return ret
  133. def flatten_choices_dict(choices):
  134. """
  135. Convert a group choices dict into a flat dict of choices.
  136. flatten_choices_dict({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'}
  137. flatten_choices_dict({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'}
  138. """
  139. ret = OrderedDict()
  140. for key, value in choices.items():
  141. if isinstance(value, dict):
  142. # grouped choices (category, sub choices)
  143. for sub_key, sub_value in value.items():
  144. ret[sub_key] = sub_value
  145. else:
  146. # choice (key, display value)
  147. ret[key] = value
  148. return ret
  149. def iter_options(grouped_choices, cutoff=None, cutoff_text=None):
  150. """
  151. Helper function for options and option groups in templates.
  152. """
  153. class StartOptionGroup:
  154. start_option_group = True
  155. end_option_group = False
  156. def __init__(self, label):
  157. self.label = label
  158. class EndOptionGroup:
  159. start_option_group = False
  160. end_option_group = True
  161. class Option:
  162. start_option_group = False
  163. end_option_group = False
  164. def __init__(self, value, display_text, disabled=False):
  165. self.value = value
  166. self.display_text = display_text
  167. self.disabled = disabled
  168. count = 0
  169. for key, value in grouped_choices.items():
  170. if cutoff and count >= cutoff:
  171. break
  172. if isinstance(value, dict):
  173. yield StartOptionGroup(label=key)
  174. for sub_key, sub_value in value.items():
  175. if cutoff and count >= cutoff:
  176. break
  177. yield Option(value=sub_key, display_text=sub_value)
  178. count += 1
  179. yield EndOptionGroup()
  180. else:
  181. yield Option(value=key, display_text=value)
  182. count += 1
  183. if cutoff and count >= cutoff and cutoff_text:
  184. cutoff_text = cutoff_text.format(count=cutoff)
  185. yield Option(value='n/a', display_text=cutoff_text, disabled=True)
  186. def get_error_detail(exc_info):
  187. """
  188. Given a Django ValidationError, return a list of ErrorDetail,
  189. with the `code` populated.
  190. """
  191. code = getattr(exc_info, 'code', None) or 'invalid'
  192. try:
  193. error_dict = exc_info.error_dict
  194. except AttributeError:
  195. return [
  196. ErrorDetail((error.message % error.params) if error.params else error.message,
  197. code=error.code if error.code else code)
  198. for error in exc_info.error_list]
  199. return {
  200. k: [
  201. ErrorDetail((error.message % error.params) if error.params else error.message,
  202. code=error.code if error.code else code)
  203. for error in errors
  204. ] for k, errors in error_dict.items()
  205. }
  206. class CreateOnlyDefault:
  207. """
  208. This class may be used to provide default values that are only used
  209. for create operations, but that do not return any value for update
  210. operations.
  211. """
  212. requires_context = True
  213. def __init__(self, default):
  214. self.default = default
  215. def __call__(self, serializer_field):
  216. is_update = serializer_field.parent.instance is not None
  217. if is_update:
  218. raise SkipField()
  219. if callable(self.default):
  220. if hasattr(self.default, 'set_context'):
  221. warnings.warn(
  222. "Method `set_context` on defaults is deprecated and will "
  223. "no longer be called starting with 3.13. Instead set "
  224. "`requires_context = True` on the class, and accept the "
  225. "context as an additional argument.",
  226. RemovedInDRF313Warning, stacklevel=2
  227. )
  228. self.default.set_context(self)
  229. if getattr(self.default, 'requires_context', False):
  230. return self.default(serializer_field)
  231. else:
  232. return self.default()
  233. return self.default
  234. def __repr__(self):
  235. return '%s(%s)' % (self.__class__.__name__, repr(self.default))
  236. class CurrentUserDefault:
  237. requires_context = True
  238. def __call__(self, serializer_field):
  239. return serializer_field.context['request'].user
  240. def __repr__(self):
  241. return '%s()' % self.__class__.__name__
  242. class SkipField(Exception):
  243. pass
  244. REGEX_TYPE = type(re.compile(''))
  245. NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`'
  246. NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`'
  247. NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`'
  248. USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField'
  249. MISSING_ERROR_MESSAGE = (
  250. 'ValidationError raised by `{class_name}`, but error key `{key}` does '
  251. 'not exist in the `error_messages` dictionary.'
  252. )
  253. class Field:
  254. _creation_counter = 0
  255. default_error_messages = {
  256. 'required': _('This field is required.'),
  257. 'null': _('This field may not be null.')
  258. }
  259. default_validators = []
  260. default_empty_html = empty
  261. initial = None
  262. def __init__(self, read_only=False, write_only=False,
  263. required=None, default=empty, initial=empty, source=None,
  264. label=None, help_text=None, style=None,
  265. error_messages=None, validators=None, allow_null=False):
  266. self._creation_counter = Field._creation_counter
  267. Field._creation_counter += 1
  268. # If `required` is unset, then use `True` unless a default is provided.
  269. if required is None:
  270. required = default is empty and not read_only
  271. # Some combinations of keyword arguments do not make sense.
  272. assert not (read_only and write_only), NOT_READ_ONLY_WRITE_ONLY
  273. assert not (read_only and required), NOT_READ_ONLY_REQUIRED
  274. assert not (required and default is not empty), NOT_REQUIRED_DEFAULT
  275. assert not (read_only and self.__class__ == Field), USE_READONLYFIELD
  276. self.read_only = read_only
  277. self.write_only = write_only
  278. self.required = required
  279. self.default = default
  280. self.source = source
  281. self.initial = self.initial if (initial is empty) else initial
  282. self.label = label
  283. self.help_text = help_text
  284. self.style = {} if style is None else style
  285. self.allow_null = allow_null
  286. if self.default_empty_html is not empty:
  287. if default is not empty:
  288. self.default_empty_html = default
  289. if validators is not None:
  290. self.validators = list(validators)
  291. # These are set up by `.bind()` when the field is added to a serializer.
  292. self.field_name = None
  293. self.parent = None
  294. # Collect default error message from self and parent classes
  295. messages = {}
  296. for cls in reversed(self.__class__.__mro__):
  297. messages.update(getattr(cls, 'default_error_messages', {}))
  298. messages.update(error_messages or {})
  299. self.error_messages = messages
  300. def bind(self, field_name, parent):
  301. """
  302. Initializes the field name and parent for the field instance.
  303. Called when a field is added to the parent serializer instance.
  304. """
  305. # In order to enforce a consistent style, we error if a redundant
  306. # 'source' argument has been used. For example:
  307. # my_field = serializer.CharField(source='my_field')
  308. assert self.source != field_name, (
  309. "It is redundant to specify `source='%s'` on field '%s' in "
  310. "serializer '%s', because it is the same as the field name. "
  311. "Remove the `source` keyword argument." %
  312. (field_name, self.__class__.__name__, parent.__class__.__name__)
  313. )
  314. self.field_name = field_name
  315. self.parent = parent
  316. # `self.label` should default to being based on the field name.
  317. if self.label is None:
  318. self.label = field_name.replace('_', ' ').capitalize()
  319. # self.source should default to being the same as the field name.
  320. if self.source is None:
  321. self.source = field_name
  322. # self.source_attrs is a list of attributes that need to be looked up
  323. # when serializing the instance, or populating the validated data.
  324. if self.source == '*':
  325. self.source_attrs = []
  326. else:
  327. self.source_attrs = self.source.split('.')
  328. # .validators is a lazily loaded property, that gets its default
  329. # value from `get_validators`.
  330. @property
  331. def validators(self):
  332. if not hasattr(self, '_validators'):
  333. self._validators = self.get_validators()
  334. return self._validators
  335. @validators.setter
  336. def validators(self, validators):
  337. self._validators = validators
  338. def get_validators(self):
  339. return list(self.default_validators)
  340. def get_initial(self):
  341. """
  342. Return a value to use when the field is being returned as a primitive
  343. value, without any object instance.
  344. """
  345. if callable(self.initial):
  346. return self.initial()
  347. return self.initial
  348. def get_value(self, dictionary):
  349. """
  350. Given the *incoming* primitive data, return the value for this field
  351. that should be validated and transformed to a native value.
  352. """
  353. if html.is_html_input(dictionary):
  354. # HTML forms will represent empty fields as '', and cannot
  355. # represent None or False values directly.
  356. if self.field_name not in dictionary:
  357. if getattr(self.root, 'partial', False):
  358. return empty
  359. return self.default_empty_html
  360. ret = dictionary[self.field_name]
  361. if ret == '' and self.allow_null:
  362. # If the field is blank, and null is a valid value then
  363. # determine if we should use null instead.
  364. return '' if getattr(self, 'allow_blank', False) else None
  365. elif ret == '' and not self.required:
  366. # If the field is blank, and emptiness is valid then
  367. # determine if we should use emptiness instead.
  368. return '' if getattr(self, 'allow_blank', False) else empty
  369. return ret
  370. return dictionary.get(self.field_name, empty)
  371. def get_attribute(self, instance):
  372. """
  373. Given the *outgoing* object instance, return the primitive value
  374. that should be used for this field.
  375. """
  376. try:
  377. return get_attribute(instance, self.source_attrs)
  378. except BuiltinSignatureError as exc:
  379. msg = (
  380. 'Field source for `{serializer}.{field}` maps to a built-in '
  381. 'function type and is invalid. Define a property or method on '
  382. 'the `{instance}` instance that wraps the call to the built-in '
  383. 'function.'.format(
  384. serializer=self.parent.__class__.__name__,
  385. field=self.field_name,
  386. instance=instance.__class__.__name__,
  387. )
  388. )
  389. raise type(exc)(msg)
  390. except (KeyError, AttributeError) as exc:
  391. if self.default is not empty:
  392. return self.get_default()
  393. if self.allow_null:
  394. return None
  395. if not self.required:
  396. raise SkipField()
  397. msg = (
  398. 'Got {exc_type} when attempting to get a value for field '
  399. '`{field}` on serializer `{serializer}`.\nThe serializer '
  400. 'field might be named incorrectly and not match '
  401. 'any attribute or key on the `{instance}` instance.\n'
  402. 'Original exception text was: {exc}.'.format(
  403. exc_type=type(exc).__name__,
  404. field=self.field_name,
  405. serializer=self.parent.__class__.__name__,
  406. instance=instance.__class__.__name__,
  407. exc=exc
  408. )
  409. )
  410. raise type(exc)(msg)
  411. def get_default(self):
  412. """
  413. Return the default value to use when validating data if no input
  414. is provided for this field.
  415. If a default has not been set for this field then this will simply
  416. raise `SkipField`, indicating that no value should be set in the
  417. validated data for this field.
  418. """
  419. if self.default is empty or getattr(self.root, 'partial', False):
  420. # No default, or this is a partial update.
  421. raise SkipField()
  422. if callable(self.default):
  423. if hasattr(self.default, 'set_context'):
  424. warnings.warn(
  425. "Method `set_context` on defaults is deprecated and will "
  426. "no longer be called starting with 3.13. Instead set "
  427. "`requires_context = True` on the class, and accept the "
  428. "context as an additional argument.",
  429. RemovedInDRF313Warning, stacklevel=2
  430. )
  431. self.default.set_context(self)
  432. if getattr(self.default, 'requires_context', False):
  433. return self.default(self)
  434. else:
  435. return self.default()
  436. return self.default
  437. def validate_empty_values(self, data):
  438. """
  439. Validate empty values, and either:
  440. * Raise `ValidationError`, indicating invalid data.
  441. * Raise `SkipField`, indicating that the field should be ignored.
  442. * Return (True, data), indicating an empty value that should be
  443. returned without any further validation being applied.
  444. * Return (False, data), indicating a non-empty value, that should
  445. have validation applied as normal.
  446. """
  447. if self.read_only:
  448. return (True, self.get_default())
  449. if data is empty:
  450. if getattr(self.root, 'partial', False):
  451. raise SkipField()
  452. if self.required:
  453. self.fail('required')
  454. return (True, self.get_default())
  455. if data is None:
  456. if not self.allow_null:
  457. self.fail('null')
  458. # Nullable `source='*'` fields should not be skipped when its named
  459. # field is given a null value. This is because `source='*'` means
  460. # the field is passed the entire object, which is not null.
  461. elif self.source == '*':
  462. return (False, None)
  463. return (True, None)
  464. return (False, data)
  465. def run_validation(self, data=empty):
  466. """
  467. Validate a simple representation and return the internal value.
  468. The provided data may be `empty` if no representation was included
  469. in the input.
  470. May raise `SkipField` if the field should not be included in the
  471. validated data.
  472. """
  473. (is_empty_value, data) = self.validate_empty_values(data)
  474. if is_empty_value:
  475. return data
  476. value = self.to_internal_value(data)
  477. self.run_validators(value)
  478. return value
  479. def run_validators(self, value):
  480. """
  481. Test the given value against all the validators on the field,
  482. and either raise a `ValidationError` or simply return.
  483. """
  484. errors = []
  485. for validator in self.validators:
  486. if hasattr(validator, 'set_context'):
  487. warnings.warn(
  488. "Method `set_context` on validators is deprecated and will "
  489. "no longer be called starting with 3.13. Instead set "
  490. "`requires_context = True` on the class, and accept the "
  491. "context as an additional argument.",
  492. RemovedInDRF313Warning, stacklevel=2
  493. )
  494. validator.set_context(self)
  495. try:
  496. if getattr(validator, 'requires_context', False):
  497. validator(value, self)
  498. else:
  499. validator(value)
  500. except ValidationError as exc:
  501. # If the validation error contains a mapping of fields to
  502. # errors then simply raise it immediately rather than
  503. # attempting to accumulate a list of errors.
  504. if isinstance(exc.detail, dict):
  505. raise
  506. errors.extend(exc.detail)
  507. except DjangoValidationError as exc:
  508. errors.extend(get_error_detail(exc))
  509. if errors:
  510. raise ValidationError(errors)
  511. def to_internal_value(self, data):
  512. """
  513. Transform the *incoming* primitive data into a native value.
  514. """
  515. raise NotImplementedError(
  516. '{cls}.to_internal_value() must be implemented for field '
  517. '{field_name}. If you do not need to support write operations '
  518. 'you probably want to subclass `ReadOnlyField` instead.'.format(
  519. cls=self.__class__.__name__,
  520. field_name=self.field_name,
  521. )
  522. )
  523. def to_representation(self, value):
  524. """
  525. Transform the *outgoing* native value into primitive data.
  526. """
  527. raise NotImplementedError(
  528. '{cls}.to_representation() must be implemented for field {field_name}.'.format(
  529. cls=self.__class__.__name__,
  530. field_name=self.field_name,
  531. )
  532. )
  533. def fail(self, key, **kwargs):
  534. """
  535. A helper method that simply raises a validation error.
  536. """
  537. try:
  538. msg = self.error_messages[key]
  539. except KeyError:
  540. class_name = self.__class__.__name__
  541. msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
  542. raise AssertionError(msg)
  543. message_string = msg.format(**kwargs)
  544. raise ValidationError(message_string, code=key)
  545. @property
  546. def root(self):
  547. """
  548. Returns the top-level serializer for this field.
  549. """
  550. root = self
  551. while root.parent is not None:
  552. root = root.parent
  553. return root
  554. @property
  555. def context(self):
  556. """
  557. Returns the context as passed to the root serializer on initialization.
  558. """
  559. return getattr(self.root, '_context', {})
  560. def __new__(cls, *args, **kwargs):
  561. """
  562. When a field is instantiated, we store the arguments that were used,
  563. so that we can present a helpful representation of the object.
  564. """
  565. instance = super().__new__(cls)
  566. instance._args = args
  567. instance._kwargs = kwargs
  568. return instance
  569. def __deepcopy__(self, memo):
  570. """
  571. When cloning fields we instantiate using the arguments it was
  572. originally created with, rather than copying the complete state.
  573. """
  574. # Treat regexes and validators as immutable.
  575. # See https://github.com/encode/django-rest-framework/issues/1954
  576. # and https://github.com/encode/django-rest-framework/pull/4489
  577. args = [
  578. copy.deepcopy(item) if not isinstance(item, REGEX_TYPE) else item
  579. for item in self._args
  580. ]
  581. kwargs = {
  582. key: (copy.deepcopy(value, memo) if (key not in ('validators', 'regex')) else value)
  583. for key, value in self._kwargs.items()
  584. }
  585. return self.__class__(*args, **kwargs)
  586. def __repr__(self):
  587. """
  588. Fields are represented using their initial calling arguments.
  589. This allows us to create descriptive representations for serializer
  590. instances that show all the declared fields on the serializer.
  591. """
  592. return representation.field_repr(self)
  593. # Boolean types...
  594. class BooleanField(Field):
  595. default_error_messages = {
  596. 'invalid': _('Must be a valid boolean.')
  597. }
  598. default_empty_html = False
  599. initial = False
  600. TRUE_VALUES = {
  601. 't', 'T',
  602. 'y', 'Y', 'yes', 'YES',
  603. 'true', 'True', 'TRUE',
  604. 'on', 'On', 'ON',
  605. '1', 1,
  606. True
  607. }
  608. FALSE_VALUES = {
  609. 'f', 'F',
  610. 'n', 'N', 'no', 'NO',
  611. 'false', 'False', 'FALSE',
  612. 'off', 'Off', 'OFF',
  613. '0', 0, 0.0,
  614. False
  615. }
  616. NULL_VALUES = {'null', 'Null', 'NULL', '', None}
  617. def to_internal_value(self, data):
  618. try:
  619. if data in self.TRUE_VALUES:
  620. return True
  621. elif data in self.FALSE_VALUES:
  622. return False
  623. elif data in self.NULL_VALUES and self.allow_null:
  624. return None
  625. except TypeError: # Input is an unhashable type
  626. pass
  627. self.fail('invalid', input=data)
  628. def to_representation(self, value):
  629. if value in self.TRUE_VALUES:
  630. return True
  631. elif value in self.FALSE_VALUES:
  632. return False
  633. if value in self.NULL_VALUES and self.allow_null:
  634. return None
  635. return bool(value)
  636. class NullBooleanField(Field):
  637. default_error_messages = {
  638. 'invalid': _('Must be a valid boolean.')
  639. }
  640. initial = None
  641. TRUE_VALUES = {
  642. 't', 'T',
  643. 'y', 'Y', 'yes', 'YES',
  644. 'true', 'True', 'TRUE',
  645. 'on', 'On', 'ON',
  646. '1', 1,
  647. True
  648. }
  649. FALSE_VALUES = {
  650. 'f', 'F',
  651. 'n', 'N', 'no', 'NO',
  652. 'false', 'False', 'FALSE',
  653. 'off', 'Off', 'OFF',
  654. '0', 0, 0.0,
  655. False
  656. }
  657. NULL_VALUES = {'null', 'Null', 'NULL', '', None}
  658. def __init__(self, **kwargs):
  659. assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
  660. kwargs['allow_null'] = True
  661. super().__init__(**kwargs)
  662. def to_internal_value(self, data):
  663. try:
  664. if data in self.TRUE_VALUES:
  665. return True
  666. elif data in self.FALSE_VALUES:
  667. return False
  668. elif data in self.NULL_VALUES:
  669. return None
  670. except TypeError: # Input is an unhashable type
  671. pass
  672. self.fail('invalid', input=data)
  673. def to_representation(self, value):
  674. if value in self.NULL_VALUES:
  675. return None
  676. if value in self.TRUE_VALUES:
  677. return True
  678. elif value in self.FALSE_VALUES:
  679. return False
  680. return bool(value)
  681. # String types...
  682. class CharField(Field):
  683. default_error_messages = {
  684. 'invalid': _('Not a valid string.'),
  685. 'blank': _('This field may not be blank.'),
  686. 'max_length': _('Ensure this field has no more than {max_length} characters.'),
  687. 'min_length': _('Ensure this field has at least {min_length} characters.'),
  688. }
  689. initial = ''
  690. def __init__(self, **kwargs):
  691. self.allow_blank = kwargs.pop('allow_blank', False)
  692. self.trim_whitespace = kwargs.pop('trim_whitespace', True)
  693. self.max_length = kwargs.pop('max_length', None)
  694. self.min_length = kwargs.pop('min_length', None)
  695. super().__init__(**kwargs)
  696. if self.max_length is not None:
  697. message = lazy_format(self.error_messages['max_length'], max_length=self.max_length)
  698. self.validators.append(
  699. MaxLengthValidator(self.max_length, message=message))
  700. if self.min_length is not None:
  701. message = lazy_format(self.error_messages['min_length'], min_length=self.min_length)
  702. self.validators.append(
  703. MinLengthValidator(self.min_length, message=message))
  704. # ProhibitNullCharactersValidator is None on Django < 2.0
  705. if ProhibitNullCharactersValidator is not None:
  706. self.validators.append(ProhibitNullCharactersValidator())
  707. def run_validation(self, data=empty):
  708. # Test for the empty string here so that it does not get validated,
  709. # and so that subclasses do not need to handle it explicitly
  710. # inside the `to_internal_value()` method.
  711. if data == '' or (self.trim_whitespace and str(data).strip() == ''):
  712. if not self.allow_blank:
  713. self.fail('blank')
  714. return ''
  715. return super().run_validation(data)
  716. def to_internal_value(self, data):
  717. # We're lenient with allowing basic numerics to be coerced into strings,
  718. # but other types should fail. Eg. unclear if booleans should represent as `true` or `True`,
  719. # and composites such as lists are likely user error.
  720. if isinstance(data, bool) or not isinstance(data, (str, int, float,)):
  721. self.fail('invalid')
  722. value = str(data)
  723. return value.strip() if self.trim_whitespace else value
  724. def to_representation(self, value):
  725. return str(value)
  726. class EmailField(CharField):
  727. default_error_messages = {
  728. 'invalid': _('Enter a valid email address.')
  729. }
  730. def __init__(self, **kwargs):
  731. super().__init__(**kwargs)
  732. validator = EmailValidator(message=self.error_messages['invalid'])
  733. self.validators.append(validator)
  734. class RegexField(CharField):
  735. default_error_messages = {
  736. 'invalid': _('This value does not match the required pattern.')
  737. }
  738. def __init__(self, regex, **kwargs):
  739. super().__init__(**kwargs)
  740. validator = RegexValidator(regex, message=self.error_messages['invalid'])
  741. self.validators.append(validator)
  742. class SlugField(CharField):
  743. default_error_messages = {
  744. 'invalid': _('Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.'),
  745. 'invalid_unicode': _('Enter a valid "slug" consisting of Unicode letters, numbers, underscores, or hyphens.')
  746. }
  747. def __init__(self, allow_unicode=False, **kwargs):
  748. super().__init__(**kwargs)
  749. self.allow_unicode = allow_unicode
  750. if self.allow_unicode:
  751. validator = RegexValidator(re.compile(r'^[-\w]+\Z', re.UNICODE), message=self.error_messages['invalid_unicode'])
  752. else:
  753. validator = RegexValidator(re.compile(r'^[-a-zA-Z0-9_]+$'), message=self.error_messages['invalid'])
  754. self.validators.append(validator)
  755. class URLField(CharField):
  756. default_error_messages = {
  757. 'invalid': _('Enter a valid URL.')
  758. }
  759. def __init__(self, **kwargs):
  760. super().__init__(**kwargs)
  761. validator = URLValidator(message=self.error_messages['invalid'])
  762. self.validators.append(validator)
  763. class UUIDField(Field):
  764. valid_formats = ('hex_verbose', 'hex', 'int', 'urn')
  765. default_error_messages = {
  766. 'invalid': _('Must be a valid UUID.'),
  767. }
  768. def __init__(self, **kwargs):
  769. self.uuid_format = kwargs.pop('format', 'hex_verbose')
  770. if self.uuid_format not in self.valid_formats:
  771. raise ValueError(
  772. 'Invalid format for uuid representation. '
  773. 'Must be one of "{}"'.format('", "'.join(self.valid_formats))
  774. )
  775. super().__init__(**kwargs)
  776. def to_internal_value(self, data):
  777. if not isinstance(data, uuid.UUID):
  778. try:
  779. if isinstance(data, int):
  780. return uuid.UUID(int=data)
  781. elif isinstance(data, str):
  782. return uuid.UUID(hex=data)
  783. else:
  784. self.fail('invalid', value=data)
  785. except (ValueError):
  786. self.fail('invalid', value=data)
  787. return data
  788. def to_representation(self, value):
  789. if self.uuid_format == 'hex_verbose':
  790. return str(value)
  791. else:
  792. return getattr(value, self.uuid_format)
  793. class IPAddressField(CharField):
  794. """Support both IPAddressField and GenericIPAddressField"""
  795. default_error_messages = {
  796. 'invalid': _('Enter a valid IPv4 or IPv6 address.'),
  797. }
  798. def __init__(self, protocol='both', **kwargs):
  799. self.protocol = protocol.lower()
  800. self.unpack_ipv4 = (self.protocol == 'both')
  801. super().__init__(**kwargs)
  802. validators, error_message = ip_address_validators(protocol, self.unpack_ipv4)
  803. self.validators.extend(validators)
  804. def to_internal_value(self, data):
  805. if not isinstance(data, str):
  806. self.fail('invalid', value=data)
  807. if ':' in data:
  808. try:
  809. if self.protocol in ('both', 'ipv6'):
  810. return clean_ipv6_address(data, self.unpack_ipv4)
  811. except DjangoValidationError:
  812. self.fail('invalid', value=data)
  813. return super().to_internal_value(data)
  814. # Number types...
  815. class IntegerField(Field):
  816. default_error_messages = {
  817. 'invalid': _('A valid integer is required.'),
  818. 'max_value': _('Ensure this value is less than or equal to {max_value}.'),
  819. 'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
  820. 'max_string_length': _('String value too large.')
  821. }
  822. MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
  823. re_decimal = re.compile(r'\.0*\s*$') # allow e.g. '1.0' as an int, but not '1.2'
  824. def __init__(self, **kwargs):
  825. self.max_value = kwargs.pop('max_value', None)
  826. self.min_value = kwargs.pop('min_value', None)
  827. super().__init__(**kwargs)
  828. if self.max_value is not None:
  829. message = lazy_format(self.error_messages['max_value'], max_value=self.max_value)
  830. self.validators.append(
  831. MaxValueValidator(self.max_value, message=message))
  832. if self.min_value is not None:
  833. message = lazy_format(self.error_messages['min_value'], min_value=self.min_value)
  834. self.validators.append(
  835. MinValueValidator(self.min_value, message=message))
  836. def to_internal_value(self, data):
  837. if isinstance(data, str) and len(data) > self.MAX_STRING_LENGTH:
  838. self.fail('max_string_length')
  839. try:
  840. data = int(self.re_decimal.sub('', str(data)))
  841. except (ValueError, TypeError):
  842. self.fail('invalid')
  843. return data
  844. def to_representation(self, value):
  845. return int(value)
  846. class FloatField(Field):
  847. default_error_messages = {
  848. 'invalid': _('A valid number is required.'),
  849. 'max_value': _('Ensure this value is less than or equal to {max_value}.'),
  850. 'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
  851. 'max_string_length': _('String value too large.')
  852. }
  853. MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
  854. def __init__(self, **kwargs):
  855. self.max_value = kwargs.pop('max_value', None)
  856. self.min_value = kwargs.pop('min_value', None)
  857. super().__init__(**kwargs)
  858. if self.max_value is not None:
  859. message = lazy_format(self.error_messages['max_value'], max_value=self.max_value)
  860. self.validators.append(
  861. MaxValueValidator(self.max_value, message=message))
  862. if self.min_value is not None:
  863. message = lazy_format(self.error_messages['min_value'], min_value=self.min_value)
  864. self.validators.append(
  865. MinValueValidator(self.min_value, message=message))
  866. def to_internal_value(self, data):
  867. if isinstance(data, str) and len(data) > self.MAX_STRING_LENGTH:
  868. self.fail('max_string_length')
  869. try:
  870. return float(data)
  871. except (TypeError, ValueError):
  872. self.fail('invalid')
  873. def to_representation(self, value):
  874. return float(value)
  875. class DecimalField(Field):
  876. default_error_messages = {
  877. 'invalid': _('A valid number is required.'),
  878. 'max_value': _('Ensure this value is less than or equal to {max_value}.'),
  879. 'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
  880. 'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'),
  881. 'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'),
  882. 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.'),
  883. 'max_string_length': _('String value too large.')
  884. }
  885. MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
  886. def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None,
  887. localize=False, rounding=None, **kwargs):
  888. self.max_digits = max_digits
  889. self.decimal_places = decimal_places
  890. self.localize = localize
  891. if coerce_to_string is not None:
  892. self.coerce_to_string = coerce_to_string
  893. if self.localize:
  894. self.coerce_to_string = True
  895. self.max_value = max_value
  896. self.min_value = min_value
  897. if self.max_digits is not None and self.decimal_places is not None:
  898. self.max_whole_digits = self.max_digits - self.decimal_places
  899. else:
  900. self.max_whole_digits = None
  901. super().__init__(**kwargs)
  902. if self.max_value is not None:
  903. message = lazy_format(self.error_messages['max_value'], max_value=self.max_value)
  904. self.validators.append(
  905. MaxValueValidator(self.max_value, message=message))
  906. if self.min_value is not None:
  907. message = lazy_format(self.error_messages['min_value'], min_value=self.min_value)
  908. self.validators.append(
  909. MinValueValidator(self.min_value, message=message))
  910. if rounding is not None:
  911. valid_roundings = [v for k, v in vars(decimal).items() if k.startswith('ROUND_')]
  912. assert rounding in valid_roundings, (
  913. 'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings))
  914. self.rounding = rounding
  915. def to_internal_value(self, data):
  916. """
  917. Validate that the input is a decimal number and return a Decimal
  918. instance.
  919. """
  920. data = smart_str(data).strip()
  921. if self.localize:
  922. data = sanitize_separators(data)
  923. if len(data) > self.MAX_STRING_LENGTH:
  924. self.fail('max_string_length')
  925. try:
  926. value = decimal.Decimal(data)
  927. except decimal.DecimalException:
  928. self.fail('invalid')
  929. if value.is_nan():
  930. self.fail('invalid')
  931. # Check for infinity and negative infinity.
  932. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')):
  933. self.fail('invalid')
  934. return self.quantize(self.validate_precision(value))
  935. def validate_precision(self, value):
  936. """
  937. Ensure that there are no more than max_digits in the number, and no
  938. more than decimal_places digits after the decimal point.
  939. Override this method to disable the precision validation for input
  940. values or to enhance it in any way you need to.
  941. """
  942. sign, digittuple, exponent = value.as_tuple()
  943. if exponent >= 0:
  944. # 1234500.0
  945. total_digits = len(digittuple) + exponent
  946. whole_digits = total_digits
  947. decimal_places = 0
  948. elif len(digittuple) > abs(exponent):
  949. # 123.45
  950. total_digits = len(digittuple)
  951. whole_digits = total_digits - abs(exponent)
  952. decimal_places = abs(exponent)
  953. else:
  954. # 0.001234
  955. total_digits = abs(exponent)
  956. whole_digits = 0
  957. decimal_places = total_digits
  958. if self.max_digits is not None and total_digits > self.max_digits:
  959. self.fail('max_digits', max_digits=self.max_digits)
  960. if self.decimal_places is not None and decimal_places > self.decimal_places:
  961. self.fail('max_decimal_places', max_decimal_places=self.decimal_places)
  962. if self.max_whole_digits is not None and whole_digits > self.max_whole_digits:
  963. self.fail('max_whole_digits', max_whole_digits=self.max_whole_digits)
  964. return value
  965. def to_representation(self, value):
  966. coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING)
  967. if not isinstance(value, decimal.Decimal):
  968. value = decimal.Decimal(str(value).strip())
  969. quantized = self.quantize(value)
  970. if not coerce_to_string:
  971. return quantized
  972. if self.localize:
  973. return localize_input(quantized)
  974. return '{:f}'.format(quantized)
  975. def quantize(self, value):
  976. """
  977. Quantize the decimal value to the configured precision.
  978. """
  979. if self.decimal_places is None:
  980. return value
  981. context = decimal.getcontext().copy()
  982. if self.max_digits is not None:
  983. context.prec = self.max_digits
  984. return value.quantize(
  985. decimal.Decimal('.1') ** self.decimal_places,
  986. rounding=self.rounding,
  987. context=context
  988. )
  989. # Date & time fields...
  990. class DateTimeField(Field):
  991. default_error_messages = {
  992. 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}.'),
  993. 'date': _('Expected a datetime but got a date.'),
  994. 'make_aware': _('Invalid datetime for the timezone "{timezone}".'),
  995. 'overflow': _('Datetime value out of range.')
  996. }
  997. datetime_parser = datetime.datetime.strptime
  998. def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs):
  999. if format is not empty:
  1000. self.format = format
  1001. if input_formats is not None:
  1002. self.input_formats = input_formats
  1003. if default_timezone is not None:
  1004. self.timezone = default_timezone
  1005. super().__init__(*args, **kwargs)
  1006. def enforce_timezone(self, value):
  1007. """
  1008. When `self.default_timezone` is `None`, always return naive datetimes.
  1009. When `self.default_timezone` is not `None`, always return aware datetimes.
  1010. """
  1011. field_timezone = getattr(self, 'timezone', self.default_timezone())
  1012. if field_timezone is not None:
  1013. if timezone.is_aware(value):
  1014. try:
  1015. return value.astimezone(field_timezone)
  1016. except OverflowError:
  1017. self.fail('overflow')
  1018. try:
  1019. return timezone.make_aware(value, field_timezone)
  1020. except InvalidTimeError:
  1021. self.fail('make_aware', timezone=field_timezone)
  1022. elif (field_timezone is None) and timezone.is_aware(value):
  1023. return timezone.make_naive(value, utc)
  1024. return value
  1025. def default_timezone(self):
  1026. return timezone.get_current_timezone() if settings.USE_TZ else None
  1027. def to_internal_value(self, value):
  1028. input_formats = getattr(self, 'input_formats', api_settings.DATETIME_INPUT_FORMATS)
  1029. if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
  1030. self.fail('date')
  1031. if isinstance(value, datetime.datetime):
  1032. return self.enforce_timezone(value)
  1033. for input_format in input_formats:
  1034. if input_format.lower() == ISO_8601:
  1035. try:
  1036. parsed = parse_datetime(value)
  1037. if parsed is not None:
  1038. return self.enforce_timezone(parsed)
  1039. except (ValueError, TypeError):
  1040. pass
  1041. else:
  1042. try:
  1043. parsed = self.datetime_parser(value, input_format)
  1044. return self.enforce_timezone(parsed)
  1045. except (ValueError, TypeError):
  1046. pass
  1047. humanized_format = humanize_datetime.datetime_formats(input_formats)
  1048. self.fail('invalid', format=humanized_format)
  1049. def to_representation(self, value):
  1050. if not value:
  1051. return None
  1052. output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT)
  1053. if output_format is None or isinstance(value, str):
  1054. return value
  1055. value = self.enforce_timezone(value)
  1056. if output_format.lower() == ISO_8601:
  1057. value = value.isoformat()
  1058. if value.endswith('+00:00'):
  1059. value = value[:-6] + 'Z'
  1060. return value
  1061. return value.strftime(output_format)
  1062. class DateField(Field):
  1063. default_error_messages = {
  1064. 'invalid': _('Date has wrong format. Use one of these formats instead: {format}.'),
  1065. 'datetime': _('Expected a date but got a datetime.'),
  1066. }
  1067. datetime_parser = datetime.datetime.strptime
  1068. def __init__(self, format=empty, input_formats=None, *args, **kwargs):
  1069. if format is not empty:
  1070. self.format = format
  1071. if input_formats is not None:
  1072. self.input_formats = input_formats
  1073. super().__init__(*args, **kwargs)
  1074. def to_internal_value(self, value):
  1075. input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS)
  1076. if isinstance(value, datetime.datetime):
  1077. self.fail('datetime')
  1078. if isinstance(value, datetime.date):
  1079. return value
  1080. for input_format in input_formats:
  1081. if input_format.lower() == ISO_8601:
  1082. try:
  1083. parsed = parse_date(value)
  1084. except (ValueError, TypeError):
  1085. pass
  1086. else:
  1087. if parsed is not None:
  1088. return parsed
  1089. else:
  1090. try:
  1091. parsed = self.datetime_parser(value, input_format)
  1092. except (ValueError, TypeError):
  1093. pass
  1094. else:
  1095. return parsed.date()
  1096. humanized_format = humanize_datetime.date_formats(input_formats)
  1097. self.fail('invalid', format=humanized_format)
  1098. def to_representation(self, value):
  1099. if not value:
  1100. return None
  1101. output_format = getattr(self, 'format', api_settings.DATE_FORMAT)
  1102. if output_format is None or isinstance(value, str):
  1103. return value
  1104. # Applying a `DateField` to a datetime value is almost always
  1105. # not a sensible thing to do, as it means naively dropping
  1106. # any explicit or implicit timezone info.
  1107. assert not isinstance(value, datetime.datetime), (
  1108. 'Expected a `date`, but got a `datetime`. Refusing to coerce, '
  1109. 'as this may mean losing timezone information. Use a custom '
  1110. 'read-only field and deal with timezone issues explicitly.'
  1111. )
  1112. if output_format.lower() == ISO_8601:
  1113. return value.isoformat()
  1114. return value.strftime(output_format)
  1115. class TimeField(Field):
  1116. default_error_messages = {
  1117. 'invalid': _('Time has wrong format. Use one of these formats instead: {format}.'),
  1118. }
  1119. datetime_parser = datetime.datetime.strptime
  1120. def __init__(self, format=empty, input_formats=None, *args, **kwargs):
  1121. if format is not empty:
  1122. self.format = format
  1123. if input_formats is not None:
  1124. self.input_formats = input_formats
  1125. super().__init__(*args, **kwargs)
  1126. def to_internal_value(self, value):
  1127. input_formats = getattr(self, 'input_formats', api_settings.TIME_INPUT_FORMATS)
  1128. if isinstance(value, datetime.time):
  1129. return value
  1130. for input_format in input_formats:
  1131. if input_format.lower() == ISO_8601:
  1132. try:
  1133. parsed = parse_time(value)
  1134. except (ValueError, TypeError):
  1135. pass
  1136. else:
  1137. if parsed is not None:
  1138. return parsed
  1139. else:
  1140. try:
  1141. parsed = self.datetime_parser(value, input_format)
  1142. except (ValueError, TypeError):
  1143. pass
  1144. else:
  1145. return parsed.time()
  1146. humanized_format = humanize_datetime.time_formats(input_formats)
  1147. self.fail('invalid', format=humanized_format)
  1148. def to_representation(self, value):
  1149. if value in (None, ''):
  1150. return None
  1151. output_format = getattr(self, 'format', api_settings.TIME_FORMAT)
  1152. if output_format is None or isinstance(value, str):
  1153. return value
  1154. # Applying a `TimeField` to a datetime value is almost always
  1155. # not a sensible thing to do, as it means naively dropping
  1156. # any explicit or implicit timezone info.
  1157. assert not isinstance(value, datetime.datetime), (
  1158. 'Expected a `time`, but got a `datetime`. Refusing to coerce, '
  1159. 'as this may mean losing timezone information. Use a custom '
  1160. 'read-only field and deal with timezone issues explicitly.'
  1161. )
  1162. if output_format.lower() == ISO_8601:
  1163. return value.isoformat()
  1164. return value.strftime(output_format)
  1165. class DurationField(Field):
  1166. default_error_messages = {
  1167. 'invalid': _('Duration has wrong format. Use one of these formats instead: {format}.'),
  1168. 'max_value': _('Ensure this value is less than or equal to {max_value}.'),
  1169. 'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
  1170. }
  1171. def __init__(self, **kwargs):
  1172. self.max_value = kwargs.pop('max_value', None)
  1173. self.min_value = kwargs.pop('min_value', None)
  1174. super().__init__(**kwargs)
  1175. if self.max_value is not None:
  1176. message = lazy_format(self.error_messages['max_value'], max_value=self.max_value)
  1177. self.validators.append(
  1178. MaxValueValidator(self.max_value, message=message))
  1179. if self.min_value is not None:
  1180. message = lazy_format(self.error_messages['min_value'], min_value=self.min_value)
  1181. self.validators.append(
  1182. MinValueValidator(self.min_value, message=message))
  1183. def to_internal_value(self, value):
  1184. if isinstance(value, datetime.timedelta):
  1185. return value
  1186. parsed = parse_duration(str(value))
  1187. if parsed is not None:
  1188. return parsed
  1189. self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')
  1190. def to_representation(self, value):
  1191. return duration_string(value)
  1192. # Choice types...
  1193. class ChoiceField(Field):
  1194. default_error_messages = {
  1195. 'invalid_choice': _('"{input}" is not a valid choice.')
  1196. }
  1197. html_cutoff = None
  1198. html_cutoff_text = _('More than {count} items...')
  1199. def __init__(self, choices, **kwargs):
  1200. self.choices = choices
  1201. self.html_cutoff = kwargs.pop('html_cutoff', self.html_cutoff)
  1202. self.html_cutoff_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text)
  1203. self.allow_blank = kwargs.pop('allow_blank', False)
  1204. super().__init__(**kwargs)
  1205. def to_internal_value(self, data):
  1206. if data == '' and self.allow_blank:
  1207. return ''
  1208. try:
  1209. return self.choice_strings_to_values[str(data)]
  1210. except KeyError:
  1211. self.fail('invalid_choice', input=data)
  1212. def to_representation(self, value):
  1213. if value in ('', None):
  1214. return value
  1215. return self.choice_strings_to_values.get(str(value), value)
  1216. def iter_options(self):
  1217. """
  1218. Helper method for use with templates rendering select widgets.
  1219. """
  1220. return iter_options(
  1221. self.grouped_choices,
  1222. cutoff=self.html_cutoff,
  1223. cutoff_text=self.html_cutoff_text
  1224. )
  1225. def _get_choices(self):
  1226. return self._choices
  1227. def _set_choices(self, choices):
  1228. self.grouped_choices = to_choices_dict(choices)
  1229. self._choices = flatten_choices_dict(self.grouped_choices)
  1230. # Map the string representation of choices to the underlying value.
  1231. # Allows us to deal with eg. integer choices while supporting either
  1232. # integer or string input, but still get the correct datatype out.
  1233. self.choice_strings_to_values = {
  1234. str(key): key for key in self.choices
  1235. }
  1236. choices = property(_get_choices, _set_choices)
  1237. class MultipleChoiceField(ChoiceField):
  1238. default_error_messages = {
  1239. 'invalid_choice': _('"{input}" is not a valid choice.'),
  1240. 'not_a_list': _('Expected a list of items but got type "{input_type}".'),
  1241. 'empty': _('This selection may not be empty.')
  1242. }
  1243. default_empty_html = []
  1244. def __init__(self, *args, **kwargs):
  1245. self.allow_empty = kwargs.pop('allow_empty', True)
  1246. super().__init__(*args, **kwargs)
  1247. def get_value(self, dictionary):
  1248. if self.field_name not in dictionary:
  1249. if getattr(self.root, 'partial', False):
  1250. return empty
  1251. # We override the default field access in order to support
  1252. # lists in HTML forms.
  1253. if html.is_html_input(dictionary):
  1254. return dictionary.getlist(self.field_name)
  1255. return dictionary.get(self.field_name, empty)
  1256. def to_internal_value(self, data):
  1257. if isinstance(data, str) or not hasattr(data, '__iter__'):
  1258. self.fail('not_a_list', input_type=type(data).__name__)
  1259. if not self.allow_empty and len(data) == 0:
  1260. self.fail('empty')
  1261. return {
  1262. super(MultipleChoiceField, self).to_internal_value(item)
  1263. for item in data
  1264. }
  1265. def to_representation(self, value):
  1266. return {
  1267. self.choice_strings_to_values.get(str(item), item) for item in value
  1268. }
  1269. class FilePathField(ChoiceField):
  1270. default_error_messages = {
  1271. 'invalid_choice': _('"{input}" is not a valid path choice.')
  1272. }
  1273. def __init__(self, path, match=None, recursive=False, allow_files=True,
  1274. allow_folders=False, required=None, **kwargs):
  1275. # Defer to Django's FilePathField implementation to get the
  1276. # valid set of choices.
  1277. field = DjangoFilePathField(
  1278. path, match=match, recursive=recursive, allow_files=allow_files,
  1279. allow_folders=allow_folders, required=required
  1280. )
  1281. kwargs['choices'] = field.choices
  1282. super().__init__(**kwargs)
  1283. # File types...
  1284. class FileField(Field):
  1285. default_error_messages = {
  1286. 'required': _('No file was submitted.'),
  1287. 'invalid': _('The submitted data was not a file. Check the encoding type on the form.'),
  1288. 'no_name': _('No filename could be determined.'),
  1289. 'empty': _('The submitted file is empty.'),
  1290. 'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'),
  1291. }
  1292. def __init__(self, *args, **kwargs):
  1293. self.max_length = kwargs.pop('max_length', None)
  1294. self.allow_empty_file = kwargs.pop('allow_empty_file', False)
  1295. if 'use_url' in kwargs:
  1296. self.use_url = kwargs.pop('use_url')
  1297. super().__init__(*args, **kwargs)
  1298. def to_internal_value(self, data):
  1299. try:
  1300. # `UploadedFile` objects should have name and size attributes.
  1301. file_name = data.name
  1302. file_size = data.size
  1303. except AttributeError:
  1304. self.fail('invalid')
  1305. if not file_name:
  1306. self.fail('no_name')
  1307. if not self.allow_empty_file and not file_size:
  1308. self.fail('empty')
  1309. if self.max_length and len(file_name) > self.max_length:
  1310. self.fail('max_length', max_length=self.max_length, length=len(file_name))
  1311. return data
  1312. def to_representation(self, value):
  1313. if not value:
  1314. return None
  1315. use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL)
  1316. if use_url:
  1317. try:
  1318. url = value.url
  1319. except AttributeError:
  1320. return None
  1321. request = self.context.get('request', None)
  1322. if request is not None:
  1323. return request.build_absolute_uri(url)
  1324. return url
  1325. return value.name
  1326. class ImageField(FileField):
  1327. default_error_messages = {
  1328. 'invalid_image': _(
  1329. 'Upload a valid image. The file you uploaded was either not an image or a corrupted image.'
  1330. ),
  1331. }
  1332. def __init__(self, *args, **kwargs):
  1333. self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField)
  1334. super().__init__(*args, **kwargs)
  1335. def to_internal_value(self, data):
  1336. # Image validation is a bit grungy, so we'll just outright
  1337. # defer to Django's implementation so we don't need to
  1338. # consider it, or treat PIL as a test dependency.
  1339. file_object = super().to_internal_value(data)
  1340. django_field = self._DjangoImageField()
  1341. django_field.error_messages = self.error_messages
  1342. return django_field.clean(file_object)
  1343. # Composite field types...
  1344. class _UnvalidatedField(Field):
  1345. def __init__(self, *args, **kwargs):
  1346. super().__init__(*args, **kwargs)
  1347. self.allow_blank = True
  1348. self.allow_null = True
  1349. def to_internal_value(self, data):
  1350. return data
  1351. def to_representation(self, value):
  1352. return value
  1353. class ListField(Field):
  1354. child = _UnvalidatedField()
  1355. initial = []
  1356. default_error_messages = {
  1357. 'not_a_list': _('Expected a list of items but got type "{input_type}".'),
  1358. 'empty': _('This list may not be empty.'),
  1359. 'min_length': _('Ensure this field has at least {min_length} elements.'),
  1360. 'max_length': _('Ensure this field has no more than {max_length} elements.')
  1361. }
  1362. def __init__(self, *args, **kwargs):
  1363. self.child = kwargs.pop('child', copy.deepcopy(self.child))
  1364. self.allow_empty = kwargs.pop('allow_empty', True)
  1365. self.max_length = kwargs.pop('max_length', None)
  1366. self.min_length = kwargs.pop('min_length', None)
  1367. assert not inspect.isclass(self.child), '`child` has not been instantiated.'
  1368. assert self.child.source is None, (
  1369. "The `source` argument is not meaningful when applied to a `child=` field. "
  1370. "Remove `source=` from the field declaration."
  1371. )
  1372. super().__init__(*args, **kwargs)
  1373. self.child.bind(field_name='', parent=self)
  1374. if self.max_length is not None:
  1375. message = lazy_format(self.error_messages['max_length'], max_length=self.max_length)
  1376. self.validators.append(MaxLengthValidator(self.max_length, message=message))
  1377. if self.min_length is not None:
  1378. message = lazy_format(self.error_messages['min_length'], min_length=self.min_length)
  1379. self.validators.append(MinLengthValidator(self.min_length, message=message))
  1380. def get_value(self, dictionary):
  1381. if self.field_name not in dictionary:
  1382. if getattr(self.root, 'partial', False):
  1383. return empty
  1384. # We override the default field access in order to support
  1385. # lists in HTML forms.
  1386. if html.is_html_input(dictionary):
  1387. val = dictionary.getlist(self.field_name, [])
  1388. if len(val) > 0:
  1389. # Support QueryDict lists in HTML input.
  1390. return val
  1391. return html.parse_html_list(dictionary, prefix=self.field_name, default=empty)
  1392. return dictionary.get(self.field_name, empty)
  1393. def to_internal_value(self, data):
  1394. """
  1395. List of dicts of native values <- List of dicts of primitive datatypes.
  1396. """
  1397. if html.is_html_input(data):
  1398. data = html.parse_html_list(data, default=[])
  1399. if isinstance(data, (str, Mapping)) or not hasattr(data, '__iter__'):
  1400. self.fail('not_a_list', input_type=type(data).__name__)
  1401. if not self.allow_empty and len(data) == 0:
  1402. self.fail('empty')
  1403. return self.run_child_validation(data)
  1404. def to_representation(self, data):
  1405. """
  1406. List of object instances -> List of dicts of primitive datatypes.
  1407. """
  1408. return [self.child.to_representation(item) if item is not None else None for item in data]
  1409. def run_child_validation(self, data):
  1410. result = []
  1411. errors = OrderedDict()
  1412. for idx, item in enumerate(data):
  1413. try:
  1414. result.append(self.child.run_validation(item))
  1415. except ValidationError as e:
  1416. errors[idx] = e.detail
  1417. if not errors:
  1418. return result
  1419. raise ValidationError(errors)
  1420. class DictField(Field):
  1421. child = _UnvalidatedField()
  1422. initial = {}
  1423. default_error_messages = {
  1424. 'not_a_dict': _('Expected a dictionary of items but got type "{input_type}".'),
  1425. 'empty': _('This dictionary may not be empty.'),
  1426. }
  1427. def __init__(self, *args, **kwargs):
  1428. self.child = kwargs.pop('child', copy.deepcopy(self.child))
  1429. self.allow_empty = kwargs.pop('allow_empty', True)
  1430. assert not inspect.isclass(self.child), '`child` has not been instantiated.'
  1431. assert self.child.source is None, (
  1432. "The `source` argument is not meaningful when applied to a `child=` field. "
  1433. "Remove `source=` from the field declaration."
  1434. )
  1435. super().__init__(*args, **kwargs)
  1436. self.child.bind(field_name='', parent=self)
  1437. def get_value(self, dictionary):
  1438. # We override the default field access in order to support
  1439. # dictionaries in HTML forms.
  1440. if html.is_html_input(dictionary):
  1441. return html.parse_html_dict(dictionary, prefix=self.field_name)
  1442. return dictionary.get(self.field_name, empty)
  1443. def to_internal_value(self, data):
  1444. """
  1445. Dicts of native values <- Dicts of primitive datatypes.
  1446. """
  1447. if html.is_html_input(data):
  1448. data = html.parse_html_dict(data)
  1449. if not isinstance(data, dict):
  1450. self.fail('not_a_dict', input_type=type(data).__name__)
  1451. if not self.allow_empty and len(data) == 0:
  1452. self.fail('empty')
  1453. return self.run_child_validation(data)
  1454. def to_representation(self, value):
  1455. return {
  1456. str(key): self.child.to_representation(val) if val is not None else None
  1457. for key, val in value.items()
  1458. }
  1459. def run_child_validation(self, data):
  1460. result = {}
  1461. errors = OrderedDict()
  1462. for key, value in data.items():
  1463. key = str(key)
  1464. try:
  1465. result[key] = self.child.run_validation(value)
  1466. except ValidationError as e:
  1467. errors[key] = e.detail
  1468. if not errors:
  1469. return result
  1470. raise ValidationError(errors)
  1471. class HStoreField(DictField):
  1472. child = CharField(allow_blank=True, allow_null=True)
  1473. def __init__(self, *args, **kwargs):
  1474. super().__init__(*args, **kwargs)
  1475. assert isinstance(self.child, CharField), (
  1476. "The `child` argument must be an instance of `CharField`, "
  1477. "as the hstore extension stores values as strings."
  1478. )
  1479. class JSONField(Field):
  1480. default_error_messages = {
  1481. 'invalid': _('Value must be valid JSON.')
  1482. }
  1483. def __init__(self, *args, **kwargs):
  1484. self.binary = kwargs.pop('binary', False)
  1485. self.encoder = kwargs.pop('encoder', None)
  1486. super().__init__(*args, **kwargs)
  1487. def get_value(self, dictionary):
  1488. if html.is_html_input(dictionary) and self.field_name in dictionary:
  1489. # When HTML form input is used, mark up the input
  1490. # as being a JSON string, rather than a JSON primitive.
  1491. class JSONString(str):
  1492. def __new__(cls, value):
  1493. ret = str.__new__(cls, value)
  1494. ret.is_json_string = True
  1495. return ret
  1496. return JSONString(dictionary[self.field_name])
  1497. return dictionary.get(self.field_name, empty)
  1498. def to_internal_value(self, data):
  1499. try:
  1500. if self.binary or getattr(data, 'is_json_string', False):
  1501. if isinstance(data, bytes):
  1502. data = data.decode()
  1503. return json.loads(data)
  1504. else:
  1505. json.dumps(data, cls=self.encoder)
  1506. except (TypeError, ValueError):
  1507. self.fail('invalid')
  1508. return data
  1509. def to_representation(self, value):
  1510. if self.binary:
  1511. value = json.dumps(value, cls=self.encoder)
  1512. value = value.encode()
  1513. return value
  1514. # Miscellaneous field types...
  1515. class ReadOnlyField(Field):
  1516. """
  1517. A read-only field that simply returns the field value.
  1518. If the field is a method with no parameters, the method will be called
  1519. and its return value used as the representation.
  1520. For example, the following would call `get_expiry_date()` on the object:
  1521. class ExampleSerializer(Serializer):
  1522. expiry_date = ReadOnlyField(source='get_expiry_date')
  1523. """
  1524. def __init__(self, **kwargs):
  1525. kwargs['read_only'] = True
  1526. super().__init__(**kwargs)
  1527. def to_representation(self, value):
  1528. return value
  1529. class HiddenField(Field):
  1530. """
  1531. A hidden field does not take input from the user, or present any output,
  1532. but it does populate a field in `validated_data`, based on its default
  1533. value. This is particularly useful when we have a `unique_for_date`
  1534. constraint on a pair of fields, as we need some way to include the date in
  1535. the validated data.
  1536. """
  1537. def __init__(self, **kwargs):
  1538. assert 'default' in kwargs, 'default is a required argument.'
  1539. kwargs['write_only'] = True
  1540. super().__init__(**kwargs)
  1541. def get_value(self, dictionary):
  1542. # We always use the default value for `HiddenField`.
  1543. # User input is never provided or accepted.
  1544. return empty
  1545. def to_internal_value(self, data):
  1546. return data
  1547. class SerializerMethodField(Field):
  1548. """
  1549. A read-only field that get its representation from calling a method on the
  1550. parent serializer class. The method called will be of the form
  1551. "get_{field_name}", and should take a single argument, which is the
  1552. object being serialized.
  1553. For example:
  1554. class ExampleSerializer(self):
  1555. extra_info = SerializerMethodField()
  1556. def get_extra_info(self, obj):
  1557. return ... # Calculate some data to return.
  1558. """
  1559. def __init__(self, method_name=None, **kwargs):
  1560. self.method_name = method_name
  1561. kwargs['source'] = '*'
  1562. kwargs['read_only'] = True
  1563. super().__init__(**kwargs)
  1564. def bind(self, field_name, parent):
  1565. # In order to enforce a consistent style, we error if a redundant
  1566. # 'method_name' argument has been used. For example:
  1567. # my_field = serializer.SerializerMethodField(method_name='get_my_field')
  1568. default_method_name = 'get_{field_name}'.format(field_name=field_name)
  1569. # The method name should default to `get_{field_name}`.
  1570. if self.method_name is None:
  1571. self.method_name = default_method_name
  1572. super().bind(field_name, parent)
  1573. def to_representation(self, value):
  1574. method = getattr(self.parent, self.method_name)
  1575. return method(value)
  1576. class ModelField(Field):
  1577. """
  1578. A generic field that can be used against an arbitrary model field.
  1579. This is used by `ModelSerializer` when dealing with custom model fields,
  1580. that do not have a serializer field to be mapped to.
  1581. """
  1582. default_error_messages = {
  1583. 'max_length': _('Ensure this field has no more than {max_length} characters.'),
  1584. }
  1585. def __init__(self, model_field, **kwargs):
  1586. self.model_field = model_field
  1587. # The `max_length` option is supported by Django's base `Field` class,
  1588. # so we'd better support it here.
  1589. self.max_length = kwargs.pop('max_length', None)
  1590. super().__init__(**kwargs)
  1591. if self.max_length is not None:
  1592. message = lazy_format(self.error_messages['max_length'], max_length=self.max_length)
  1593. self.validators.append(
  1594. MaxLengthValidator(self.max_length, message=message))
  1595. def to_internal_value(self, data):
  1596. rel = self.model_field.remote_field
  1597. if rel is not None:
  1598. return rel.model._meta.get_field(rel.field_name).to_python(data)
  1599. return self.model_field.to_python(data)
  1600. def get_attribute(self, obj):
  1601. # We pass the object instance onto `to_representation`,
  1602. # not just the field attribute.
  1603. return obj
  1604. def to_representation(self, obj):
  1605. value = self.model_field.value_from_object(obj)
  1606. if is_protected_type(value):
  1607. return value
  1608. return self.model_field.value_to_string(obj)