Merge branch 'master' into extra_csrf

This commit is contained in:
Rick Yazwinski 2013-01-17 15:56:55 -05:00
commit ef4c25ace6
28 changed files with 412 additions and 81 deletions

View File

@ -81,6 +81,17 @@ To run the tests.
# Changelog # Changelog
### 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 ### 2.1.15
**Date**: 3rd Jan 2013 **Date**: 3rd Jan 2013
@ -283,5 +294,4 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[urlobject]: https://github.com/zacharyvoase/urlobject [urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/ [markdown]: http://pypi.python.org/pypi/Markdown/
[pyyaml]: http://pypi.python.org/pypi/PyYAML [pyyaml]: http://pypi.python.org/pypi/PyYAML
[django-filter]: https://github.com/alex/django-filter [django-filter]: http://pypi.python.org/pypi/django-filter

View File

@ -52,7 +52,7 @@ Or, if you're using the `@api_view` decorator with function based views.
@api_view(['GET']) @api_view(['GET'])
@authentication_classes((SessionAuthentication, BasicAuthentication)) @authentication_classes((SessionAuthentication, BasicAuthentication))
@permissions_classes((IsAuthenticated,)) @permission_classes((IsAuthenticated,))
def example_view(request, format=None): def example_view(request, format=None):
content = { content = {
'user': unicode(request.user), # `django.contrib.auth.User` instance. 'user': unicode(request.user), # `django.contrib.auth.User` instance.
@ -125,17 +125,6 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
<!--
## OAuthAuthentication
This policy uses the [OAuth 2.0][oauth] protocol to authenticate requests. OAuth is appropriate for server-server setups, such as when you want to allow a third-party service to access your API on a user's behalf.
If successfully authenticated, `OAuthAuthentication` provides the following credentials.
* `request.user` will be a Django `User` instance.
* `request.auth` will be a `rest_framework.models.OAuthToken` instance.
-->
## SessionAuthentication ## SessionAuthentication
This policy 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 policy 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.
@ -145,6 +134,8 @@ If successfully authenticated, `SessionAuthentication` provides the following cr
* `request.user` will be a Django `User` instance. * `request.user` will be a Django `User` instance.
* `request.auth` will be `None`. * `request.auth` will be `None`.
If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details.
# Custom authentication # Custom authentication
To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise. To implement a custom authentication policy, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise.
@ -154,3 +145,4 @@ To implement a custom authentication policy, subclass `BaseAuthentication` and o
[oauth]: http://oauth.net/2/ [oauth]: http://oauth.net/2/
[permission]: permissions.md [permission]: permissions.md
[throttling]: throttling.md [throttling]: throttling.md
[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

View File

@ -97,6 +97,8 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie
paginate_by = 10 paginate_by = 10
paginate_by_param = 'page_size' paginate_by_param = 'page_size'
Note that using a `paginate_by` value of `None` will turn off pagination for the view.
For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods. For more complex requirements such as serialization that differs depending on the requested media type you can override the `.get_paginate_by()` and `.get_pagination_serializer_class()` methods.
--- ---

View File

@ -167,7 +167,7 @@ The following third party packages are also available.
## MessagePack ## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack]. [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack

View File

@ -279,7 +279,11 @@ The following third party packages are also available.
## MessagePack ## MessagePack
[MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the `djangorestframework-msgpack` package which provides MessagePack renderer and parser support for REST framework. Documentation is [available here][djangorestframework-msgpack]. [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework.
## CSV
Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework.
[cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process
[conneg]: content-negotiation.md [conneg]: content-negotiation.md
@ -290,6 +294,8 @@ The following third party packages are also available.
[application/vnd.github+json]: http://developer.github.com/v3/media/ [application/vnd.github+json]: http://developer.github.com/v3/media/
[application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/ [application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/
[django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views [django-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [messagepack]: http://msgpack.org/
[juanriaza]: https://github.com/juanriaza [juanriaza]: https://github.com/juanriaza
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [mjumbewu]: https://github.com/mjumbewu
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv

View File

@ -65,7 +65,7 @@ Default:
( (
'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.UserBasicAuthentication' 'rest_framework.authentication.BasicAuthentication'
) )
## DEFAULT_PERMISSION_CLASSES ## DEFAULT_PERMISSION_CLASSES

View File

@ -166,7 +166,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[urlobject]: https://github.com/zacharyvoase/urlobject [urlobject]: https://github.com/zacharyvoase/urlobject
[markdown]: http://pypi.python.org/pypi/Markdown/ [markdown]: http://pypi.python.org/pypi/Markdown/
[yaml]: http://pypi.python.org/pypi/PyYAML [yaml]: http://pypi.python.org/pypi/PyYAML
[django-filter]: https://github.com/alex/django-filter [django-filter]: http://pypi.python.org/pypi/django-filter
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X [0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
[image]: img/quickstart.png [image]: img/quickstart.png
[sandbox]: http://restframework.herokuapp.com/ [sandbox]: http://restframework.herokuapp.com/

View File

@ -88,6 +88,10 @@ The following people have helped make REST framework great.
* Juan Riaza - [juanriaza] * Juan Riaza - [juanriaza]
* Michael Mior - [michaelmior] * Michael Mior - [michaelmior]
* Marc Tamlyn - [mjtamlyn] * Marc Tamlyn - [mjtamlyn]
* Richard Wackerbarth - [wackerbarth]
* Johannes Spielmann - [shezi]
* James Cleveland - [radiosilence]
* Steve Gregory - [steve-gregory]
Many thanks to everyone who's contributed to the project. Many thanks to everyone who's contributed to the project.
@ -211,3 +215,7 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[juanriaza]: https://github.com/juanriaza [juanriaza]: https://github.com/juanriaza
[michaelmior]: https://github.com/michaelmior [michaelmior]: https://github.com/michaelmior
[mjtamlyn]: https://github.com/mjtamlyn [mjtamlyn]: https://github.com/mjtamlyn
[wackerbarth]: https://github.com/wackerbarth
[shezi]: https://github.com/shezi
[radiosilence]: https://github.com/radiosilence
[steve-gregory]: https://github.com/steve-gregory

View File

@ -18,9 +18,21 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi
### Master ### Master
* Deprecate django.utils.simplejson in favor of Python 2.6's built-in json module. * Support json encoding of timedelta objects.
* Bugfix: Support nullable FKs with `SlugRelatedField`.
### 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 serializers receive incorrect types.
* Bugfix: Validation errors instead of exceptions when related fields 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
**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details.
### 2.1.15 ### 2.1.15
@ -314,3 +326,4 @@ This change will not affect user code, so long as it's following the recommended
[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
[announcement]: rest-framework-2-announcement.md [announcement]: rest-framework-2-announcement.md
[#582]: https://github.com/tomchristie/django-rest-framework/issues/582

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 final code for this tutorial is available in the [tomchristie/rest-framework-tutorial][repo] repository on GitHub. There is also 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. 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].
--- ---
@ -60,7 +60,7 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I
INSTALLED_APPS = ( INSTALLED_APPS = (
... ...
'rest_framework', 'rest_framework',
'snippets' 'snippets',
) )
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
@ -73,14 +73,15 @@ Okay, we're ready to roll.
## Creating a model to work with ## Creating a model to work with
For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
from django.db import models from django.db import models
from pygments.lexers import get_all_lexers from pygments.lexers import get_all_lexers
from pygments.styles import get_all_styles from pygments.styles import get_all_styles
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()]) LEXERS = [item for item in get_all_lexers() if item[1]]
STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles())) LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())
class Snippet(models.Model): class Snippet(models.Model):
@ -202,8 +203,6 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer`
model = Snippet model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style') fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
## Writing regular Django views using our Serializer ## Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class. Let's see how we can write some API views using our new Serializer class.
@ -229,7 +228,6 @@ Edit the `snippet/views.py` file, and add the following.
kwargs['content_type'] = 'application/json' kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs) super(JSONResponse, self).__init__(content, **kwargs)
The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet.
@csrf_exempt @csrf_exempt
@ -288,16 +286,45 @@ Finally we need to wire these views up. Create the `snippets/urls.py` file:
urlpatterns = patterns('snippets.views', urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'), url(r'^snippets/$', 'snippet_list'),
url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail') url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
) )
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now. It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
## Testing our first attempt at a Web API ## Testing our first attempt at a Web API
**TODO: Describe using runserver and making example requests from console** Now we can start up a sample server that serves our snippets.
**TODO: Describe opening in a web browser and viewing json output** Quit out of the shell
quit()
and start up Django's development server
python manage.py runserver
Validating models...
0 errors found
Django version 1.4.3, using settings 'tutorial.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
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)
curl http://127.0.0.1:8000/snippets/
[{"id": 1, "title": "", "code": "print \"hello, world\"\n", "linenos": false, "language": "python", "style": "friendly"}]
or we can get a particular snippet by referencing its id
curl http://127.0.0.1:8000/snippets/1/
{"id": 1, "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.
## Where are we now ## Where are we now

View File

@ -31,7 +31,6 @@ These wrappers provide a few bits of functionality such as making sure you recei
The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input. The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input.
## Pulling it all together ## Pulling it all together
Okay, let's go ahead and start using these new components to write a few views. Okay, let's go ahead and start using these new components to write a few views.
@ -63,7 +62,6 @@ We don't need our `JSONResponse` class anymore, so go ahead and delete that. On
else: else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious. Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious.
Here is the view for an individual snippet. Here is the view for an individual snippet.
@ -117,7 +115,7 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
urlpatterns = patterns('snippets.views', urlpatterns = patterns('snippets.views',
url(r'^snippets/$', 'snippet_list'), url(r'^snippets/$', 'snippet_list'),
url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail') url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'),
) )
urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns = format_suffix_patterns(urlpatterns)
@ -138,7 +136,6 @@ Because the API chooses a return format based on what the client asks for, it wi
See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it. See the [browsable api][browseable-api] topic for more information about the browsable API feature and how to customize it.
## What's next? ## What's next?
In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write. In [tutorial part 3][tut-3], we'll start using class based views, and see how generic views reduce the amount of code we need to write.

View File

@ -70,7 +70,7 @@ We'll also need to refactor our URLconf slightly now we're using class based vie
urlpatterns = patterns('', urlpatterns = patterns('',
url(r'^snippets/$', views.SnippetList.as_view()), url(r'^snippets/$', views.SnippetList.as_view()),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()) url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
) )
urlpatterns = format_suffix_patterns(urlpatterns) urlpatterns = format_suffix_patterns(urlpatterns)

View File

@ -29,7 +29,7 @@ And now we can add a `.save()` method to our model class:
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
""" """
Use the `pygments` library to create an highlighted HTML Use the `pygments` library to create a highlighted HTML
representation of the code snippet. representation of the code snippet.
""" """
lexer = get_lexer_by_name(self.language) lexer = get_lexer_by_name(self.language)
@ -77,7 +77,7 @@ We'll also add a couple of views. We'd like to just use read-only views for the
Finally we need to add those views into the API, by referencing them from the URL conf. Finally we need to add those views into the API, by referencing them from the URL conf.
url(r'^users/$', views.UserList.as_view()), url(r'^users/$', views.UserList.as_view()),
url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view()) url(r'^users/(?P<pk>[0-9]+)/$', views.UserInstance.as_view()),
## Associating Snippets with Users ## Associating Snippets with Users
@ -134,7 +134,7 @@ And, at the end of the file, add a pattern to include the login and logout views
urlpatterns += patterns('', urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls', url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')) namespace='rest_framework')),
) )
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace. The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace.

View File

@ -15,8 +15,8 @@ Right now we have endpoints for 'snippets' and 'users', but we don't have a sing
@api_view(('GET',)) @api_view(('GET',))
def api_root(request, format=None): def api_root(request, format=None):
return Response({ return Response({
'users': reverse('user-list', request=request), 'users': reverse('user-list', request=request, format=format),
'snippets': reverse('snippet-list', request=request) 'snippets': reverse('snippet-list', request=request, format=format)
}) })
Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs. Notice that we're using REST framework's `reverse` function in order to return fully-qualified URLs.
@ -116,7 +116,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
url(r'^snippets/(?P<pk>[0-9]+)/$', url(r'^snippets/(?P<pk>[0-9]+)/$',
views.SnippetDetail.as_view(), views.SnippetDetail.as_view(),
name='snippet-detail'), name='snippet-detail'),
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$' url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
views.SnippetHighlight.as_view(), views.SnippetHighlight.as_view(),
name='snippet-highlight'), name='snippet-highlight'),
url(r'^users/$', url(r'^users/$',
@ -130,7 +130,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should
# Login and logout views for the browsable API # Login and logout views for the browsable API
urlpatterns += patterns('', urlpatterns += patterns('',
url(r'^api-auth/', include('rest_framework.urls', url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')) namespace='rest_framework')),
) )
## Adding pagination ## Adding pagination

View File

@ -1,3 +1,3 @@
__version__ = '2.1.15' __version__ = '2.1.16'
VERSION = __version__ # synonym VERSION = __version__ # synonym

View File

@ -12,10 +12,11 @@ class ObtainAuthToken(APIView):
permission_classes = () permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,) renderer_classes = (renderers.JSONRenderer,)
serializer_class = AuthTokenSerializer
model = Token model = Token
def post(self, request): def post(self, request):
serializer = AuthTokenSerializer(data=request.DATA) serializer = self.serializer_class(data=request.DATA)
if serializer.is_valid(): if serializer.is_valid():
token, created = Token.objects.get_or_create(user=serializer.object['user']) token, created = Token.objects.get_or_create(user=serializer.object['user'])
return Response({'token': token.key}) return Response({'token': token.key})

View File

@ -101,7 +101,13 @@ class RelatedField(WritableField):
### Regular serializer stuff... ### Regular serializer stuff...
def field_to_native(self, obj, field_name): def field_to_native(self, obj, field_name):
value = getattr(obj, self.source or field_name) try:
value = getattr(obj, self.source or field_name)
except ObjectDoesNotExist:
return None
if value is None:
return None
return self.to_native(value) return self.to_native(value)
def field_from_native(self, data, files, field_name, into): def field_from_native(self, data, files, field_name, into):
@ -211,7 +217,10 @@ class PrimaryKeyRelatedField(RelatedField):
pk = obj.serializable_value(self.source or field_name) pk = obj.serializable_value(self.source or field_name)
except AttributeError: except AttributeError:
# RelatedObject (reverse relationship) # RelatedObject (reverse relationship)
obj = getattr(obj, self.source or field_name) try:
obj = getattr(obj, self.source or field_name)
except ObjectDoesNotExist:
return None
return self.to_native(obj.pk) return self.to_native(obj.pk)
# Forward relationship # Forward relationship
return self.to_native(pk) return self.to_native(pk)
@ -367,13 +376,13 @@ class HyperlinkedRelatedField(RelatedField):
kwargs = {self.slug_url_kwarg: slug} kwargs = {self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass
kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass
@ -490,13 +499,13 @@ class HyperlinkedIdentityField(Field):
kwargs = {self.slug_url_kwarg: slug} kwargs = {self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass
kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug}
try: try:
return reverse(self.view_name, kwargs=kwargs, request=request, format=format) return reverse(view_name, kwargs=kwargs, request=request, format=format)
except: except:
pass pass

View File

@ -298,15 +298,18 @@ class BaseSerializer(Field):
Override default so that we can apply ModelSerializer as a nested Override default so that we can apply ModelSerializer as a nested
field to relationships. field to relationships.
""" """
if self.source: try:
for component in self.source.split('.'): if self.source:
obj = getattr(obj, component) for component in self.source.split('.'):
obj = getattr(obj, component)
if is_simple_callable(obj):
obj = obj()
else:
obj = getattr(obj, field_name)
if is_simple_callable(obj): if is_simple_callable(obj):
obj = obj() obj = obj()
else: except ObjectDoesNotExist:
obj = getattr(obj, field_name) return None
if is_simple_callable(obj):
obj = value()
# If the object has an "all" method, assume it's a relationship # If the object has an "all" method, assume it's a relationship
if is_simple_callable(getattr(obj, 'all', None)): if is_simple_callable(getattr(obj, 'all', None)):
@ -412,7 +415,7 @@ class ModelSerializer(Serializer):
""" """
Returns a default instance of the pk field. Returns a default instance of the pk field.
""" """
return Field() return self.get_field(model_field)
def get_nested_field(self, model_field): def get_nested_field(self, model_field):
""" """
@ -430,7 +433,7 @@ class ModelSerializer(Serializer):
# TODO: filter queryset using: # TODO: filter queryset using:
# .using(db).complex_filter(self.rel.limit_choices_to) # .using(db).complex_filter(self.rel.limit_choices_to)
kwargs = { kwargs = {
'null': model_field.null, 'null': model_field.null or model_field.blank,
'queryset': model_field.rel.to._default_manager 'queryset': model_field.rel.to._default_manager
} }
@ -449,6 +452,9 @@ class ModelSerializer(Serializer):
if model_field.null or model_field.blank: if model_field.null or model_field.blank:
kwargs['required'] = False kwargs['required'] = False
if isinstance(model_field, models.AutoField) or not model_field.editable:
kwargs['read_only'] = True
if model_field.has_default(): if model_field.has_default():
kwargs['required'] = False kwargs['required'] = False
kwargs['default'] = model_field.get_default() kwargs['default'] = model_field.get_default()
@ -462,6 +468,7 @@ class ModelSerializer(Serializer):
return ChoiceField(**kwargs) return ChoiceField(**kwargs)
field_mapping = { field_mapping = {
models.AutoField: IntegerField,
models.FloatField: FloatField, models.FloatField: FloatField,
models.IntegerField: IntegerField, models.IntegerField: IntegerField,
models.PositiveIntegerField: IntegerField, models.PositiveIntegerField: IntegerField,

View File

@ -112,7 +112,7 @@
<div class="request-info"> <div class="request-info">
<pre class="prettyprint"><b>{{ request.method }}</b> {{ request.get_full_path }}</pre> <pre class="prettyprint"><b>{{ request.method }}</b> {{ request.get_full_path }}</pre>
<div> </div>
<div class="response-info"> <div class="response-info">
<pre class="prettyprint"><div class="meta nocode"><b>HTTP {{ response.status_code }} {{ response.status_text }}</b>{% autoescape off %} <pre class="prettyprint"><div class="meta nocode"><b>HTTP {{ response.status_code }} {{ response.status_text }}</b>{% autoescape off %}
{% for key, val in response.items %}<b>{{ key }}:</b> <span class="lit">{{ val|urlize_quoted_links }}</span> {% for key, val in response.items %}<b>{{ key }}:</b> <span class="lit">{{ val|urlize_quoted_links }}</span>

View File

@ -1,5 +1,4 @@
from django.test import TestCase from django.test import TestCase
from django.test.client import RequestFactory
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.renderers import JSONRenderer from rest_framework.renderers import JSONRenderer

View File

@ -0,0 +1,49 @@
"""
General serializer field tests.
"""
from django.db import models
from django.test import TestCase
from rest_framework import serializers
class TimestampedModel(models.Model):
added = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class CharPrimaryKeyModel(models.Model):
id = models.CharField(max_length=20, primary_key=True)
class TimestampedModelSerializer(serializers.ModelSerializer):
class Meta:
model = TimestampedModel
class CharPrimaryKeyModelSerializer(serializers.ModelSerializer):
class Meta:
model = CharPrimaryKeyModel
class ReadOnlyFieldTests(TestCase):
def test_auto_now_fields_read_only(self):
"""
auto_now and auto_now_add fields should be read_only by default.
"""
serializer = TimestampedModelSerializer()
self.assertEquals(serializer.fields['added'].read_only, True)
def test_auto_pk_fields_read_only(self):
"""
AutoField fields should be read_only by default.
"""
serializer = TimestampedModelSerializer()
self.assertEquals(serializer.fields['id'].read_only, True)
def test_non_auto_pk_fields_not_read_only(self):
"""
PK fields other than AutoField fields should not be read_only by default.
"""
serializer = CharPrimaryKeyModelSerializer()
self.assertEquals(serializer.fields['id'].read_only, False)

View File

@ -205,3 +205,14 @@ class NullableForeignKeySource(RESTFrameworkModel):
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True, target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True,
related_name='nullable_sources') related_name='nullable_sources')
# OneToOne
class OneToOneTarget(RESTFrameworkModel):
name = models.CharField(max_length=100)
class NullableOneToOneSource(RESTFrameworkModel):
name = models.CharField(max_length=100)
target = models.OneToOneField(OneToOneTarget, null=True, blank=True,
related_name='nullable_source')

View File

@ -181,10 +181,10 @@ class UnitTestPagination(TestCase):
""" """
Ensure context gets passed through to the object serializer. Ensure context gets passed through to the object serializer.
""" """
serializer = PassOnContextPaginationSerializer(self.first_page) serializer = PassOnContextPaginationSerializer(self.first_page, context={'foo': 'bar'})
serializer.data serializer.data
results = serializer.fields[serializer.results_field] results = serializer.fields[serializer.results_field]
self.assertTrue(serializer.context is results.context) self.assertEquals(serializer.context, results.context)
class TestUnpaginated(TestCase): class TestUnpaginated(TestCase):

View File

@ -1,8 +1,8 @@
from django.db import models
from django.test import TestCase from django.test import TestCase
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 from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
def dummy_view(request, pk): def dummy_view(request, pk):
pass pass
@ -13,8 +13,11 @@ urlpatterns = patterns('',
url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'),
url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'),
url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'),
url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'),
url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'),
) )
class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer):
sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail') sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail')
@ -40,18 +43,19 @@ class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
# Nullable ForeignKey # Nullable ForeignKey
class NullableForeignKeySource(models.Model):
name = models.CharField(max_length=100)
target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True,
related_name='nullable_sources')
class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
class Meta: class Meta:
model = NullableForeignKeySource model = NullableForeignKeySource
# OneToOne
class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer):
nullable_source = serializers.HyperlinkedRelatedField(view_name='nullableonetoonesource-detail')
class Meta:
model = OneToOneTarget
# TODO: Add test that .data cannot be accessed prior to .is_valid # TODO: Add test that .data cannot be accessed prior to .is_valid
class HyperlinkedManyToManyTests(TestCase): class HyperlinkedManyToManyTests(TestCase):
@ -409,3 +413,24 @@ class HyperlinkedNullableForeignKeyTests(TestCase):
# {'id': 2, 'name': u'target-2', 'sources': []}, # {'id': 2, 'name': u'target-2', 'sources': []},
# ] # ]
# self.assertEquals(serializer.data, expected) # self.assertEquals(serializer.data, expected)
class HyperlinkedNullableOneToOneTests(TestCase):
urls = 'rest_framework.tests.relations_hyperlink'
def setUp(self):
target = OneToOneTarget(name='target-1')
target.save()
new_target = OneToOneTarget(name='target-2')
new_target.save()
source = NullableOneToOneSource(name='source-1', target=target)
source.save()
def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset)
expected = [
{'url': '/onetoonetarget/1/', 'name': u'target-1', 'nullable_source': '/nullableonetoonesource/1/'},
{'url': '/onetoonetarget/2/', 'name': u'target-2', 'nullable_source': None},
]
self.assertEquals(serializer.data, expected)

View File

@ -1,7 +1,6 @@
from django.db import models
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 ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
class ForeignKeySourceSerializer(serializers.ModelSerializer): class ForeignKeySourceSerializer(serializers.ModelSerializer):
@ -28,6 +27,18 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
model = NullableForeignKeySource model = NullableForeignKeySource
class NullableOneToOneSourceSerializer(serializers.ModelSerializer):
class Meta:
model = NullableOneToOneSource
class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
nullable_source = NullableOneToOneSourceSerializer()
class Meta:
model = OneToOneTarget
class ReverseForeignKeyTests(TestCase): class ReverseForeignKeyTests(TestCase):
def setUp(self): def setUp(self):
target = ForeignKeyTarget(name='target-1') target = ForeignKeyTarget(name='target-1')
@ -82,3 +93,22 @@ class NestedNullableForeignKeyTests(TestCase):
{'id': 3, 'name': u'source-3', 'target': None}, {'id': 3, 'name': u'source-3', 'target': None},
] ]
self.assertEquals(serializer.data, expected) self.assertEquals(serializer.data, expected)
class NestedNullableOneToOneTests(TestCase):
def setUp(self):
target = OneToOneTarget(name='target-1')
target.save()
new_target = OneToOneTarget(name='target-2')
new_target.save()
source = NullableOneToOneSource(name='source-1', target=target)
source.save()
def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'nullable_source': {'id': 1, 'name': u'source-1', 'target': 1}},
{'id': 2, 'name': u'target-2', 'nullable_source': None},
]
self.assertEquals(serializer.data, expected)

View File

@ -1,7 +1,6 @@
from django.db import models
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 from rest_framework.tests.models import ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
class ManyToManyTargetSerializer(serializers.ModelSerializer): class ManyToManyTargetSerializer(serializers.ModelSerializer):
@ -33,6 +32,14 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
model = NullableForeignKeySource model = NullableForeignKeySource
# OneToOne
class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
nullable_source = serializers.PrimaryKeyRelatedField()
class Meta:
model = OneToOneTarget
# TODO: Add test that .data cannot be accessed prior to .is_valid # TODO: Add test that .data cannot be accessed prior to .is_valid
class PKManyToManyTests(TestCase): class PKManyToManyTests(TestCase):
@ -199,7 +206,7 @@ class PKForeignKeyTests(TestCase):
expected = [ expected = [
{'id': 1, 'name': u'target-1', 'sources': [1, 2, 3]}, {'id': 1, 'name': u'target-1', 'sources': [1, 2, 3]},
{'id': 2, 'name': u'target-2', 'sources': []}, {'id': 2, 'name': u'target-2', 'sources': []},
] ]
self.assertEquals(new_serializer.data, expected) self.assertEquals(new_serializer.data, expected)
serializer.save() serializer.save()
@ -383,3 +390,22 @@ class PKNullableForeignKeyTests(TestCase):
# {'id': 2, 'name': u'target-2', 'sources': []}, # {'id': 2, 'name': u'target-2', 'sources': []},
# ] # ]
# self.assertEquals(serializer.data, expected) # self.assertEquals(serializer.data, expected)
class PKNullableOneToOneTests(TestCase):
def setUp(self):
target = OneToOneTarget(name='target-1')
target.save()
new_target = OneToOneTarget(name='target-2')
new_target.save()
source = NullableOneToOneSource(name='source-1', target=target)
source.save()
def test_reverse_foreign_key_retrieve_with_null(self):
queryset = OneToOneTarget.objects.all()
serializer = NullableOneToOneTargetSerializer(queryset)
expected = [
{'id': 1, 'name': u'target-1', 'nullable_source': 1},
{'id': 2, 'name': u'target-2', 'nullable_source': None},
]
self.assertEquals(serializer.data, expected)

View File

@ -0,0 +1,117 @@
from django.test import TestCase
from rest_framework import serializers
from rest_framework.tests.models import NullableForeignKeySource, ForeignKeyTarget
class NullableSlugSourceSerializer(serializers.ModelSerializer):
target = serializers.SlugRelatedField(slug_field='name', null=True)
class Meta:
model = NullableForeignKeySource
# TODO: M2M Tests, FKTests (Non-nulable), One2One
class SlugNullableForeignKeyTests(TestCase):
def setUp(self):
target = ForeignKeyTarget(name='target-1')
target.save()
for idx in range(1, 4):
if idx == 3:
target = None
source = NullableForeignKeySource(name='source-%d' % idx, target=target)
source.save()
def test_foreign_key_retrieve_with_null(self):
queryset = NullableForeignKeySource.objects.all()
serializer = NullableSlugSourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None},
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_create_with_valid_null(self):
data = {'id': 4, 'name': u'source-4', 'target': None}
serializer = NullableSlugSourceSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
self.assertEquals(serializer.data, data)
self.assertEqual(obj.name, u'source-4')
# Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableSlugSourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None},
{'id': 4, 'name': u'source-4', 'target': None}
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_create_with_valid_emptystring(self):
"""
The emptystring should be interpreted as null in the context
of relationships.
"""
data = {'id': 4, 'name': u'source-4', 'target': ''}
expected_data = {'id': 4, 'name': u'source-4', 'target': None}
serializer = NullableSlugSourceSerializer(data=data)
self.assertTrue(serializer.is_valid())
obj = serializer.save()
self.assertEquals(serializer.data, expected_data)
self.assertEqual(obj.name, u'source-4')
# Ensure source 4 is created, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableSlugSourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': 'target-1'},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None},
{'id': 4, 'name': u'source-4', 'target': None}
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_update_with_valid_null(self):
data = {'id': 1, 'name': u'source-1', 'target': None}
instance = NullableForeignKeySource.objects.get(pk=1)
serializer = NullableSlugSourceSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, data)
serializer.save()
# Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableSlugSourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': None},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None}
]
self.assertEquals(serializer.data, expected)
def test_foreign_key_update_with_valid_emptystring(self):
"""
The emptystring should be interpreted as null in the context
of relationships.
"""
data = {'id': 1, 'name': u'source-1', 'target': ''}
expected_data = {'id': 1, 'name': u'source-1', 'target': None}
instance = NullableForeignKeySource.objects.get(pk=1)
serializer = NullableSlugSourceSerializer(instance, data=data)
self.assertTrue(serializer.is_valid())
self.assertEquals(serializer.data, expected_data)
serializer.save()
# Ensure source 1 is updated, and everything else is as expected
queryset = NullableForeignKeySource.objects.all()
serializer = NullableSlugSourceSerializer(queryset)
expected = [
{'id': 1, 'name': u'source-1', 'target': None},
{'id': 2, 'name': u'source-2', 'target': 'target-1'},
{'id': 3, 'name': u'source-3', 'target': None}
]
self.assertEquals(serializer.data, expected)

View File

@ -12,7 +12,7 @@ from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata
class JSONEncoder(json.JSONEncoder): class JSONEncoder(json.JSONEncoder):
""" """
JSONEncoder subclass that knows how to encode date/time, JSONEncoder subclass that knows how to encode date/time/timedelta,
decimal types, and generators. decimal types, and generators.
""" """
def default(self, o): def default(self, o):
@ -34,6 +34,8 @@ class JSONEncoder(json.JSONEncoder):
if o.microsecond: if o.microsecond:
r = r[:12] r = r[:12]
return r return r
elif isinstance(o, datetime.timedelta):
return str(o.total_seconds())
elif isinstance(o, decimal.Decimal): elif isinstance(o, decimal.Decimal):
return str(o) return str(o)
elif hasattr(o, '__iter__'): elif hasattr(o, '__iter__'):