fields.py 68 KB

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