diff --git a/api-guide/authentication/index.html b/api-guide/authentication/index.html index f59001286..e40fba126 100644 --- a/api-guide/authentication/index.html +++ b/api-guide/authentication/index.html @@ -65,7 +65,7 @@ - Search @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -761,7 +769,7 @@ class ExampleAuthentication(authentication.BaseAuthentication): diff --git a/api-guide/content-negotiation/index.html b/api-guide/content-negotiation/index.html index 2384a86b1..453cc5147 100644 --- a/api-guide/content-negotiation/index.html +++ b/api-guide/content-negotiation/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -466,7 +474,7 @@ class NoNegotiationView(APIView): diff --git a/api-guide/exceptions/index.html b/api-guide/exceptions/index.html index 30939688a..70c51cac3 100644 --- a/api-guide/exceptions/index.html +++ b/api-guide/exceptions/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -389,6 +397,10 @@ Throttled +
  • + ValidationError +
  • + @@ -484,7 +496,7 @@ class ServiceUnavailable(APIException):

    ParseError

    Signature: ParseError(detail=None)

    -

    Raised if the request contains malformed data when accessing request.DATA or request.FILES.

    +

    Raised if the request contains malformed data when accessing request.data.

    By default this exception results in a response with the HTTP status code "400 Bad Request".

    AuthenticationFailed

    Signature: AuthenticationFailed(detail=None)

    @@ -504,12 +516,25 @@ class ServiceUnavailable(APIException):

    By default this exception results in a response with the HTTP status code "405 Method Not Allowed".

    UnsupportedMediaType

    Signature: UnsupportedMediaType(media_type, detail=None)

    -

    Raised if there are no parsers that can handle the content type of the request data when accessing request.DATA or request.FILES.

    +

    Raised if there are no parsers that can handle the content type of the request data when accessing request.data.

    By default this exception results in a response with the HTTP status code "415 Unsupported Media Type".

    Throttled

    Signature: Throttled(wait=None, detail=None)

    Raised when an incoming request fails the throttling checks.

    By default this exception results in a response with the HTTP status code "429 Too Many Requests".

    +

    ValidationError

    +

    Signature: ValidationError(detail)

    +

    The ValidationError exception is slightly different from the other APIException classes:

    + +

    The ValidationError class should be used for serializer and field validation, and by validator classes. It is also raised when calling serializer.is_valid with the raise_exception keyword argument:

    +
    serializer.is_valid(raise_exception=True)
    +
    +

    The generic views use the raise_exception=True flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above.

    +

    By default this exception results in a response with the HTTP status code "400 Bad Request".

    @@ -524,7 +549,7 @@ class ServiceUnavailable(APIException): diff --git a/api-guide/fields/index.html b/api-guide/fields/index.html index f626507fc..9b4ad3e30 100644 --- a/api-guide/fields/index.html +++ b/api-guide/fields/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -349,31 +357,7 @@
  • - Generic Fields -
  • - - -
  • - Field -
  • - -
  • - WritableField -
  • - -
  • - ModelField -
  • - -
  • - SerializerMethodField -
  • - - - - -
  • - Typed Fields + Boolean fields
  • @@ -381,22 +365,22 @@ BooleanField +
  • + NullBooleanField +
  • + + + + +
  • + String fields +
  • + +
  • CharField
  • -
  • - URLField -
  • - -
  • - SlugField -
  • - -
  • - ChoiceField -
  • -
  • EmailField
  • @@ -406,16 +390,20 @@
  • - DateTimeField + SlugField
  • - DateField + URLField
  • -
  • - TimeField -
  • + + + +
  • + Numeric fields +
  • +
  • IntegerField @@ -429,6 +417,54 @@ DecimalField
  • + + + +
  • + Date and time fields +
  • + + +
  • + DateTimeField +
  • + +
  • + DateField +
  • + +
  • + TimeField +
  • + + + + +
  • + Choice selection fields +
  • + + +
  • + ChoiceField +
  • + +
  • + MultipleChoiceField +
  • + + + + +
  • + File upload fields +
  • + + +
  • + Parsers and file uploads. +
  • +
  • FileField
  • @@ -440,6 +476,42 @@ +
  • + Composite fields +
  • + + +
  • + ListField +
  • + + + + +
  • + Miscellaneous fields +
  • + + +
  • + ReadOnlyField +
  • + +
  • + HiddenField +
  • + +
  • + ModelField +
  • + +
  • + SerializerMethodField +
  • + + + +
  • Custom fields
  • @@ -492,21 +564,20 @@ -

    Serializer fields

    +
    +

    Note: This is the documentation for the version 3.0 of REST framework. Documentation for version 2.4 is also available.

    +
    +

    Serializer fields

    Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format.

    Django documentation

    Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects.


    -

    Note: The serializer fields are declared in fields.py, but by convention you should import them using from rest_framework import serializers and refer to fields as serializers.<FieldName>.

    +

    Note: The serializer fields are declared in fields.py, but by convention you should import them using from rest_framework import serializers and refer to fields as serializers.<FieldName>.


    Core arguments

    Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:

    -

    source

    -

    The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as Field(source='get_absolute_url'), or may use dotted notation to traverse attributes, such as Field(source='user.email').

    -

    The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations. (See the implementation of the PaginationSerializer class for an example.)

    -

    Defaults to the name of the field.

    read_only

    Set this to True to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization.

    Defaults to False

    @@ -517,111 +588,135 @@

    Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization.

    Defaults to True.

    +

    allow_null

    +

    Normally an error will be raised if None is passed to a serializer field. Set this keyword argument to True if None should be considered a valid value.

    +

    Defaults to False

    default

    If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all.

    May be set to a function or other callable, in which case the value will be evaluated each time it is used.

    +

    Note that setting a default value implies that the field is not required. Including both the default and required keyword arguments is invalid and will raise an error.

    +

    source

    +

    The name of the attribute that will be used to populate the field. May be a method that only takes a self argument, such as URLField('get_absolute_url'), or may use dotted notation to traverse attributes, such as EmailField(source='user.email').

    +

    The value source='*' has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation.

    +

    Defaults to the name of the field.

    validators

    -

    A list of Django validators that should be used to validate deserialized values.

    +

    A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise serializers.ValidationError, but Django's built-in ValidationError is also supported for compatibility with validators defined in the Django codebase or third party Django packages.

    error_messages

    A dictionary of error codes to error messages.

    -

    widget

    -

    Used only if rendering the field to HTML. -This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see the Django documentation on form widgets.

    label

    A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.

    help_text

    A text string that may be used as a description of the field in HTML form fields or other descriptive elements.

    -
    -

    Generic Fields

    -

    These generic fields are used for representing arbitrary model fields or the output of model methods.

    -

    Field

    -

    A generic, read-only field. You can use this field for any attribute that does not need to support write operations.

    -

    For example, using the following model.

    -
    from django.db import models
    -from django.utils.timezone import now
    +

    initial

    +

    A value that should be used for pre-populating the value of HTML form fields.

    +

    style

    +

    A dictionary of key-value pairs that can be used to control how renderers should render the field. The API for this should still be considered experimental, and will be formalized with the 3.1 release.

    +

    Two options are currently used in HTML form generation, 'input_type' and 'base_template'.

    +
    # Use <input type="password"> for the input.
    +password = serializers.CharField(
    +    style={'input_type': 'password'}
    +)
     
    -class Account(models.Model):
    -    owner = models.ForeignKey('auth.user')
    -    name = models.CharField(max_length=100)
    -    created = models.DateTimeField(auto_now_add=True)
    -    payment_expiry = models.DateTimeField()
    -
    -    def has_expired(self):
    -        return now() > self.payment_expiry
    -
    -

    A serializer definition that looked like this:

    -
    from rest_framework import serializers
    -
    -class AccountSerializer(serializers.HyperlinkedModelSerializer):
    -    expired = serializers.Field(source='has_expired')
    -
    -    class Meta:
    -        model = Account
    -        fields = ('url', 'owner', 'name', 'expired')
    -
    -

    Would produce output similar to:

    -
    {
    -    'url': 'http://example.com/api/accounts/3/',
    -    'owner': 'http://example.com/api/users/12/',
    -    'name': 'FooCorp business account',
    -    'expired': True
    +# Use a radio input instead of a select input.
    +color_channel = serializers.ChoiceField(
    +    choices=['red', 'green', 'blue']
    +    style = {'base_template': 'radio.html'}
     }
     
    -

    By default, the Field class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.

    -

    You can customize this behavior by overriding the .to_native(self, value) method.

    -

    WritableField

    -

    A field that supports both read and write operations. By itself WritableField does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the .to_native(self, value) and .from_native(self, value) methods.

    -

    ModelField

    -

    A generic field that can be tied to any arbitrary model field. The ModelField class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.

    -

    The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field'))

    -

    Signature: ModelField(model_field=<Django ModelField instance>)

    -

    SerializerMethodField

    -

    This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:

    -
    from django.contrib.auth.models import User
    -from django.utils.timezone import now
    -from rest_framework import serializers
    -
    -class UserSerializer(serializers.ModelSerializer):
    -    days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
    -
    -    class Meta:
    -        model = User
    -
    -    def get_days_since_joined(self, obj):
    -        return (now() - obj.date_joined).days
    -
    +

    Note: The style argument replaces the old-style version 2.x widget keyword argument. Because REST framework 3 now uses templated HTML form generation, the widget option that was used to support Django built-in widgets can no longer be supported. Version 3.1 is planned to include public API support for customizing HTML form generation.


    -

    Typed Fields

    -

    These fields represent basic datatypes, and support both reading and writing values.

    +

    Boolean fields

    BooleanField

    -

    A Boolean representation.

    +

    A boolean representation.

    Corresponds to django.db.models.fields.BooleanField.

    +

    Signature: BooleanField()

    +

    NullBooleanField

    +

    A boolean representation that also accepts None as a valid value.

    +

    Corresponds to django.db.models.fields.NullBooleanField.

    +

    Signature: NullBooleanField()

    +
    +

    String fields

    CharField

    -

    A text representation, optionally validates the text to be shorter than max_length and longer than min_length. -If allow_none is False (default), None values will be converted to an empty string.

    -

    Corresponds to django.db.models.fields.CharField -or django.db.models.fields.TextField.

    -

    Signature: CharField(max_length=None, min_length=None, allow_none=False)

    -

    URLField

    -

    Corresponds to django.db.models.fields.URLField. Uses Django's django.core.validators.URLValidator for validation.

    -

    Signature: URLField(max_length=200, min_length=None)

    -

    SlugField

    -

    Corresponds to django.db.models.fields.SlugField.

    -

    Signature: SlugField(max_length=50, min_length=None)

    -

    ChoiceField

    -

    A field that can accept a value out of a limited set of choices. Optionally takes a blank_display_value parameter that customizes the display value of an empty choice.

    -

    Signature: ChoiceField(choices=(), blank_display_value=None)

    +

    A text representation. Optionally validates the text to be shorter than max_length and longer than min_length.

    +

    Corresponds to django.db.models.fields.CharField or django.db.models.fields.TextField.

    +

    Signature: CharField(max_length=None, min_length=None, allow_blank=False)

    + +

    The allow_null option is also available for string fields, although its usage is discouraged in favor of allow_blank. It is valid to set both allow_blank=True and allow_null=True, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs.

    EmailField

    A text representation, validates the text to be a valid e-mail address.

    Corresponds to django.db.models.fields.EmailField

    +

    Signature: EmailField(max_length=None, min_length=None, allow_blank=False)

    RegexField

    A text representation, that validates the given value matches against a certain regular expression.

    +

    Corresponds to django.forms.fields.RegexField.

    +

    Signature: RegexField(regex, max_length=None, min_length=None, allow_blank=False)

    +

    The mandatory regex argument may either be a string, or a compiled python regular expression object.

    Uses Django's django.core.validators.RegexValidator for validation.

    -

    Corresponds to django.forms.fields.RegexField

    -

    Signature: RegexField(regex, max_length=None, min_length=None)

    +

    SlugField

    +

    A RegexField that validates the input against the pattern [a-zA-Z0-9_-]+.

    +

    Corresponds to django.db.models.fields.SlugField.

    +

    Signature: SlugField(max_length=50, min_length=None, allow_blank=False)

    +

    URLField

    +

    A RegexField that validates the input against a URL matching pattern. Expects fully qualified URLs of the form http://<host>/<path>.

    +

    Corresponds to django.db.models.fields.URLField. Uses Django's django.core.validators.URLValidator for validation.

    +

    Signature: URLField(max_length=200, min_length=None, allow_blank=False)

    +
    +

    Numeric fields

    +

    IntegerField

    +

    An integer representation.

    +

    Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField.

    +

    Signature: IntegerField(max_value=None, min_value=None)

    + +

    FloatField

    +

    A floating point representation.

    +

    Corresponds to django.db.models.fields.FloatField.

    +

    Signature: FloatField(max_value=None, min_value=None)

    + +

    DecimalField

    +

    A decimal representation, represented in Python by a Decimal instance.

    +

    Corresponds to django.db.models.fields.DecimalField.

    +

    Signature: DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)

    + +

    Example usage

    +

    To validate numbers up to 999 with a resolution of 2 decimal places, you would use:

    +
    serializers.DecimalField(max_digits=5, decimal_places=2)
    +
    +

    And to validate numbers up to anything less than one billion with a resolution of 10 decimal places:

    +
    serializers.DecimalField(max_digits=19, decimal_places=10)
    +
    +

    This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer.

    +

    If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.

    +
    +

    Date and time fields

    DateTimeField

    A date and time representation.

    -

    Corresponds to django.db.models.fields.DateTimeField

    +

    Corresponds to django.db.models.fields.DateTimeField.

    +

    Signature: DateTimeField(format=None, input_formats=None)

    + +

    DateTimeField format strings.

    +

    Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')

    +

    When a value of None is used for the format datetime objects will be returned by to_representation and the final output representation will determined by the renderer class.

    +

    In the case of JSON this means the default datetime representation uses the ECMA 262 date time string specification. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: 2013-01-29T12:34:56.123Z.

    +

    auto_now and auto_now_add model fields.

    When using ModelSerializer or HyperlinkedModelSerializer, note that any model fields with auto_now=True or auto_now_add=True will use serializer fields that are read_only=True by default.

    If you want to override this behavior, you'll need to declare the DateTimeField explicitly on the serializer. For example:

    class CommentSerializer(serializers.ModelSerializer):
    @@ -630,84 +725,134 @@ or django.db.models.fields.TextField.

    class Meta: model = Comment
    -

    Note that by default, datetime representations are determined by the renderer in use, although this can be explicitly overridden as detailed below.

    -

    In the case of JSON this means the default datetime representation uses the ECMA 262 date time string specification. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: 2013-01-29T12:34:56.123Z.

    -

    Signature: DateTimeField(format=None, input_formats=None)

    - -

    DateTime format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style datetimes should be used. (eg '2013-01-29T12:34:56.000000Z')

    DateField

    A date representation.

    Corresponds to django.db.models.fields.DateField

    Signature: DateField(format=None, input_formats=None)

    -

    Date format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29')

    +

    DateField format strings

    +

    Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style dates should be used. (eg '2013-01-29')

    TimeField

    A time representation.

    -

    Optionally takes format as parameter to replace the matching pattern.

    Corresponds to django.db.models.fields.TimeField

    Signature: TimeField(format=None, input_formats=None)

    -

    Time format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000')

    -

    IntegerField

    -

    An integer representation.

    -

    Corresponds to django.db.models.fields.IntegerField, django.db.models.fields.SmallIntegerField, django.db.models.fields.PositiveIntegerField and django.db.models.fields.PositiveSmallIntegerField

    -

    FloatField

    -

    A floating point representation.

    -

    Corresponds to django.db.models.fields.FloatField.

    -

    DecimalField

    -

    A decimal representation, represented in Python by a Decimal instance.

    -

    Has two required arguments:

    +

    TimeField format strings

    +

    Format strings may either be Python strftime formats which explicitly specify the format, or the special string 'iso-8601', which indicates that ISO 8601 style times should be used. (eg '12:34:56.000000')

    +
    +

    Choice selection fields

    +

    ChoiceField

    +

    A field that can accept a value out of a limited set of choices.

    +

    Used by ModelSerializer to automatically generate fields if the corresponding model field includes a choices=… argument.

    +

    Signature: ChoiceField(choices)

    -

    For example, to validate numbers up to 999 with a resolution of 2 decimal places, you would use:

    -
    serializers.DecimalField(max_digits=5, decimal_places=2)
    -
    -

    And to validate numbers up to anything less than one billion with a resolution of 10 decimal places:

    -
    serializers.DecimalField(max_digits=19, decimal_places=10)
    -
    -

    This field also takes an optional argument, coerce_to_string. If set to True the representation will be output as a string. If set to False the representation will be left as a Decimal instance and the final representation will be determined by the renderer.

    -

    If unset, this will default to the same value as the COERCE_DECIMAL_TO_STRING setting, which is True unless set otherwise.

    -

    Signature: DecimalField(max_digits, decimal_places, coerce_to_string=None)

    -

    Corresponds to django.db.models.fields.DecimalField.

    +

    MultipleChoiceField

    +

    A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. to_internal_representation returns a set containing the selected values.

    +

    Signature: MultipleChoiceField(choices)

    + +
    +

    File upload fields

    +

    Parsers and file uploads.

    +

    The FileField and ImageField classes are only suitable for use with MultiPartParser or FileUploadParser. Most parsers, such as e.g. JSON don't support file uploads. +Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.

    FileField

    A file representation. Performs Django's standard FileField validation.

    Corresponds to django.forms.fields.FileField.

    -

    Signature: FileField(max_length=None, allow_empty_file=False)

    +

    Signature: FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

    ImageField

    -

    An image representation.

    +

    An image representation. Validates the uploaded file content as matching a known image format.

    Corresponds to django.forms.fields.ImageField.

    +

    Signature: ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)

    +

    Requires either the Pillow package or PIL package. The Pillow package is recommended, as PIL is no longer actively maintained.

    -

    Signature and validation is the same as with FileField.


    -

    Note: FileFields and ImageFields are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads. -Django's regular FILE_UPLOAD_HANDLERS are used for handling uploaded files.

    +

    Composite fields

    +

    ListField

    +

    A field class that validates a list of objects.

    +

    Signature: ListField(child)

    + +

    For example, to validate a list of integers you might use something like the following:

    +
    scores = serializers.ListField(
    +   child=serializers.IntegerField(min_value=0, max_value=100)
    +)
    +
    +

    The ListField class also supports a declarative style that allows you to write reusable list field classes.

    +
    class StringListField(serializers.ListField):
    +    child = serializers.CharField()
    +
    +

    We can now reuse our custom StringListField class throughout our application, without having to provide a child argument to it.

    +
    +

    Miscellaneous fields

    +

    ReadOnlyField

    +

    A field class that simply returns the value of the field without modification.

    +

    This field is used by default with ModelSerializer when including field names that relate to an attribute rather than a model field.

    +

    Signature: ReadOnlyField()

    +

    For example, is has_expired was a property on the Account model, then the following serializer would automatically generate it as a ReadOnlyField:

    +
    class AccountSerializer(serializers.ModelSerializer):
    +    class Meta:
    +        model = Account
    +        fields = ('id', 'account_name', 'has_expired')
    +
    +

    HiddenField

    +

    A field class that does not take a value based on user input, but instead takes its value from a default value or callable.

    +

    Signature: HiddenField()

    +

    For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following:

    +
    modified = serializer.HiddenField(default=timezone.now)
    +
    +

    The HiddenField class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user.

    +

    For further examples on HiddenField see the validators documentation.

    +

    ModelField

    +

    A generic field that can be tied to any arbitrary model field. The ModelField class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field.

    +

    This field is used by ModelSerializer to correspond to custom model field classes.

    +

    Signature: ModelField(model_field=<Django ModelField instance>)

    +

    The ModelField class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a ModelField, it must be passed a field that is attached to an instantiated model. For example: ModelField(model_field=MyModel()._meta.get_field('custom_field'))

    +

    SerializerMethodField

    +

    This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.

    +

    Signature: SerializerMethodField(method_name=None)

    + +

    The serializer method referred to by the method_name argument should accept a single argument (in addition to self), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:

    +
    from django.contrib.auth.models import User
    +from django.utils.timezone import now
    +from rest_framework import serializers
    +
    +class UserSerializer(serializers.ModelSerializer):
    +    days_since_joined = serializers.SerializerMethodField()
    +
    +    class Meta:
    +        model = User
    +
    +    def get_days_since_joined(self, obj):
    +        return (now() - obj.date_joined).days
    +

    Custom fields

    -

    If you want to create a custom field, you'll probably want to override either one or both of the .to_native() and .from_native() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects.

    -

    The .to_native() method is called to convert the initial datatype into a primitive, serializable datatype. The from_native() method is called to restore a primitive datatype into its initial representation.

    +

    If you want to create a custom field, you'll need to subclass Field and then override either one or both of the .to_representation() and .to_internal_value() methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using.

    +

    The .to_representation() method is called to convert the initial datatype into a primitive, serializable datatype.

    +

    The to_internal_value() method is called to restore a primitive datatype into its internal python representation.

    +

    Note that the WritableField class that was present in version 2.x no longer exists. You should subclass Field and override to_internal_value() if the field supports data input.

    Examples

    Let's look at an example of serializing a class that represents an RGB color value:

    class Color(object):
    @@ -719,22 +864,27 @@ Django's regular 
    -

    By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .field_to_native() and/or .field_from_native().

    +

    By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override .get_attribute() and/or .get_value().

    As an example, let's create a field that can be used represent the class name of the object being serialized:

    class ClassNameField(serializers.Field):
    -    def field_to_native(self, obj, field_name):
    +    def get_attribute(self, obj):
    +        # We pass the object instance onto `to_representation`,
    +        # not just the field attribute.
    +        return obj
    +
    +    def to_representation(self, obj):
             """
             Serialize the object's class name.
             """
    @@ -764,7 +914,7 @@ class ColourField(serializers.WritableField):
       
     
       
     
    diff --git a/api-guide/filtering/index.html b/api-guide/filtering/index.html
    index d7b5b88c4..654d7b054 100644
    --- a/api-guide/filtering/index.html
    +++ b/api-guide/filtering/index.html
    @@ -164,6 +164,10 @@
                         Serializer relations
                       
                       
    +                  
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -756,7 +764,7 @@ class ProductFilter(django_filters.FilterSet): diff --git a/api-guide/format-suffixes/index.html b/api-guide/format-suffixes/index.html index 3f66cf148..3ebd2d8fd 100644 --- a/api-guide/format-suffixes/index.html +++ b/api-guide/format-suffixes/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -432,7 +440,7 @@ def comment_list(request, format=None): diff --git a/api-guide/generic-views/index.html b/api-guide/generic-views/index.html index e39d4118e..c0a6ef8c2 100644 --- a/api-guide/generic-views/index.html +++ b/api-guide/generic-views/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -488,12 +496,15 @@ -

    Generic views

    +
    +

    Note: This is the documentation for the version 3.0 of REST framework. Documentation for version 2.4 is also available.

    +
    +

    Generic views

    Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself.

    Django Documentation

    -

    One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.

    +

    One of the key benefits of class based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns.

    The generic views provided by REST framework allow you to quickly build API views that map closely to your database models.

    If the generic views don't suit the needs of your API, you can drop down to using the regular APIView class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views.

    Examples

    @@ -618,22 +629,23 @@ class UserList(generics.ListCreateAPIView): return 20 return 100
    -

    Save / deletion hooks:

    -

    The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by GenericAPIView, but they are overridden and used by some of the mixin classes.

    +

    Save and deletion hooks:

    +

    The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.

      -
    • pre_save(self, obj) - A hook that is called before saving an object.
    • -
    • post_save(self, obj, created=False) - A hook that is called after saving an object.
    • -
    • pre_delete(self, obj) - A hook that is called before deleting an object.
    • -
    • post_delete(self, obj) - A hook that is called after deleting an object.
    • +
    • perform_create(self, serializer) - Called by CreateModelMixin when saving a new object instance.
    • +
    • perform_update(self, serializer) - Called by UpdateModelMixin when saving an existing object instance.
    • +
    • perform_destroy(self, instance) - Called by DestroyModelMixin when deleting an object instance.
    -

    The pre_save method in particular is a useful hook for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.

    -
    def pre_save(self, obj):
    -    """
    -    Set the object's owner, based on the incoming request.
    -    """
    -    obj.owner = self.request.user
    +

    These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.

    +
    def perform_create(self, serializer):
    +    serializer.save(user=self.request.user)
     
    -

    Remember that the pre_save() method is not called by GenericAPIView itself, but it is called by create() and update() methods on the CreateModelMixin and UpdateModelMixin classes.

    +

    These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update.

    +
    def perform_update(self, serializer):
    +    instance = serializer.save()
    +    send_email_confirmation(user=self.request.user, modified=instance)
    +
    +

    Note: These methods replace the old-style version 2.x pre_save, post_save, pre_delete and post_delete methods, which are no longer available.

    Other methods:

    You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using GenericAPIView.

      @@ -728,7 +740,7 @@ class UserList(generics.ListCreateAPIView): serializer_class = UserSerializer lookup_fields = ('account', 'username')
    -

    Using custom mixins is a good option if you have custom behavior that needs to be used

    +

    Using custom mixins is a good option if you have custom behavior that needs to be used.

    Creating custom base classes

    If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example:

    class BaseRetrieveView(MultipleFieldLookupMixin,
    @@ -765,7 +777,7 @@ class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin,
       
     
       
     
    diff --git a/api-guide/pagination/index.html b/api-guide/pagination/index.html
    index 28f278963..769a0b9a1 100644
    --- a/api-guide/pagination/index.html
    +++ b/api-guide/pagination/index.html
    @@ -164,6 +164,10 @@
                         Serializer relations
                       
                       
    +                  
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -540,7 +548,7 @@ class CustomPaginationSerializer(pagination.BasePaginationSerializer): diff --git a/api-guide/parsers/index.html b/api-guide/parsers/index.html index 5a026c0e5..b43065797 100644 --- a/api-guide/parsers/index.html +++ b/api-guide/parsers/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -449,7 +457,7 @@ sending more complex data than simple forms

    REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts.

    How the parser is determined

    -

    The set of valid parsers for a view is always defined as a list of classes. When either request.DATA or request.FILES is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content.

    +

    The set of valid parsers for a view is always defined as a list of classes. When request.data is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content.


    Note: When developing client applications always remember to make sure you're setting the Content-Type header when sending data in an HTTP request.

    If you don't set the content type, most clients will default to using 'application/x-www-form-urlencoded', which may not be what you wanted.

    @@ -476,7 +484,7 @@ class ExampleView(APIView): parser_classes = (YAMLParser,) def post(self, request, format=None): - return Response({'received data': request.DATA}) + return Response({'received data': request.data})

    Or, if you're using the @api_view decorator with function based views.

    @api_view(['POST'])
    @@ -485,7 +493,7 @@ def example_view(request, format=None):
         """
         A view that can accept POST requests with YAML content.
         """
    -    return Response({'received data': request.DATA})
    +    return Response({'received data': request.data})
     

    API Reference

    @@ -503,15 +511,15 @@ def example_view(request, format=None):

    Requires the defusedxml package to be installed.

    .media_type: application/xml

    FormParser

    -

    Parses HTML form content. request.DATA will be populated with a QueryDict of data, request.FILES will be populated with an empty QueryDict of data.

    +

    Parses HTML form content. request.data will be populated with a QueryDict of data.

    You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.

    .media_type: application/x-www-form-urlencoded

    MultiPartParser

    -

    Parses multipart HTML form content, which supports file uploads. Both request.DATA and request.FILES will be populated with a QueryDict.

    +

    Parses multipart HTML form content, which supports file uploads. Both request.data will be populated with a QueryDict.

    You will typically want to use both FormParser and MultiPartParser together in order to fully support HTML form data.

    .media_type: multipart/form-data

    FileUploadParser

    -

    Parses raw file upload content. The request.DATA property will be an empty QueryDict, and request.FILES will be a dictionary with a single key 'file' containing the uploaded file.

    +

    Parses raw file upload content. The request.data property will be a dictionary with a single key 'file' containing the uploaded file.

    If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.

    .media_type: */*

    Notes:
    @@ -525,7 +533,7 @@ def example_view(request, format=None): parser_classes = (FileUploadParser,) def put(self, request, filename, format=None): - file_obj = request.FILES['file'] + file_obj = request.data['file'] # ... # do some staff with uploaded file # ... @@ -534,7 +542,7 @@ def example_view(request, format=None):

    Custom parsers

    To implement a custom parser, you should override BaseParser, set the .media_type property, and implement the .parse(self, stream, media_type, parser_context) method.

    -

    The method should return the data that will be used to populate the request.DATA property.

    +

    The method should return the data that will be used to populate the request.data property.

    The arguments passed to .parse() are:

    stream

    A stream-like object representing the body of the request.

    @@ -545,7 +553,7 @@ def example_view(request, format=None):

    Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content.

    By default this will include the following keys: view, request, args, kwargs.

    Example

    -

    The following is an example plaintext parser that will populate the request.DATA property with a string representing the body of the request.

    +

    The following is an example plaintext parser that will populate the request.data property with a string representing the body of the request.

    class PlainTextParser(BaseParser):
     """
     Plain text parser.
    @@ -580,7 +588,7 @@ def parse(self, stream, media_type=None, parser_context=None):
       
     
       
     
    diff --git a/api-guide/permissions/index.html b/api-guide/permissions/index.html
    index 521791670..331a3928b 100644
    --- a/api-guide/permissions/index.html
    +++ b/api-guide/permissions/index.html
    @@ -164,6 +164,10 @@
                         Serializer relations
                       
                       
    +                  
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -632,7 +640,7 @@ class BlacklistPermission(permissions.BasePermission): diff --git a/api-guide/relations/index.html b/api-guide/relations/index.html index 3f3a24602..0fe39d355 100644 --- a/api-guide/relations/index.html +++ b/api-guide/relations/index.html @@ -62,7 +62,7 @@

    This should all feel very familiar - it is not a lot different from working with regular Django views.

    -

    Notice that we're no longer explicitly tying our requests or responses to a given content type. request.DATA can handle incoming json requests, but it can also handle yaml and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.

    +

    Notice that we're no longer explicitly tying our requests or responses to a given content type. request.data can handle incoming json requests, but it can also handle yaml and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.

    Adding optional format suffixes to our URLs

    To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as http://example.com/api/items/4.json.

    Start by adding a format keyword argument to both of the views, like so.

    @@ -532,7 +540,7 @@ curl -X POST http://127.0.0.1:8000/snippets/ -d '{"code": "print 456"}' -H "Cont diff --git a/tutorial/3-class-based-views/index.html b/tutorial/3-class-based-views/index.html index bdeebb79a..eac633aab 100644 --- a/tutorial/3-class-based-views/index.html +++ b/tutorial/3-class-based-views/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -388,7 +396,7 @@ class SnippetList(APIView): return Response(serializer.data) def post(self, request, format=None): - serializer = SnippetSerializer(data=request.DATA) + serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) @@ -412,7 +420,7 @@ class SnippetList(APIView): def put(self, request, pk, format=None): snippet = self.get_object(pk) - serializer = SnippetSerializer(snippet, data=request.DATA) + serializer = SnippetSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) @@ -509,7 +517,7 @@ class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): diff --git a/tutorial/4-authentication-and-permissions/index.html b/tutorial/4-authentication-and-permissions/index.html index 12ecfafa9..df92f540a 100644 --- a/tutorial/4-authentication-and-permissions/index.html +++ b/tutorial/4-authentication-and-permissions/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -566,7 +574,7 @@ class IsOwnerOrReadOnly(permissions.BasePermission): diff --git a/tutorial/5-relationships-and-hyperlinked-apis/index.html b/tutorial/5-relationships-and-hyperlinked-apis/index.html index 5446c25b6..80e840044 100644 --- a/tutorial/5-relationships-and-hyperlinked-apis/index.html +++ b/tutorial/5-relationships-and-hyperlinked-apis/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -519,7 +527,7 @@ urlpatterns += [ diff --git a/tutorial/6-viewsets-and-routers/index.html b/tutorial/6-viewsets-and-routers/index.html index 69cc3bad4..0740d4963 100644 --- a/tutorial/6-viewsets-and-routers/index.html +++ b/tutorial/6-viewsets-and-routers/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -509,7 +517,7 @@ urlpatterns = [ diff --git a/tutorial/quickstart/index.html b/tutorial/quickstart/index.html index 4ab94527a..762c9aeb6 100644 --- a/tutorial/quickstart/index.html +++ b/tutorial/quickstart/index.html @@ -164,6 +164,10 @@ Serializer relations +
  • + Validators +
  • +
  • Authentication
  • @@ -263,6 +267,10 @@ 2.4 Announcement +
  • + 3.0 Announcement +
  • +
  • Kickstarter Announcement
  • @@ -530,7 +538,7 @@ REST_FRAMEWORK = {