diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 541c65756..0eea31d72 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -119,6 +119,8 @@ To use the `TokenAuthentication` scheme, include `rest_framework.authtoken` in y ... 'rest_framework.authtoken' ) + +Make sure to run `manage.py syncdb` after changing your settings. You'll also need to create tokens for your users. @@ -140,6 +142,10 @@ Unauthenticated responses that are denied permission will result in an `HTTP 401 WWW-Authenticate: Token +The `curl` command line tool may be useful for testing token authenticated APIs. For example: + + curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' + --- **Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https` only. @@ -294,7 +300,7 @@ The only thing needed to make the `OAuth2Authentication` class work is to insert The command line to test the authentication looks like: - curl -H "Authorization: Bearer " http://localhost:8000/api/?client_id=YOUR_CLIENT_ID\&client_secret=YOUR_CLIENT_SECRET + curl -H "Authorization: Bearer " http://localhost:8000/api/ --- diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 9a745cf19..42f89f46a 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -197,12 +197,16 @@ If you want to override this behavior, you'll need to declare the `DateTimeField class Meta: model = Comment +Note that by default, datetime representations are deteremined 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][ecma262]. 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)` -* `format` - A string representing the output format. If not specified, the `DATETIME_FORMAT` setting will be used, which defaults to `'iso-8601'`. +* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `datetime` objects should be returned by `to_native`. In this case the datetime encoding will be determined by the renderer. * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. -DateTime format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000'`) +DateTime format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`) ## DateField @@ -212,7 +216,7 @@ Corresponds to `django.db.models.fields.DateField` **Signature:** `DateField(format=None, input_formats=None)` -* `format` - A string representing the output format. If not specified, the `DATE_FORMAT` setting will be used, which defaults to `'iso-8601'`. +* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `date` objects should be returned by `to_native`. In this case the date encoding will be determined by the renderer. * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. Date format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) @@ -227,7 +231,7 @@ Corresponds to `django.db.models.fields.TimeField` **Signature:** `TimeField(format=None, input_formats=None)` -* `format` - A string representing the output format. If not specified, the `TIME_FORMAT` setting will be used, which defaults to `'iso-8601'`. +* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that python `time` objects should be returned by `to_native`. In this case the time encoding will be determined by the renderer. * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. Time format strings may either be [python strftime formats][strftime] which explicitly specifiy the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) @@ -273,7 +277,51 @@ Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. --- +# 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 intial datatype, and a primative, serializable datatype. Primative 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 primative objects. + +The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation. + +## Examples + +Let's look at an example of serializing a class that represents an RGB color value: + + class Color(object): + """ + A color represented in the RGB colorspace. + """ + def __init__(self, red, green, blue): + assert(red >= 0 and green >= 0 and blue >= 0) + assert(red < 256 and green < 256 and blue < 256) + self.red, self.green, self.blue = red, green, blue + + class ColourField(serializers.WritableField): + """ + Color objects are serialized into "rgb(#, #, #)" notation. + """ + def to_native(self, obj): + return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) + + def from_native(self, data): + data = data.strip('rgb(').rstrip(')') + red, green, blue = [int(col) for col in data.split(',')] + return Color(red, green, blue) + + +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()`. + +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): + """ + Serialize the object's class name. + """ + return obj.__class__ + [cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data [FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS +[ecma262]: http://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 [strftime]: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior [iso8601]: http://www.w3.org/TR/NOTE-datetime diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 42edf9af1..1a3c3431b 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -37,9 +37,6 @@ Declaring a serializer looks very similar to declaring a form: """ Given a dictionary of deserialized field values, either update an existing model instance, or create a new model instance. - - Note that if we don't define this method, then deserializing - data will simply return a dictionary of items. """ if instance is not None: instance.title = attrs.get('title', instance.title) @@ -48,7 +45,9 @@ Declaring a serializer looks very similar to declaring a form: return instance return Comment(**attrs) -The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. The `restore_object` method is optional, and is only required if we want our serializer to support deserialization. +The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data. + +The `restore_object` method is optional, and is only required if we want our serializer to support deserialization into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items. ## Serializing objects @@ -88,23 +87,21 @@ By default, serializers must be passed values for all required fields or they wi serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `instance` with partial data -## Serializing querysets - -To serialize a queryset instead of an object instance, you should pass the `many=True` flag when instantiating the serializer. - - queryset = Comment.objects.all() - serializer = CommentSerializer(queryset, many=True) - serializer.data - # [{'email': u'leila@example.com', 'content': u'foo bar', 'created': datetime.datetime(2012, 8, 22, 16, 20, 9, 822774)}, {'email': u'jamie@example.com', 'content': u'baz', 'created': datetime.datetime(2013, 1, 12, 16, 12, 45, 104445)}] - ## Validation -When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. +When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example: + + serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) + serializer.is_valid() + # False + serializer.errors + # {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']} + Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items. -### Field-level validation +#### Field-level validation You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are analagous to `.clean_` methods on Django forms, but accept slightly different arguments. @@ -127,7 +124,7 @@ Your `validate_` methods should either just return the `attrs` dictio raise serializers.ValidationError("Blog post is not about Django") return attrs -### Object-level validation +#### Object-level validation To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. For example: @@ -148,26 +145,44 @@ To do any other validation that requires access to multiple fields, add a method ## Saving object state -Serializers also include a `.save()` method that you can override if you want to provide a method of persisting the state of a deserialized object. The default behavior of the method is to simply call `.save()` on the deserialized object instance. +To save the deserialized objects created by a serializer, call the `.save()` method: + + if serializer.is_valid(): + serializer.save() + +The default behavior of the method is to simply call `.save()` on the deserialized object instance. You can override the default save behaviour by overriding the `.save_object(obj)` method on the serializer class. The generic views provided by REST framework call the `.save()` method when updating or creating entities. ## Dealing with nested objects -The previous example is fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, -where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. +The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another. class UserSerializer(serializers.Serializer): - email = serializers.Field() - username = serializers.Field() + email = serializers.EmailField() + username = serializers.CharField(max_length=100) class CommentSerializer(serializers.Serializer): user = UserSerializer() - title = serializers.Field() - content = serializers.Field() - created = serializers.Field() + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() + +If a nested representation may optionally accept the `None` value you should pass the `required=False` flag to the nested serializer. + + class CommentSerializer(serializers.Serializer): + user = UserSerializer(required=False) # May be an anonymous user. + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() + +Similarly if a nested representation should be a list of items, you should the `many=True` flag to the nested serialized. + + class CommentSerializer(serializers.Serializer): + user = UserSerializer(required=False) + edits = EditItemSerializer(many=True) # A nested list of 'edit' items. + content = serializers.CharField(max_length=200) + created = serializers.DateTimeField() --- @@ -175,6 +190,96 @@ The `Serializer` class is itself a type of `Field`, and can be used to represent --- +## Dealing with multiple objects + +The `Serializer` class can also handle serializing or deserializing lists of objects. + +#### Serializing multiple objects + +To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized. + + queryset = Book.objects.all() + serializer = BookSerializer(queryset, many=True) + serializer.data + # [ + # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'}, + # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'}, + # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} + # ] + +#### Deserializing multiple objects for creation + +To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the `many=True` flag, and pass a list of data to be deserialized. + +This allows you to write views that create multiple items when a `POST` request is made. + +For example: + + data = [ + {'title': 'The bell jar', 'author': 'Sylvia Plath'}, + {'title': 'For whom the bell tolls', 'author': 'Ernest Hemingway'} + ] + serializer = BookSerializer(data=data, many=True) + serializer.is_valid() + # True + serializer.save() # `.save()` will be called on each deserialized instance + +#### Deserializing multiple objects for update + +You can also deserialize a list of objects as part of a bulk update of multiple existing items. +In this case you need to supply both an existing list or queryset of items, as well as a list of data to update those items with. + +This allows you to write views that update or create multiple items when a `PUT` request is made. + + # Capitalizing the titles of the books + queryset = Book.objects.all() + data = [ + {'id': 3, 'title': 'The Bell Jar', 'author': 'Sylvia Plath'}, + {'id': 4, 'title': 'For Whom the Bell Tolls', 'author': 'Ernest Hemingway'} + ] + serializer = BookSerializer(queryset, data=data, many=True) + serializer.is_valid() + # True + serialize.save() # `.save()` will be called on each updated or newly created instance. + +By default bulk updates will be limited to updating instances that already exist in the provided queryset. + +When performing a bulk update you may want to allow new items to be created, and missing items to be deleted. To do so, pass `allow_add_remove=True` to the serializer. + + serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True) + serializer.is_valid() + # True + serializer.save() # `.save()` will be called on updated or newly created instances. + # `.delete()` will be called on any other items in the `queryset`. + +Passing `allow_add_remove=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects. + +#### How identity is determined when performing bulk updates + +Performing a bulk update is slightly more complicated than performing a bulk creation, because the serializer needs a way to determine how the items in the incoming data should be matched against the existing object instances. + +By default the serializer class will use the `id` key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the `get_identity` method on the `Serializer` class. For example: + + class AccountSerializer(serializers.Serializer): + slug = serializers.CharField(max_length=100) + created = serializers.DateTimeField() + ... # Various other fields + + def get_identity(self, data): + """ + This hook is required for bulk update. + We need to override the default, to use the slug as the identity. + + Note that the data has not yet been validated at this point, + so we need to deal gracefully with incorrect datatypes. + """ + try: + return data.get('slug', None) + except AttributeError: + return None + +To map the incoming data items to their corresponding object instances, the `.get_identity()` method will be called both against the incoming data, and against the serialized representation of the existing objects. + ## Including extra context There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs. @@ -187,47 +292,6 @@ You can provide arbitrary additional context by passing a `context` argument whe The context dictionary can be used within any serializer field logic, such as a custom `.to_native()` method, by accessing the `self.context` attribute. -## Creating 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 intial datatype, and a primative, serializable datatype. Primative 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 primative objects. - -The `.to_native()` method is called to convert the initial datatype into a primative, serializable datatype. The `from_native()` method is called to restore a primative datatype into it's initial representation. - -Let's look at an example of serializing a class that represents an RGB color value: - - class Color(object): - """ - A color represented in the RGB colorspace. - """ - def __init__(self, red, green, blue): - assert(red >= 0 and green >= 0 and blue >= 0) - assert(red < 256 and green < 256 and blue < 256) - self.red, self.green, self.blue = red, green, blue - - class ColourField(serializers.WritableField): - """ - Color objects are serialized into "rgb(#, #, #)" notation. - """ - def to_native(self, obj): - return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue) - - def from_native(self, data): - data = data.strip('rgb(').rstrip(')') - red, green, blue = [int(col) for col in data.split(',')] - return Color(red, green, blue) - - -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()`. - -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): - """ - Serialize the object's class name. - """ - return obj.__class__ - --- # ModelSerializers diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 116386969..c0d8d9eea 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -192,44 +192,56 @@ Default: `'format'` --- -## Date/Time formatting +## Date and time formatting *The following settings are used to control how date and time representations may be parsed and rendered.* #### DATETIME_FORMAT -A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. +A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return python `datetime` objects, and the datetime encoding will be determined by the renderer. -Default: `'iso-8601'` +May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string. + +Default: `None'` #### DATETIME_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields. +May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings. + Default: `['iso-8601']` #### DATE_FORMAT -A format string that should be used by default for rendering the output of `DateField` serializer fields. +A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return python `date` objects, and the date encoding will be determined by the renderer. -Default: `'iso-8601'` +May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string. + +Default: `None` #### DATE_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields. +May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings. + Default: `['iso-8601']` #### TIME_FORMAT -A format string that should be used by default for rendering the output of `TimeField` serializer fields. +A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return python `time` objects, and the time encoding will be determined by the renderer. -Default: `'iso-8601'` +May be any of `None`, `'iso-8601'` or a python [strftime format][strftime] string. + +Default: `None` #### TIME_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields. +May be a list including the string `'iso-8601'` or python [strftime format][strftime] strings. + Default: `['iso-8601']` --- @@ -243,3 +255,4 @@ The name of a parameter in the URL conf that may be used to provide a format suf Default: `'format'` [cite]: http://www.python.org/dev/peps/pep-0020/ +[strftime]: http://docs.python.org/2/library/time.html#time.strftime \ No newline at end of file diff --git a/docs/css/default.css b/docs/css/default.css index c160b63d1..173d70e0d 100644 --- a/docs/css/default.css +++ b/docs/css/default.css @@ -277,3 +277,14 @@ footer a { footer a:hover { color: gray; } + +.btn-inverse { + background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#606060), to(#404040)) !important; + background-image: -webkit-linear-gradient(top, #606060, #404040) !important; +} + +.modal-open .modal,.btn:focus{outline:none;} + +@media (max-width: 650px) { + .repo-link.btn-inverse {display: none;} +} diff --git a/docs/index.md b/docs/index.md index 5357536d9..4c2720c89 100644 --- a/docs/index.md +++ b/docs/index.md @@ -9,9 +9,9 @@ # Django REST framework -**Web APIs for Django, made easy.** +**Awesome web-browseable Web APIs.** -Django REST framework is a flexible, powerful library that makes it incredibly easy to build Web APIs. It is designed as a modular and easy to customize architecture, based on Django's class based views. +Django REST framework is a flexible, powerful Web API toolkit. It is designed as a modular and easy to customize architecture, based on Django's class based views. APIs built using REST framework are fully self-describing and web browseable - a huge useability win for your developers. It also supports a wide range of media types, authentication and permission policies out of the box. diff --git a/docs/template.html b/docs/template.html index 3e0f29aa0..7e9297627 100644 --- a/docs/template.html +++ b/docs/template.html @@ -41,6 +41,9 @@