Merge branch 'master' into reversedrelation

This commit is contained in:
eofs 2013-01-14 15:07:46 +02:00
commit 0ff3123f3a
17 changed files with 114 additions and 31 deletions

View File

@ -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,5 @@ 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

View File

@ -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.

View File

@ -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/

View File

@ -88,6 +88,7 @@ The following people have helped make REST framework great.
* Juan Riaza - [juanriaza]
* Michael Mior - [michaelmior]
* Marc Tamlyn - [mjtamlyn]
* Richard Wackerbarth - [wackerbarth]
Many thanks to everyone who's contributed to the project.
@ -211,3 +212,4 @@ 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

View File

@ -16,9 +16,13 @@ Major version numbers (x.0.0) are reserved for project milestones. No major poi
## 2.1.x series
### Master
### 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

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 = (
...
'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,7 +73,7 @@ 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
@ -202,8 +202,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 +227,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 +285,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<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.
## 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

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.
## 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<pk>[0-9]+)$', 'snippet_detail')
url(r'^snippets/(?P<pk>[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.

View File

@ -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<pk>[0-9]+)/$', views.SnippetDetail.as_view())
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
)
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):
"""
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<pk>[0-9]+)/$', views.UserInstance.as_view())
url(r'^users/(?P<pk>[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.

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',))
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<pk>[0-9]+)/$',
views.SnippetDetail.as_view(),
name='snippet-detail'),
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$'
url(r'^snippets/(?P<pk>[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

View File

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

View File

@ -432,7 +432,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):
"""
@ -478,6 +478,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()
@ -491,6 +494,7 @@ class ModelSerializer(Serializer):
return ChoiceField(**kwargs)
field_mapping = {
models.AutoField: IntegerField,
models.FloatField: FloatField,
models.IntegerField: IntegerField,
models.PositiveIntegerField: IntegerField,

View File

@ -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

View File

@ -0,0 +1,43 @@
"""
General tests for relational fields.
"""
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 readonly by default.
"""
serializer = TimestampedModelSerializer()
self.assertEquals(serializer.fields['added'].read_only, True)
def test_auto_pk_fields_read_only(self):
serializer = TimestampedModelSerializer()
self.assertEquals(serializer.fields['id'].read_only, True)
def test_non_auto_pk_fields_not_read_only(self):
serializer = CharPrimaryKeyModelSerializer()
self.assertEquals(serializer.fields['id'].read_only, False)

View File

@ -1,4 +1,3 @@
from django.db import models
from django.test import TestCase
from rest_framework import serializers
from rest_framework.compat import patterns, url

View File

@ -1,4 +1,3 @@
from django.db import models
from django.test import TestCase
from rest_framework import serializers
from rest_framework.tests.models import ForeignKeyTarget, ForeignKeySource, NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource

View File

@ -1,4 +1,3 @@
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, OneToOneTarget, NullableOneToOneSource