aboutsummaryrefslogtreecommitdiffstats
path: root/rest_framework
diff options
context:
space:
mode:
Diffstat (limited to 'rest_framework')
-rw-r--r--rest_framework/compat.py2
-rw-r--r--rest_framework/decorators.py2
-rw-r--r--rest_framework/fields.py2
-rw-r--r--rest_framework/generics.py7
-rw-r--r--rest_framework/mixins.py26
-rw-r--r--rest_framework/renderers.py2
-rw-r--r--rest_framework/response.py7
-rw-r--r--rest_framework/serializers.py10
-rw-r--r--rest_framework/settings.py2
-rw-r--r--rest_framework/tests/hyperlinkedserializers.py9
-rw-r--r--rest_framework/tests/throttling.py2
-rw-r--r--rest_framework/urlpatterns.py2
-rw-r--r--rest_framework/urls.py4
-rw-r--r--rest_framework/views.py2
14 files changed, 48 insertions, 31 deletions
diff --git a/rest_framework/compat.py b/rest_framework/compat.py
index 5055bfd3..e38e7c33 100644
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -1,6 +1,6 @@
"""
The `compat` module provides support for backwards compatibility with older
-versions of django/python, and compatbility wrappers around optional packages.
+versions of django/python, and compatibility wrappers around optional packages.
"""
# flake8: noqa
import django
diff --git a/rest_framework/decorators.py b/rest_framework/decorators.py
index a231f191..1b710a03 100644
--- a/rest_framework/decorators.py
+++ b/rest_framework/decorators.py
@@ -17,7 +17,7 @@ def api_view(http_method_names):
)
# Note, the above allows us to set the docstring.
- # It is the equivelent of:
+ # It is the equivalent of:
#
# class WrappedAPIView(APIView):
# pass
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
index 4c206426..6ef53975 100644
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -317,7 +317,7 @@ class RelatedField(WritableField):
choices = property(_get_choices, _set_choices)
- ### Regular serializier stuff...
+ ### Regular serializer stuff...
def field_to_native(self, obj, field_name):
value = getattr(obj, self.source or field_name)
diff --git a/rest_framework/generics.py b/rest_framework/generics.py
index ebd06e45..9ad03f71 100644
--- a/rest_framework/generics.py
+++ b/rest_framework/generics.py
@@ -66,9 +66,6 @@ class MultipleObjectAPIView(MultipleObjectMixin, GenericAPIView):
backend = self.filter_backend()
return backend.filter_queryset(self.request, queryset, self)
- def get_filtered_queryset(self):
- return self.filter_queryset(self.get_queryset())
-
def get_pagination_serializer_class(self):
"""
Return the class to use for the pagination serializer.
@@ -92,11 +89,11 @@ class SingleObjectAPIView(SingleObjectMixin, GenericAPIView):
pk_url_kwarg = 'pk' # Not provided in Django 1.3
slug_url_kwarg = 'slug' # Not provided in Django 1.3
- def get_object(self):
+ def get_object(self, queryset=None):
"""
Override default to add support for object-level permissions.
"""
- obj = super(SingleObjectAPIView, self).get_object()
+ obj = super(SingleObjectAPIView, self).get_object(queryset)
if not self.has_permission(self.request, obj):
self.permission_denied(self.request)
return obj
diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py
index d85e0bfb..0da4c2cc 100644
--- a/rest_framework/mixins.py
+++ b/rest_framework/mixins.py
@@ -20,9 +20,16 @@ class CreateModelMixin(object):
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save()
- return Response(serializer.data, status=status.HTTP_201_CREATED)
+ headers = self.get_success_headers(serializer.data)
+ return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+ def get_success_headers(self, data):
+ try:
+ return {'Location': data['url']}
+ except (TypeError, KeyError):
+ return {}
+
def pre_save(self, obj):
pass
@@ -36,14 +43,16 @@ class ListModelMixin(object):
page_size_kwarg = api_settings.PAGE_SIZE_KWARG
def list(self, request, *args, **kwargs):
- self.object_list = self.get_filtered_queryset()
+ queryset = self.get_queryset()
+ self.object_list = self.filter_queryset(queryset)
# Default is to allow empty querysets. This can be altered by setting
# `.allow_empty = False`, to raise 404 errors on empty querysets.
allow_empty = self.get_allow_empty()
- if not allow_empty and len(self.object_list) == 0:
- error_args = {'class_name': self.__class__.__name__}
- raise Http404(self.empty_error % error_args)
+ if not allow_empty and not self.object_list:
+ class_name = self.__class__.__name__
+ error_msg = self.empty_error % {'class_name': class_name}
+ raise Http404(error_msg)
# Pagination size is set by the `.paginate_by` attribute,
# which may be `None` to disable pagination.
@@ -88,17 +97,18 @@ class UpdateModelMixin(object):
def update(self, request, *args, **kwargs):
try:
self.object = self.get_object()
- success_status = status.HTTP_200_OK
+ created = False
except Http404:
self.object = None
- success_status = status.HTTP_201_CREATED
+ created = True
serializer = self.get_serializer(self.object, data=request.DATA)
if serializer.is_valid():
self.pre_save(serializer.object)
self.object = serializer.save()
- return Response(serializer.data, status=success_status)
+ status_code = created and status.HTTP_201_CREATED or status.HTTP_200_OK
+ return Response(serializer.data, status=status_code)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
index 22fd6e74..870464f0 100644
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -4,7 +4,7 @@ Renderers are used to serialize a response into specific media types.
They give us a generic way of being able to handle various media types
on the response, such as JSON encoded data or HTML output.
-REST framework also provides an HTML renderer the renders the browseable API.
+REST framework also provides an HTML renderer the renders the browsable API.
"""
import copy
import string
diff --git a/rest_framework/response.py b/rest_framework/response.py
index 0de01204..be78c43a 100644
--- a/rest_framework/response.py
+++ b/rest_framework/response.py
@@ -15,14 +15,17 @@ class Response(SimpleTemplateResponse):
Alters the init arguments slightly.
For example, drop 'template_name', and instead use 'data'.
- Setting 'renderer' and 'media_type' will typically be defered,
+ Setting 'renderer' and 'media_type' will typically be deferred,
For example being set automatically by the `APIView`.
"""
super(Response, self).__init__(None, status=status)
self.data = data
- self.headers = headers and headers[:] or []
self.template_name = template_name
self.exception = exception
+
+ if headers:
+ for name,value in headers.iteritems():
+ self[name] = value
@property
def rendered_content(self):
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
index 46d4765e..0f943ac1 100644
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -89,7 +89,7 @@ class BaseSerializer(Field):
pass
_options_class = SerializerOptions
- _dict_class = SortedDictWithMetadata # Set to unsorted dict for backwards compatability with unsorted implementations.
+ _dict_class = SortedDictWithMetadata # Set to unsorted dict for backwards compatibility with unsorted implementations.
def __init__(self, instance=None, data=None, context=None, **kwargs):
super(BaseSerializer, self).__init__(**kwargs)
@@ -163,7 +163,7 @@ class BaseSerializer(Field):
self.opts.depth = parent.opts.depth - 1
#####
- # Methods to convert or revert from objects <--> primative representations.
+ # Methods to convert or revert from objects <--> primitive representations.
def get_field_key(self, field_name):
"""
@@ -244,7 +244,7 @@ class BaseSerializer(Field):
def to_native(self, obj):
"""
- Serialize objects -> primatives.
+ Serialize objects -> primitives.
"""
if hasattr(obj, '__iter__'):
return [self.convert_object(item) for item in obj]
@@ -252,7 +252,7 @@ class BaseSerializer(Field):
def from_native(self, data):
"""
- Deserialize primatives -> objects.
+ Deserialize primitives -> objects.
"""
if hasattr(data, '__iter__') and not isinstance(data, dict):
# TODO: error data when deserializing lists
@@ -334,7 +334,7 @@ class ModelSerializer(Serializer):
"""
Return all the fields that should be serialized for the model.
"""
- # TODO: Modfiy this so that it's called on init, and drop
+ # TODO: Modify this so that it's called on init, and drop
# serialize/obj/data arguments.
#
# We *could* provide a hook for dynamic fields, but
diff --git a/rest_framework/settings.py b/rest_framework/settings.py
index c7b0643f..8883b963 100644
--- a/rest_framework/settings.py
+++ b/rest_framework/settings.py
@@ -154,7 +154,7 @@ class APISettings(object):
def validate_setting(self, attr, val):
if attr == 'FILTER_BACKEND' and val is not None:
- # Make sure we can initilize the class
+ # Make sure we can initialize the class
val()
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
diff --git a/rest_framework/tests/hyperlinkedserializers.py b/rest_framework/tests/hyperlinkedserializers.py
index 5ab850af..d7effce7 100644
--- a/rest_framework/tests/hyperlinkedserializers.py
+++ b/rest_framework/tests/hyperlinkedserializers.py
@@ -8,12 +8,13 @@ factory = RequestFactory()
class BlogPostCommentSerializer(serializers.ModelSerializer):
+ url = serializers.HyperlinkedIdentityField(view_name='blogpostcomment-detail')
text = serializers.CharField()
blog_post_url = serializers.HyperlinkedRelatedField(source='blog_post', view_name='blogpost-detail')
class Meta:
model = BlogPostComment
- fields = ('text', 'blog_post_url')
+ fields = ('text', 'blog_post_url', 'url')
class PhotoSerializer(serializers.Serializer):
@@ -53,6 +54,9 @@ class BlogPostCommentListCreate(generics.ListCreateAPIView):
model = BlogPostComment
serializer_class = BlogPostCommentSerializer
+class BlogPostCommentDetail(generics.RetrieveAPIView):
+ model = BlogPostComment
+ serializer_class = BlogPostCommentSerializer
class BlogPostDetail(generics.RetrieveAPIView):
model = BlogPost
@@ -80,6 +84,7 @@ urlpatterns = patterns('',
url(r'^manytomany/(?P<pk>\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'),
url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'),
url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'),
+ url(r'^comments/(?P<pk>\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'),
url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'),
url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'),
url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'),
@@ -191,6 +196,7 @@ class TestCreateWithForeignKeys(TestCase):
request = factory.post('/comments/', data=data)
response = self.create_view(request).render()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertEqual(response['Location'], 'http://testserver/comments/1/')
self.assertEqual(self.post.blogpostcomment_set.count(), 1)
self.assertEqual(self.post.blogpostcomment_set.all()[0].text, 'A test comment')
@@ -215,6 +221,7 @@ class TestCreateWithForeignKeysAndCustomSlug(TestCase):
request = factory.post('/photos/', data=data)
response = self.list_create_view(request).render()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+ self.assertNotIn('Location', response, msg='Location should only be included if there is a "url" field on the serializer')
self.assertEqual(self.post.photo_set.count(), 1)
self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo')
diff --git a/rest_framework/tests/throttling.py b/rest_framework/tests/throttling.py
index 0b94c25b..4b98b941 100644
--- a/rest_framework/tests/throttling.py
+++ b/rest_framework/tests/throttling.py
@@ -106,7 +106,7 @@ class ThrottlingTests(TestCase):
if expect is not None:
self.assertEquals(response['X-Throttle-Wait-Seconds'], expect)
else:
- self.assertFalse('X-Throttle-Wait-Seconds' in response.headers)
+ self.assertFalse('X-Throttle-Wait-Seconds' in response)
def test_seconds_fields(self):
"""
diff --git a/rest_framework/urlpatterns.py b/rest_framework/urlpatterns.py
index 316ccd19..0ad926fa 100644
--- a/rest_framework/urlpatterns.py
+++ b/rest_framework/urlpatterns.py
@@ -4,7 +4,7 @@ from rest_framework.settings import api_settings
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None):
"""
- Supplement existing urlpatterns with corrosponding patterns that also
+ Supplement existing urlpatterns with corresponding patterns that also
include a '.format' suffix. Retains urlpattern ordering.
urlpatterns:
diff --git a/rest_framework/urls.py b/rest_framework/urls.py
index 1a81101f..bcdc23e7 100644
--- a/rest_framework/urls.py
+++ b/rest_framework/urls.py
@@ -1,7 +1,7 @@
"""
-Login and logout views for the browseable API.
+Login and logout views for the browsable API.
-Add these to your root URLconf if you're using the browseable API and
+Add these to your root URLconf if you're using the browsable API and
your API requires authentication.
The urls must be namespaced as 'rest_framework', and you should make sure
diff --git a/rest_framework/views.py b/rest_framework/views.py
index 1afbd697..10bdd5a5 100644
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -140,7 +140,7 @@ class APIView(View):
def http_method_not_allowed(self, request, *args, **kwargs):
"""
- Called if `request.method` does not corrospond to a handler method.
+ Called if `request.method` does not correspond to a handler method.
"""
raise exceptions.MethodNotAllowed(request.method)