rest_framework.fields

Module Contents

class empty

This class is used to represent no data being provided for a given input or output value.

It is required because None may be a valid input or output value.

is_simple_callable(obj)

True if the object is a callable that takes no arguments.

get_attribute(instance, attrs)

Similar to Python’s built in getattr(instance, attr), but takes a list of nested attributes, instead of a single attribute.

Also accepts either attribute lookup on objects or dictionary lookups.

set_value(dictionary, keys, value)

Similar to Python’s built in dictionary[key] = value, but takes a list of nested keys instead of a single key.

set_value({‘a’: 1}, [], {‘b’: 2}) -> {‘a’: 1, ‘b’: 2} set_value({‘a’: 1}, [‘x’], 2) -> {‘a’: 1, ‘x’: 2} set_value({‘a’: 1}, [‘x’, ‘y’], 2) -> {‘a’: 1, ‘x’: {‘y’: 2}}

to_choices_dict(choices)

Convert choices into key/value dicts.

to_choices_dict([1]) -> {1: 1} to_choices_dict([(1, ‘1st’), (2, ‘2nd’)]) -> {1: ‘1st’, 2: ‘2nd’} to_choices_dict([(‘Group’, ((1, ‘1st’), 2))]) -> {‘Group’: {1: ‘1st’, 2: ‘2’}}

flatten_choices_dict(choices)

Convert a group choices dict into a flat dict of choices.

flatten_choices_dict({1: ‘1st’, 2: ‘2nd’}) -> {1: ‘1st’, 2: ‘2nd’} flatten_choices_dict({‘Group’: {1: ‘1st’, 2: ‘2nd’}}) -> {1: ‘1st’, 2: ‘2nd’}

iter_options(grouped_choices, cutoff=None, cutoff_text=None)

Helper function for options and option groups in templates.

get_error_detail(exc_info)

Given a Django ValidationError, return a list of ErrorDetail, with the code populated.

class CreateOnlyDefault(default)

Bases:object

This class may be used to provide default values that are only used for create operations, but that do not return any value for update operations.

set_context(self, serializer_field)
__call__(self)
__repr__(self)
class CurrentUserDefault

Bases:object

set_context(self, serializer_field)
__call__(self)
__repr__(self)
exception SkipField

Bases:Exception

REGEX_TYPE
NOT_READ_ONLY_WRITE_ONLY = May not set both `read_only` and `write_only`
NOT_READ_ONLY_REQUIRED = May not set both `read_only` and `required`
NOT_REQUIRED_DEFAULT = May not set both `required` and `default`
USE_READONLYFIELD = Field(read_only=True) should be ReadOnlyField
MISSING_ERROR_MESSAGE = ValidationError raised by `{class_name}`, but error key `{key}` does not exist in the `error_messages` dictionary.
class Field(read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False)

Bases:object

_creation_counter = 0
default_error_messages
default_validators = []
default_empty_html
initial
validators
root

Returns the top-level serializer for this field.

context

Returns the context as passed to the root serializer on initialization.

bind(self, field_name, parent)

Initializes the field name and parent for the field instance. Called when a field is added to the parent serializer instance.

get_validators(self)
get_initial(self)

Return a value to use when the field is being returned as a primitive value, without any object instance.

get_value(self, dictionary)

Given the incoming primitive data, return the value for this field that should be validated and transformed to a native value.

get_attribute(self, instance)

Given the outgoing object instance, return the primitive value that should be used for this field.

get_default(self)

Return the default value to use when validating data if no input is provided for this field.

If a default has not been set for this field then this will simply raise SkipField, indicating that no value should be set in the validated data for this field.

validate_empty_values(self, data)

Validate empty values, and either:

  • Raise ValidationError, indicating invalid data.
  • Raise SkipField, indicating that the field should be ignored.
  • Return (True, data), indicating an empty value that should be returned without any further validation being applied.
  • Return (False, data), indicating a non-empty value, that should have validation applied as normal.
run_validation(self, data=empty)

Validate a simple representation and return the internal value.

The provided data may be empty if no representation was included in the input.

May raise SkipField if the field should not be included in the validated data.

run_validators(self, value)

Test the given value against all the validators on the field, and either raise a ValidationError or simply return.

to_internal_value(self, data)

Transform the incoming primitive data into a native value.

to_representation(self, value)

Transform the outgoing native value into primitive data.

fail(self, key, **kwargs)

A helper method that simply raises a validation error.

classmethod __new__(cls, *args, **kwargs)

When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object.

__deepcopy__(self, memo)

When cloning fields we instantiate using the arguments it was originally created with, rather than copying the complete state.

__repr__(self)

Fields are represented using their initial calling arguments. This allows us to create descriptive representations for serializer instances that show all the declared fields on the serializer.

class BooleanField

Bases:rest_framework.fields.Field

default_error_messages
default_empty_html = False
initial = False
TRUE_VALUES
FALSE_VALUES
NULL_VALUES
to_internal_value(self, data)
to_representation(self, value)
class NullBooleanField(**kwargs)

Bases:rest_framework.fields.Field

default_error_messages
initial
TRUE_VALUES
FALSE_VALUES
NULL_VALUES
to_internal_value(self, data)
to_representation(self, value)
class CharField(**kwargs)

Bases:rest_framework.fields.Field

default_error_messages
initial =
run_validation(self, data=empty)
to_internal_value(self, data)
to_representation(self, value)
class EmailField(**kwargs)

Bases:rest_framework.fields.CharField

default_error_messages
class RegexField(regex, **kwargs)

Bases:rest_framework.fields.CharField

default_error_messages
class SlugField(allow_unicode=False, **kwargs)

Bases:rest_framework.fields.CharField

default_error_messages
class URLField(**kwargs)

Bases:rest_framework.fields.CharField

default_error_messages
class UUIDField(**kwargs)

Bases:rest_framework.fields.Field

valid_formats = ['hex_verbose', 'hex', 'int', 'urn']
default_error_messages
to_internal_value(self, data)
to_representation(self, value)
class IPAddressField(protocol='both', **kwargs)

Bases:rest_framework.fields.CharField

Support both IPAddressField and GenericIPAddressField

default_error_messages
to_internal_value(self, data)
class IntegerField(**kwargs)

Bases:rest_framework.fields.Field

default_error_messages
MAX_STRING_LENGTH = 1000
re_decimal
to_internal_value(self, data)
to_representation(self, value)
class FloatField(**kwargs)

Bases:rest_framework.fields.Field

default_error_messages
MAX_STRING_LENGTH = 1000
to_internal_value(self, data)
to_representation(self, value)
class DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None, localize=False, rounding=None, **kwargs)

Bases:rest_framework.fields.Field

default_error_messages
MAX_STRING_LENGTH = 1000
to_internal_value(self, data)

Validate that the input is a decimal number and return a Decimal instance.

validate_precision(self, value)

Ensure that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point.

Override this method to disable the precision validation for input values or to enhance it in any way you need to.

to_representation(self, value)
quantize(self, value)

Quantize the decimal value to the configured precision.

class DateTimeField(format=empty, input_formats=None, default_timezone=None, *args, **kwargs)

Bases:rest_framework.fields.Field

default_error_messages
datetime_parser
enforce_timezone(self, value)

When self.default_timezone is None, always return naive datetimes. When self.default_timezone is not None, always return aware datetimes.

default_timezone(self)
to_internal_value(self, value)
to_representation(self, value)
class DateField(format=empty, input_formats=None, *args, **kwargs)

Bases:rest_framework.fields.Field

default_error_messages
datetime_parser
to_internal_value(self, value)
to_representation(self, value)
class TimeField(format=empty, input_formats=None, *args, **kwargs)

Bases:rest_framework.fields.Field

default_error_messages
datetime_parser
to_internal_value(self, value)
to_representation(self, value)
class DurationField(**kwargs)

Bases:rest_framework.fields.Field

default_error_messages
to_internal_value(self, value)
to_representation(self, value)
class ChoiceField(choices, **kwargs)

Bases:rest_framework.fields.Field

default_error_messages
html_cutoff
html_cutoff_text
choices
to_internal_value(self, data)
to_representation(self, value)
iter_options(self)

Helper method for use with templates rendering select widgets.

_get_choices(self)
_set_choices(self, choices)
class MultipleChoiceField(*args, **kwargs)

Bases:rest_framework.fields.ChoiceField

default_error_messages
default_empty_html = []
get_value(self, dictionary)
to_internal_value(self, data)
to_representation(self, value)
class FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)

Bases:rest_framework.fields.ChoiceField

default_error_messages
class FileField(*args, **kwargs)

Bases:rest_framework.fields.Field

default_error_messages
to_internal_value(self, data)
to_representation(self, value)
class ImageField(*args, **kwargs)

Bases:rest_framework.fields.FileField

default_error_messages
to_internal_value(self, data)
class _UnvalidatedField(*args, **kwargs)

Bases:rest_framework.fields.Field

to_internal_value(self, data)
to_representation(self, value)
class ListField(*args, **kwargs)

Bases:rest_framework.fields.Field

child
initial = []
default_error_messages
get_value(self, dictionary)
to_internal_value(self, data)

List of dicts of native values <- List of dicts of primitive datatypes.

to_representation(self, data)

List of object instances -> List of dicts of primitive datatypes.

run_child_validation(self, data)
class DictField(*args, **kwargs)

Bases:rest_framework.fields.Field

child
initial
default_error_messages
get_value(self, dictionary)
to_internal_value(self, data)

Dicts of native values <- Dicts of primitive datatypes.

to_representation(self, value)
run_child_validation(self, data)
class HStoreField(*args, **kwargs)

Bases:rest_framework.fields.DictField

child
class JSONField(*args, **kwargs)

Bases:rest_framework.fields.Field

default_error_messages
get_value(self, dictionary)
to_internal_value(self, data)
to_representation(self, value)
class ReadOnlyField(**kwargs)

Bases:rest_framework.fields.Field

A read-only field that simply returns the field value.

If the field is a method with no parameters, the method will be called and its return value used as the representation.

For example, the following would call get_expiry_date() on the object:

class ExampleSerializer(Serializer):
expiry_date = ReadOnlyField(source=’get_expiry_date’)
to_representation(self, value)
class HiddenField(**kwargs)

Bases:rest_framework.fields.Field

A hidden field does not take input from the user, or present any output, but it does populate a field in validated_data, based on its default value. This is particularly useful when we have a unique_for_date constraint on a pair of fields, as we need some way to include the date in the validated data.

get_value(self, dictionary)
to_internal_value(self, data)
class SerializerMethodField(method_name=None, **kwargs)

Bases:rest_framework.fields.Field

A read-only field that get its representation from calling a method on the parent serializer class. The method called will be of the form “get_{field_name}”, and should take a single argument, which is the object being serialized.

For example:

class ExampleSerializer(self):

extra_info = SerializerMethodField()

def get_extra_info(self, obj):
return … # Calculate some data to return.
bind(self, field_name, parent)
to_representation(self, value)
class ModelField(model_field, **kwargs)

Bases:rest_framework.fields.Field

A generic field that can be used against an arbitrary model field.

This is used by ModelSerializer when dealing with custom model fields, that do not have a serializer field to be mapped to.

default_error_messages
to_internal_value(self, data)
get_attribute(self, obj)
to_representation(self, obj)