Commit 52686420 by Tom Christie

Merge branch 'bennbollay-patch-1' into 2.4.0

Conflicts:
	.travis.yml
	docs/api-guide/routers.md
	rest_framework/compat.py
	tox.ini
parents 9c41c007 83b31e7e
...@@ -16,7 +16,7 @@ install: ...@@ -16,7 +16,7 @@ install:
- pip install defusedxml==0.3 - pip install defusedxml==0.3
- pip install django-filter==0.6 - pip install django-filter==0.6
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install oauth2==1.5.211 --use-mirrors; fi" - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install oauth2==1.5.211 --use-mirrors; fi"
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth-plus==2.0 --use-mirrors; fi" - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth-plus==2.2.1; fi"
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth2-provider==0.2.4 --use-mirrors; fi" - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-oauth2-provider==0.2.4 --use-mirrors; fi"
- "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-guardian==1.1.1 --use-mirrors; fi" - "if [[ ${TRAVIS_PYTHON_VERSION::1} != '3' ]]; then pip install django-guardian==1.1.1 --use-mirrors; fi"
- export PYTHONPATH=. - export PYTHONPATH=.
......
This diff is collapsed. Click to expand it.
...@@ -88,6 +88,14 @@ The **base class** for all exceptions raised inside REST framework. ...@@ -88,6 +88,14 @@ The **base class** for all exceptions raised inside REST framework.
To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class. To provide a custom exception, subclass `APIException` and set the `.status_code` and `.detail` properties on the class.
For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so:
from rest_framework.exceptions import APIException
class ServiceUnavailable(APIException):
status_code = 503
detail = 'Service temporarily unavailable, try again later.'
## ParseError ## ParseError
**Signature:** `ParseError(detail=None)` **Signature:** `ParseError(detail=None)`
......
...@@ -186,9 +186,15 @@ The following third party packages are also available. ...@@ -186,9 +186,15 @@ The following third party packages are also available.
[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. [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.
## CamelCase JSON
[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy].
[jquery-ajax]: http://api.jquery.com/jQuery.ajax/ [jquery-ajax]: http://api.jquery.com/jQuery.ajax/
[cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion
[upload-handlers]: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers [upload-handlers]: https://docs.djangoproject.com/en/dev/topics/http/file-uploads/#upload-handlers
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
[juanriaza]: https://github.com/juanriaza [juanriaza]: https://github.com/juanriaza
[vbabiy]: https://github.com/vbabiy
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
\ No newline at end of file
...@@ -442,7 +442,18 @@ In the 2.4 release, these parts of the API will be removed entirely. ...@@ -442,7 +442,18 @@ In the 2.4 release, these parts of the API will be removed entirely.
For more details see the [2.2 release announcement][2.2-announcement]. For more details see the [2.2 release announcement][2.2-announcement].
---
# Third Party Packages
The following third party packages are also available.
## DRF Nested Routers
The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
[cite]: http://lwn.net/Articles/193245/ [cite]: http://lwn.net/Articles/193245/
[reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward [reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward
[generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1 [generic-relations]: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1
[2.2-announcement]: ../topics/2.2-announcement.md [2.2-announcement]: ../topics/2.2-announcement.md
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
...@@ -419,6 +419,11 @@ Comma-separated values are a plain-text tabular data format, that can be easily ...@@ -419,6 +419,11 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package. [UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Jacob Haslehurst][hzy] maintains the [drf-ujson-renderer][drf-ujson-renderer] package which implements JSON rendering using the UJSON package.
## CamelCase JSON
[djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy].
[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
[browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers
...@@ -435,8 +440,10 @@ Comma-separated values are a plain-text tabular data format, that can be easily ...@@ -435,8 +440,10 @@ Comma-separated values are a plain-text tabular data format, that can be easily
[messagepack]: http://msgpack.org/ [messagepack]: http://msgpack.org/
[juanriaza]: https://github.com/juanriaza [juanriaza]: https://github.com/juanriaza
[mjumbewu]: https://github.com/mjumbewu [mjumbewu]: https://github.com/mjumbewu
[vbabiy]: https://github.com/vbabiy
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
[ultrajson]: https://github.com/esnme/ultrajson [ultrajson]: https://github.com/esnme/ultrajson
[hzy]: https://github.com/hzy [hzy]: https://github.com/hzy
[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer [drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
\ No newline at end of file
...@@ -222,9 +222,6 @@ The following third party packages are also available. ...@@ -222,9 +222,6 @@ The following third party packages are also available.
The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources. The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources.
[cite]: http://guides.rubyonrails.org/routing.html
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
## wq.db ## wq.db
The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `app.router.register_model` is a model class. Reasonable defaults for a url prefix and viewset will be inferred from the model and global configuration. The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `app.router.register_model` is a model class. Reasonable defaults for a url prefix and viewset will be inferred from the model and global configuration.
...@@ -236,5 +233,6 @@ The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (an ...@@ -236,5 +233,6 @@ The [wq.db package][wq.db] provides an advanced [Router][wq.db-router] class (an
[cite]: http://guides.rubyonrails.org/routing.html [cite]: http://guides.rubyonrails.org/routing.html
[route-decorators]: viewsets.html#marking-extra-actions-for-routing [route-decorators]: viewsets.html#marking-extra-actions-for-routing
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
[wq.db]: http://wq.io/wq.db [wq.db]: http://wq.io/wq.db
[wq.db-router]: http://wq.io/docs/app.py [wq.db-router]: http://wq.io/docs/app.py
* Writable nested serializers.
* List/detail routes.
* 1.3 Support dropped, install six for <=1.4.?.
* Note title ordering changed
\ No newline at end of file
...@@ -10,7 +10,7 @@ There are many ways you can contribute to Django REST framework. We'd like it t ...@@ -10,7 +10,7 @@ There are many ways you can contribute to Django REST framework. We'd like it t
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case. The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particularJjavascript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with. If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular Javascript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with.
Other really great ways you can help move the community forward include helping answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag. Other really great ways you can help move the community forward include helping answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag.
......
...@@ -181,6 +181,7 @@ The following people have helped make REST framework great. ...@@ -181,6 +181,7 @@ The following people have helped make REST framework great.
* Alex Good - [alexjg] * Alex Good - [alexjg]
* Ian Foote - [ian-foote] * Ian Foote - [ian-foote]
* Chuck Harmston - [chuckharmston] * Chuck Harmston - [chuckharmston]
* Philip Forget - [philipforget]
Many thanks to everyone who's contributed to the project. Many thanks to everyone who's contributed to the project.
...@@ -398,3 +399,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter. ...@@ -398,3 +399,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[alexjg]: https://github.com/alexjg [alexjg]: https://github.com/alexjg
[ian-foote]: https://github.com/ian-foote [ian-foote]: https://github.com/ian-foote
[chuckharmston]: https://github.com/chuckharmston [chuckharmston]: https://github.com/chuckharmston
[philipforget]: https://github.com/philipforget
...@@ -53,7 +53,9 @@ You can determine your currently installed version using `pip freeze`: ...@@ -53,7 +53,9 @@ You can determine your currently installed version using `pip freeze`:
### Master ### Master
* JSON renderer now deals with objects that implement a dict-like interface. * JSON renderer now deals with objects that implement a dict-like interface.
* Fix compatiblity with newer versions of `django-oauth-plus`.
* Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unneccessary queryset re-evaluations. * Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unneccessary queryset re-evaluations.
* Bugfix: Allow defaults on BooleanFields to be properly honored when values are not supplied.
### 2.3.10 ### 2.3.10
...@@ -98,6 +100,19 @@ You can determine your currently installed version using `pip freeze`: ...@@ -98,6 +100,19 @@ You can determine your currently installed version using `pip freeze`:
* Bugfix: `client.force_authenticate(None)` should also clear session info if it exists. * Bugfix: `client.force_authenticate(None)` should also clear session info if it exists.
* Bugfix: Client sending empty string instead of file now clears `FileField`. * Bugfix: Client sending empty string instead of file now clears `FileField`.
* Bugfix: Empty values on ChoiceFields with `required=False` now consistently return `None`. * Bugfix: Empty values on ChoiceFields with `required=False` now consistently return `None`.
* Bugfix: Clients setting `page=0` now simply returns the default page size, instead of disabling pagination. [*]
---
[*] Note that the change in `page=0` behaviour fixes what is considered to be a bug in how clients can effect the pagination size. However if you were relying on this behavior you will need to add the following mixin to your list views in order to preserve the existing behavior.
class DisablePaginationMixin(object):
def get_paginate_by(self, queryset=None):
if self.request.QUERY_PARAMS['self.paginate_by_param'] == '0':
return None
return super(DisablePaginationMixin, self).get_paginate_by(queryset)
---
### 2.3.7 ### 2.3.7
......
...@@ -183,9 +183,11 @@ At this point we've translated the model instance into Python native datatypes. ...@@ -183,9 +183,11 @@ At this point we've translated the model instance into Python native datatypes.
Deserialization is similar. First we parse a stream into Python native datatypes... Deserialization is similar. First we parse a stream into Python native datatypes...
import StringIO # This import will use either `StringIO.StringIO` or `io.BytesIO`
# as appropriate, depending on if we're running Python 2 or Python 3.
from rest_framework.compat import BytesIO
stream = StringIO.StringIO(content) stream = BytesIO(content)
data = JSONParser().parse(stream) data = JSONParser().parse(stream)
...then we restore those native datatypes into to a fully populated object instance. ...then we restore those native datatypes into to a fully populated object instance.
...@@ -261,7 +263,6 @@ The root of our API is going to be a view that supports listing all the existing ...@@ -261,7 +263,6 @@ The root of our API is going to be a view that supports listing all the existing
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return JSONResponse(serializer.data, status=201) return JSONResponse(serializer.data, status=201)
else:
return JSONResponse(serializer.errors, status=400) return JSONResponse(serializer.errors, status=400)
Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now. Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now.
...@@ -288,7 +289,6 @@ We'll also need a view which corresponds to an individual snippet, and can be us ...@@ -288,7 +289,6 @@ We'll also need a view which corresponds to an individual snippet, and can be us
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return JSONResponse(serializer.data) return JSONResponse(serializer.data)
else:
return JSONResponse(serializer.errors, status=400) return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE': elif request.method == 'DELETE':
......
...@@ -59,7 +59,6 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de ...@@ -59,7 +59,6 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.data, status=status.HTTP_201_CREATED)
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.
...@@ -85,7 +84,6 @@ Here is the view for an individual snippet, in the `views.py` module. ...@@ -85,7 +84,6 @@ Here is the view for an individual snippet, in the `views.py` module.
if serializer.is_valid(): if serializer.is_valid():
serializer.save() serializer.save()
return Response(serializer.data) return Response(serializer.data)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
elif request.method == 'DELETE': elif request.method == 'DELETE':
......
...@@ -170,7 +170,7 @@ In the snippets app, create a new file, `permissions.py` ...@@ -170,7 +170,7 @@ In the snippets app, create a new file, `permissions.py`
if request.method in permissions.SAFE_METHODS: if request.method in permissions.SAFE_METHODS:
return True return True
# Write permissions are only allowed to the owner of the snippet # Write permissions are only allowed to the owner of the snippet.
return obj.owner == request.user return obj.owner == request.user
Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` class: Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` class:
......
...@@ -144,7 +144,7 @@ for (dirpath, dirnames, filenames) in os.walk(docs_dir): ...@@ -144,7 +144,7 @@ for (dirpath, dirnames, filenames) in os.walk(docs_dir):
if filename == 'index.md': if filename == 'index.md':
main_title = 'Django REST framework - APIs made easy' main_title = 'Django REST framework - APIs made easy'
else: else:
main_title = 'Django REST framework - ' + main_title main_title = main_title + ' - Django REST framework'
if relative_path == 'index.md': if relative_path == 'index.md':
canonical_url = base_url canonical_url = base_url
......
...@@ -2,6 +2,6 @@ markdown>=2.1.0 ...@@ -2,6 +2,6 @@ markdown>=2.1.0
PyYAML>=3.10 PyYAML>=3.10
defusedxml>=0.3 defusedxml>=0.3
django-filter>=0.5.4 django-filter>=0.5.4
django-oauth-plus>=2.0 django-oauth-plus>=2.2.1
oauth2>=1.5.211 oauth2>=1.5.211
django-oauth2-provider>=0.2.4 django-oauth2-provider>=0.2.4
...@@ -9,7 +9,7 @@ from django.core.exceptions import ImproperlyConfigured ...@@ -9,7 +9,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.middleware.csrf import CsrfViewMiddleware from django.middleware.csrf import CsrfViewMiddleware
from rest_framework import exceptions, HTTP_HEADER_ENCODING from rest_framework import exceptions, HTTP_HEADER_ENCODING
from rest_framework.compat import oauth, oauth_provider, oauth_provider_store from rest_framework.compat import oauth, oauth_provider, oauth_provider_store
from rest_framework.compat import oauth2_provider, provider_now from rest_framework.compat import oauth2_provider, provider_now, check_nonce
from rest_framework.authtoken.models import Token from rest_framework.authtoken.models import Token
...@@ -281,7 +281,9 @@ class OAuthAuthentication(BaseAuthentication): ...@@ -281,7 +281,9 @@ class OAuthAuthentication(BaseAuthentication):
""" """
Checks nonce of request, and return True if valid. Checks nonce of request, and return True if valid.
""" """
return oauth_provider_store.check_nonce(request, oauth_request, oauth_request['oauth_nonce']) oauth_nonce = oauth_request['oauth_nonce']
oauth_timestamp = oauth_request['oauth_timestamp']
return check_nonce(request, oauth_request, oauth_nonce, oauth_timestamp)
class OAuth2Authentication(BaseAuthentication): class OAuth2Authentication(BaseAuthentication):
......
import uuid import uuid
import hmac import hmac
from hashlib import sha1 from hashlib import sha1
from rest_framework.compat import AUTH_USER_MODEL
from django.conf import settings from django.conf import settings
from django.db import models from django.db import models
# Prior to Django 1.5, the AUTH_USER_MODEL setting does not exist.
# Note that we don't perform this code in the compat module due to
# bug report #1297
# See: https://github.com/tomchristie/django-rest-framework/issues/1297
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class Token(models.Model): class Token(models.Model):
""" """
The default authorization token model. The default authorization token model.
......
...@@ -6,6 +6,7 @@ versions of django/python, and compatibility wrappers around optional packages. ...@@ -6,6 +6,7 @@ versions of django/python, and compatibility wrappers around optional packages.
# flake8: noqa # flake8: noqa
from __future__ import unicode_literals from __future__ import unicode_literals
import django import django
import inspect
from django.core.exceptions import ImproperlyConfigured from django.core.exceptions import ImproperlyConfigured
from django.conf import settings from django.conf import settings
...@@ -99,13 +100,6 @@ def get_concrete_model(model_cls): ...@@ -99,13 +100,6 @@ def get_concrete_model(model_cls):
return model_cls return model_cls
# Django 1.5 add support for custom auth user model
if django.VERSION >= (1, 5):
AUTH_USER_MODEL = settings.AUTH_USER_MODEL
else:
AUTH_USER_MODEL = 'auth.User'
# View._allowed_methods only present from 1.5 onwards # View._allowed_methods only present from 1.5 onwards
if django.VERSION >= (1, 5): if django.VERSION >= (1, 5):
from django.views.generic import View from django.views.generic import View
...@@ -201,9 +195,23 @@ except ImportError: ...@@ -201,9 +195,23 @@ except ImportError:
try: try:
import oauth_provider import oauth_provider
from oauth_provider.store import store as oauth_provider_store from oauth_provider.store import store as oauth_provider_store
# check_nonce's calling signature in django-oauth-plus changes sometime
# between versions 2.0 and 2.2.1
def check_nonce(request, oauth_request, oauth_nonce, oauth_timestamp):
check_nonce_args = inspect.getargspec(oauth_provider_store.check_nonce).args
if 'timestamp' in check_nonce_args:
return oauth_provider_store.check_nonce(
request, oauth_request, oauth_nonce, oauth_timestamp
)
return oauth_provider_store.check_nonce(
request, oauth_request, oauth_nonce
)
except (ImportError, ImproperlyConfigured): except (ImportError, ImproperlyConfigured):
oauth_provider = None oauth_provider = None
oauth_provider_store = None oauth_provider_store = None
check_nonce = None
# OAuth 2 support is optional # OAuth 2 support is optional
......
...@@ -423,7 +423,7 @@ class BooleanField(WritableField): ...@@ -423,7 +423,7 @@ class BooleanField(WritableField):
def field_from_native(self, data, files, field_name, into): def field_from_native(self, data, files, field_name, into):
# HTML checkboxes do not explicitly represent unchecked as `False` # HTML checkboxes do not explicitly represent unchecked as `False`
# we deal with that here... # we deal with that here...
if isinstance(data, QueryDict): if isinstance(data, QueryDict) and self.default is None:
self.default = False self.default = False
return super(BooleanField, self).field_from_native( return super(BooleanField, self).field_from_native(
......
...@@ -44,9 +44,7 @@ class IsAuthenticated(BasePermission): ...@@ -44,9 +44,7 @@ class IsAuthenticated(BasePermission):
""" """
def has_permission(self, request, view): def has_permission(self, request, view):
if request.user and request.user.is_authenticated(): return request.user and request.user.is_authenticated()
return True
return False
class IsAdminUser(BasePermission): class IsAdminUser(BasePermission):
...@@ -55,9 +53,7 @@ class IsAdminUser(BasePermission): ...@@ -55,9 +53,7 @@ class IsAdminUser(BasePermission):
""" """
def has_permission(self, request, view): def has_permission(self, request, view):
if request.user and request.user.is_staff: return request.user and request.user.is_staff
return True
return False
class IsAuthenticatedOrReadOnly(BasePermission): class IsAuthenticatedOrReadOnly(BasePermission):
...@@ -66,11 +62,9 @@ class IsAuthenticatedOrReadOnly(BasePermission): ...@@ -66,11 +62,9 @@ class IsAuthenticatedOrReadOnly(BasePermission):
""" """
def has_permission(self, request, view): def has_permission(self, request, view):
if (request.method in SAFE_METHODS or return (request.method in SAFE_METHODS or
request.user and request.user and
request.user.is_authenticated()): request.user.is_authenticated())
return True
return False
class DjangoModelPermissions(BasePermission): class DjangoModelPermissions(BasePermission):
...@@ -128,11 +122,9 @@ class DjangoModelPermissions(BasePermission): ...@@ -128,11 +122,9 @@ class DjangoModelPermissions(BasePermission):
perms = self.get_required_permissions(request.method, model_cls) perms = self.get_required_permissions(request.method, model_cls)
if (request.user and return (request.user and
(request.user.is_authenticated() or not self.authenticated_users_only) and (request.user.is_authenticated() or not self.authenticated_users_only) and
request.user.has_perms(perms)): request.user.has_perms(perms))
return True
return False
class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions): class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):
......
...@@ -208,18 +208,24 @@ class SimpleRouter(BaseRouter): ...@@ -208,18 +208,24 @@ class SimpleRouter(BaseRouter):
bound_methods[method] = action bound_methods[method] = action
return bound_methods return bound_methods
def get_lookup_regex(self, viewset): def get_lookup_regex(self, viewset, lookup_prefix=''):
""" """
Given a viewset, return the portion of URL regex that is used Given a viewset, return the portion of URL regex that is used
to match against a single instance. to match against a single instance.
Note that lookup_prefix is not used directly inside REST rest_framework
itself, but is required in order to nicely support nested router
implementations, such as drf-nested-routers.
https://github.com/alanjds/drf-nested-routers
""" """
if self.trailing_slash: if self.trailing_slash:
base_regex = '(?P<{lookup_field}>[^/]+)' base_regex = '(?P<{lookup_prefix}{lookup_field}>[^/]+)'
else: else:
# Don't consume `.json` style suffixes # Don't consume `.json` style suffixes
base_regex = '(?P<{lookup_field}>[^/.]+)' base_regex = '(?P<{lookup_prefix}{lookup_field}>[^/.]+)'
lookup_field = getattr(viewset, 'lookup_field', 'pk') lookup_field = getattr(viewset, 'lookup_field', 'pk')
return base_regex.format(lookup_field=lookup_field) return base_regex.format(lookup_field=lookup_field, lookup_prefix=lookup_prefix)
def get_urls(self): def get_urls(self):
""" """
......
...@@ -416,7 +416,9 @@ class BaseSerializer(WritableField): ...@@ -416,7 +416,9 @@ class BaseSerializer(WritableField):
if self.source == '*': if self.source == '*':
if value: if value:
into.update(value) reverted_data = self.restore_fields(value, {})
if not self._errors:
into.update(reverted_data)
else: else:
if value in (None, ''): if value in (None, ''):
into[(self.source or field_name)] = None into[(self.source or field_name)] = None
...@@ -602,6 +604,7 @@ class ModelSerializer(Serializer): ...@@ -602,6 +604,7 @@ class ModelSerializer(Serializer):
models.TextField: CharField, models.TextField: CharField,
models.CommaSeparatedIntegerField: CharField, models.CommaSeparatedIntegerField: CharField,
models.BooleanField: BooleanField, models.BooleanField: BooleanField,
models.NullBooleanField: BooleanField,
models.FileField: FileField, models.FileField: FileField,
models.ImageField: ImageField, models.ImageField: ImageField,
} }
...@@ -695,7 +698,9 @@ class ModelSerializer(Serializer): ...@@ -695,7 +698,9 @@ class ModelSerializer(Serializer):
is_m2m = isinstance(relation.field, is_m2m = isinstance(relation.field,
models.fields.related.ManyToManyField) models.fields.related.ManyToManyField)
if is_m2m and not relation.field.rel.through._meta.auto_created: if (is_m2m and
hasattr(relation.field.rel, 'through') and
not relation.field.rel.through._meta.auto_created):
has_through_model = True has_through_model = True
if nested: if nested:
......
...@@ -70,6 +70,7 @@ class Comment(RESTFrameworkModel): ...@@ -70,6 +70,7 @@ class Comment(RESTFrameworkModel):
class ActionItem(RESTFrameworkModel): class ActionItem(RESTFrameworkModel):
title = models.CharField(max_length=200) title = models.CharField(max_length=200)
started = models.NullBooleanField(default=False)
done = models.BooleanField(default=False) done = models.BooleanField(default=False)
info = CustomField(default='---', max_length=12) info = CustomField(default='---', max_length=12)
......
...@@ -249,7 +249,7 @@ class OAuthTests(TestCase): ...@@ -249,7 +249,7 @@ class OAuthTests(TestCase):
def setUp(self): def setUp(self):
# these imports are here because oauth is optional and hiding them in try..except block or compat # these imports are here because oauth is optional and hiding them in try..except block or compat
# could obscure problems if something breaks # could obscure problems if something breaks
from oauth_provider.models import Consumer, Resource from oauth_provider.models import Consumer, Scope
from oauth_provider.models import Token as OAuthToken from oauth_provider.models import Token as OAuthToken
from oauth_provider import consts from oauth_provider import consts
...@@ -269,8 +269,8 @@ class OAuthTests(TestCase): ...@@ -269,8 +269,8 @@ class OAuthTests(TestCase):
self.consumer = Consumer.objects.create(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET, self.consumer = Consumer.objects.create(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET,
name='example', user=self.user, status=self.consts.ACCEPTED) name='example', user=self.user, status=self.consts.ACCEPTED)
self.resource = Resource.objects.create(name="resource name", url="api/") self.scope = Scope.objects.create(name="resource name", url="api/")
self.token = OAuthToken.objects.create(user=self.user, consumer=self.consumer, resource=self.resource, self.token = OAuthToken.objects.create(user=self.user, consumer=self.consumer, scope=self.scope,
token_type=OAuthToken.ACCESS, key=self.TOKEN_KEY, secret=self.TOKEN_SECRET, is_approved=True token_type=OAuthToken.ACCESS, key=self.TOKEN_KEY, secret=self.TOKEN_SECRET, is_approved=True
) )
...@@ -362,7 +362,8 @@ class OAuthTests(TestCase): ...@@ -362,7 +362,8 @@ class OAuthTests(TestCase):
def test_post_form_with_urlencoded_parameters(self): def test_post_form_with_urlencoded_parameters(self):
"""Ensure POSTing with x-www-form-urlencoded auth parameters passes""" """Ensure POSTing with x-www-form-urlencoded auth parameters passes"""
params = self._create_authorization_url_parameters() params = self._create_authorization_url_parameters()
response = self.csrf_client.post('/oauth/', params) auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth/', params, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed') @unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed')
...@@ -397,10 +398,10 @@ class OAuthTests(TestCase): ...@@ -397,10 +398,10 @@ class OAuthTests(TestCase):
@unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed') @unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed')
@unittest.skipUnless(oauth, 'oauth2 not installed') @unittest.skipUnless(oauth, 'oauth2 not installed')
def test_get_form_with_readonly_resource_passing_auth(self): def test_get_form_with_readonly_resource_passing_auth(self):
"""Ensure POSTing with a readonly resource instead of a write scope fails""" """Ensure POSTing with a readonly scope instead of a write scope fails"""
read_only_access_token = self.token read_only_access_token = self.token
read_only_access_token.resource.is_readonly = True read_only_access_token.scope.is_readonly = True
read_only_access_token.resource.save() read_only_access_token.scope.save()
params = self._create_authorization_url_parameters() params = self._create_authorization_url_parameters()
response = self.csrf_client.get('/oauth-with-scope/', params) response = self.csrf_client.get('/oauth-with-scope/', params)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
...@@ -410,8 +411,8 @@ class OAuthTests(TestCase): ...@@ -410,8 +411,8 @@ class OAuthTests(TestCase):
def test_post_form_with_readonly_resource_failing_auth(self): def test_post_form_with_readonly_resource_failing_auth(self):
"""Ensure POSTing with a readonly resource instead of a write scope fails""" """Ensure POSTing with a readonly resource instead of a write scope fails"""
read_only_access_token = self.token read_only_access_token = self.token
read_only_access_token.resource.is_readonly = True read_only_access_token.scope.is_readonly = True
read_only_access_token.resource.save() read_only_access_token.scope.save()
params = self._create_authorization_url_parameters() params = self._create_authorization_url_parameters()
response = self.csrf_client.post('/oauth-with-scope/', params) response = self.csrf_client.post('/oauth-with-scope/', params)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)) self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
...@@ -421,10 +422,11 @@ class OAuthTests(TestCase): ...@@ -421,10 +422,11 @@ class OAuthTests(TestCase):
def test_post_form_with_write_resource_passing_auth(self): def test_post_form_with_write_resource_passing_auth(self):
"""Ensure POSTing with a write resource succeed""" """Ensure POSTing with a write resource succeed"""
read_write_access_token = self.token read_write_access_token = self.token
read_write_access_token.resource.is_readonly = False read_write_access_token.scope.is_readonly = False
read_write_access_token.resource.save() read_write_access_token.scope.save()
params = self._create_authorization_url_parameters() params = self._create_authorization_url_parameters()
response = self.csrf_client.post('/oauth-with-scope/', params) auth = self._create_authorization_header()
response = self.csrf_client.post('/oauth-with-scope/', params, HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, 200) self.assertEqual(response.status_code, 200)
@unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed') @unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed')
......
...@@ -105,6 +105,17 @@ class ModelSerializerWithNestedSerializer(serializers.ModelSerializer): ...@@ -105,6 +105,17 @@ class ModelSerializerWithNestedSerializer(serializers.ModelSerializer):
model = Person model = Person
class NestedSerializerWithRenamedField(serializers.Serializer):
renamed_info = serializers.Field(source='info')
class ModelSerializerWithNestedSerializerWithRenamedField(serializers.ModelSerializer):
nested = NestedSerializerWithRenamedField(source='*')
class Meta:
model = Person
class PersonSerializerInvalidReadOnly(serializers.ModelSerializer): class PersonSerializerInvalidReadOnly(serializers.ModelSerializer):
""" """
Testing for #652. Testing for #652.
...@@ -456,6 +467,20 @@ class ValidationTests(TestCase): ...@@ -456,6 +467,20 @@ class ValidationTests(TestCase):
) )
self.assertEqual(serializer.is_valid(), True) self.assertEqual(serializer.is_valid(), True)
def test_writable_star_source_with_inner_source_fields(self):
"""
Tests that a serializer with source="*" correctly expands the
it's fields into the outer serializer even if they have their
own 'source' parameters.
"""
serializer = ModelSerializerWithNestedSerializerWithRenamedField(data={
'name': 'marko',
'nested': {'renamed_info': 'hi'}},
)
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.errors, {})
class CustomValidationTests(TestCase): class CustomValidationTests(TestCase):
class CommentSerializerWithFieldValidator(CommentSerializer): class CommentSerializerWithFieldValidator(CommentSerializer):
...@@ -1743,3 +1768,75 @@ class TestSerializerTransformMethods(TestCase): ...@@ -1743,3 +1768,75 @@ class TestSerializerTransformMethods(TestCase):
'b_renamed': None, 'b_renamed': None,
} }
) )
class DefaultTrueBooleanModel(models.Model):
cat = models.BooleanField(default=True)
dog = models.BooleanField(default=False)
class SerializerDefaultTrueBoolean(TestCase):
def setUp(self):
super(SerializerDefaultTrueBoolean, self).setUp()
class DefaultTrueBooleanSerializer(serializers.ModelSerializer):
class Meta:
model = DefaultTrueBooleanModel
fields = ('cat', 'dog')
self.default_true_boolean_serializer = DefaultTrueBooleanSerializer
def test_enabled_as_false(self):
serializer = self.default_true_boolean_serializer(data={'cat': False,
'dog': False})
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.data['cat'], False)
self.assertEqual(serializer.data['dog'], False)
def test_enabled_as_true(self):
serializer = self.default_true_boolean_serializer(data={'cat': True,
'dog': True})
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.data['cat'], True)
self.assertEqual(serializer.data['dog'], True)
def test_enabled_partial(self):
serializer = self.default_true_boolean_serializer(data={'cat': False},
partial=True)
self.assertEqual(serializer.is_valid(), True)
self.assertEqual(serializer.data['cat'], False)
self.assertEqual(serializer.data['dog'], False)
class BoolenFieldTypeTest(TestCase):
'''
Ensure the various Boolean based model fields are rendered as the proper
field type
'''
def setUp(self):
'''
Setup an ActionItemSerializer for BooleanTesting
'''
data = {
'title': 'b' * 201,
}
self.serializer = ActionItemSerializer(data=data)
def test_booleanfield_type(self):
'''
Test that BooleanField is infered from models.BooleanField
'''
bfield = self.serializer.get_fields()['done']
self.assertEqual(type(bfield), fields.BooleanField)
def test_nullbooleanfield_type(self):
'''
Test that BooleanField is infered from models.NullBooleanField
https://groups.google.com/forum/#!topic/django-rest-framework/D9mXEftpuQ8
'''
bfield = self.serializer.get_fields()['started']
self.assertEqual(type(bfield), fields.BooleanField)
...@@ -47,12 +47,18 @@ class ShouldValidateModel(models.Model): ...@@ -47,12 +47,18 @@ class ShouldValidateModel(models.Model):
class ShouldValidateModelSerializer(serializers.ModelSerializer): class ShouldValidateModelSerializer(serializers.ModelSerializer):
renamed = serializers.CharField(source='should_validate_field', required=False) renamed = serializers.CharField(source='should_validate_field', required=False)
def validate_renamed(self, attrs, source):
value = attrs[source]
if len(value) < 3:
raise serializers.ValidationError('Minimum 3 characters.')
return attrs
class Meta: class Meta:
model = ShouldValidateModel model = ShouldValidateModel
fields = ('renamed',) fields = ('renamed',)
class TestPreSaveValidationExclusions(TestCase): class TestPreSaveValidationExclusionsSerializer(TestCase):
def test_renamed_fields_are_model_validated(self): def test_renamed_fields_are_model_validated(self):
""" """
Ensure fields with 'source' applied do get still get model validation. Ensure fields with 'source' applied do get still get model validation.
...@@ -61,6 +67,19 @@ class TestPreSaveValidationExclusions(TestCase): ...@@ -61,6 +67,19 @@ class TestPreSaveValidationExclusions(TestCase):
# does not have `blank=True`, so this serializer should not validate. # does not have `blank=True`, so this serializer should not validate.
serializer = ShouldValidateModelSerializer(data={'renamed': ''}) serializer = ShouldValidateModelSerializer(data={'renamed': ''})
self.assertEqual(serializer.is_valid(), False) self.assertEqual(serializer.is_valid(), False)
self.assertIn('renamed', serializer.errors)
self.assertNotIn('should_validate_field', serializer.errors)
class TestCustomValidationMethods(TestCase):
def test_custom_validation_method_is_executed(self):
serializer = ShouldValidateModelSerializer(data={'renamed': 'fo'})
self.assertFalse(serializer.is_valid())
self.assertIn('renamed', serializer.errors)
def test_custom_validation_method_passing(self):
serializer = ShouldValidateModelSerializer(data={'renamed': 'foo'})
self.assertTrue(serializer.is_valid())
class ValidationSerializer(serializers.Serializer): class ValidationSerializer(serializers.Serializer):
......
...@@ -22,7 +22,7 @@ basepython = python2.7 ...@@ -22,7 +22,7 @@ basepython = python2.7
deps = Django==1.6.1 deps = Django==1.6.1
django-filter==0.6a1 django-filter==0.6a1
defusedxml==0.3 defusedxml==0.3
django-oauth-plus==2.0 django-oauth-plus==2.2.1
oauth2==1.5.211 oauth2==1.5.211
django-oauth2-provider==0.2.4 django-oauth2-provider==0.2.4
django-guardian==1.1.1 django-guardian==1.1.1
...@@ -32,7 +32,7 @@ basepython = python2.6 ...@@ -32,7 +32,7 @@ basepython = python2.6
deps = Django==1.6.1 deps = Django==1.6.1
django-filter==0.6a1 django-filter==0.6a1
defusedxml==0.3 defusedxml==0.3
django-oauth-plus==2.0 django-oauth-plus==2.2.1
oauth2==1.5.211 oauth2==1.5.211
django-oauth2-provider==0.2.4 django-oauth2-provider==0.2.4
django-guardian==1.1.1 django-guardian==1.1.1
...@@ -54,7 +54,7 @@ basepython = python2.7 ...@@ -54,7 +54,7 @@ basepython = python2.7
deps = django==1.5.5 deps = django==1.5.5
django-filter==0.6a1 django-filter==0.6a1
defusedxml==0.3 defusedxml==0.3
django-oauth-plus==2.0 django-oauth-plus==2.2.1
oauth2==1.5.211 oauth2==1.5.211
django-oauth2-provider==0.2.3 django-oauth2-provider==0.2.3
django-guardian==1.1.1 django-guardian==1.1.1
...@@ -64,7 +64,7 @@ basepython = python2.6 ...@@ -64,7 +64,7 @@ basepython = python2.6
deps = django==1.5.5 deps = django==1.5.5
django-filter==0.6a1 django-filter==0.6a1
defusedxml==0.3 defusedxml==0.3
django-oauth-plus==2.0 django-oauth-plus==2.2.1
oauth2==1.5.211 oauth2==1.5.211
django-oauth2-provider==0.2.3 django-oauth2-provider==0.2.3
django-guardian==1.1.1 django-guardian==1.1.1
...@@ -74,7 +74,7 @@ basepython = python2.7 ...@@ -74,7 +74,7 @@ basepython = python2.7
deps = django==1.4.10 deps = django==1.4.10
django-filter==0.6a1 django-filter==0.6a1
defusedxml==0.3 defusedxml==0.3
django-oauth-plus==2.0 django-oauth-plus==2.2.1
oauth2==1.5.211 oauth2==1.5.211
django-oauth2-provider==0.2.3 django-oauth2-provider==0.2.3
django-guardian==1.1.1 django-guardian==1.1.1
...@@ -84,7 +84,7 @@ basepython = python2.6 ...@@ -84,7 +84,7 @@ basepython = python2.6
deps = django==1.4.10 deps = django==1.4.10
django-filter==0.6a1 django-filter==0.6a1
defusedxml==0.3 defusedxml==0.3
django-oauth-plus==2.0 django-oauth-plus==2.2.1
oauth2==1.5.211 oauth2==1.5.211
django-oauth2-provider==0.2.3 django-oauth2-provider==0.2.3
django-guardian==1.1.1 django-guardian==1.1.1
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment