Debian Codegraph @

rest_framework/fields.py

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