diff --git a/README.md b/README.md index 8a9149cf1..d7cc1c6d6 100644 --- a/README.md +++ b/README.md @@ -81,6 +81,17 @@ To run the tests. # 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 **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 [markdown]: http://pypi.python.org/pypi/Markdown/ [pyyaml]: http://pypi.python.org/pypi/PyYAML -[django-filter]: https://github.com/alex/django-filter - +[django-filter]: http://pypi.python.org/pypi/django-filter diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 43fc15d2d..afd9a2619 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -52,7 +52,7 @@ Or, if you're using the `@api_view` decorator with function based views. @api_view(['GET']) @authentication_classes((SessionAuthentication, BasicAuthentication)) - @permissions_classes((IsAuthenticated,)) + @permission_classes((IsAuthenticated,)) def example_view(request, format=None): content = { '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' } - - ## 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. @@ -145,6 +134,8 @@ If successfully authenticated, `SessionAuthentication` provides the following cr * `request.user` will be a Django `User` instance. * `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 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/ [permission]: permissions.md [throttling]: throttling.md +[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index ab335e6e2..71253afb0 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -97,6 +97,8 @@ You can also set the pagination style on a per-view basis, using the `ListAPIVie paginate_by = 10 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. --- diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index 9356b4205..de9685578 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -167,7 +167,7 @@ The following third party packages are also available. ## 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 [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 389dec1f6..b4f7ec3d4 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -279,7 +279,11 @@ The following third party packages are also available. ## 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 [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.collection+json]: http://www.amundsen.com/media-types/collection/ [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 -[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack \ No newline at end of file +[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 \ No newline at end of file diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 8c87f2ca5..a422e5f61 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -65,7 +65,7 @@ Default: ( 'rest_framework.authentication.SessionAuthentication', - 'rest_framework.authentication.UserBasicAuthentication' + 'rest_framework.authentication.BasicAuthentication' ) ## DEFAULT_PERMISSION_CLASSES diff --git a/docs/index.md b/docs/index.md index 080eca6f2..497f19004 100644 --- a/docs/index.md +++ b/docs/index.md @@ -166,7 +166,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [urlobject]: https://github.com/zacharyvoase/urlobject [markdown]: http://pypi.python.org/pypi/Markdown/ [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 [image]: img/quickstart.png [sandbox]: http://restframework.herokuapp.com/ diff --git a/docs/topics/credits.md b/docs/topics/credits.md index 83272766e..68d07f200 100644 --- a/docs/topics/credits.md +++ b/docs/topics/credits.md @@ -88,6 +88,10 @@ The following people have helped make REST framework great. * Juan Riaza - [juanriaza] * Michael Mior - [michaelmior] * 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. @@ -211,3 +215,7 @@ You can also contact [@_tomchristie][twitter] directly on twitter. [juanriaza]: https://github.com/juanriaza [michaelmior]: https://github.com/michaelmior [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 diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md index edd948ac8..e00a5e937 100644 --- a/docs/topics/release-notes.md +++ b/docs/topics/release-notes.md @@ -18,9 +18,21 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi ### 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 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 @@ -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 [2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion [announcement]: rest-framework-2-announcement.md +[#582]: https://github.com/tomchristie/django-rest-framework/issues/582 diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index e61fb9469..d3ada9e3a 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -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 = ( ... '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. @@ -73,14 +73,15 @@ Okay, we're ready to roll. ## 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 pygments.lexers import get_all_lexers from pygments.styles import get_all_styles - - LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in get_all_lexers()]) - STYLE_CHOICES = sorted((item, item) for item in list(get_all_styles())) + + LEXERS = [item for item in get_all_lexers() if item[1]] + 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): @@ -202,8 +203,6 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer` model = Snippet fields = ('id', 'title', 'code', 'linenos', 'language', 'style') - - ## Writing regular Django views using our Serializer 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' 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. @csrf_exempt @@ -288,16 +286,45 @@ Finally we need to wire these views up. Create the `snippets/urls.py` file: urlpatterns = patterns('snippets.views', url(r'^snippets/$', 'snippet_list'), - url(r'^snippets/(?P[0-9]+)/$', 'snippet_detail') + url(r'^snippets/(?P[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. ## 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 diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 08cf91cdb..340ea28ee 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -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. - ## Pulling it all together 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: 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. 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', url(r'^snippets/$', 'snippet_list'), - url(r'^snippets/(?P[0-9]+)$', 'snippet_detail') + url(r'^snippets/(?P[0-9]+)$', 'snippet_detail'), ) 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. - ## 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. diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index b115b0229..290ea5e9d 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -70,7 +70,7 @@ We'll also need to refactor our URLconf slightly now we're using class based vie urlpatterns = patterns('', url(r'^snippets/$', views.SnippetList.as_view()), - url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()) + url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view()), ) urlpatterns = format_suffix_patterns(urlpatterns) diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md index 9576a7f0b..f6daebb7a 100644 --- a/docs/tutorial/4-authentication-and-permissions.md +++ b/docs/tutorial/4-authentication-and-permissions.md @@ -29,7 +29,7 @@ And now we can add a `.save()` method to our model class: 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. """ 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. url(r'^users/$', views.UserList.as_view()), - url(r'^users/(?P[0-9]+)/$', views.UserInstance.as_view()) + url(r'^users/(?P[0-9]+)/$', views.UserInstance.as_view()), ## 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('', 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. diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index 216ca4338..27898f7b9 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -15,8 +15,8 @@ Right now we have endpoints for 'snippets' and 'users', but we don't have a sing @api_view(('GET',)) def api_root(request, format=None): return Response({ - 'users': reverse('user-list', request=request), - 'snippets': reverse('snippet-list', request=request) + 'users': reverse('user-list', request=request, format=format), + '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. @@ -116,7 +116,7 @@ After adding all those names into our URLconf, our final `'urls.py'` file should url(r'^snippets/(?P[0-9]+)/$', views.SnippetDetail.as_view(), name='snippet-detail'), - url(r'^snippets/(?P[0-9]+)/highlight/$' + url(r'^snippets/(?P[0-9]+)/highlight/$', views.SnippetHighlight.as_view(), name='snippet-highlight'), 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 urlpatterns += patterns('', url(r'^api-auth/', include('rest_framework.urls', - namespace='rest_framework')) + namespace='rest_framework')), ) ## Adding pagination diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 1d25ee7f7..bc267fad7 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -1,3 +1,3 @@ -__version__ = '2.1.15' +__version__ = '2.1.16' VERSION = __version__ # synonym diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py index d318c7233..7c03cb766 100644 --- a/rest_framework/authtoken/views.py +++ b/rest_framework/authtoken/views.py @@ -12,10 +12,11 @@ class ObtainAuthToken(APIView): permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) + serializer_class = AuthTokenSerializer model = Token def post(self, request): - serializer = AuthTokenSerializer(data=request.DATA) + serializer = self.serializer_class(data=request.DATA) if serializer.is_valid(): token, created = Token.objects.get_or_create(user=serializer.object['user']) return Response({'token': token.key}) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index 0d93f4480..7ded38918 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -101,7 +101,13 @@ class RelatedField(WritableField): ### Regular serializer stuff... 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) 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) except AttributeError: # 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) # Forward relationship return self.to_native(pk) @@ -367,13 +376,13 @@ class HyperlinkedRelatedField(RelatedField): kwargs = {self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass @@ -490,13 +499,13 @@ class HyperlinkedIdentityField(Field): kwargs = {self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass kwargs = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: slug} try: - return reverse(self.view_name, kwargs=kwargs, request=request, format=format) + return reverse(view_name, kwargs=kwargs, request=request, format=format) except: pass diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index fa92838b6..27458f968 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -298,15 +298,18 @@ class BaseSerializer(Field): Override default so that we can apply ModelSerializer as a nested field to relationships. """ - if self.source: - for component in self.source.split('.'): - obj = getattr(obj, component) + try: + if self.source: + 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): obj = obj() - else: - obj = getattr(obj, field_name) - if is_simple_callable(obj): - obj = value() + except ObjectDoesNotExist: + return None # If the object has an "all" method, assume it's a relationship if is_simple_callable(getattr(obj, 'all', None)): @@ -412,7 +415,7 @@ class ModelSerializer(Serializer): """ Returns a default instance of the pk field. """ - return Field() + return self.get_field(model_field) def get_nested_field(self, model_field): """ @@ -430,7 +433,7 @@ class ModelSerializer(Serializer): # TODO: filter queryset using: # .using(db).complex_filter(self.rel.limit_choices_to) kwargs = { - 'null': model_field.null, + 'null': model_field.null or model_field.blank, 'queryset': model_field.rel.to._default_manager } @@ -449,6 +452,9 @@ class ModelSerializer(Serializer): if model_field.null or model_field.blank: kwargs['required'] = False + if isinstance(model_field, models.AutoField) or not model_field.editable: + kwargs['read_only'] = True + if model_field.has_default(): kwargs['required'] = False kwargs['default'] = model_field.get_default() @@ -462,6 +468,7 @@ class ModelSerializer(Serializer): return ChoiceField(**kwargs) field_mapping = { + models.AutoField: IntegerField, models.FloatField: FloatField, models.IntegerField: IntegerField, models.PositiveIntegerField: IntegerField, diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index 42e49cb90..092bf2e47 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -112,7 +112,7 @@
{{ request.method }} {{ request.get_full_path }}
-
+
HTTP {{ response.status_code }} {{ response.status_text }}{% autoescape off %} {% for key, val in response.items %}{{ key }}: {{ val|urlize_quoted_links }} diff --git a/rest_framework/tests/decorators.py b/rest_framework/tests/decorators.py index bc44a45b0..5e6bce4ef 100644 --- a/rest_framework/tests/decorators.py +++ b/rest_framework/tests/decorators.py @@ -1,5 +1,4 @@ from django.test import TestCase -from django.test.client import RequestFactory from rest_framework import status from rest_framework.response import Response from rest_framework.renderers import JSONRenderer diff --git a/rest_framework/tests/fields.py b/rest_framework/tests/fields.py new file mode 100644 index 000000000..8068272d4 --- /dev/null +++ b/rest_framework/tests/fields.py @@ -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) diff --git a/rest_framework/tests/models.py b/rest_framework/tests/models.py index 59c350740..93f097615 100644 --- a/rest_framework/tests/models.py +++ b/rest_framework/tests/models.py @@ -205,3 +205,14 @@ class NullableForeignKeySource(RESTFrameworkModel): name = models.CharField(max_length=100) target = models.ForeignKey(ForeignKeyTarget, null=True, blank=True, 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') diff --git a/rest_framework/tests/pagination.py b/rest_framework/tests/pagination.py index 81d297a1f..3b5508779 100644 --- a/rest_framework/tests/pagination.py +++ b/rest_framework/tests/pagination.py @@ -181,10 +181,10 @@ class UnitTestPagination(TestCase): """ Ensure context gets passed through to the object serializer. """ - serializer = PassOnContextPaginationSerializer(self.first_page) + serializer = PassOnContextPaginationSerializer(self.first_page, context={'foo': 'bar'}) serializer.data results = serializer.fields[serializer.results_field] - self.assertTrue(serializer.context is results.context) + self.assertEquals(serializer.context, results.context) class TestUnpaginated(TestCase): diff --git a/rest_framework/tests/relations_hyperlink.py b/rest_framework/tests/relations_hyperlink.py index a7f8a0351..7d65eae79 100644 --- a/rest_framework/tests/relations_hyperlink.py +++ b/rest_framework/tests/relations_hyperlink.py @@ -1,8 +1,8 @@ -from django.db import models from django.test import TestCase from rest_framework import serializers 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): pass @@ -13,8 +13,11 @@ urlpatterns = patterns('', url(r'^foreignkeysource/(?P[0-9]+)/$', dummy_view, name='foreignkeysource-detail'), url(r'^foreignkeytarget/(?P[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'), url(r'^nullableforeignkeysource/(?P[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'), + url(r'^onetoonetarget/(?P[0-9]+)/$', dummy_view, name='onetoonetarget-detail'), + url(r'^nullableonetoonesource/(?P[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'), ) + class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer): sources = serializers.ManyHyperlinkedRelatedField(view_name='manytomanysource-detail') @@ -40,18 +43,19 @@ class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): # 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 Meta: 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 class HyperlinkedManyToManyTests(TestCase): @@ -409,3 +413,24 @@ class HyperlinkedNullableForeignKeyTests(TestCase): # {'id': 2, 'name': u'target-2', 'sources': []}, # ] # 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) diff --git a/rest_framework/tests/relations_nested.py b/rest_framework/tests/relations_nested.py index 5710c1ef4..0e129fae2 100644 --- a/rest_framework/tests/relations_nested.py +++ b/rest_framework/tests/relations_nested.py @@ -1,7 +1,6 @@ -from django.db import models from django.test import TestCase 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): @@ -28,6 +27,18 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer): model = NullableForeignKeySource +class NullableOneToOneSourceSerializer(serializers.ModelSerializer): + class Meta: + model = NullableOneToOneSource + + +class NullableOneToOneTargetSerializer(serializers.ModelSerializer): + nullable_source = NullableOneToOneSourceSerializer() + + class Meta: + model = OneToOneTarget + + class ReverseForeignKeyTests(TestCase): def setUp(self): target = ForeignKeyTarget(name='target-1') @@ -82,3 +93,22 @@ class NestedNullableForeignKeyTests(TestCase): {'id': 3, 'name': u'source-3', 'target': None}, ] 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) diff --git a/rest_framework/tests/relations_pk.py b/rest_framework/tests/relations_pk.py index af6da2c0b..dd1e86b57 100644 --- a/rest_framework/tests/relations_pk.py +++ b/rest_framework/tests/relations_pk.py @@ -1,7 +1,6 @@ -from django.db import models from django.test import TestCase 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): @@ -33,6 +32,14 @@ class NullableForeignKeySourceSerializer(serializers.ModelSerializer): 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 class PKManyToManyTests(TestCase): @@ -199,7 +206,7 @@ class PKForeignKeyTests(TestCase): expected = [ {'id': 1, 'name': u'target-1', 'sources': [1, 2, 3]}, {'id': 2, 'name': u'target-2', 'sources': []}, - ] + ] self.assertEquals(new_serializer.data, expected) serializer.save() @@ -383,3 +390,22 @@ class PKNullableForeignKeyTests(TestCase): # {'id': 2, 'name': u'target-2', 'sources': []}, # ] # 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) diff --git a/rest_framework/tests/relations_slug.py b/rest_framework/tests/relations_slug.py new file mode 100644 index 000000000..503b61e81 --- /dev/null +++ b/rest_framework/tests/relations_slug.py @@ -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) diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py index c70b24dda..7afe100a8 100644 --- a/rest_framework/utils/encoders.py +++ b/rest_framework/utils/encoders.py @@ -12,7 +12,7 @@ from rest_framework.serializers import DictWithMetadata, SortedDictWithMetadata 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. """ def default(self, o): @@ -34,6 +34,8 @@ class JSONEncoder(json.JSONEncoder): if o.microsecond: r = r[:12] return r + elif isinstance(o, datetime.timedelta): + return str(o.total_seconds()) elif isinstance(o, decimal.Decimal): return str(o) elif hasattr(o, '__iter__'):