Merge remote-tracking branch 'upstream/master' into writable-nested-serializers

This commit is contained in:
Mark Aaron Shirley 2013-02-17 10:07:50 -08:00
commit 14e2034cf7
43 changed files with 880 additions and 479 deletions

196
README.md
View File

@ -4,7 +4,7 @@
**Author:** Tom Christie. [Follow me on Twitter][twitter]. **Author:** Tom Christie. [Follow me on Twitter][twitter].
**Support:** [REST framework discussion group][group]. **Support:** [REST framework group][group], or `#restframework` on freenode IRC.
[![build-status-image]][travis] [![build-status-image]][travis]
@ -26,7 +26,7 @@ There is also a sandbox API you can use for testing purposes, [available here][s
# Requirements # Requirements
* Python (2.6, 2.7, 3.2, 3.3) * Python (2.6.5+, 2.7, 3.2, 3.3)
* Django (1.3, 1.4, 1.5) * Django (1.3, 1.4, 1.5)
**Optional:** **Optional:**
@ -77,198 +77,6 @@ To run the tests.
./rest_framework/runtests/runtests.py ./rest_framework/runtests/runtests.py
# Changelog
### 2.1.17
**Date**: 26th Jan 2013
* Support proper 401 Unauthorized responses where appropriate, instead of always using 403 Forbidden.
* Support json encoding of timedelta objects.
* `format_suffix_patterns()` now supports `include` style URL patterns.
* Bugfix: Fix issues with custom pagination serializers.
* Bugfix: Nested serializers now accept `source='*'` argument.
* Bugfix: Return proper validation errors when incorrect types supplied for relational fields.
* Bugfix: Support nullable FKs with `SlugRelatedField`.
* Bugfix: Don't call custom validation methods if the field has an error.
**Note**: If the primary authentication class is `TokenAuthentication` or `BasicAuthentication`, a view will now correctly return 401 responses to unauthenticated access, with an appropriate `WWW-Authenticate` header, instead of 403 responses.
### 2.1.16
**Date**: 14th Jan 2013
* Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module.
* Bugfix: `auto_now`, `auto_now_add` and other `editable=False` fields now default to read-only.
* Bugfix: PK fields now only default to read-only if they are an AutoField or if `editable=False`.
* Bugfix: Validation errors instead of exceptions when serializers receive incorrect types.
* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
### 2.1.15
**Date**: 3rd Jan 2013
* Added `PATCH` support.
* Added `RetrieveUpdateAPIView`.
* Relation changes are now persisted in `.save` instead of in `.restore_object`.
* Remove unused internal `save_m2m` flag on `ModelSerializer.save()`.
* Tweak behavior of hyperlinked fields with an explicit format suffix.
* Bugfix: Fix issue with FileField raising exception instead of validation error when files=None.
* Bugfix: Partial updates should not set default values if field is not included.
### 2.1.14
**Date**: 31st Dec 2012
* Bugfix: ModelSerializers now include reverse FK fields on creation.
* Bugfix: Model fields with `blank=True` are now `required=False` by default.
* Bugfix: Nested serializers now support nullable relationships.
**Note**: From 2.1.14 onwards, relational fields move out of the `fields.py` module and into the new `relations.py` module, in order to seperate them from regular data type fields, such as `CharField` and `IntegerField`.
This change will not affect user code, so long as it's following the recommended import style of `from rest_framework import serializers` and refering to fields using the style `serializers.PrimaryKeyRelatedField`.
### 2.1.13
**Date**: 28th Dec 2012
* Support configurable `STATICFILES_STORAGE` storage.
* Bugfix: Related fields now respect the required flag, and may be required=False.
### 2.1.12
**Date**: 21st Dec 2012
* Bugfix: Fix bug that could occur using ChoiceField.
* Bugfix: Fix exception in browseable API on DELETE.
* Bugfix: Fix issue where pk was was being set to a string if set by URL kwarg.
### 2.1.11
**Date**: 17th Dec 2012
* Bugfix: Fix issue with M2M fields in browseable API.
### 2.1.10
**Date**: 17th Dec 2012
* Bugfix: Ensure read-only fields don't have model validation applied.
* Bugfix: Fix hyperlinked fields in paginated results.
### 2.1.9
**Date**: 11th Dec 2012
* Bugfix: Fix broken nested serialization.
* Bugfix: Fix `Meta.fields` only working as tuple not as list.
* Bugfix: Edge case if unnecessarily specifying `required=False` on read only field.
### 2.1.8
**Date**: 8th Dec 2012
* Fix for creating nullable Foreign Keys with `''` as well as `None`.
* Added `null=<bool>` related field option.
### 2.1.7
**Date**: 7th Dec 2012
* Serializers now properly support nullable Foreign Keys.
* Serializer validation now includes model field validation, such as uniqueness constraints.
* Support 'true' and 'false' string values for BooleanField.
* Added pickle support for serialized data.
* Support `source='dotted.notation'` style for nested serializers.
* Make `Request.user` settable.
* Bugfix: Fix `RegexField` to work with `BrowsableAPIRenderer`
### 2.1.6
**Date**: 23rd Nov 2012
* Bugfix: Unfix DjangoModelPermissions. (I am a doofus.)
### 2.1.5
**Date**: 23rd Nov 2012
* Bugfix: Fix DjangoModelPermissions.
### 2.1.4
**Date**: 22nd Nov 2012
* Support for partial updates with serializers.
* Added `RegexField`.
* Added `SerializerMethodField`.
* Serializer performance improvements.
* Added `obtain_token_view` to get tokens when using `TokenAuthentication`.
* Bugfix: Django 1.5 configurable user support for `TokenAuthentication`.
### 2.1.3
**Date**: 16th Nov 2012
* Added `FileField` and `ImageField`. For use with `MultiPartParser`.
* Added `URLField` and `SlugField`.
* Support for `read_only_fields` on `ModelSerializer` classes.
* Support for clients overriding the pagination page sizes. Use the `PAGINATE_BY_PARAM` setting or set the `paginate_by_param` attribute on a generic view.
* 201 Responses now return a 'Location' header.
* Bugfix: Serializer fields now respect `max_length`.
### 2.1.2
**Date**: 9th Nov 2012
* **Filtering support.**
* Bugfix: Support creation of objects with reverse M2M relations.
### 2.1.1
**Date**: 7th Nov 2012
* Support use of HTML exception templates. Eg. `403.html`
* Hyperlinked fields take optional `slug_field`, `slug_url_kwarg` and `pk_url_kwarg` arguments.
* Bugfix: Deal with optional trailing slashs properly when generating breadcrumbs.
* Bugfix: Make textareas same width as other fields in browsable API.
* Private API change: `.get_serializer` now uses same `instance` and `data` ordering as serializer initialization.
### 2.1.0
**Date**: 5th Nov 2012
**Warning**: Please read [this thread][2.1.0-notes] regarding the `instance` and `data` keyword args before updating to 2.1.0.
* **Serializer `instance` and `data` keyword args have their position swapped.**
* `queryset` argument is now optional on writable model fields.
* Hyperlinked related fields optionally take `slug_field` and `slug_field_kwarg` arguments.
* Support Django's cache framework.
* Minor field improvements. (Don't stringify dicts, more robust many-pk fields.)
* Bugfixes (Support choice field in Browseable API)
### 2.0.2
**Date**: 2nd Nov 2012
* Fix issues with pk related fields in the browsable API.
### 2.0.1
**Date**: 1st Nov 2012
* Add support for relational fields in the browsable API.
* Added SlugRelatedField and ManySlugRelatedField.
* If PUT creates an instance return '201 Created', instead of '200 OK'.
### 2.0.0
**Date**: 30th Oct 2012
* Redesign of core components.
* **Fix all of the things**.
# License # License
Copyright (c) 2011-2013, Tom Christie Copyright (c) 2011-2013, Tom Christie

View File

@ -167,6 +167,8 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead.
## SessionAuthentication ## SessionAuthentication
This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website.

View File

@ -203,6 +203,12 @@ If you want to override this behavior, you'll need to declare the `DateTimeField
class Meta: class Meta:
model = Comment model = Comment
## TimeField
A time representation.
Corresponds to `django.db.models.fields.TimeField`
## IntegerField ## IntegerField
An integer representation. An integer representation.

View File

@ -37,7 +37,7 @@ We could now return that data in a `Response` object, and it would be rendered i
## Paginating QuerySets ## Paginating QuerySets
Our first example worked because we were using primative objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself with. Our first example worked because we were using primitive objects. If we wanted to paginate a queryset or other complex data, we'd need to specify a serializer to use to serialize the result set itself.
We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example. We can do this using the `object_serializer_class` attribute on the inner `Meta` class of the pagination serializer. For example.

View File

@ -100,28 +100,73 @@ The default behaviour can also be overridden to support custom model permissions
To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details.
The `DjangoModelPermissions` class also supports object-level permissions. Third-party authorization backends such as [django-guardian][guardian] that provide object-level permissions should work just fine with `DjangoModelPermissions` without any custom configuration required.
--- ---
# Custom permissions # Custom permissions
To implement a custom permission, override `BasePermission` and implement the `.has_permission(self, request, view, obj=None)` method. To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods:
The method should return `True` if the request should be granted access, and `False` otherwise. * `.has_permission(self, request, view)`
* `.has_object_permission(self, request, view, obj)`
## Example The methods should return `True` if the request should be granted access, and `False` otherwise.
If you need to test if a request is a read operation or a write operation, you should check the request method against the constant `SAFE_METHODS`, which is a tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example:
if request.method in permissions.SAFE_METHODS:
# Check permissions for read-only request
else:
# Check permissions for write request
---
**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.
As of version 2.2 this signature has now been replaced with two seperate method calls, which is more explict and obvious. The old style signature continues to work, but it's use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
For more details see the [2.2 release announcement][2.2-announcement].
---
## Examples
The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted. The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted.
class BlacklistPermission(permissions.BasePermission): class BlacklistPermission(permissions.BasePermission):
def has_permission(self, request, view, obj=None): """
Global permission check for blacklisted IPs.
"""
def has_permission(self, request, view):
ip_addr = request.META['REMOTE_ADDR'] ip_addr = request.META['REMOTE_ADDR']
blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists() blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists()
return not blacklisted return not blacklisted
As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example:
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Instance must have an attribute named `owner`.
return obj.owner == request.user
Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling `self.check_object_permissions(request, obj)` from the view once you have the object instance. This call will raise an appropriate `APIException` if any object-level permission checks fail, and will otherwise simply return.
Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details.
[cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html
[authentication]: authentication.md [authentication]: authentication.md
[throttling]: throttling.md [throttling]: throttling.md
[contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions [contribauth]: https://docs.djangoproject.com/en/1.0/topics/auth/#permissions
[guardian]: https://github.com/lukaszb/django-guardian [guardian]: https://github.com/lukaszb/django-guardian
[2.2-announcement]: ../topics/2.2-announcement.md
[filtering]: filtering.md

View File

@ -32,6 +32,7 @@ In order to explain the various types of relational fields, we'll use a couple o
class Meta: class Meta:
unique_together = ('album', 'order') unique_together = ('album', 'order')
order_by = 'order'
def __unicode__(self): def __unicode__(self):
return '%d: %s' % (self.order, self.title) return '%d: %s' % (self.order, self.title)
@ -64,6 +65,10 @@ Would serialize to the following representation.
This field is read only. This field is read only.
**Arguments**:
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
## PrimaryKeyRelatedField ## PrimaryKeyRelatedField
`PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key. `PrimaryKeyRelatedField` may be used to represent the target of the relationship using it's primary key.
@ -94,8 +99,9 @@ By default this field is read-write, although you can change this behavior using
**Arguments**: **Arguments**:
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. * `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
## HyperlinkedRelatedField ## HyperlinkedRelatedField
@ -129,6 +135,7 @@ By default this field is read-write, although you can change this behavior using
**Arguments**: **Arguments**:
* `view_name` - The view name that should be used as the target of the relationship. **required**. * `view_name` - The view name that should be used as the target of the relationship. **required**.
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships. * `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
* `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`. * `slug_field` - The field on the target that should be used for the lookup. Default is `'slug'`.
@ -168,16 +175,17 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
**Arguments**: **Arguments**:
* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. * `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required**
* `many` - If applied to a to-many relationship, you should set this argument to `True`.
* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`. * `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
* `null` - If set to `True`, the field will accept values of `None` or the empty-string for nullable relationships.
## HyperLinkedIdentityField ## HyperlinkedIdentityField
This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer:
class AlbumSerializer(serializers.HyperlinkedModelSerializer): class AlbumSerializer(serializers.HyperlinkedModelSerializer):
track_listing = HyperLinkedIdentityField(view_name='track-list') track_listing = HyperlinkedIdentityField(view_name='track-list')
class Meta: class Meta:
model = Album model = Album
@ -201,12 +209,23 @@ This field is always read-only.
* `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`. * `slug_url_kwarg` - The named url parameter for the slug field lookup. Default is to use the same value as given for `slug_field`.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
## Nested relationships ---
Nested relationships can be expressed by using serializers as fields. For example: # Nested relationships
Nested relationships can be expressed by using serializers as fields.
If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field.
Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style.
## Example
For example, the following serializer:
class TrackSerializer(serializer.ModelSerializer): class TrackSerializer(serializer.ModelSerializer):
class Meta: class Meta:
model = Track
fields = ('order', 'title') fields = ('order', 'title')
class AlbumSerializer(serializer.ModelSerializer): class AlbumSerializer(serializer.ModelSerializer):
@ -216,17 +235,57 @@ Nested relationships can be expressed by using serializers as fields. For examp
model = Album model = Album
fields = ('album_name', 'artist', 'tracks') fields = ('album_name', 'artist', 'tracks')
Note that nested relationships are currently read-only. For read-write relationships, you should use a flat relational style. Would serialize to a nested representation like this:
## Custom relational fields {
'album_name': 'The Grey Album',
'artist': 'Danger Mouse'
'tracks': [
{'order': 1, 'title': 'Public Service Annoucement'},
{'order': 2, 'title': 'What More Can I Say'},
{'order': 3, 'title': 'Encore'},
...
],
}
# Custom relational fields
To implement a custom relational field, you should override `RelatedField`, and implement the `.to_native(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. To implement a custom relational field, you should override `RelatedField`, and implement the `.to_native(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target.
If you want to implement a read-write relational field, you must also implement the `.from_native(self, data)` method, and add `read_only = False` to the class definition.
## Example
For, example, we could define a relational field, to serialize a track to a custom string representation, using it's ordering, title, and duration.
import time
class TrackListingField(serializers.RelatedField): class TrackListingField(serializers.RelatedField):
def to_native(self, value): def to_native(self, value):
return 'Track %d: %s' % (value.ordering, value.name) duration = time.strftime('%M:%S', time.gmtime(value.duration))
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
If you want to implement a read-write relational field, you must also implement the `.from_native(self, data)` method, and add `read_only = False` to the class definition. class AlbumSerializer(serializer.ModelSerializer):
tracks = TrackListingField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
This custom field would then serialize to the following representation.
{
'album_name': 'Sometimes I Wish We Were an Eagle',
'artist': 'Bill Callahan'
'tracks': [
'Track 1: Jim Cain (04:39)',
'Track 2: Eid Ma Clack Shaw (04:19)',
'Track 3: The Wind and the Dove (04:34)',
...
]
}
---
# Further notes # Further notes
@ -337,18 +396,24 @@ For more information see [the Django documentation on generic relations][generic
--- ---
## Deprecated relational fields ## Deprecated APIs
The following classes have been deprecated, in favor of the `many=<bool>` syntax. The following classes have been deprecated, in favor of the `many=<bool>` syntax.
They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default. They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default.
In the 2.3 release, this warning will be escalated to a `DeprecationWarning`.
In the 2.4 release, they will be removed entirely.
* `ManyRelatedField` * `ManyRelatedField`
* `ManyPrimaryKeyRelatedField` * `ManyPrimaryKeyRelatedField`
* `ManyHyperlinkedRelatedField` * `ManyHyperlinkedRelatedField`
* `ManySlugRelatedField` * `ManySlugRelatedField`
The `null=<bool>` flag has been deprecated in favor of the `required=<bool>` flag. It will continue to function, but will raise a `PendingDeprecationWarning`.
In the 2.3 release, these warnings will be escalated to a `DeprecationWarning`, which is loud by default.
In the 2.4 release, these parts of the API will be removed entirely.
For more details see the [2.2 release announcement][2.2-announcement].
[cite]: http://lwn.net/Articles/193245/ [cite]: http://lwn.net/Articles/193245/
[reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward [reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
[generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 [generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
[2.2-announcement]: ../topics/2.2-announcement.md

View File

@ -80,6 +80,15 @@ 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 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 ## 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` and `.non_field_errors` properties will contain 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` and `.non_field_errors` properties will contain the resulting error messages.
@ -114,7 +123,7 @@ To do any other validation that requires access to multiple fields, add a method
from rest_framework import serializers from rest_framework import serializers
class EventSerializer(serializers.Serializer): class EventSerializer(serializers.Serializer):
description = serializers.CahrField(max_length=100) description = serializers.CharField(max_length=100)
start = serializers.DateTimeField() start = serializers.DateTimeField()
finish = serializers.DateTimeField() finish = serializers.DateTimeField()
@ -155,6 +164,17 @@ The `Serializer` class is itself a type of `Field`, and can be used to represent
--- ---
## 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.
You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example:
serializer = AccountSerializer(account, context={'request': request})
serializer.data
# {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'}
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 ## Creating custom fields

View File

@ -6,8 +6,6 @@
> >
> [Twitter API rate limiting response][cite] > [Twitter API rate limiting response][cite]
[cite]: https://dev.twitter.com/docs/error-codes-responses
Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API. Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API.
As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests. As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests.
@ -63,6 +61,10 @@ Or, if you're using the `@api_view` decorator with function based views.
} }
return Response(content) return Response(content)
## Setting up the cache
The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details.
--- ---
# API Reference # API Reference
@ -162,4 +164,7 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
def allow_request(self, request, view): def allow_request(self, request, view):
return random.randint(1, 10) == 1 return random.randint(1, 10) == 1
[cite]: https://dev.twitter.com/docs/error-codes-responses
[permissions]: permissions.md [permissions]: permissions.md
[cache-setting]: https://docs.djangoproject.com/en/dev/ref/settings/#caches
[cache-docs]: https://docs.djangoproject.com/en/dev/topics/cache/#setting-up-the-cache

View File

@ -76,11 +76,11 @@ The following methods are used by REST framework to instantiate the various plug
The following methods are called before dispatching to the handler method. The following methods are called before dispatching to the handler method.
### .check_permissions(...) ### .check_permissions(self, request)
### .check_throttles(...) ### .check_throttles(self, request)
### .perform_content_negotiation(...) ### .perform_content_negotiation(self, request, force=False)
## Dispatch methods ## Dispatch methods

View File

@ -1,7 +1,7 @@
<p class="badges"> <p class="badges">
<iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&amp;repo=django-rest-framework&amp;type=watch&amp;count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe> <iframe src="http://ghbtns.com/github-btn.html?user=tomchristie&amp;repo=django-rest-framework&amp;type=watch&amp;count=true" class="github-star-button" allowtransparency="true" frameborder="0" scrolling="0" width="110px" height="20px"></iframe>
<a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Current status: Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none">Tweet</a> <a href="https://twitter.com/share" class="twitter-share-button" data-url="django-rest-framework.org" data-text="Checking out the totally awesome Django REST framework! http://django-rest-framework.org" data-count="none">Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script> <script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="http://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>
<img alt="Travis build image" src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image"> <img alt="Travis build image" src="https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master" class="travis-build-image">
@ -27,7 +27,7 @@ There is also a sandbox API you can use for testing purposes, [available here][s
REST framework requires the following: REST framework requires the following:
* Python (2.6, 2.7, 3.2, 3.3) * Python (2.6.5+, 2.7, 3.2, 3.3)
* Django (1.3, 1.4, 1.5) * Django (1.3, 1.4, 1.5)
The following packages are optional: The following packages are optional:
@ -116,6 +116,7 @@ General guides to using REST framework.
* [The Browsable API][browsableapi] * [The Browsable API][browsableapi]
* [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas] * [REST, Hypermedia & HATEOAS][rest-hypermedia-hateoas]
* [2.0 Announcement][rest-framework-2-announcement] * [2.0 Announcement][rest-framework-2-announcement]
* [2.2 Announcement][2.2-announcement]
* [Release Notes][release-notes] * [Release Notes][release-notes]
* [Credits][credits] * [Credits][credits]
@ -211,6 +212,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md [rest-hypermedia-hateoas]: topics/rest-hypermedia-hateoas.md
[contributing]: topics/contributing.md [contributing]: topics/contributing.md
[rest-framework-2-announcement]: topics/rest-framework-2-announcement.md [rest-framework-2-announcement]: topics/rest-framework-2-announcement.md
[2.2-announcement]: topics/2.2-announcement.md
[release-notes]: topics/release-notes.md [release-notes]: topics/release-notes.md
[credits]: topics/credits.md [credits]: topics/credits.md

View File

@ -94,6 +94,7 @@
<li><a href="{{ base_url }}/topics/browsable-api{{ suffix }}">The Browsable API</a></li> <li><a href="{{ base_url }}/topics/browsable-api{{ suffix }}">The Browsable API</a></li>
<li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li> <li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li>
<li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li> <li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li>
<li><a href="{{ base_url }}/topics/2.2-announcement{{ suffix }}">2.2 Announcement</a></li>
<li><a href="{{ base_url }}/topics/release-notes{{ suffix }}">Release Notes</a></li> <li><a href="{{ base_url }}/topics/release-notes{{ suffix }}">Release Notes</a></li>
<li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li> <li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li>
</ul> </ul>

View File

@ -1,4 +1,4 @@
# REST framework 2.2 release notes # REST framework 2.2 announcement
The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy. The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy.
@ -10,13 +10,15 @@ Django 1.6's Python 3 support is expected to be officially labeled as 'productio
If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation. If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation.
Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with [Django 1.5's Python compatibility][python-compat].
## Deprecation policy ## Deprecation policy
We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework. We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.
The timeline for deprecation works as follows: The timeline for deprecation works as follows:
* Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise `PendingDeprecationWarning` warnings if you use bits API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make. * Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise `PendingDeprecationWarning` warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is loud by default. * Version 2.3 will escalate these warnings to `DeprecationWarning`, which is loud by default.
@ -30,13 +32,11 @@ As of the 2.2 merge, we've also hit an impressive milestone. The number of comm
Our [mailing list][mailing-list] and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great [django-rest-framework-docs][django-rest-framework-docs] package from [Marc Gibbons][marcgibbons]. Our [mailing list][mailing-list] and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great [django-rest-framework-docs][django-rest-framework-docs] package from [Marc Gibbons][marcgibbons].
## Issue management ---
All the design work that went into version 2 of Django REST framework has made keeping on top of issues much easier. We've been super-focused on keeping the [issues list][issues] strictly under control, and we've hit another important milestone. At the point of releasing 2.2 there are currently **no open 'bug' tickets**, and the plan is to keep it that way for as much of the time as possible.
## API changes ## API changes
The 2.2 release makes a few changes to the serializer fields API, in order to make it more consistent, simple, and easier to use. The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use.
### Cleaner to-many related fields ### Cleaner to-many related fields
@ -101,9 +101,55 @@ In keeping with Django's CharField API, REST framework's `CharField` will only e
The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`. The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`.
### Simpler object-level permissions
Custom permissions classes previously used the signatute `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance.
The global permissions check and object-level permissions check are now seperated into two seperate methods, which gives a cleaner, more obvious API.
* Global permission checks now use the `.has_permission(self, request, view)` signature.
* Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`.
For example, the following custom permission class:
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to view or edit it.
Model instances are expected to include an `owner` attribute.
"""
def has_permission(self, request, view, obj=None):
if obj is None:
# Ignore global permissions check
return True
return obj.owner == request.user
Now becomes:
class IsOwner(permissions.BasePermission):
"""
Custom permission to only allow owners of an object to view or edit it.
Model instances are expected to include an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
return obj.owner == request.user
If you're overriding the `BasePermission` class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but it's use will raise a `PendingDeprecationWarning`.
Note also that the usage of the internal APIs for permission checking on the `View` class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions.
### More explicit hyperlink relations behavior
When using a serializer with a `HyperlinkedRelatedField` or `HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs if the serializer context included a `'request'` key, and fallback to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not.
From version 2.2 onwards, serializers with hyperlinked relationships *always* require a `'request'` key to be supplied in the context dictionary. The implicit behavior will continue to function, but it's use will raise a `PendingDeprecationWarning`.
[xordoquy]: https://github.com/xordoquy [xordoquy]: https://github.com/xordoquy
[django-python-3]: https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3 [django-python-3]: https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3
[porting-python-3]: https://docs.djangoproject.com/en/dev/topics/python3/ [porting-python-3]: https://docs.djangoproject.com/en/dev/topics/python3/
[python-compat]: https://docs.djangoproject.com/en/dev/releases/1.5/#python-compatibility
[django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy [django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy
[credits]: http://django-rest-framework.org/topics/credits.html [credits]: http://django-rest-framework.org/topics/credits.html
[mailing-list]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [mailing-list]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework

View File

@ -19,7 +19,7 @@ The following people have helped make REST framework great.
* Craig Blaszczyk - [jakul] * Craig Blaszczyk - [jakul]
* Garcia Solero - [garciasolero] * Garcia Solero - [garciasolero]
* Tom Drummond - [devioustree] * Tom Drummond - [devioustree]
* Danilo Bargen - [gwrtheyrn] * Danilo Bargen - [dbrgn]
* Andrew McCloud - [amccloud] * Andrew McCloud - [amccloud]
* Thomas Steinacher - [thomasst] * Thomas Steinacher - [thomasst]
* Meurig Freeman - [meurig] * Meurig Freeman - [meurig]
@ -102,6 +102,8 @@ The following people have helped make REST framework great.
* Andrea de Marco - [z4r] * Andrea de Marco - [z4r]
* Fernando Rocha - [fernandogrd] * Fernando Rocha - [fernandogrd]
* Xavier Ordoquy - [xordoquy] * Xavier Ordoquy - [xordoquy]
* Adam Wentz - [floppya]
* Andreas Pelme - [pelme]
Many thanks to everyone who's contributed to the project. Many thanks to everyone who's contributed to the project.
@ -155,7 +157,7 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[jakul]: https://github.com/jakul [jakul]: https://github.com/jakul
[garciasolero]: https://github.com/garciasolero [garciasolero]: https://github.com/garciasolero
[devioustree]: https://github.com/devioustree [devioustree]: https://github.com/devioustree
[gwrtheyrn]: https://github.com/gwrtheyrn [dbrgn]: https://github.com/dbrgn
[amccloud]: https://github.com/amccloud [amccloud]: https://github.com/amccloud
[thomasst]: https://github.com/thomasst [thomasst]: https://github.com/thomasst
[meurig]: https://github.com/meurig [meurig]: https://github.com/meurig
@ -238,3 +240,5 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[z4r]: https://github.com/z4r [z4r]: https://github.com/z4r
[fernandogrd]: https://github.com/fernandogrd [fernandogrd]: https://github.com/fernandogrd
[xordoquy]: https://github.com/xordoquy [xordoquy]: https://github.com/xordoquy
[floppya]: https://github.com/floppya
[pelme]: https://github.com/pelme

View File

@ -8,9 +8,23 @@
Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes. Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes.
Medium version numbers (0.x.0) may include minor API changes. You should read the release notes carefully before upgrading between medium point releases. Medium version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
Major version numbers (x.0.0) are reserved for project milestones. No major point releases are currently planned. Major version numbers (x.0.0) are reserved for substantial project milestones. No major point releases are currently planned.
## Deprecation policy
REST framework releases follow a formal deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy].
The timeline for deprecation of a feature present in version 1.0 would work as follows:
* Version 1.1 would remain **fully backwards compatible** with 1.0, but would raise `PendingDeprecationWarning` warnings if you use the feature that are due to be deprecated. These warnings are **silent by default**, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make.
* Version 1.2 would escalate these warnings to `DeprecationWarning`, which is loud by default.
* Version 1.3 would remove the deprecated bits of API entirely.
Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change.
## Upgrading ## Upgrading
@ -24,16 +38,39 @@ You can determine your currently installed version using `pip freeze`:
--- ---
## 2.1.x series ## 2.2.x series
### Master ### Master
* Added TimeField.
* Serializer fields can be mapped to any method that takes no args, or only takes kwargs which have defaults.
* Bugfix: request.DATA should return an empty `QueryDict` with no data, not `None`.
* Bugfix: Remove unneeded field validation, which caused extra queries.
### 2.2.0
**Date**: 13th Feb 2013
* Python 3 support.
* Added a `post_save()` hook to the generic views. * Added a `post_save()` hook to the generic views.
* Allow serializers to handle dicts as well as objects. * Allow serializers to handle dicts as well as objects.
* Deprecate `ManyRelatedField()` syntax in favor of `RelatedField(many=True)`
* Deprecate `null=True` on relations in favor of `required=False`.
* Deprecate `blank=True` on CharFields, just use `required=False`.
* Deprecate optional `obj` argument in permissions checks in favor of `has_object_permission`.
* Deprecate implicit hyperlinked relations behavior.
* Bugfix: Fix broken DjangoModelPermissions.
* Bugfix: Allow serializer output to be cached.
* Bugfix: Fix styling on browsable API login. * Bugfix: Fix styling on browsable API login.
* Bugfix: Fix issue with deserializing empty to-many relations. * Bugfix: Fix issue with deserializing empty to-many relations.
* Bugfix: Ensure model field validation is still applied for ModelSerializer subclasses with an custom `.restore_object()` method. * Bugfix: Ensure model field validation is still applied for ModelSerializer subclasses with an custom `.restore_object()` method.
**Note**: See the [2.2 announcement][2.2-announcement] for full details.
---
## 2.1.x series
### 2.1.17 ### 2.1.17
**Date**: 26th Jan 2013 **Date**: 26th Jan 2013
@ -350,6 +387,9 @@ This change will not affect user code, so long as it's following the recommended
* Initial release. * Initial release.
[cite]: http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html [cite]: http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html
[deprecation-policy]: #deprecation-policy
[django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy
[2.2-announcement]: 2.2-announcement.md
[staticfiles14]: https://docs.djangoproject.com/en/1.4/howto/static-files/#with-a-template-tag [staticfiles14]: https://docs.djangoproject.com/en/1.4/howto/static-files/#with-a-template-tag
[staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag [staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag
[2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion

View File

@ -8,7 +8,7 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o
--- ---
**Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. As pieces of code are introduced, they are committed to this repository. The completed implementation is also online as a sandbox version for testing, [available here][sandbox]. **Note**: The code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox].
--- ---
@ -109,7 +109,7 @@ The first thing we need to get started on our Web API is provide a way of serial
from django.forms import widgets from django.forms import widgets
from rest_framework import serializers from rest_framework import serializers
from snippets.models import Snippet from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES
class SnippetSerializer(serializers.Serializer): class SnippetSerializer(serializers.Serializer):
@ -119,9 +119,9 @@ The first thing we need to get started on our Web API is provide a way of serial
code = serializers.CharField(widget=widgets.Textarea, code = serializers.CharField(widget=widgets.Textarea,
max_length=100000) max_length=100000)
linenos = serializers.BooleanField(required=False) linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=models.LANGUAGE_CHOICES, language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
default='python') default='python')
style = serializers.ChoiceField(choices=models.STYLE_CHOICES, style = serializers.ChoiceField(choices=STYLE_CHOICES,
default='friendly') default='friendly')
def restore_object(self, attrs, instance=None): def restore_object(self, attrs, instance=None):
@ -150,13 +150,16 @@ Before we go any further we'll familiarize ourselves with using our new Serializ
python manage.py shell python manage.py shell
Okay, once we've got a few imports out of the way, let's create a code snippet to work with. Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with.
from snippets.models import Snippet from snippets.models import Snippet
from snippets.serializers import SnippetSerializer from snippets.serializers import SnippetSerializer
from rest_framework.renderers import JSONRenderer from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser from rest_framework.parsers import JSONParser
snippet = Snippet(code='foo = "bar"\n')
snippet.save()
snippet = Snippet(code='print "hello, world"\n') snippet = Snippet(code='print "hello, world"\n')
snippet.save() snippet.save()
@ -164,13 +167,13 @@ We've now got a few snippet instances to play with. Let's take a look at serial
serializer = SnippetSerializer(snippet) serializer = SnippetSerializer(snippet)
serializer.data serializer.data
# {'pk': 1, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'} # {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}
At this point we've translated the model instance into python native datatypes. To finalize the serialization process we render the data into `json`. At this point we've translated the model instance into python native datatypes. To finalize the serialization process we render the data into `json`.
content = JSONRenderer().render(serializer.data) content = JSONRenderer().render(serializer.data)
content content
# '{"pk": 1, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}' # '{"pk": 2, "title": "", "code": "print \\"hello, world\\"\\n", "linenos": false, "language": "python", "style": "friendly"}'
Deserialization is similar. First we parse a stream into python native datatypes... Deserialization is similar. First we parse a stream into python native datatypes...
@ -189,6 +192,12 @@ Deserialization is similar. First we parse a stream into python native datatype
Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer. Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer.
We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments.
serializer = SnippetSerializer(Snippet.objects.all(), many=True)
serializer.data
# [{'pk': 1, 'title': u'', 'code': u'foo = "bar"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}, {'pk': 2, 'title': u'', 'code': u'print "hello, world"\n', 'linenos': False, 'language': u'python', 'style': u'friendly'}]
## Using ModelSerializers ## Using ModelSerializers
Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep out code a bit more concise. Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep out code a bit more concise.
@ -237,7 +246,7 @@ The root of our API is going to be a view that supports listing all the existing
""" """
if request.method == 'GET': if request.method == 'GET':
snippets = Snippet.objects.all() snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets) serializer = SnippetSerializer(snippets, many=True)
return JSONResponse(serializer.data) return JSONResponse(serializer.data)
elif request.method == 'POST': elif request.method == 'POST':
@ -312,19 +321,19 @@ and start up Django's development server
In another terminal window, we can test the server. In another terminal window, we can test the server.
We can get a list of all of the snippets (we only have one at the moment) We can get a list of all of the snippets.
curl http://127.0.0.1:8000/snippets/ curl http://127.0.0.1:8000/snippets/
[{"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}] [{"id": 1, "title": "", "code": "foo = \"bar\"\n", "linenos": false, "language": "python", "style": "friendly"}, {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
or we can get a particular snippet by referencing its id or we can get a particular snippet by referencing its id
curl http://127.0.0.1:8000/snippets/1/ curl http://127.0.0.1:8000/snippets/2/
{"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"} {"id": 2, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}
Similarly, you can have the same json displayed by referencing these URLs from your favorite web browser. Similarly, you can have the same json displayed by visiting these URLs in a web browser.
## Where are we now ## Where are we now

View File

@ -51,7 +51,7 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
""" """
if request.method == 'GET': if request.method == 'GET':
snippets = Snippet.objects.all() snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets) serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data) return Response(serializer.data)
elif request.method == 'POST': elif request.method == 'POST':

View File

@ -20,7 +20,7 @@ We'll start by rewriting the root view as a class based view. All this involves
""" """
def get(self, request, format=None): def get(self, request, format=None):
snippets = Snippet.objects.all() snippets = Snippet.objects.all()
serializer = SnippetSerializer(snippets) serializer = SnippetSerializer(snippets, many=True)
return Response(serializer.data) return Response(serializer.data)
def post(self, request, format=None): def post(self, request, format=None):

View File

@ -57,7 +57,7 @@ Now that we've got some users to work with, we'd better add representations of t
from django.contrib.auth.models import User from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer): class UserSerializer(serializers.ModelSerializer):
snippets = serializers.ManyPrimaryKeyRelatedField() snippets = serializers.PrimaryKeyRelatedField(many=True)
class Meta: class Meta:
model = User model = User
@ -161,11 +161,7 @@ In the snippets app, create a new file, `permissions.py`
Custom permission to only allow owners of an object to edit it. Custom permission to only allow owners of an object to edit it.
""" """
def has_permission(self, request, view, obj=None): def has_object_permission(self, request, view, obj):
# Skip the check unless this is an object-level test
if obj is None:
return True
# Read permissions are allowed to any request, # Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests. # so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS: if request.method in permissions.SAFE_METHODS:

View File

@ -70,8 +70,8 @@ The `HyperlinkedModelSerializer` has the following differences from `ModelSerial
* It does not include the `pk` field by default. * It does not include the `pk` field by default.
* It includes a `url` field, using `HyperlinkedIdentityField`. * It includes a `url` field, using `HyperlinkedIdentityField`.
* Relationships use `HyperlinkedRelatedField` and `ManyHyperlinkedRelatedField`, * Relationships use `HyperlinkedRelatedField`,
instead of `PrimaryKeyRelatedField` and `ManyPrimaryKeyRelatedField`. instead of `PrimaryKeyRelatedField`.
We can easily re-write our existing serializers to use hyperlinking. We can easily re-write our existing serializers to use hyperlinking.
@ -86,7 +86,7 @@ We can easily re-write our existing serializers to use hyperlinking.
class UserSerializer(serializers.HyperlinkedModelSerializer): class UserSerializer(serializers.HyperlinkedModelSerializer):
snippets = serializers.ManyHyperlinkedRelatedField(view_name='snippet-detail') snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippet-detail')
class Meta: class Meta:
model = User model = User

View File

@ -1,4 +1,4 @@
__version__ = '2.1.17' __version__ = '2.2.0'
VERSION = __version__ # synonym VERSION = __version__ # synonym

View File

@ -349,7 +349,7 @@ except ImportError:
# dateparse is ALSO new in Django 1.4 # dateparse is ALSO new in Django 1.4
try: try:
from django.utils.dateparse import parse_date, parse_datetime from django.utils.dateparse import parse_date, parse_datetime, parse_time
except ImportError: except ImportError:
import datetime import datetime
import re import re

View File

@ -18,16 +18,21 @@ from rest_framework.compat import timezone
from rest_framework.compat import BytesIO from rest_framework.compat import BytesIO
from rest_framework.compat import six from rest_framework.compat import six
from rest_framework.compat import smart_text from rest_framework.compat import smart_text
from rest_framework.compat import parse_time
def is_simple_callable(obj): def is_simple_callable(obj):
""" """
True if the object is a callable that takes no arguments. True if the object is a callable that takes no arguments.
""" """
return ( try:
(inspect.isfunction(obj) and not inspect.getargspec(obj)[0]) or args, _, _, defaults = inspect.getargspec(obj)
(inspect.ismethod(obj) and len(inspect.getargspec(obj)[0]) <= 1) except TypeError:
) return False
else:
len_args = len(args) if inspect.isfunction(obj) else len(args) - 1
len_defaults = len(defaults) if defaults else 0
return len_args <= len_defaults
def get_component(obj, attr_name): def get_component(obj, attr_name):
@ -94,12 +99,14 @@ class Field(object):
if self.source == '*': if self.source == '*':
return self.to_native(obj) return self.to_native(obj)
if self.source: source = self.source or field_name
value = obj value = obj
for component in self.source.split('.'):
value = get_component(value, component) for component in source.split('.'):
else: value = get_component(value, component)
value = get_component(obj, field_name) if value is None:
break
return self.to_native(value) return self.to_native(value)
def to_native(self, value): def to_native(self, value):
@ -529,6 +536,33 @@ class DateTimeField(WritableField):
raise ValidationError(msg) raise ValidationError(msg)
class TimeField(WritableField):
type_name = 'TimeField'
widget = widgets.TimeInput
form_field_class = forms.TimeField
default_error_messages = {
'invalid': _("'%s' value has an invalid format. It must be a valid "
"time in the HH:MM[:ss[.uuuuuu]] format."),
}
empty = None
def from_native(self, value):
if value in validators.EMPTY_VALUES:
return None
if isinstance(value, datetime.time):
return value
try:
parsed = parse_time(value)
assert parsed is not None
return parsed
except ValueError:
msg = self.error_messages['invalid'] % value
raise ValidationError(msg)
class IntegerField(WritableField): class IntegerField(WritableField):
type_name = 'IntegerField' type_name = 'IntegerField'
form_field_class = forms.IntegerField form_field_class = forms.IntegerField

View File

@ -131,8 +131,7 @@ class SingleObjectAPIView(SingleObjectMixin, GenericAPIView):
Override default to add support for object-level permissions. Override default to add support for object-level permissions.
""" """
obj = super(SingleObjectAPIView, self).get_object(queryset) obj = super(SingleObjectAPIView, self).get_object(queryset)
if not self.has_permission(self.request, obj): self.check_object_permissions(self.request, obj)
self.permission_denied(self.request)
return obj return obj

View File

@ -9,6 +9,7 @@ from __future__ import unicode_literals
from django.http import Http404 from django.http import Http404
from rest_framework import status from rest_framework import status
from rest_framework.response import Response from rest_framework.response import Response
from rest_framework.request import clone_request
class CreateModelMixin(object): class CreateModelMixin(object):
@ -90,6 +91,9 @@ class UpdateModelMixin(object):
try: try:
self.object = self.get_object() self.object = self.get_object()
except Http404: except Http404:
# If this is a PUT-as-create operation, we need to ensure that
# we have relevant permissions, as if this was a POST request.
self.check_permissions(clone_request(request, 'POST'))
created = True created = True
success_status_code = status.HTTP_201_CREATED success_status_code = status.HTTP_201_CREATED
else: else:

View File

@ -2,6 +2,8 @@
Provides a set of pluggable permission policies. Provides a set of pluggable permission policies.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
import inspect
import warnings
SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS'] SAFE_METHODS = ['GET', 'HEAD', 'OPTIONS']
@ -11,11 +13,22 @@ class BasePermission(object):
A base class from which all permission classes should inherit. A base class from which all permission classes should inherit.
""" """
def has_permission(self, request, view, obj=None): def has_permission(self, request, view):
""" """
Return `True` if permission is granted, `False` otherwise. Return `True` if permission is granted, `False` otherwise.
""" """
raise NotImplementedError(".has_permission() must be overridden.") return True
def has_object_permission(self, request, view, obj):
"""
Return `True` if permission is granted, `False` otherwise.
"""
if len(inspect.getargspec(self.has_permission)[0]) == 4:
warnings.warn('The `obj` argument in `has_permission` is due to be deprecated. '
'Use `has_object_permission()` instead for object permissions.',
PendingDeprecationWarning, stacklevel=2)
return self.has_permission(request, view, obj)
return True
class AllowAny(BasePermission): class AllowAny(BasePermission):
@ -25,7 +38,7 @@ class AllowAny(BasePermission):
permission_classes list, but it's useful because it makes the intention permission_classes list, but it's useful because it makes the intention
more explicit. more explicit.
""" """
def has_permission(self, request, view, obj=None): def has_permission(self, request, view):
return True return True
@ -34,7 +47,7 @@ class IsAuthenticated(BasePermission):
Allows access only to authenticated users. Allows access only to authenticated users.
""" """
def has_permission(self, request, view, obj=None): def has_permission(self, request, view):
if request.user and request.user.is_authenticated(): if request.user and request.user.is_authenticated():
return True return True
return False return False
@ -45,7 +58,7 @@ class IsAdminUser(BasePermission):
Allows access only to admin users. Allows access only to admin users.
""" """
def has_permission(self, request, view, obj=None): def has_permission(self, request, view):
if request.user and request.user.is_staff: if request.user and request.user.is_staff:
return True return True
return False return False
@ -56,7 +69,7 @@ class IsAuthenticatedOrReadOnly(BasePermission):
The request is authenticated as a user, or is a read-only request. The request is authenticated as a user, or is a read-only request.
""" """
def has_permission(self, request, view, obj=None): def has_permission(self, request, view):
if (request.method in SAFE_METHODS or if (request.method in SAFE_METHODS or
request.user and request.user and
request.user.is_authenticated()): request.user.is_authenticated()):
@ -100,7 +113,7 @@ class DjangoModelPermissions(BasePermission):
} }
return [perm % kwargs for perm in self.perms_map[method]] return [perm % kwargs for perm in self.perms_map[method]]
def has_permission(self, request, view, obj=None): def has_permission(self, request, view):
model_cls = getattr(view, 'model', None) model_cls = getattr(view, 'model', None)
if not model_cls: if not model_cls:
return True return True
@ -109,6 +122,6 @@ class DjangoModelPermissions(BasePermission):
if (request.user and if (request.user and
request.user.is_authenticated() and request.user.is_authenticated() and
request.user.has_perms(perms, obj)): request.user.has_perms(perms)):
return True return True
return False return False

View File

@ -5,7 +5,7 @@ from django import forms
from django.forms import widgets from django.forms import widgets
from django.forms.models import ModelChoiceIterator from django.forms.models import ModelChoiceIterator
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from rest_framework.fields import Field, WritableField from rest_framework.fields import Field, WritableField, get_component
from rest_framework.reverse import reverse from rest_framework.reverse import reverse
from rest_framework.compat import urlparse from rest_framework.compat import urlparse
from rest_framework.compat import smart_text from rest_framework.compat import smart_text
@ -116,7 +116,16 @@ class RelatedField(WritableField):
def field_to_native(self, obj, field_name): def field_to_native(self, obj, field_name):
try: try:
value = getattr(obj, self.source or field_name) if self.source == '*':
return self.to_native(obj)
source = self.source or field_name
value = obj
for component in source.split('.'):
value = get_component(value, component)
if value is None:
break
except ObjectDoesNotExist: except ObjectDoesNotExist:
return None return None
@ -311,6 +320,13 @@ class HyperlinkedRelatedField(RelatedField):
view_name = self.view_name view_name = self.view_name
request = self.context.get('request', None) request = self.context.get('request', None)
format = self.format or self.context.get('format', None) format = self.format or self.context.get('format', None)
if request is None:
warnings.warn("Using `HyperlinkedRelatedField` without including the "
"request in the serializer context is due to be deprecated. "
"Add `context={'request': request}` when instantiating the serializer.",
PendingDeprecationWarning, stacklevel=4)
pk = getattr(obj, 'pk', None) pk = getattr(obj, 'pk', None)
if pk is None: if pk is None:
return return
@ -420,6 +436,12 @@ class HyperlinkedIdentityField(Field):
view_name = self.view_name or self.parent.opts.view_name view_name = self.view_name or self.parent.opts.view_name
kwargs = {self.pk_url_kwarg: obj.pk} kwargs = {self.pk_url_kwarg: obj.pk}
if request is None:
warnings.warn("Using `HyperlinkedIdentityField` without including the "
"request in the serializer context is due to be deprecated. "
"Add `context={'request': request}` when instantiating the serializer.",
PendingDeprecationWarning, stacklevel=4)
# By default use whatever format is given for the current context # By default use whatever format is given for the current context
# unless the target is a different type to the source. # unless the target is a different type to the source.
# #

View File

@ -21,8 +21,7 @@ from rest_framework.request import clone_request
from rest_framework.utils import dict2xml from rest_framework.utils import dict2xml
from rest_framework.utils import encoders from rest_framework.utils import encoders
from rest_framework.utils.breadcrumbs import get_breadcrumbs from rest_framework.utils.breadcrumbs import get_breadcrumbs
from rest_framework import VERSION, status from rest_framework import exceptions, parsers, status, VERSION
from rest_framework import parsers
class BaseRenderer(object): class BaseRenderer(object):
@ -299,12 +298,10 @@ class BrowsableAPIRenderer(BaseRenderer):
if not api_settings.FORM_METHOD_OVERRIDE: if not api_settings.FORM_METHOD_OVERRIDE:
return # Cannot use form overloading return # Cannot use form overloading
request = clone_request(request, method)
try: try:
if not view.has_permission(request, obj): view.check_permissions(clone_request(request, method))
return # Don't have permission except exceptions.APIException:
except Exception: return False # Doesn't have permissions
return # Don't have permission and exception explicitly raise
return True return True
def serializer_to_form_fields(self, serializer): def serializer_to_form_fields(self, serializer):

View File

@ -11,7 +11,9 @@ The wrapped request then offers a richer API, in particular :
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
from django.conf import settings from django.conf import settings
from django.http import QueryDict
from django.http.multipartparser import parse_header from django.http.multipartparser import parse_header
from django.utils.datastructures import MultiValueDict
from rest_framework import HTTP_HEADER_ENCODING from rest_framework import HTTP_HEADER_ENCODING
from rest_framework import exceptions from rest_framework import exceptions
from rest_framework.compat import BytesIO from rest_framework.compat import BytesIO
@ -44,10 +46,11 @@ def clone_request(request, method):
Internal helper method to clone a request, replacing with a different Internal helper method to clone a request, replacing with a different
HTTP method. Used for checking permissions against other methods. HTTP method. Used for checking permissions against other methods.
""" """
ret = Request(request._request, ret = Request(request=request._request,
request.parsers, parsers=request.parsers,
request.authenticators, authenticators=request.authenticators,
request.parser_context) negotiator=request.negotiator,
parser_context=request.parser_context)
ret._data = request._data ret._data = request._data
ret._files = request._files ret._files = request._files
ret._content_type = request._content_type ret._content_type = request._content_type
@ -57,6 +60,8 @@ def clone_request(request, method):
ret._user = request._user ret._user = request._user
if hasattr(request, '_auth'): if hasattr(request, '_auth'):
ret._auth = request._auth ret._auth = request._auth
if hasattr(request, '_authenticator'):
ret._authenticator = request._authenticator
return ret return ret
@ -88,7 +93,6 @@ class Request(object):
self._method = Empty self._method = Empty
self._content_type = Empty self._content_type = Empty
self._stream = Empty self._stream = Empty
self._authenticator = None
if self.parser_context is None: if self.parser_context is None:
self.parser_context = {} self.parser_context = {}
@ -175,12 +179,12 @@ class Request(object):
@user.setter @user.setter
def user(self, value): def user(self, value):
""" """
Sets the user on the current request. This is necessary to maintain Sets the user on the current request. This is necessary to maintain
compatilbility with django.contrib.auth where the user proprety is compatilbility with django.contrib.auth where the user proprety is
set in the login and logout functions. set in the login and logout functions.
""" """
self._user = value self._user = value
@property @property
def auth(self): def auth(self):
@ -206,6 +210,8 @@ class Request(object):
Return the instance of the authentication instance class that was used Return the instance of the authentication instance class that was used
to authenticate the request, or `None`. to authenticate the request, or `None`.
""" """
if not hasattr(self, '_authenticator'):
self._authenticator, self._user, self._auth = self._authenticate()
return self._authenticator return self._authenticator
def _load_data_and_files(self): def _load_data_and_files(self):
@ -293,7 +299,9 @@ class Request(object):
media_type = self.content_type media_type = self.content_type
if stream is None or media_type is None: if stream is None or media_type is None:
return (None, None) empty_data = QueryDict('', self._request._encoding)
empty_files = MultiValueDict()
return (empty_data, empty_files)
parser = self.negotiator.select_parser(self, self.parsers) parser = self.negotiator.select_parser(self, self.parsers)
@ -307,7 +315,8 @@ class Request(object):
try: try:
return (parsed.data, parsed.files) return (parsed.data, parsed.files)
except AttributeError: except AttributeError:
return (parsed, None) empty_files = MultiValueDict()
return (parsed, empty_files)
def _authenticate(self): def _authenticate(self):
""" """

View File

@ -52,12 +52,15 @@ def main():
if os.path.basename(path) in ['tests', 'runtests', 'migrations']: if os.path.basename(path) in ['tests', 'runtests', 'migrations']:
continue continue
# Drop the compat module from coverage, since we're not interested in the coverage # Drop the compat and six modules from coverage, since we're not interested in the coverage
# of a module which is specifically for resolving environment dependant imports. # of modules which are specifically for resolving environment dependant imports.
# (Because we'll end up getting different coverage reports for it for each environment) # (Because we'll end up getting different coverage reports for it for each environment)
if 'compat.py' in files: if 'compat.py' in files:
files.remove('compat.py') files.remove('compat.py')
if 'six.py' in files:
files.remove('six.py')
# Same applies to template tags module. # Same applies to template tags module.
# This module has to include branching on Django versions, # This module has to include branching on Django versions,
# so it's never possible for it to have full coverage. # so it's never possible for it to have full coverage.

View File

@ -102,6 +102,15 @@ INSTALLED_APPS = (
STATIC_URL = '/static/' STATIC_URL = '/static/'
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
import django import django
if django.VERSION < (1, 3): if django.VERSION < (1, 3):

View File

@ -33,7 +33,7 @@ class DictWithMetadata(dict):
""" """
# return an instance of the first dict in MRO that isn't a DictWithMetadata # return an instance of the first dict in MRO that isn't a DictWithMetadata
for base in self.__class__.__mro__: for base in self.__class__.__mro__:
if not isinstance(base, DictWithMetadata) and isinstance(base, dict): if not issubclass(base, DictWithMetadata) and issubclass(base, dict):
return base(self) return base(self)
@ -348,6 +348,10 @@ class BaseSerializer(WritableField):
many = self.many many = self.many
else: else:
many = hasattr(data, '__iter__') and not isinstance(data, (Page, dict)) many = hasattr(data, '__iter__') and not isinstance(data, (Page, dict))
if many:
warnings.warn('Implict list/queryset serialization is due to be deprecated. '
'Use the `many=True` flag when instantiating the serializer.',
PendingDeprecationWarning, stacklevel=3)
# TODO: error data when deserializing lists # TODO: error data when deserializing lists
if many: if many:
@ -373,6 +377,10 @@ class BaseSerializer(WritableField):
many = self.many many = self.many
else: else:
many = hasattr(obj, '__iter__') and not isinstance(obj, (Page, dict)) many = hasattr(obj, '__iter__') and not isinstance(obj, (Page, dict))
if many:
warnings.warn('Implict list/queryset serialization is due to be deprecated. '
'Use the `many=True` flag when instantiating the serializer.',
PendingDeprecationWarning, stacklevel=2)
if many: if many:
self._data = [self.to_native(item) for item in obj] self._data = [self.to_native(item) for item in obj]
@ -541,6 +549,7 @@ class ModelSerializer(Serializer):
models.PositiveSmallIntegerField: IntegerField, models.PositiveSmallIntegerField: IntegerField,
models.DateTimeField: DateTimeField, models.DateTimeField: DateTimeField,
models.DateField: DateField, models.DateField: DateField,
models.TimeField: TimeField,
models.EmailField: EmailField, models.EmailField: EmailField,
models.CharField: CharField, models.CharField: CharField,
models.URLField: URLField, models.URLField: URLField,
@ -615,12 +624,6 @@ class ModelSerializer(Serializer):
else: else:
instance = self.opts.model(**attrs) instance = self.opts.model(**attrs)
try:
instance.full_clean(exclude=self.get_validation_exclusions())
except ValidationError as err:
self._errors = err.message_dict
return None
return instance return instance
def from_native(self, data, files): def from_native(self, data, files):

View File

@ -2,8 +2,10 @@
General serializer field tests. General serializer field tests.
""" """
from __future__ import unicode_literals from __future__ import unicode_literals
import datetime
from django.db import models from django.db import models
from django.test import TestCase from django.test import TestCase
from django.core import validators
from rest_framework import serializers from rest_framework import serializers
@ -26,7 +28,16 @@ class CharPrimaryKeyModelSerializer(serializers.ModelSerializer):
model = CharPrimaryKeyModel model = CharPrimaryKeyModel
class ReadOnlyFieldTests(TestCase): class TimeFieldModel(models.Model):
clock = models.TimeField()
class TimeFieldModelSerializer(serializers.ModelSerializer):
class Meta:
model = TimeFieldModel
class BasicFieldTests(TestCase):
def test_auto_now_fields_read_only(self): def test_auto_now_fields_read_only(self):
""" """
auto_now and auto_now_add fields should be read_only by default. auto_now and auto_now_add fields should be read_only by default.
@ -47,3 +58,38 @@ class ReadOnlyFieldTests(TestCase):
""" """
serializer = CharPrimaryKeyModelSerializer() serializer = CharPrimaryKeyModelSerializer()
self.assertEquals(serializer.fields['id'].read_only, False) self.assertEquals(serializer.fields['id'].read_only, False)
def test_TimeField_from_native(self):
f = serializers.TimeField()
result = f.from_native('12:34:56.987654')
self.assertEqual(datetime.time(12, 34, 56, 987654), result)
def test_TimeField_from_native_datetime_time(self):
"""
Make sure from_native() accepts a datetime.time instance.
"""
f = serializers.TimeField()
result = f.from_native(datetime.time(12, 34, 56))
self.assertEqual(result, datetime.time(12, 34, 56))
def test_TimeField_from_native_empty(self):
f = serializers.TimeField()
result = f.from_native('')
self.assertEqual(result, None)
def test_TimeField_from_native_invalid_time(self):
f = serializers.TimeField()
try:
f.from_native('12:69:12')
except validators.ValidationError as e:
self.assertEqual(e.messages, ["'12:69:12' value has an invalid "
"format. It must be a valid time "
"in the HH:MM[:ss[.uuuuuu]] format."])
else:
self.fail("ValidationError was not properly raised")
def test_TimeFieldModelSerializer(self):
serializer = TimeFieldModelSerializer()
self.assertTrue(isinstance(serializer.fields['clock'], serializers.TimeField))

View File

@ -82,7 +82,7 @@ class TestGenericRelations(TestCase):
model = Tag model = Tag
exclude = ('id', 'content_type', 'object_id') exclude = ('id', 'content_type', 'object_id')
serializer = TagSerializer(Tag.objects.all()) serializer = TagSerializer(Tag.objects.all(), many=True)
expected = [ expected = [
{ {
'tag': 'django', 'tag': 'django',

View File

@ -0,0 +1,153 @@
from __future__ import unicode_literals
from django.contrib.auth.models import User, Permission
from django.db import models
from django.test import TestCase
from rest_framework import generics, status, permissions, authentication, HTTP_HEADER_ENCODING
from rest_framework.tests.utils import RequestFactory
import base64
import json
factory = RequestFactory()
class BasicModel(models.Model):
text = models.CharField(max_length=100)
class RootView(generics.ListCreateAPIView):
model = BasicModel
authentication_classes = [authentication.BasicAuthentication]
permission_classes = [permissions.DjangoModelPermissions]
class InstanceView(generics.RetrieveUpdateDestroyAPIView):
model = BasicModel
authentication_classes = [authentication.BasicAuthentication]
permission_classes = [permissions.DjangoModelPermissions]
root_view = RootView.as_view()
instance_view = InstanceView.as_view()
def basic_auth_header(username, password):
credentials = ('%s:%s' % (username, password))
base64_credentials = base64.b64encode(credentials.encode(HTTP_HEADER_ENCODING)).decode(HTTP_HEADER_ENCODING)
return 'Basic %s' % base64_credentials
class ModelPermissionsIntegrationTests(TestCase):
def setUp(self):
User.objects.create_user('disallowed', 'disallowed@example.com', 'password')
user = User.objects.create_user('permitted', 'permitted@example.com', 'password')
user.user_permissions = [
Permission.objects.get(codename='add_basicmodel'),
Permission.objects.get(codename='change_basicmodel'),
Permission.objects.get(codename='delete_basicmodel')
]
user = User.objects.create_user('updateonly', 'updateonly@example.com', 'password')
user.user_permissions = [
Permission.objects.get(codename='change_basicmodel'),
]
self.permitted_credentials = basic_auth_header('permitted', 'password')
self.disallowed_credentials = basic_auth_header('disallowed', 'password')
self.updateonly_credentials = basic_auth_header('updateonly', 'password')
BasicModel(text='foo').save()
def test_has_create_permissions(self):
request = factory.post('/', json.dumps({'text': 'foobar'}),
content_type='application/json',
HTTP_AUTHORIZATION=self.permitted_credentials)
response = root_view(request, pk=1)
self.assertEquals(response.status_code, status.HTTP_201_CREATED)
def test_has_put_permissions(self):
request = factory.put('/1', json.dumps({'text': 'foobar'}),
content_type='application/json',
HTTP_AUTHORIZATION=self.permitted_credentials)
response = instance_view(request, pk='1')
self.assertEquals(response.status_code, status.HTTP_200_OK)
def test_has_delete_permissions(self):
request = factory.delete('/1', HTTP_AUTHORIZATION=self.permitted_credentials)
response = instance_view(request, pk=1)
self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
def test_does_not_have_create_permissions(self):
request = factory.post('/', json.dumps({'text': 'foobar'}),
content_type='application/json',
HTTP_AUTHORIZATION=self.disallowed_credentials)
response = root_view(request, pk=1)
self.assertEquals(response.status_code, status.HTTP_403_FORBIDDEN)
def test_does_not_have_put_permissions(self):
request = factory.put('/1', json.dumps({'text': 'foobar'}),
content_type='application/json',
HTTP_AUTHORIZATION=self.disallowed_credentials)
response = instance_view(request, pk='1')
self.assertEquals(response.status_code, status.HTTP_403_FORBIDDEN)
def test_does_not_have_delete_permissions(self):
request = factory.delete('/1', HTTP_AUTHORIZATION=self.disallowed_credentials)
response = instance_view(request, pk=1)
self.assertEquals(response.status_code, status.HTTP_403_FORBIDDEN)
def test_has_put_as_create_permissions(self):
# User only has update permissions - should be able to update an entity.
request = factory.put('/1', json.dumps({'text': 'foobar'}),
content_type='application/json',
HTTP_AUTHORIZATION=self.updateonly_credentials)
response = instance_view(request, pk='1')
self.assertEquals(response.status_code, status.HTTP_200_OK)
# But if PUTing to a new entity, permission should be denied.
request = factory.put('/2', json.dumps({'text': 'foobar'}),
content_type='application/json',
HTTP_AUTHORIZATION=self.updateonly_credentials)
response = instance_view(request, pk='2')
self.assertEquals(response.status_code, status.HTTP_403_FORBIDDEN)
class OwnerModel(models.Model):
text = models.CharField(max_length=100)
owner = models.ForeignKey(User)
class IsOwnerPermission(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
return request.user == obj.owner
class OwnerInstanceView(generics.RetrieveUpdateDestroyAPIView):
model = OwnerModel
authentication_classes = [authentication.BasicAuthentication]
permission_classes = [IsOwnerPermission]
owner_instance_view = OwnerInstanceView.as_view()
class ObjectPermissionsIntegrationTests(TestCase):
"""
Integration tests for the object level permissions API.
"""
def setUp(self):
User.objects.create_user('not_owner', 'not_owner@example.com', 'password')
user = User.objects.create_user('owner', 'owner@example.com', 'password')
self.not_owner_credentials = basic_auth_header('not_owner', 'password')
self.owner_credentials = basic_auth_header('owner', 'password')
OwnerModel(text='foo', owner=user).save()
def test_owner_has_delete_permissions(self):
request = factory.delete('/1', HTTP_AUTHORIZATION=self.owner_credentials)
response = owner_instance_view(request, pk='1')
self.assertEquals(response.status_code, status.HTTP_204_NO_CONTENT)
def test_non_owner_does_not_have_delete_permissions(self):
request = factory.delete('/1', HTTP_AUTHORIZATION=self.not_owner_credentials)
response = owner_instance_view(request, pk='1')
self.assertEquals(response.status_code, status.HTTP_403_FORBIDDEN)

View File

@ -1,8 +1,15 @@
from __future__ import unicode_literals from __future__ import unicode_literals
from django.test import TestCase from django.test import TestCase
from django.test.client import RequestFactory
from rest_framework import serializers from rest_framework import serializers
from rest_framework.compat import patterns, url from rest_framework.compat import patterns, url
from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource from rest_framework.tests.models import (
ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource,
NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
)
factory = RequestFactory()
request = factory.get('/') # Just to ensure we have a request in the serializer context
def dummy_view(request, pk): def dummy_view(request, pk):
@ -73,64 +80,64 @@ class HyperlinkedManyToManyTests(TestCase):
def test_many_to_many_retrieve(self): def test_many_to_many_retrieve(self):
queryset = ManyToManySource.objects.all() queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset) serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/manytomanysource/1/', 'name': 'source-1', 'targets': ['/manytomanytarget/1/']}, {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
{'url': '/manytomanysource/2/', 'name': 'source-2', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']}, {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': 'source-3', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']} {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_reverse_many_to_many_retrieve(self): def test_reverse_many_to_many_retrieve(self):
queryset = ManyToManyTarget.objects.all() queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset) serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/manytomanytarget/1/', 'name': 'target-1', 'sources': ['/manytomanysource/1/', '/manytomanysource/2/', '/manytomanysource/3/']}, {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': '/manytomanytarget/2/', 'name': 'target-2', 'sources': ['/manytomanysource/2/', '/manytomanysource/3/']}, {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': '/manytomanytarget/3/', 'name': 'target-3', 'sources': ['/manytomanysource/3/']} {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_many_to_many_update(self): def test_many_to_many_update(self):
data = {'url': '/manytomanysource/1/', 'name': 'source-1', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']} data = {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
instance = ManyToManySource.objects.get(pk=1) instance = ManyToManySource.objects.get(pk=1)
serializer = ManyToManySourceSerializer(instance, data=data) serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
serializer.save() serializer.save()
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = ManyToManySource.objects.all() queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset) serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/manytomanysource/1/', 'name': 'source-1', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}, {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
{'url': '/manytomanysource/2/', 'name': 'source-2', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']}, {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': 'source-3', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']} {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_reverse_many_to_many_update(self): def test_reverse_many_to_many_update(self):
data = {'url': '/manytomanytarget/1/', 'name': 'target-1', 'sources': ['/manytomanysource/1/']} data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}
instance = ManyToManyTarget.objects.get(pk=1) instance = ManyToManyTarget.objects.get(pk=1)
serializer = ManyToManyTargetSerializer(instance, data=data) serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
serializer.save() serializer.save()
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
# Ensure target 1 is updated, and everything else is as expected # Ensure target 1 is updated, and everything else is as expected
queryset = ManyToManyTarget.objects.all() queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset) serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/manytomanytarget/1/', 'name': 'target-1', 'sources': ['/manytomanysource/1/']}, {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']},
{'url': '/manytomanytarget/2/', 'name': 'target-2', 'sources': ['/manytomanysource/2/', '/manytomanysource/3/']}, {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': '/manytomanytarget/3/', 'name': 'target-3', 'sources': ['/manytomanysource/3/']} {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_many_to_many_create(self): def test_many_to_many_create(self):
data = {'url': '/manytomanysource/4/', 'name': 'source-4', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/3/']} data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
serializer = ManyToManySourceSerializer(data=data) serializer = ManyToManySourceSerializer(data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
obj = serializer.save() obj = serializer.save()
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
@ -138,18 +145,18 @@ class HyperlinkedManyToManyTests(TestCase):
# Ensure source 4 is added, and everything else is as expected # Ensure source 4 is added, and everything else is as expected
queryset = ManyToManySource.objects.all() queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset) serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/manytomanysource/1/', 'name': 'source-1', 'targets': ['/manytomanytarget/1/']}, {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
{'url': '/manytomanysource/2/', 'name': 'source-2', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/']}, {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
{'url': '/manytomanysource/3/', 'name': 'source-3', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/2/', '/manytomanytarget/3/']}, {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
{'url': '/manytomanysource/4/', 'name': 'source-4', 'targets': ['/manytomanytarget/1/', '/manytomanytarget/3/']} {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_reverse_many_to_many_create(self): def test_reverse_many_to_many_create(self):
data = {'url': '/manytomanytarget/4/', 'name': 'target-4', 'sources': ['/manytomanysource/1/', '/manytomanysource/3/']} data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
serializer = ManyToManyTargetSerializer(data=data) serializer = ManyToManyTargetSerializer(data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
obj = serializer.save() obj = serializer.save()
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
@ -157,12 +164,12 @@ class HyperlinkedManyToManyTests(TestCase):
# Ensure target 4 is added, and everything else is as expected # Ensure target 4 is added, and everything else is as expected
queryset = ManyToManyTarget.objects.all() queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset) serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/manytomanytarget/1/', 'name': 'target-1', 'sources': ['/manytomanysource/1/', '/manytomanysource/2/', '/manytomanysource/3/']}, {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': '/manytomanytarget/2/', 'name': 'target-2', 'sources': ['/manytomanysource/2/', '/manytomanysource/3/']}, {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
{'url': '/manytomanytarget/3/', 'name': 'target-3', 'sources': ['/manytomanysource/3/']}, {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']},
{'url': '/manytomanytarget/4/', 'name': 'target-4', 'sources': ['/manytomanysource/1/', '/manytomanysource/3/']} {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
@ -181,60 +188,60 @@ class HyperlinkedForeignKeyTests(TestCase):
def test_foreign_key_retrieve(self): def test_foreign_key_retrieve(self):
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/foreignkeysource/1/', 'name': 'source-1', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/foreignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/foreignkeysource/3/', 'name': 'source-3', 'target': '/foreignkeytarget/1/'} {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_reverse_foreign_key_retrieve(self): def test_reverse_foreign_key_retrieve(self):
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']}, {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/2/', 'http://testserver/foreignkeysource/3/']},
{'url': '/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_update(self): def test_foreign_key_update(self):
data = {'url': '/foreignkeysource/1/', 'name': 'source-1', 'target': '/foreignkeytarget/2/'} data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'}
instance = ForeignKeySource.objects.get(pk=1) instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data) serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
serializer.save() serializer.save()
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/foreignkeysource/1/', 'name': 'source-1', 'target': '/foreignkeytarget/2/'}, {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'},
{'url': '/foreignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/foreignkeysource/3/', 'name': 'source-3', 'target': '/foreignkeytarget/1/'} {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_update_incorrect_type(self): def test_foreign_key_update_incorrect_type(self):
data = {'url': '/foreignkeysource/1/', 'name': 'source-1', 'target': 2} data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 2}
instance = ForeignKeySource.objects.get(pk=1) instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data) serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
self.assertFalse(serializer.is_valid()) self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': ['Incorrect type. Expected url string, received int.']}) self.assertEquals(serializer.errors, {'target': ['Incorrect type. Expected url string, received int.']})
def test_reverse_foreign_key_update(self): def test_reverse_foreign_key_update(self):
data = {'url': '/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']} data = {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}
instance = ForeignKeyTarget.objects.get(pk=2) instance = ForeignKeyTarget.objects.get(pk=2)
serializer = ForeignKeyTargetSerializer(instance, data=data) serializer = ForeignKeyTargetSerializer(instance, data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
# We shouldn't have saved anything to the db yet since save # We shouldn't have saved anything to the db yet since save
# hasn't been called. # hasn't been called.
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
new_serializer = ForeignKeyTargetSerializer(queryset) new_serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/2/', '/foreignkeysource/3/']}, {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/2/', 'http://testserver/foreignkeysource/3/']},
{'url': '/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
] ]
self.assertEquals(new_serializer.data, expected) self.assertEquals(new_serializer.data, expected)
@ -243,16 +250,16 @@ class HyperlinkedForeignKeyTests(TestCase):
# Ensure target 2 is update, and everything else is as expected # Ensure target 2 is update, and everything else is as expected
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['/foreignkeysource/2/']}, {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']},
{'url': '/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}, {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_create(self): def test_foreign_key_create(self):
data = {'url': '/foreignkeysource/4/', 'name': 'source-4', 'target': '/foreignkeytarget/2/'} data = {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'}
serializer = ForeignKeySourceSerializer(data=data) serializer = ForeignKeySourceSerializer(data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
obj = serializer.save() obj = serializer.save()
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
@ -260,18 +267,18 @@ class HyperlinkedForeignKeyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/foreignkeysource/1/', 'name': 'source-1', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/foreignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/foreignkeysource/3/', 'name': 'source-3', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/foreignkeysource/4/', 'name': 'source-4', 'target': '/foreignkeytarget/2/'}, {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_reverse_foreign_key_create(self): def test_reverse_foreign_key_create(self):
data = {'url': '/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']} data = {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}
serializer = ForeignKeyTargetSerializer(data=data) serializer = ForeignKeyTargetSerializer(data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
obj = serializer.save() obj = serializer.save()
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
@ -279,18 +286,18 @@ class HyperlinkedForeignKeyTests(TestCase):
# Ensure target 4 is added, and everything else is as expected # Ensure target 4 is added, and everything else is as expected
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['/foreignkeysource/2/']}, {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']},
{'url': '/foreignkeytarget/2/', 'name': 'target-2', 'sources': []}, {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
{'url': '/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['/foreignkeysource/1/', '/foreignkeysource/3/']}, {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_update_with_invalid_null(self): def test_foreign_key_update_with_invalid_null(self):
data = {'url': '/foreignkeysource/1/', 'name': 'source-1', 'target': None} data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': None}
instance = ForeignKeySource.objects.get(pk=1) instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data) serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
self.assertFalse(serializer.is_valid()) self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': ['This field is required.']}) self.assertEquals(serializer.errors, {'target': ['This field is required.']})
@ -309,17 +316,17 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
def test_foreign_key_retrieve_with_null(self): def test_foreign_key_retrieve_with_null(self):
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_create_with_valid_null(self): def test_foreign_key_create_with_valid_null(self):
data = {'url': '/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
serializer = NullableForeignKeySourceSerializer(data=data) serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
obj = serializer.save() obj = serializer.save()
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
@ -327,12 +334,12 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
# Ensure source 4 is created, and everything else is as expected # Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
{'url': '/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
@ -341,9 +348,9 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
The emptystring should be interpreted as null in the context The emptystring should be interpreted as null in the context
of relationships. of relationships.
""" """
data = {'url': '/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''} data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''}
expected_data = {'url': '/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} expected_data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
serializer = NullableForeignKeySourceSerializer(data=data) serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
obj = serializer.save() obj = serializer.save()
self.assertEquals(serializer.data, expected_data) self.assertEquals(serializer.data, expected_data)
@ -351,30 +358,30 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
# Ensure source 4 is created, and everything else is as expected # Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
{'url': '/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None} {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
def test_foreign_key_update_with_valid_null(self): def test_foreign_key_update_with_valid_null(self):
data = {'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}
instance = NullableForeignKeySource.objects.get(pk=1) instance = NullableForeignKeySource.objects.get(pk=1)
serializer = NullableForeignKeySourceSerializer(instance, data=data) serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, data) self.assertEquals(serializer.data, data)
serializer.save() serializer.save()
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None},
{'url': '/nullableforeignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
@ -383,21 +390,21 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
The emptystring should be interpreted as null in the context The emptystring should be interpreted as null in the context
of relationships. of relationships.
""" """
data = {'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''} data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''}
expected_data = {'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None} expected_data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}
instance = NullableForeignKeySource.objects.get(pk=1) instance = NullableForeignKeySource.objects.get(pk=1)
serializer = NullableForeignKeySourceSerializer(instance, data=data) serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request})
self.assertTrue(serializer.is_valid()) self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, expected_data) self.assertEquals(serializer.data, expected_data)
serializer.save() serializer.save()
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}, {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None},
{'url': '/nullableforeignkeysource/2/', 'name': 'source-2', 'target': '/foreignkeytarget/1/'}, {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
{'url': '/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None}, {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
@ -415,7 +422,7 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
# # Ensure target 1 is updated, and everything else is as expected # # Ensure target 1 is updated, and everything else is as expected
# queryset = ForeignKeyTarget.objects.all() # queryset = ForeignKeyTarget.objects.all()
# serializer = ForeignKeyTargetSerializer(queryset) # serializer = ForeignKeyTargetSerializer(queryset, many=True)
# expected = [ # expected = [
# {'id': 1, 'name': 'target-1', 'sources': [1]}, # {'id': 1, 'name': 'target-1', 'sources': [1]},
# {'id': 2, 'name': 'target-2', 'sources': []}, # {'id': 2, 'name': 'target-2', 'sources': []},
@ -436,9 +443,9 @@ class HyperlinkedNullableOneToOneTests(TestCase):
def test_reverse_foreign_key_retrieve_with_null(self): def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all() queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset) serializer = NullableOneToOneTargetSerializer(queryset, many=True, context={'request': request})
expected = [ expected = [
{'url': '/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': '/nullableonetoonesource/1/'}, {'url': 'http://testserver/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': 'http://testserver/nullableonetoonesource/1/'},
{'url': '/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)

View File

@ -52,7 +52,7 @@ class ReverseForeignKeyTests(TestCase):
def test_foreign_key_retrieve(self): def test_foreign_key_retrieve(self):
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
{'id': 2, 'name': 'source-2', 'target': {'id': 1, 'name': 'target-1'}}, {'id': 2, 'name': 'source-2', 'target': {'id': 1, 'name': 'target-1'}},
@ -62,7 +62,7 @@ class ReverseForeignKeyTests(TestCase):
def test_reverse_foreign_key_retrieve(self): def test_reverse_foreign_key_retrieve(self):
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [ {'id': 1, 'name': 'target-1', 'sources': [
{'id': 1, 'name': 'source-1', 'target': 1}, {'id': 1, 'name': 'source-1', 'target': 1},
@ -87,7 +87,7 @@ class NestedNullableForeignKeyTests(TestCase):
def test_foreign_key_retrieve_with_null(self): def test_foreign_key_retrieve_with_null(self):
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
{'id': 2, 'name': 'source-2', 'target': {'id': 1, 'name': 'target-1'}}, {'id': 2, 'name': 'source-2', 'target': {'id': 1, 'name': 'target-1'}},
@ -107,7 +107,7 @@ class NestedNullableOneToOneTests(TestCase):
def test_reverse_foreign_key_retrieve_with_null(self): def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all() queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset) serializer = NullableOneToOneTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'nullable_source': {'id': 1, 'name': 'source-1', 'target': 1}}, {'id': 1, 'name': 'target-1', 'nullable_source': {'id': 1, 'name': 'source-1', 'target': 1}},
{'id': 2, 'name': 'target-2', 'nullable_source': None}, {'id': 2, 'name': 'target-2', 'nullable_source': None},

View File

@ -2,6 +2,7 @@ from __future__ import unicode_literals
from django.test import TestCase from django.test import TestCase
from rest_framework import serializers from rest_framework import serializers
from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
from rest_framework.compat import six
class ManyToManyTargetSerializer(serializers.ModelSerializer): class ManyToManyTargetSerializer(serializers.ModelSerializer):
@ -55,7 +56,7 @@ class PKManyToManyTests(TestCase):
def test_many_to_many_retrieve(self): def test_many_to_many_retrieve(self):
queryset = ManyToManySource.objects.all() queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset) serializer = ManyToManySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'targets': [1]}, {'id': 1, 'name': 'source-1', 'targets': [1]},
{'id': 2, 'name': 'source-2', 'targets': [1, 2]}, {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
@ -65,7 +66,7 @@ class PKManyToManyTests(TestCase):
def test_reverse_many_to_many_retrieve(self): def test_reverse_many_to_many_retrieve(self):
queryset = ManyToManyTarget.objects.all() queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset) serializer = ManyToManyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': 'target-2', 'sources': [2, 3]}, {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
@ -83,7 +84,7 @@ class PKManyToManyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = ManyToManySource.objects.all() queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset) serializer = ManyToManySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}, {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]},
{'id': 2, 'name': 'source-2', 'targets': [1, 2]}, {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
@ -101,7 +102,7 @@ class PKManyToManyTests(TestCase):
# Ensure target 1 is updated, and everything else is as expected # Ensure target 1 is updated, and everything else is as expected
queryset = ManyToManyTarget.objects.all() queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset) serializer = ManyToManyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [1]}, {'id': 1, 'name': 'target-1', 'sources': [1]},
{'id': 2, 'name': 'target-2', 'sources': [2, 3]}, {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
@ -119,7 +120,7 @@ class PKManyToManyTests(TestCase):
# Ensure source 4 is added, and everything else is as expected # Ensure source 4 is added, and everything else is as expected
queryset = ManyToManySource.objects.all() queryset = ManyToManySource.objects.all()
serializer = ManyToManySourceSerializer(queryset) serializer = ManyToManySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'targets': [1]}, {'id': 1, 'name': 'source-1', 'targets': [1]},
{'id': 2, 'name': 'source-2', 'targets': [1, 2]}, {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
@ -138,7 +139,7 @@ class PKManyToManyTests(TestCase):
# Ensure target 4 is added, and everything else is as expected # Ensure target 4 is added, and everything else is as expected
queryset = ManyToManyTarget.objects.all() queryset = ManyToManyTarget.objects.all()
serializer = ManyToManyTargetSerializer(queryset) serializer = ManyToManyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': 'target-2', 'sources': [2, 3]}, {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
@ -160,7 +161,7 @@ class PKForeignKeyTests(TestCase):
def test_foreign_key_retrieve(self): def test_foreign_key_retrieve(self):
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 1}, {'id': 1, 'name': 'source-1', 'target': 1},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -170,7 +171,7 @@ class PKForeignKeyTests(TestCase):
def test_reverse_foreign_key_retrieve(self): def test_reverse_foreign_key_retrieve(self):
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': 'target-2', 'sources': []}, {'id': 2, 'name': 'target-2', 'sources': []},
@ -187,7 +188,7 @@ class PKForeignKeyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 2}, {'id': 1, 'name': 'source-1', 'target': 2},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -200,7 +201,7 @@ class PKForeignKeyTests(TestCase):
instance = ForeignKeySource.objects.get(pk=1) instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data) serializer = ForeignKeySourceSerializer(instance, data=data)
self.assertFalse(serializer.is_valid()) self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': ['Incorrect type. Expected pk value, received str.']}) self.assertEquals(serializer.errors, {'target': ['Incorrect type. Expected pk value, received %s.' % six.text_type.__name__]})
def test_reverse_foreign_key_update(self): def test_reverse_foreign_key_update(self):
data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]} data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]}
@ -210,7 +211,7 @@ class PKForeignKeyTests(TestCase):
# We shouldn't have saved anything to the db yet since save # We shouldn't have saved anything to the db yet since save
# hasn't been called. # hasn't been called.
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
new_serializer = ForeignKeyTargetSerializer(queryset) new_serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]}, {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': 'target-2', 'sources': []}, {'id': 2, 'name': 'target-2', 'sources': []},
@ -222,7 +223,7 @@ class PKForeignKeyTests(TestCase):
# Ensure target 2 is update, and everything else is as expected # Ensure target 2 is update, and everything else is as expected
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [2]}, {'id': 1, 'name': 'target-1', 'sources': [2]},
{'id': 2, 'name': 'target-2', 'sources': [1, 3]}, {'id': 2, 'name': 'target-2', 'sources': [1, 3]},
@ -239,7 +240,7 @@ class PKForeignKeyTests(TestCase):
# Ensure source 4 is added, and everything else is as expected # Ensure source 4 is added, and everything else is as expected
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 1}, {'id': 1, 'name': 'source-1', 'target': 1},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -258,7 +259,7 @@ class PKForeignKeyTests(TestCase):
# Ensure target 3 is added, and everything else is as expected # Ensure target 3 is added, and everything else is as expected
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': [2]}, {'id': 1, 'name': 'target-1', 'sources': [2]},
{'id': 2, 'name': 'target-2', 'sources': []}, {'id': 2, 'name': 'target-2', 'sources': []},
@ -271,7 +272,7 @@ class PKForeignKeyTests(TestCase):
instance = ForeignKeySource.objects.get(pk=1) instance = ForeignKeySource.objects.get(pk=1)
serializer = ForeignKeySourceSerializer(instance, data=data) serializer = ForeignKeySourceSerializer(instance, data=data)
self.assertFalse(serializer.is_valid()) self.assertFalse(serializer.is_valid())
self.assertEquals(serializer.errors, {'target': ['Value may not be null']}) self.assertEquals(serializer.errors, {'target': ['This field is required.']})
class PKNullableForeignKeyTests(TestCase): class PKNullableForeignKeyTests(TestCase):
@ -286,7 +287,7 @@ class PKNullableForeignKeyTests(TestCase):
def test_foreign_key_retrieve_with_null(self): def test_foreign_key_retrieve_with_null(self):
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 1}, {'id': 1, 'name': 'source-1', 'target': 1},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -304,7 +305,7 @@ class PKNullableForeignKeyTests(TestCase):
# Ensure source 4 is created, and everything else is as expected # Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 1}, {'id': 1, 'name': 'source-1', 'target': 1},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -328,7 +329,7 @@ class PKNullableForeignKeyTests(TestCase):
# Ensure source 4 is created, and everything else is as expected # Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 1}, {'id': 1, 'name': 'source-1', 'target': 1},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -347,7 +348,7 @@ class PKNullableForeignKeyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': None}, {'id': 1, 'name': 'source-1', 'target': None},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -370,7 +371,7 @@ class PKNullableForeignKeyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': None}, {'id': 1, 'name': 'source-1', 'target': None},
{'id': 2, 'name': 'source-2', 'target': 1}, {'id': 2, 'name': 'source-2', 'target': 1},
@ -392,7 +393,7 @@ class PKNullableForeignKeyTests(TestCase):
# # Ensure target 1 is updated, and everything else is as expected # # Ensure target 1 is updated, and everything else is as expected
# queryset = ForeignKeyTarget.objects.all() # queryset = ForeignKeyTarget.objects.all()
# serializer = ForeignKeyTargetSerializer(queryset) # serializer = ForeignKeyTargetSerializer(queryset, many=True)
# expected = [ # expected = [
# {'id': 1, 'name': 'target-1', 'sources': [1]}, # {'id': 1, 'name': 'target-1', 'sources': [1]},
# {'id': 2, 'name': 'target-2', 'sources': []}, # {'id': 2, 'name': 'target-2', 'sources': []},
@ -411,7 +412,7 @@ class PKNullableOneToOneTests(TestCase):
def test_reverse_foreign_key_retrieve_with_null(self): def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all() queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset) serializer = NullableOneToOneTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'nullable_source': 1}, {'id': 1, 'name': 'target-1', 'nullable_source': 1},
{'id': 2, 'name': 'target-2', 'nullable_source': None}, {'id': 2, 'name': 'target-2', 'nullable_source': None},

View File

@ -25,7 +25,7 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
# TODO: M2M Tests, FKTests (Non-nulable), One2One # TODO: M2M Tests, FKTests (Non-nulable), One2One
class PKForeignKeyTests(TestCase): class SlugForeignKeyTests(TestCase):
def setUp(self): def setUp(self):
target = ForeignKeyTarget(name='target-1') target = ForeignKeyTarget(name='target-1')
target.save() target.save()
@ -37,7 +37,7 @@ class PKForeignKeyTests(TestCase):
def test_foreign_key_retrieve(self): def test_foreign_key_retrieve(self):
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 'target-1'}, {'id': 1, 'name': 'source-1', 'target': 'target-1'},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},
@ -47,7 +47,7 @@ class PKForeignKeyTests(TestCase):
def test_reverse_foreign_key_retrieve(self): def test_reverse_foreign_key_retrieve(self):
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
{'id': 2, 'name': 'target-2', 'sources': []}, {'id': 2, 'name': 'target-2', 'sources': []},
@ -64,7 +64,7 @@ class PKForeignKeyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 'target-2'}, {'id': 1, 'name': 'source-1', 'target': 'target-2'},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},
@ -87,7 +87,7 @@ class PKForeignKeyTests(TestCase):
# We shouldn't have saved anything to the db yet since save # We shouldn't have saved anything to the db yet since save
# hasn't been called. # hasn't been called.
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
new_serializer = ForeignKeyTargetSerializer(queryset) new_serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']}, {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
{'id': 2, 'name': 'target-2', 'sources': []}, {'id': 2, 'name': 'target-2', 'sources': []},
@ -99,7 +99,7 @@ class PKForeignKeyTests(TestCase):
# Ensure target 2 is update, and everything else is as expected # Ensure target 2 is update, and everything else is as expected
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': ['source-2']}, {'id': 1, 'name': 'target-1', 'sources': ['source-2']},
{'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']}, {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']},
@ -117,7 +117,7 @@ class PKForeignKeyTests(TestCase):
# Ensure source 4 is added, and everything else is as expected # Ensure source 4 is added, and everything else is as expected
queryset = ForeignKeySource.objects.all() queryset = ForeignKeySource.objects.all()
serializer = ForeignKeySourceSerializer(queryset) serializer = ForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 'target-1'}, {'id': 1, 'name': 'source-1', 'target': 'target-1'},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},
@ -136,7 +136,7 @@ class PKForeignKeyTests(TestCase):
# Ensure target 3 is added, and everything else is as expected # Ensure target 3 is added, and everything else is as expected
queryset = ForeignKeyTarget.objects.all() queryset = ForeignKeyTarget.objects.all()
serializer = ForeignKeyTargetSerializer(queryset) serializer = ForeignKeyTargetSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'target-1', 'sources': ['source-2']}, {'id': 1, 'name': 'target-1', 'sources': ['source-2']},
{'id': 2, 'name': 'target-2', 'sources': []}, {'id': 2, 'name': 'target-2', 'sources': []},
@ -164,7 +164,7 @@ class SlugNullableForeignKeyTests(TestCase):
def test_foreign_key_retrieve_with_null(self): def test_foreign_key_retrieve_with_null(self):
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 'target-1'}, {'id': 1, 'name': 'source-1', 'target': 'target-1'},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},
@ -182,7 +182,7 @@ class SlugNullableForeignKeyTests(TestCase):
# Ensure source 4 is created, and everything else is as expected # Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 'target-1'}, {'id': 1, 'name': 'source-1', 'target': 'target-1'},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},
@ -206,7 +206,7 @@ class SlugNullableForeignKeyTests(TestCase):
# Ensure source 4 is created, and everything else is as expected # Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': 'target-1'}, {'id': 1, 'name': 'source-1', 'target': 'target-1'},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},
@ -225,7 +225,7 @@ class SlugNullableForeignKeyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': None}, {'id': 1, 'name': 'source-1', 'target': None},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},
@ -248,7 +248,7 @@ class SlugNullableForeignKeyTests(TestCase):
# Ensure source 1 is updated, and everything else is as expected # Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all() queryset = NullableForeignKeySource.objects.all()
serializer = NullableForeignKeySourceSerializer(queryset) serializer = NullableForeignKeySourceSerializer(queryset, many=True)
expected = [ expected = [
{'id': 1, 'name': 'source-1', 'target': None}, {'id': 1, 'name': 'source-1', 'target': None},
{'id': 2, 'name': 'source-2', 'target': 'target-1'}, {'id': 2, 'name': 'source-2', 'target': 'target-1'},

View File

@ -95,7 +95,7 @@ urlpatterns = patterns('',
class POSTDeniedPermission(permissions.BasePermission): class POSTDeniedPermission(permissions.BasePermission):
def has_permission(self, request, view, obj=None): def has_permission(self, request, view):
return request.method != 'POST' return request.method != 'POST'

View File

@ -62,17 +62,17 @@ class TestMethodOverloading(TestCase):
class TestContentParsing(TestCase): class TestContentParsing(TestCase):
def test_standard_behaviour_determines_no_content_GET(self): def test_standard_behaviour_determines_no_content_GET(self):
""" """
Ensure request.DATA returns None for GET request with no content. Ensure request.DATA returns empty QueryDict for GET request.
""" """
request = Request(factory.get('/')) request = Request(factory.get('/'))
self.assertEqual(request.DATA, None) self.assertEqual(request.DATA, {})
def test_standard_behaviour_determines_no_content_HEAD(self): def test_standard_behaviour_determines_no_content_HEAD(self):
""" """
Ensure request.DATA returns None for HEAD request. Ensure request.DATA returns empty QueryDict for HEAD request.
""" """
request = Request(factory.head('/')) request = Request(factory.head('/'))
self.assertEqual(request.DATA, None) self.assertEqual(request.DATA, {})
def test_request_DATA_with_form_content(self): def test_request_DATA_with_form_content(self):
""" """

View File

@ -261,7 +261,7 @@ class ValidationTests(TestCase):
Data of the wrong type is not valid. Data of the wrong type is not valid.
""" """
data = ['i am', 'a', 'list'] data = ['i am', 'a', 'list']
serializer = CommentSerializer(self.comment, data=data) serializer = CommentSerializer(self.comment, data=data, many=True)
self.assertEquals(serializer.is_valid(), False) self.assertEquals(serializer.is_valid(), False)
self.assertEquals(serializer.errors, {'non_field_errors': ['Invalid data']}) self.assertEquals(serializer.errors, {'non_field_errors': ['Invalid data']})
@ -747,6 +747,9 @@ class ManyRelatedTests(TestCase):
class RelatedTraversalTest(TestCase): class RelatedTraversalTest(TestCase):
def test_nested_traversal(self): def test_nested_traversal(self):
"""
Source argument should support dotted.source notation.
"""
user = Person.objects.create(name="django") user = Person.objects.create(name="django")
post = BlogPost.objects.create(title="Test blog post", writer=user) post = BlogPost.objects.create(title="Test blog post", writer=user)
post.blogpostcomment_set.create(text="I love this blog post") post.blogpostcomment_set.create(text="I love this blog post")
@ -785,6 +788,41 @@ class RelatedTraversalTest(TestCase):
self.assertEqual(serializer.data, expected) self.assertEqual(serializer.data, expected)
def test_nested_traversal_with_none(self):
"""
If a component of the dotted.source is None, return None for the field.
"""
from rest_framework.tests.models import NullableForeignKeySource
instance = NullableForeignKeySource.objects.create(name='Source with null FK')
class NullableSourceSerializer(serializers.Serializer):
target_name = serializers.Field(source='target.name')
serializer = NullableSourceSerializer(instance=instance)
expected = {
'target_name': None,
}
self.assertEqual(serializer.data, expected)
def test_queryset_nested_traversal(self):
"""
Relational fields should be able to use methods as their source.
"""
BlogPost.objects.create(title='blah')
class QuerysetMethodSerializer(serializers.Serializer):
blogposts = serializers.RelatedField(many=True, source='get_all_blogposts')
class ClassWithQuerysetMethod(object):
def get_all_blogposts(self):
return BlogPost.objects
obj = ClassWithQuerysetMethod()
serializer = QuerysetMethodSerializer(obj)
self.assertEquals(serializer.data, {'blogposts': ['BlogPost object']})
class SerializerMethodFieldTests(TestCase): class SerializerMethodFieldTests(TestCase):
def setUp(self): def setUp(self):
@ -900,6 +938,13 @@ class SerializerPickleTests(TestCase):
fields = ('name', 'age') fields = ('name', 'age')
pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data) pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data)
def test_getstate_method_should_not_return_none(self):
'''Regression test for
https://github.com/tomchristie/django-rest-framework/issues/645
'''
d = serializers.DictWithMetadata({1:1})
self.assertEqual(d.__getstate__(), serializers.SortedDict({1:1}))
class DepthTest(TestCase): class DepthTest(TestCase):
def test_implicit_nesting(self): def test_implicit_nesting(self):

View File

@ -257,18 +257,28 @@ class APIView(View):
return (renderers[0], renderers[0].media_type) return (renderers[0], renderers[0].media_type)
raise raise
def has_permission(self, request, obj=None): def check_permissions(self, request):
""" """
Return `True` if the request should be permitted. Check if the request should be permitted.
Raises an appropriate exception if the request is not permitted.
""" """
for permission in self.get_permissions(): for permission in self.get_permissions():
if not permission.has_permission(request, self, obj): if not permission.has_permission(request, self):
return False self.permission_denied(request)
return True
def check_object_permissions(self, request, obj):
"""
Check if the request should be permitted for a given object.
Raises an appropriate exception if the request is not permitted.
"""
for permission in self.get_permissions():
if not permission.has_object_permission(request, self, obj):
self.permission_denied(request)
def check_throttles(self, request): def check_throttles(self, request):
""" """
Check if request should be throttled. Check if request should be throttled.
Raises an appropriate exception if the request is throttled.
""" """
for throttle in self.get_throttles(): for throttle in self.get_throttles():
if not throttle.allow_request(request, self): if not throttle.allow_request(request, self):
@ -295,8 +305,7 @@ class APIView(View):
self.format_kwarg = self.get_format_suffix(**kwargs) self.format_kwarg = self.get_format_suffix(**kwargs)
# Ensure that the incoming request is permitted # Ensure that the incoming request is permitted
if not self.has_permission(request): self.check_permissions(request)
self.permission_denied(request)
self.check_throttles(request) self.check_throttles(request)
# Perform content negotiation and store the accepted info on the request # Perform content negotiation and store the accepted info on the request

View File

@ -1,8 +1,6 @@
#!/usr/bin/env python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
#from __future__ import unicode_literals
from setuptools import setup from setuptools import setup
import re import re
import os import os
@ -59,7 +57,7 @@ setup(
url='http://django-rest-framework.org', url='http://django-rest-framework.org',
download_url='http://pypi.python.org/pypi/rest_framework/', download_url='http://pypi.python.org/pypi/rest_framework/',
license='BSD', license='BSD',
description='A lightweight REST framework for Django.', description='Web APIs for Django, made easy.',
author='Tom Christie', author='Tom Christie',
author_email='tom@tomchristie.com', # SEE NOTE BELOW (*) author_email='tom@tomchristie.com', # SEE NOTE BELOW (*)
packages=get_packages('rest_framework'), packages=get_packages('rest_framework'),
@ -67,7 +65,7 @@ setup(
test_suite='rest_framework.runtests.runtests.main', test_suite='rest_framework.runtests.runtests.main',
install_requires=[], install_requires=[],
classifiers=[ classifiers=[
'Development Status :: 4 - Beta', 'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment', 'Environment :: Web Environment',
'Framework :: Django', 'Framework :: Django',
'Intended Audience :: Developers', 'Intended Audience :: Developers',