Merge branch 'bennbollay-patch-1' into 2.4.0

Conflicts:
	.travis.yml
	docs/api-guide/routers.md
	rest_framework/compat.py
	tox.ini
This commit is contained in:
Tom Christie 2013-12-23 09:48:59 +00:00
commit 52686420f4
28 changed files with 451 additions and 71 deletions

View File

@ -16,7 +16,7 @@ install:
- pip install defusedxml==0.3
- 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 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-guardian==1.1.1 --use-mirrors; fi"
- export PYTHONPATH=.

193
CONTRIBUTING.md Normal file
View File

@ -0,0 +1,193 @@
# Contributing to REST framework
> The world can only really be changed one piece at a time. The art is picking that piece.
>
> — [Tim Berners-Lee][cite]
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
## Community
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 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.
When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant.
## Code of conduct
Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome.
Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations.
The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums.
# Issues
It's really helpful if you can make sure to address issues on the correct channel. Usage questions should be directed to the [discussion group][google-group]. Feature requests, bug reports and other issues should be raised on the GitHub [issue tracker][issues].
Some tips on good issue reporting:
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintainence overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened.
## Triaging issues
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package?
* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
# Development
To start developing on Django REST framework, clone the repo:
git clone git@github.com:tomchristie/django-rest-framework.git
Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you setup your editor to automatically indicated non-conforming styles.
## Testing
To run the tests, clone the repository, and then:
# Setup the virtual environment
virtualenv env
env/bin/activate
pip install -r requirements.txt
pip install -r optionals.txt
# Run the tests
rest_framework/runtests/runtests.py
You can also use the excellent `[tox][tox]` testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run:
tox
## Pull requests
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another seperate issue without interfering with an ongoing pull requests.
It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests.
GitHub's documentation for working on pull requests is [available here][pull-requests].
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
Once you've made a pull request take a look at the travis build status in the GitHub interface and make sure the tests are runnning as you'd expect.
![Travis status][travis-status]
*Above: Travis build notifications*
## Managing compatibility issues
Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
# Documentation
The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs].
There are many great markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended.
## Building the documentation
To build the documentation, simply run the `mkdocs.py` script.
./mkdocs.py
This will build the html output into the `html` directory.
You can build the documentation and open a preview in a browser window by using the `-p` flag.
./mkdocs.py -p
## Language style
Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible.
Some other tips:
* Keep paragraphs reasonably short.
* Use double spacing after the end of sentences.
* Don't use the abbreviations such as 'e.g.' but instead use long form, such as 'For example'.
## Markdown style
There are a couple of conventions you should follow when working on the documentation.
##### 1. Headers
Headers should use the hash style. For example:
### Some important topic
The underline style should not be used. **Don't do this:**
Some important topic
====================
##### 2. Links
Links should always use the reference style, with the referenced hyperlinks kept at the end of the document.
Here is a link to [some other thing][other-thing].
More text...
[other-thing]: http://example.com/other/thing
This style helps keep the documentation source consistent and readable.
If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example:
[authentication]: ../api-guide/authentication.md
Linking in this style means you'll be able to click the hyperlink in your markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages.
##### 3. Notes
If you want to draw attention to a note or warning, use a pair of enclosing lines, like so:
---
**Note:** A useful documentation note.
---
# Third party packages
New features to REST framework are generally recommended to be implemented as third party libraries that are developed outside of the core framework. Ideally third party libraries should be properly documented and packaged, and made available on PyPI.
## Getting started
If you have some functionality that you would like to implement as a third party package it's worth contacting the [discussion group][google-group] as others may be willing to get involved. We strongly encourage third party package development and will always try to prioritize time spent helping their development, documentation and packaging.
We recommend the [`django-reusable-app`][django-reusable-app] template as a good resource for getting up and running with implementing a third party Django package.
## Linking to your package
Once your package is decently documented and available on PyPI open a pull request or issue, and we'll add a link to it from the main REST framework documentation.
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
[code-of-conduct]: https://www.djangoproject.com/conduct/
[google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[so-filter]: http://stackexchange.com/filters/66475/rest-framework
[issues]: https://github.com/tomchristie/django-rest-framework/issues?state=open
[pep-8]: http://www.python.org/dev/peps/pep-0008/
[travis-status]: https://raw.github.com/tomchristie/django-rest-framework/master/docs/img/travis-status.png
[pull-requests]: https://help.github.com/articles/using-pull-requests
[tox]: http://tox.readthedocs.org/en/latest/
[markdown]: http://daringfireball.net/projects/markdown/basics
[docs]: https://github.com/tomchristie/django-rest-framework/tree/master/docs
[mou]: http://mouapp.com/
[django-reusable-app]: https://github.com/dabapps/django-reusable-app

View File

@ -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.
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
**Signature:** `ParseError(detail=None)`

View File

@ -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.
## 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/
[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
[messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack
[juanriaza]: https://github.com/juanriaza
[vbabiy]: https://github.com/vbabiy
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case

View File

@ -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].
---
# 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/
[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
[2.2-announcement]: ../topics/2.2-announcement.md
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers

View File

@ -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.
## 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
[conneg]: content-negotiation.md
[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
[messagepack]: http://msgpack.org/
[juanriaza]: https://github.com/juanriaza
[mjumbewu]: https://github.com/mjumbewu
[vbabiy]: https://github.com/vbabiy
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
[ultrajson]: https://github.com/esnme/ultrajson
[hzy]: https://github.com/hzy
[drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer
[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case

View File

@ -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.
[cite]: http://guides.rubyonrails.org/routing.html
[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
## 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.
@ -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
[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-router]: http://wq.io/docs/app.py

View File

@ -0,0 +1,4 @@
* Writable nested serializers.
* List/detail routes.
* 1.3 Support dropped, install six for <=1.4.?.
* Note title ordering changed

View File

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

View File

@ -181,6 +181,7 @@ The following people have helped make REST framework great.
* Alex Good - [alexjg]
* Ian Foote - [ian-foote]
* Chuck Harmston - [chuckharmston]
* Philip Forget - [philipforget]
Many thanks to everyone who's contributed to the project.
@ -398,3 +399,4 @@ You can also contact [@_tomchristie][twitter] directly on twitter.
[alexjg]: https://github.com/alexjg
[ian-foote]: https://github.com/ian-foote
[chuckharmston]: https://github.com/chuckharmston
[philipforget]: https://github.com/philipforget

View File

@ -53,7 +53,9 @@ You can determine your currently installed version using `pip freeze`:
### Master
* 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: Allow defaults on BooleanFields to be properly honored when values are not supplied.
### 2.3.10
@ -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 sending empty string instead of file now clears `FileField`.
* 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

View File

@ -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...
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)
...then we restore those native datatypes into to a fully populated object instance.
@ -261,8 +263,7 @@ The root of our API is going to be a view that supports listing all the existing
if serializer.is_valid():
serializer.save()
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.
@ -288,8 +289,7 @@ We'll also need a view which corresponds to an individual snippet, and can be us
if serializer.is_valid():
serializer.save()
return JSONResponse(serializer.data)
else:
return JSONResponse(serializer.errors, status=400)
return JSONResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
snippet.delete()

View File

@ -59,8 +59,7 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de
if serializer.is_valid():
serializer.save()
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.
@ -85,8 +84,7 @@ Here is the view for an individual snippet, in the `views.py` module.
if serializer.is_valid():
serializer.save()
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':
snippet.delete()

View File

@ -167,10 +167,10 @@ In the snippets app, create a new file, `permissions.py`
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
if request.method in permissions.SAFE_METHODS:
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
Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` class:

View File

@ -144,7 +144,7 @@ for (dirpath, dirnames, filenames) in os.walk(docs_dir):
if filename == 'index.md':
main_title = 'Django REST framework - APIs made easy'
else:
main_title = 'Django REST framework - ' + main_title
main_title = main_title + ' - Django REST framework'
if relative_path == 'index.md':
canonical_url = base_url

View File

@ -2,6 +2,6 @@ markdown>=2.1.0
PyYAML>=3.10
defusedxml>=0.3
django-filter>=0.5.4
django-oauth-plus>=2.0
django-oauth-plus>=2.2.1
oauth2>=1.5.211
django-oauth2-provider>=0.2.4

View File

@ -9,7 +9,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.middleware.csrf import CsrfViewMiddleware
from rest_framework import exceptions, HTTP_HEADER_ENCODING
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
@ -281,7 +281,9 @@ class OAuthAuthentication(BaseAuthentication):
"""
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):

View File

@ -1,11 +1,17 @@
import uuid
import hmac
from hashlib import sha1
from rest_framework.compat import AUTH_USER_MODEL
from django.conf import settings
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):
"""
The default authorization token model.

View File

@ -6,6 +6,7 @@ versions of django/python, and compatibility wrappers around optional packages.
# flake8: noqa
from __future__ import unicode_literals
import django
import inspect
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
@ -99,13 +100,6 @@ def get_concrete_model(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
if django.VERSION >= (1, 5):
from django.views.generic import View
@ -201,9 +195,23 @@ except ImportError:
try:
import oauth_provider
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):
oauth_provider = None
oauth_provider_store = None
check_nonce = None
# OAuth 2 support is optional

View File

@ -423,7 +423,7 @@ class BooleanField(WritableField):
def field_from_native(self, data, files, field_name, into):
# HTML checkboxes do not explicitly represent unchecked as `False`
# we deal with that here...
if isinstance(data, QueryDict):
if isinstance(data, QueryDict) and self.default is None:
self.default = False
return super(BooleanField, self).field_from_native(

View File

@ -44,9 +44,7 @@ class IsAuthenticated(BasePermission):
"""
def has_permission(self, request, view):
if request.user and request.user.is_authenticated():
return True
return False
return request.user and request.user.is_authenticated()
class IsAdminUser(BasePermission):
@ -55,9 +53,7 @@ class IsAdminUser(BasePermission):
"""
def has_permission(self, request, view):
if request.user and request.user.is_staff:
return True
return False
return request.user and request.user.is_staff
class IsAuthenticatedOrReadOnly(BasePermission):
@ -66,11 +62,9 @@ class IsAuthenticatedOrReadOnly(BasePermission):
"""
def has_permission(self, request, view):
if (request.method in SAFE_METHODS or
request.user and
request.user.is_authenticated()):
return True
return False
return (request.method in SAFE_METHODS or
request.user and
request.user.is_authenticated())
class DjangoModelPermissions(BasePermission):
@ -128,11 +122,9 @@ class DjangoModelPermissions(BasePermission):
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.has_perms(perms)):
return True
return False
request.user.has_perms(perms))
class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):

View File

@ -208,18 +208,24 @@ class SimpleRouter(BaseRouter):
bound_methods[method] = action
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
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:
base_regex = '(?P<{lookup_field}>[^/]+)'
base_regex = '(?P<{lookup_prefix}{lookup_field}>[^/]+)'
else:
# 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')
return base_regex.format(lookup_field=lookup_field)
return base_regex.format(lookup_field=lookup_field, lookup_prefix=lookup_prefix)
def get_urls(self):
"""

View File

@ -416,7 +416,9 @@ class BaseSerializer(WritableField):
if self.source == '*':
if value:
into.update(value)
reverted_data = self.restore_fields(value, {})
if not self._errors:
into.update(reverted_data)
else:
if value in (None, ''):
into[(self.source or field_name)] = None
@ -602,6 +604,7 @@ class ModelSerializer(Serializer):
models.TextField: CharField,
models.CommaSeparatedIntegerField: CharField,
models.BooleanField: BooleanField,
models.NullBooleanField: BooleanField,
models.FileField: FileField,
models.ImageField: ImageField,
}
@ -695,7 +698,9 @@ class ModelSerializer(Serializer):
is_m2m = isinstance(relation.field,
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
if nested:

View File

@ -70,6 +70,7 @@ class Comment(RESTFrameworkModel):
class ActionItem(RESTFrameworkModel):
title = models.CharField(max_length=200)
started = models.NullBooleanField(default=False)
done = models.BooleanField(default=False)
info = CustomField(default='---', max_length=12)

View File

@ -249,7 +249,7 @@ class OAuthTests(TestCase):
def setUp(self):
# these imports are here because oauth is optional and hiding them in try..except block or compat
# 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 import consts
@ -269,8 +269,8 @@ class OAuthTests(TestCase):
self.consumer = Consumer.objects.create(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET,
name='example', user=self.user, status=self.consts.ACCEPTED)
self.resource = Resource.objects.create(name="resource name", url="api/")
self.token = OAuthToken.objects.create(user=self.user, consumer=self.consumer, resource=self.resource,
self.scope = Scope.objects.create(name="resource name", url="api/")
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
)
@ -362,7 +362,8 @@ class OAuthTests(TestCase):
def test_post_form_with_urlencoded_parameters(self):
"""Ensure POSTing with x-www-form-urlencoded auth parameters passes"""
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)
@unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed')
@ -397,10 +398,10 @@ class OAuthTests(TestCase):
@unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed')
@unittest.skipUnless(oauth, 'oauth2 not installed')
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.resource.is_readonly = True
read_only_access_token.resource.save()
read_only_access_token.scope.is_readonly = True
read_only_access_token.scope.save()
params = self._create_authorization_url_parameters()
response = self.csrf_client.get('/oauth-with-scope/', params)
self.assertEqual(response.status_code, 200)
@ -410,8 +411,8 @@ class OAuthTests(TestCase):
def test_post_form_with_readonly_resource_failing_auth(self):
"""Ensure POSTing with a readonly resource instead of a write scope fails"""
read_only_access_token = self.token
read_only_access_token.resource.is_readonly = True
read_only_access_token.resource.save()
read_only_access_token.scope.is_readonly = True
read_only_access_token.scope.save()
params = self._create_authorization_url_parameters()
response = self.csrf_client.post('/oauth-with-scope/', params)
self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN))
@ -421,10 +422,11 @@ class OAuthTests(TestCase):
def test_post_form_with_write_resource_passing_auth(self):
"""Ensure POSTing with a write resource succeed"""
read_write_access_token = self.token
read_write_access_token.resource.is_readonly = False
read_write_access_token.resource.save()
read_write_access_token.scope.is_readonly = False
read_write_access_token.scope.save()
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)
@unittest.skipUnless(oauth_provider, 'django-oauth-plus not installed')

View File

@ -105,6 +105,17 @@ class ModelSerializerWithNestedSerializer(serializers.ModelSerializer):
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):
"""
Testing for #652.
@ -456,6 +467,20 @@ class ValidationTests(TestCase):
)
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 CommentSerializerWithFieldValidator(CommentSerializer):
@ -1743,3 +1768,75 @@ class TestSerializerTransformMethods(TestCase):
'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)

View File

@ -47,12 +47,18 @@ class ShouldValidateModel(models.Model):
class ShouldValidateModelSerializer(serializers.ModelSerializer):
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:
model = ShouldValidateModel
fields = ('renamed',)
class TestPreSaveValidationExclusions(TestCase):
class TestPreSaveValidationExclusionsSerializer(TestCase):
def test_renamed_fields_are_model_validated(self):
"""
Ensure fields with 'source' applied do get still get model validation.
@ -61,6 +67,19 @@ class TestPreSaveValidationExclusions(TestCase):
# does not have `blank=True`, so this serializer should not validate.
serializer = ShouldValidateModelSerializer(data={'renamed': ''})
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):

12
tox.ini
View File

@ -22,7 +22,7 @@ basepython = python2.7
deps = Django==1.6.1
django-filter==0.6a1
defusedxml==0.3
django-oauth-plus==2.0
django-oauth-plus==2.2.1
oauth2==1.5.211
django-oauth2-provider==0.2.4
django-guardian==1.1.1
@ -32,7 +32,7 @@ basepython = python2.6
deps = Django==1.6.1
django-filter==0.6a1
defusedxml==0.3
django-oauth-plus==2.0
django-oauth-plus==2.2.1
oauth2==1.5.211
django-oauth2-provider==0.2.4
django-guardian==1.1.1
@ -54,7 +54,7 @@ basepython = python2.7
deps = django==1.5.5
django-filter==0.6a1
defusedxml==0.3
django-oauth-plus==2.0
django-oauth-plus==2.2.1
oauth2==1.5.211
django-oauth2-provider==0.2.3
django-guardian==1.1.1
@ -64,7 +64,7 @@ basepython = python2.6
deps = django==1.5.5
django-filter==0.6a1
defusedxml==0.3
django-oauth-plus==2.0
django-oauth-plus==2.2.1
oauth2==1.5.211
django-oauth2-provider==0.2.3
django-guardian==1.1.1
@ -74,7 +74,7 @@ basepython = python2.7
deps = django==1.4.10
django-filter==0.6a1
defusedxml==0.3
django-oauth-plus==2.0
django-oauth-plus==2.2.1
oauth2==1.5.211
django-oauth2-provider==0.2.3
django-guardian==1.1.1
@ -84,7 +84,7 @@ basepython = python2.6
deps = django==1.4.10
django-filter==0.6a1
defusedxml==0.3
django-oauth-plus==2.0
django-oauth-plus==2.2.1
oauth2==1.5.211
django-oauth2-provider==0.2.3
django-guardian==1.1.1