diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 03865b755..dbdc4f627 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,196 +1,280 @@ # Contributing to REST framework -> The world can only really be changed one piece at a time. The art is picking that piece. +> 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. +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. +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. +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 to 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 +to 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. +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. +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. +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. +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]. +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 maintenance overhead of REST framework, so that the focus can be on continued stability, bug fixes, 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. +* 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 + maintenance overhead of REST framework, so that the focus can be on continued + stability, bug fixes, 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: +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. +* 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 + 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 set up your editor to automatically indicate non-conforming styles. +Changes should broadly follow the [PEP 8][pep-8] style conventions, and we +recommend you set up your editor to automatically indicate non-conforming +styles. ## Testing To run the tests, clone the repository, and then: - # Setup the virtual environment - virtualenv env - source env/bin/activate - pip install -r requirements.txt + # Setup the virtual environment virtualenv env source env/bin/activate pip + install -r requirements.txt - # Run the tests - ./runtests.py + # Run the tests ./runtests.py ### Test options Run using a more concise output style. - ./runtests.py -q + ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. - ./runtests.py --fast + ./runtests.py --fast Don't run the flake8 code linting. - ./runtests.py --nolint + ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. - ./runtests.py --lintonly + ./runtests.py --lintonly Run the tests for a given test case. - ./runtests.py MyTestCase + ./runtests.py MyTestCase Run the tests for a given test method. - ./runtests.py MyTestCase.test_this_method + ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. - ./runtests.py test_this_method + ./runtests.py test_this_method -Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. +Note: The test case and test method matching is fuzzy and will sometimes run +other tests that contain a partial string match to the given command line +input. ### Running against multiple environments -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: +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 + 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 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 separate issue without interfering with an ongoing pull requests. +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 separate 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. +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]. +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. +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 running as you'd expect. +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 running as you'd expect. ## 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. +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]. +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. +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, install MkDocs with `pip install mkdocs` and then run the following command. +To build the documentation, install MkDocs with `pip install mkdocs` and then +run the following command. - mkdocs build + mkdocs build This will build the documentation into the `site` directory. -You can build the documentation and open a preview in a browser window by using the `serve` command. +You can build the documentation and open a preview in a browser window by using +the `serve` command. - mkdocs serve + mkdocs serve ## 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. +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. -* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'. +* Don't use abbreviations such as 'e.g.' but instead use + the long form, such as 'For example'. ## Markdown style -There are a couple of conventions you should follow when working on the documentation. +There are a couple of conventions you should follow when working on the +documentation. ##### 1. Headers -Headers should use the hash style. For example: +Headers should use the hash style. For example: - ### Some important topic + ### Some important topic -The underline style should not be used. **Don't do this:** +The underline style should not be used. **Don't do this:** - Some important topic - ==================== + Some important topic ==================== ##### 2. Links -Links should always use the reference style, with the referenced hyperlinks kept at the end of the document. +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]. + Here is a link to [some other thing][other-thing]. - More text... + More text... - [other-thing]: http://example.com/other/thing + [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: +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 + [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. +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: +If you want to draw attention to a note or warning, use a pair of enclosing +lines, like so: - --- + --- - **Note:** A useful documentation note. + **Note:** A useful documentation note. - --- + --- [cite]: http://www.w3.org/People/Berners-Lee/FAQ.html diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index 8d880b037..9541837d5 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -6,31 +6,50 @@ source: authentication.py > > — Jacob Kaplan-Moss, ["REST worst practices"][cite] -Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted. +Authentication is the mechanism of associating an incoming request with a set +of identifying credentials, such as the user the request came from, or the +token that it was signed with. The [permission] and [throttling] policies can +then use those credentials to determine if the request should be permitted. -REST framework provides a number of authentication schemes out of the box, and also allows you to implement custom schemes. +REST framework provides a number of authentication schemes out of the box, and +also allows you to implement custom schemes. -Authentication is always run at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed. +Authentication is always run at the very start of the view, before the +permission and throttling checks occur, and before any other code is allowed to +proceed. -The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class. +The `request.user` property will typically be set to an instance of the +`contrib.auth` package's `User` class. -The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with. +The `request.auth` property is used for any additional authentication +information, for example, it may be used to represent an authentication token +that the request was signed with. --- -**Note:** Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with. +**Note:** Don't forget that **authentication by itself won't allow or disallow +an incoming request**, it simply identifies the credentials that the request +was made with. -For information on how to setup the permission polices for your API please see the [permissions documentation][permission]. +For information on how to setup the permission polices for your API please see +the [permissions documentation][permission]. --- ## How authentication is determined -The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates. +The authentication schemes are always defined as a list of classes. REST +framework will attempt to authenticate with each class in the list, and will +set `request.user` and `request.auth` using the return value of the first class +that successfully authenticates. -If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`. +If no class authenticates, `request.user` will be set to an instance of +`django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to +`None`. -The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings. +The value of `request.user` and `request.auth` for unauthenticated requests can +be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` +settings. ## Setting the authentication scheme @@ -76,22 +95,37 @@ Or, if you're using the `@api_view` decorator with function based views. ## Unauthorized and Forbidden responses -When an unauthenticated request is denied permission there are two different error codes that may be appropriate. +When an unauthenticated request is denied permission there are two different +error codes that may be appropriate. * [HTTP 401 Unauthorized][http401] * [HTTP 403 Permission Denied][http403] -HTTP 401 responses must always include a `WWW-Authenticate` header, that instructs the client how to authenticate. HTTP 403 responses do not include the `WWW-Authenticate` header. +HTTP 401 responses must always include a `WWW-Authenticate` header, that +instructs the client how to authenticate. HTTP 403 responses do not include +the `WWW-Authenticate` header. -The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. **The first authentication class set on the view is used when determining the type of response**. +The kind of response that will be used depends on the authentication scheme. +Although multiple authentication schemes may be in use, only one scheme may be +used to determine the type of response. **The first authentication class set +on the view is used when determining the type of response**. -Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme. +Note that when a request may successfully authenticate, but still be denied +permission to perform the request, in which case a `403 Permission Denied` +response will always be used, regardless of the authentication scheme. ## Apache mod_wsgi specific configuration -Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level. +Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the +authorization header is not passed through to a WSGI application by default, as +it is assumed that authentication will be handled by Apache, rather than at an +application level. -If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`. +If you are deploying to Apache, and using any non-session based authentication, +you will need to explicitly configure mod_wsgi to pass the required headers +through to the application. This can be done by specifying the +`WSGIPassAuthorization` directive in the appropriate context and setting it to +`'On'`. # this can go in either server config, virtual host, directory or .htaccess WSGIPassAuthorization On @@ -102,24 +136,37 @@ If you are deploying to Apache, and using any non-session based authentication, ## BasicAuthentication -This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing. +This authentication scheme uses [HTTP Basic Authentication][basicauth], signed +against a user's username and password. Basic authentication is generally only +appropriate for testing. -If successfully authenticated, `BasicAuthentication` provides the following credentials. +If successfully authenticated, `BasicAuthentication` provides the following +credentials. * `request.user` will be a Django `User` instance. * `request.auth` will be `None`. -Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example: +Unauthenticated responses that are denied permission will result in an `HTTP +401 Unauthorized` response with an appropriate WWW-Authenticate header. For +example: WWW-Authenticate: Basic realm="api" -**Note:** If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage. +**Note:** If you use `BasicAuthentication` in production you must ensure that +your API is only available over `https`. You should also ensure that your API +clients will always re-request the username and password at login, and will +never store those details to persistent storage. ## TokenAuthentication -This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. +This authentication scheme uses a simple token-based HTTP Authentication +scheme. Token authentication is appropriate for client-server setups, such as +native desktop and mobile clients. -To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting: +To use the `TokenAuthentication` scheme you'll need to [configure the +authentication classes](#setting-the-authentication-scheme) to include +`TokenAuthentication`, and additionally include `rest_framework.authtoken` in +your `INSTALLED_APPS` setting: INSTALLED_APPS = ( ... @@ -128,7 +175,8 @@ To use the `TokenAuthentication` scheme you'll need to [configure the authentica --- -**Note:** Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations. +**Note:** Make sure to run `manage.py migrate` after changing your settings. +The `rest_framework.authtoken` app provides Django database migrations. --- @@ -139,28 +187,37 @@ You'll also need to create tokens for your users. token = Token.objects.create(user=...) print token.key -For clients to authenticate, the token key should be included in the `Authorization` HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example: +For clients to authenticate, the token key should be included in the +`Authorization` HTTP header. The key should be prefixed by the string literal +"Token", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b -**Note:** If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable. +**Note:** If you want to use a different keyword in the header, such as +`Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class +variable. -If successfully authenticated, `TokenAuthentication` provides the following credentials. +If successfully authenticated, `TokenAuthentication` provides the following +credentials. * `request.user` will be a Django `User` instance. * `request.auth` will be a `rest_framework.authtoken.models.BasicToken` instance. -Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example: +Unauthenticated responses that are denied permission will result in an `HTTP +401 Unauthorized` response with an appropriate WWW-Authenticate header. For +example: WWW-Authenticate: Token -The `curl` command line tool may be useful for testing token authenticated APIs. For example: +The `curl` command line tool may be useful for testing token authenticated +APIs. For example: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' --- -**Note:** If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`. +**Note:** If you use `TokenAuthentication` in production you must ensure that +your API is only available over `https`. --- @@ -168,7 +225,8 @@ The `curl` command line tool may be useful for testing token authenticated APIs. ##### By using signals -If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal. +If you want every user to have an automatically generated Token, you can simply +catch the User's `post_save` signal. from django.conf import settings from django.db.models.signals import post_save @@ -180,9 +238,12 @@ If you want every user to have an automatically generated Token, you can simply if created: Token.objects.create(user=instance) -Note that you'll want to ensure you place this code snippet in an installed `models.py` module, or some other location that will be imported by Django on startup. +Note that you'll want to ensure you place this code snippet in an installed +`models.py` module, or some other location that will be imported by Django on +startup. -If you've already created some users, you can generate tokens for all existing users like this: +If you've already created some users, you can generate tokens for all existing +users like this: from django.contrib.auth.models import User from rest_framework.authtoken.models import Token @@ -192,7 +253,10 @@ If you've already created some users, you can generate tokens for all existing u ##### By exposing an api endpoint -When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf: +When using `TokenAuthentication`, you may want to provide a mechanism for +clients to obtain a token given the username and password. REST framework +provides a built-in view to provide this behavior. To use it, add the +`obtain_auth_token` view to your URLconf: from rest_framework.authtoken import views urlpatterns += [ @@ -201,19 +265,29 @@ When using `TokenAuthentication`, you may want to provide a mechanism for client Note that the URL part of the pattern can be whatever you want to use. -The `obtain_auth_token` view will return a JSON response when valid `username` and `password` fields are POSTed to the view using form data or JSON: +The `obtain_auth_token` view will return a JSON response when valid `username` +and `password` fields are POSTed to the view using form data or JSON: { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } -Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. If you need a customized version of the `obtain_auth_token` view, you can do so by overriding the `ObtainAuthToken` view class, and using that in your url conf instead. +Note that the default `obtain_auth_token` view explicitly uses JSON requests +and responses, rather than using default renderer and parser classes in your +settings. If you need a customized version of the `obtain_auth_token` view, +you can do so by overriding the `ObtainAuthToken` view class, and using that in +your url conf instead. -By default there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class, -and include them using the `throttle_classes` attribute. +By default there are no permissions or throttling applied to the +`obtain_auth_token` view. If you do wish to apply throttling you'll need to +override the view class, and include them using the `throttle_classes` +attribute. ##### With Django admin -It is also possible to create Tokens manually through admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`. +It is also possible to create Tokens manually through admin interface. In case +you are using a large user base, we recommend that you monkey patch the +`TokenAdmin` class to customize it to your needs, more specifically by +declaring the `user` field as `raw_field`. `your_app/admin.py`: @@ -224,35 +298,57 @@ It is also possible to create Tokens manually through admin interface. In case y ## SessionAuthentication -This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. +This authentication scheme uses Django's default session backend for +authentication. Session authentication is appropriate for AJAX clients that +are running in the same session context as your website. If successfully authenticated, `SessionAuthentication` provides the following credentials. * `request.user` will be a Django `User` instance. * `request.auth` will be `None`. -Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response. +Unauthenticated responses that are denied permission will result in an `HTTP +403 Forbidden` response. -If you're using an AJAX style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details. +If you're using an AJAX style API with SessionAuthentication, you'll need to +make sure you include a valid CSRF token for any "unsafe" HTTP method calls, +such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF +documentation][csrf-ajax] for more details. -**Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. +**Warning**: Always use Django's standard login view when creating login pages. +This will ensure your login views are properly protected. -CSRF validation in REST framework works slightly differently to standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied. +CSRF validation in REST framework works slightly differently to standard Django +due to the need to support both session and non-session based authentication to +the same views. This means that only authenticated requests require CSRF +tokens, and anonymous requests may be sent without CSRF tokens. This behaviour +is not suitable for login views, which should always have CSRF validation +applied. # Custom authentication -To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise. +To implement a custom authentication scheme, subclass `BaseAuthentication` and +override the `.authenticate(self, request)` method. The method should return a +two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise. -In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method. +In some circumstances instead of returning `None`, you may want to raise an +`AuthenticationFailed` exception from the `.authenticate()` method. Typically the approach you should take is: -* If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked. -* If authentication is attempted but fails, raise a `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes. +* If authentication is not attempted, return `None`. Any other authentication + schemes also in use will still be checked. +* If authentication is attempted but fails, raise a `AuthenticationFailed` + exception. An error response will be returned immediately, regardless of any + permissions checks, and without checking any other authentication schemes. -You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response. +You *may* also override the `.authenticate_header(self, request)` method. If +implemented, it should return a string that will be used as the value of the +`WWW-Authenticate` header in a `HTTP 401 Unauthorized` response. -If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access. +If the `.authenticate_header()` method is not overridden, the authentication +scheme will return `HTTP 403 Forbidden` responses when an unauthenticated +request is denied access. ## Example @@ -283,7 +379,11 @@ The following third party packages are also available. ## Django OAuth Toolkit -The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support, and works with Python 2.7 and Python 3.3+. The package is maintained by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**. +The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 +support, and works with Python 2.7 and Python 3.3+. The package is maintained +by [Evonove][evonove] and uses the excellent [OAuthLib][oauthlib]. The package +is well documented, and well supported and is currently our **recommended +package for OAuth 2.0 support**. #### Installation & configuration @@ -308,9 +408,11 @@ For more details see the [Django REST framework - Getting started][django-oauth- ## Django REST framework OAuth -The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework. +The [Django REST framework OAuth][django-rest-framework-oauth] package provides +both OAuth1 and OAuth2 support for REST framework. -This package was previously included directly in REST framework but is now supported and maintained as a third party package. +This package was previously included directly in REST framework but is now +supported and maintained as a third party package. #### Installation & configuration @@ -318,43 +420,86 @@ Install the package using `pip`. pip install djangorestframework-oauth -For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions]. +For details on configuration and usage see the Django REST framework OAuth +documentation for [authentication][django-rest-framework-oauth-authentication] +and [permissions][django-rest-framework-oauth-permissions]. ## Digest Authentication -HTTP digest authentication is a widely implemented scheme that was intended to replace HTTP basic authentication, and which provides a simple encrypted authentication mechanism. [Juan Riaza][juanriaza] maintains the [djangorestframework-digestauth][djangorestframework-digestauth] package which provides HTTP digest authentication support for REST framework. +HTTP digest authentication is a widely implemented scheme that was intended to +replace HTTP basic authentication, and which provides a simple encrypted +authentication mechanism. [Juan Riaza][juanriaza] maintains the +[djangorestframework-digestauth][djangorestframework-digestauth] package which +provides HTTP digest authentication support for REST framework. ## Django OAuth2 Consumer -The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is another package that provides [OAuth 2.0 support for REST framework][doac-rest-framework]. The package includes token scoping permissions on tokens, which allows finer-grained access to your API. +The [Django OAuth2 Consumer][doac] library from [Rediker Software][rediker] is +another package that provides [OAuth 2.0 support for REST +framework][doac-rest-framework]. The package includes token scoping +permissions on tokens, which allows finer-grained access to your API. ## JSON Web Token Authentication -JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. [Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] package which provides a JWT Authentication class as well as a mechanism for clients to obtain a JWT given the username and password. +JSON Web Token is a fairly new standard which can be used for token-based +authentication. Unlike the built-in TokenAuthentication scheme, JWT +Authentication doesn't need to use a database to validate a token. +[Blimp][blimp] maintains the [djangorestframework-jwt][djangorestframework-jwt] +package which provides a JWT Authentication class as well as a mechanism for +clients to obtain a JWT given the username and password. ## Hawk HTTP Authentication -The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]). +The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let +you work with [Hawk][hawk] signed requests and responses in your API. +[Hawk][hawk] lets two parties securely communicate with each other using +messages signed by a shared key. It is based on [HTTP MAC access +authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]). ## HTTP Signature Authentication -HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] package which provides an easy to use HTTP Signature Authentication mechanism. +HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a +way to achieve origin authentication and message integrity for HTTP messages. +Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by +many of its services, it permits stateless, per-request authentication. [Elvio +Toccalino][etoccalino] maintains the +[djangorestframework-httpsignature][djangorestframework-httpsignature] package +which provides an easy to use HTTP Signature Authentication mechanism. ## Djoser -[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and it uses token based authentication. This is a ready to use REST implementation of Django authentication system. +[Djoser][djoser] library provides a set of views to handle basic actions such +as registration, login, logout, password reset and account activation. The +package works with a custom user model and it uses token based authentication. +This is a ready to use REST implementation of Django authentication system. ## django-rest-auth -[Django-rest-auth][django-rest-auth] library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management. +[Django-rest-auth][django-rest-auth] library provides a set of REST API +endpoints for registration, authentication (including social media +authentication), password reset, retrieve and update user details, etc. By +having these API endpoints, your client apps such as AngularJS, iOS, Android, +and others can communicate to your Django backend site independently via REST +APIs for user management. ## django-rest-framework-social-oauth2 -[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] library provides an easy way to integrate social plugins (facebook, twitter, google, etc.) to your authentication system and an easy oauth2 setup. With this library, you will be able to authenticate users based on external tokens (e.g. facebook access token), convert these tokens to "in-house" oauth2 tokens and use and generate oauth2 tokens to authenticate your users. +[Django-rest-framework-social-oauth2][django-rest-framework-social-oauth2] +library provides an easy way to integrate social plugins (facebook, twitter, +google, etc.) to your authentication system and an easy oauth2 setup. With this +library, you will be able to authenticate users based on external tokens (e.g. +facebook access token), convert these tokens to "in-house" oauth2 tokens and +use and generate oauth2 tokens to authenticate your users. ## django-rest-knox -[Django-rest-knox][django-rest-knox] library provides models and views to handle token based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into). +[Django-rest-knox][django-rest-knox] library provides models and views to +handle token based authentication in a more secure and extensible way than the +built-in TokenAuthentication scheme - with Single Page Applications and Mobile +clients in mind. It provides per-client tokens, and views to generate them when +provided some other authentication (usually basic authentication), to delete +the token (providing a server enforced logout) and to delete all tokens (logs +out all clients that a user is logged into). [cite]: http://jacobian.org/writing/rest-worst-practices/ [http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md index bd408feba..fde33f4f6 100644 --- a/docs/api-guide/content-negotiation.md +++ b/docs/api-guide/content-negotiation.md @@ -2,20 +2,27 @@ source: negotiation.py # Content negotiation -> HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available. +> HTTP has provisions for several mechanisms for "content negotiation" - the +> process of selecting the best representation for a given response when there +> are multiple representations available. > > — [RFC 2616][cite], Fielding et al. [cite]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html -Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences. +Content negotiation is the process of selecting one of multiple possible +representations to return to a client, based on client or server preferences. ## Determining the accepted renderer -REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's `Accept:` header. The style used is partly client-driven, and partly server-driven. +REST framework uses a simple style of content negotiation to determine which +media type should be returned to a client, based on the available renderers, +the priorities of each of those renderers, and the client's `Accept:` header. +The style used is partly client-driven, and partly server-driven. 1. More specific media types are given preference to less specific media types. -2. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view. +2. If multiple media types have the same specificity, then preference is given + to based on the ordering of the renderers configured for the given view. For example, given the following `Accept` header: @@ -27,27 +34,41 @@ The priorities for each of the given media types would be: * `application/json`, `application/yaml` and `text/html` * `*/*` -If the requested view was only configured with renderers for `YAML` and `HTML`, then REST framework would select whichever renderer was listed first in the `renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting. +If the requested view was only configured with renderers for `YAML` and `HTML`, +then REST framework would select whichever renderer was listed first in the +`renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting. For more information on the `HTTP Accept` header, see [RFC 2616][accept-header] --- -**Note**: "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation. +**Note**: "q" values are not taken into account by REST framework when +determining preference. The use of "q" values negatively impacts caching, and +in the author's opinion they are an unnecessary and overcomplicated approach to +content negotiation. -This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences. +This is a valid approach as the HTTP spec deliberately underspecifies how a +server should weight server-based preferences against client-based preferences. --- # Custom content negotiation -It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override `BaseContentNegotiation`. +It's unlikely that you'll want to provide a custom content negotiation scheme +for REST framework, but you can do so if needed. To implement a custom content + negotiation scheme override `BaseContentNegotiation`. -REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the `.select_parser(request, parsers)` and `.select_renderer(request, renderers, format_suffix)` methods. +REST framework's content negotiation classes handle selection of both the +appropriate parser for the request, and the appropriate renderer for the +response, so you should implement both the `.select_parser(request, parsers)` +and `.select_renderer(request, renderers, format_suffix)` methods. -The `select_parser()` method should return one of the parser instances from the list of available parsers, or `None` if none of the parsers can handle the incoming request. +The `select_parser()` method should return one of the parser instances from the +list of available parsers, or `None` if none of the parsers can handle the +incoming request. -The `select_renderer()` method should return a two-tuple of (renderer instance, media type), or raise a `NotAcceptable` exception. +The `select_renderer()` method should return a two-tuple of (renderer instance, +media type), or raise a `NotAcceptable` exception. ## Example @@ -71,13 +92,16 @@ request when selecting the appropriate parser or renderer. ## Setting the content negotiation -The default content negotiation class may be set globally, using the `DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following settings would use our example `IgnoreClientContentNegotiation` class. +The default content negotiation class may be set globally, using the +`DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following +settings would use our example `IgnoreClientContentNegotiation` class. REST_FRAMEWORK = { 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation', } -You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views. +You can also set the content negotiation used for an individual view, or +viewset, using the `APIView` class-based views. from myapp.negotiation import IgnoreClientContentNegotiation from rest_framework.response import Response diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 3e4b3e8be..400998426 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -2,13 +2,15 @@ source: exceptions.py # Exceptions -> Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure. +> Exceptions… allow error handling to be organized cleanly in a central or +> high-level place within the program structure. > > — Doug Hellmann, [Python Exception Handling Techniques][cite] ## Exception handling in REST framework views -REST framework's views handle various exceptions, and deal with returning appropriate error responses. +REST framework's views handle various exceptions, and deal with returning +appropriate error responses. The handled exceptions are: @@ -16,7 +18,9 @@ The handled exceptions are: * Django's `Http404` exception. * Django's `PermissionDenied` exception. -In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error. +In each case, REST framework will return a response with an appropriate status +code and content-type. The body of the response will include any additional +details regarding the nature of the error. Most error responses will include a key `detail` in the body of the response. @@ -25,7 +29,8 @@ For example, the following request: DELETE http://api.example.com/foo/bar HTTP/1.1 Accept: application/json -Might receive an error response indicating that the `DELETE` method is not allowed on that resource: +Might receive an error response indicating that the `DELETE` method is not +allowed on that resource: HTTP/1.1 405 Method Not Allowed Content-Type: application/json @@ -33,7 +38,10 @@ Might receive an error response indicating that the `DELETE` method is not allow {"detail": "Method 'DELETE' not allowed."} -Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting. +Validation errors are handled slightly differently, and will include the field +names as the keys in the response. If the validation error was not specific to +a particular field then it will use the "non_field_errors" key, or whatever +string value has been set for the `NON_FIELD_ERRORS_KEY` setting. Any example validation error might look like this: @@ -45,11 +53,19 @@ Any example validation error might look like this: ## Custom exception handling -You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. +You can implement custom exception handling by creating a handler function that +converts exceptions raised in your API views into response objects. This +allows you to control the style of error responses used by your API. -The function must take a pair of arguments, this first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. +The function must take a pair of arguments, this first is the exception to be +handled, and the second is a dictionary containing any extra context such as +the view currently being handled. The exception handler function should either +return a `Response` object, or return `None` if the exception cannot be +handled. If the handler returns `None` then the exception will be re-raised +and Django will return a standard HTTP 500 'server error' response. -For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: +For example, you might want to ensure that all error responses include the HTTP +status code in the body of the response, like so: HTTP/1.1 405 Method Not Allowed Content-Type: application/json @@ -57,7 +73,8 @@ For example, you might want to ensure that all error responses include the HTTP {"status_code": 405, "detail": "Method 'DELETE' not allowed."} -In order to alter the style of the response, you could write the following custom exception handler: +In order to alter the style of the response, you could write the following +custom exception handler: from rest_framework.views import exception_handler @@ -72,21 +89,28 @@ In order to alter the style of the response, you could write the following custo return response -The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as `context['view']`. +The context argument is not used by the default handler, but can be useful if +the exception handler needs further information such as the view currently +being handled, which can be accessed as `context['view']`. -The exception handler must also be configured in your settings, using the `EXCEPTION_HANDLER` setting key. For example: +The exception handler must also be configured in your settings, using the +`EXCEPTION_HANDLER` setting key. For example: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler' } -If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard exception handler provided by REST framework: +If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard +exception handler provided by REST framework: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' } -Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the generic views when serializer validation fails. +Note that the exception handler will only be called for responses generated by +raised exceptions. It will not be used for any responses returned directly by +the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the +generic views when serializer validation fails. --- @@ -96,11 +120,15 @@ Note that the exception handler will only be called for responses generated by r **Signature:** `APIException()` -The **base class** for all exceptions raised inside an `APIView` class or `@api_view`. +The **base class** for all exceptions raised inside an `APIView` class or +`@api_view`. -To provide a custom exception, subclass `APIException` and set the `.status_code` and `.default_detail` properties on the class. +To provide a custom exception, subclass `APIException` and set the +`.status_code` and `.default_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: +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 @@ -114,7 +142,8 @@ For example, if your API relies on a third party service that may sometimes be u Raised if the request contains malformed data when accessing `request.data`. -By default this exception results in a response with the HTTP status code "400 Bad Request". +By default this exception results in a response with the HTTP status code "400 +Bad Request". ## AuthenticationFailed @@ -122,7 +151,10 @@ By default this exception results in a response with the HTTP status code "400 B Raised when an incoming request includes incorrect authentication. -By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details. +By default this exception results in a response with the HTTP status code "401 +Unauthenticated", but it may also result in a "403 Forbidden" response, +depending on the authentication scheme in use. See the [authentication +documentation][authentication] for more details. ## NotAuthenticated @@ -130,7 +162,10 @@ By default this exception results in a response with the HTTP status code "401 U Raised when an unauthenticated request fails the permission checks. -By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details. +By default this exception results in a response with the HTTP status code "401 +Unauthenticated", but it may also result in a "403 Forbidden" response, +depending on the authentication scheme in use. See the [authentication +documentation][authentication] for more details. ## PermissionDenied @@ -138,15 +173,18 @@ By default this exception results in a response with the HTTP status code "401 U Raised when an authenticated request fails the permission checks. -By default this exception results in a response with the HTTP status code "403 Forbidden". +By default this exception results in a response with the HTTP status code "403 +Forbidden". ## NotFound **Signature:** `NotFound(detail=None)` -Raised when a resource does not exists at the given URL. This exception is equivalent to the standard `Http404` Django exception. +Raised when a resource does not exists at the given URL. This exception is +equivalent to the standard `Http404` Django exception. -By default this exception results in a response with the HTTP status code "404 Not Found". +By default this exception results in a response with the HTTP status code "404 +Not Found". ## MethodNotAllowed @@ -160,17 +198,21 @@ By default this exception results in a response with the HTTP status code "405 M **Signature:** `NotAcceptable(detail=None)` -Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers. +Raised when an incoming request occurs with an `Accept` header that cannot be +satisfied by any of the available renderers. -By default this exception results in a response with the HTTP status code "406 Not Acceptable". +By default this exception results in a response with the HTTP status code "406 +Not Acceptable". ## UnsupportedMediaType **Signature:** `UnsupportedMediaType(media_type, detail=None)` -Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`. +Raised if there are no parsers that can handle the content type of the request +data when accessing `request.data`. -By default this exception results in a response with the HTTP status code "415 Unsupported Media Type". +By default this exception results in a response with the HTTP status code "415 +Unsupported Media Type". ## Throttled @@ -178,7 +220,8 @@ By default this exception results in a response with the HTTP status code "415 U Raised when an incoming request fails the throttling checks. -By default this exception results in a response with the HTTP status code "429 Too Many Requests". +By default this exception results in a response with the HTTP status code "429 +Too Many Requests". ## ValidationError @@ -187,16 +230,25 @@ By default this exception results in a response with the HTTP status code "429 T The `ValidationError` exception is slightly different from the other `APIException` classes: * The `detail` argument is mandatory, not optional. -* The `detail` argument may be a list or dictionary of error details, and may also be a nested data structure. -* By convention you should import the serializers module and use a fully qualified `ValidationError` style, in order to differentiate it from Django's built-in validation error. For example. `raise serializers.ValidationError('This field must be an integer value.')` +* The `detail` argument may be a list or dictionary of error details, and may + also be a nested data structure. +* By convention you should import the serializers module and use a fully + qualified `ValidationError` style, in order to differentiate it from Django's + built-in validation error. For example. `raise + serializers.ValidationError('This field must be an integer value.')` -The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument: +The `ValidationError` class should be used for serializer and field validation, +and by validator classes. It is also raised when calling `serializer.is_valid` +with the `raise_exception` keyword argument: serializer.is_valid(raise_exception=True) -The generic views use the `raise_exception=True` flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. +The generic views use the `raise_exception=True` flag, which means that you can +override the style of validation error responses globally in your API. To do +so, use a custom exception handler, as described above. -By default this exception results in a response with the HTTP status code "400 Bad Request". +By default this exception results in a response with the HTTP status code "400 +Bad Request". [cite]: http://www.doughellmann.com/articles/how-tos/python-exception-handling/index.html [authentication]: authentication.md diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index f986f1508..9b52b6150 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -2,72 +2,108 @@ source: fields.py # Serializer fields -> Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format. +> Each field in a Form class is responsible not only for validating data, but +> also for "cleaning" it — normalizing it to a consistent format. > > — [Django documentation][cite] -Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects. +Serializer fields handle converting between primitive values and internal +datatypes. They also deal with validating input values, as well as retrieving +and setting the values from their parent objects. --- -**Note:** The serializer fields are declared in `fields.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`. +**Note:** The serializer fields are declared in `fields.py`, but by convention +you should import them using `from rest_framework import serializers` and refer +to fields as `serializers.`. --- ## Core arguments -Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: +Each serializer field class constructor takes at least these arguments. Some +Field classes take additional, field-specific arguments, but the following +should always be accepted: ### `read_only` -Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. +Read-only fields are included in the API output, but should not be included in +the input during create or update operations. Any 'read_only' fields that are +incorrectly included in the serializer input will be ignored. -Set this to `True` to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. +Set this to `True` to ensure that the field is used when serializing a +representation, but is not used when creating or updating an instance during +deserialization. Defaults to `False` ### `write_only` -Set this to `True` to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. +Set this to `True` to ensure that the field may be used when updating or +creating an instance, but is not included when serializing the representation. Defaults to `False` ### `required` -Normally an error will be raised if a field is not supplied during deserialization. -Set to false if this field is not required to be present during deserialization. +Normally an error will be raised if a field is not supplied during +deserialization. Set to false if this field is not required to be present +during deserialization. -Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. +Setting this to `False` also allows the object attribute or dictionary key to +be omitted from output when serializing the instance. If the key is not present +it will simply not be included in the output representation. Defaults to `True`. ### `allow_null` -Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value. +Normally an error will be raised if `None` is passed to a serializer field. Set +this keyword argument to `True` if `None` should be considered a valid value. Defaults to `False` ### `default` -If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. +If set, this gives the default value that will be used for the field if no +input value is supplied. If not set the default behaviour is to not populate +the attribute at all. -The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. +The `default` is not applied during partial update operations. In the partial +update case only fields that are provided in the incoming data will have a +validated value returned. -May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `set_context` method, that will be called each time before getting the value with the field instance as only argument. This works the same way as for [validators](validators.md#using-set_context). +May be set to a function or other callable, in which case the value will be +evaluated each time it is used. When called, it will receive no arguments. If +the callable has a `set_context` method, that will be called each time before +getting the value with the field instance as only argument. This works the same +way as for [validators](validators.md#using-set_context). -Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error. +Note that setting a `default` value implies that the field is not required. +Including both the `default` and `required` keyword arguments is invalid and +will raise an error. ### `source` -The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. +The name of the attribute that will be used to populate the field. May be a +method that only takes a `self` argument, such as +`URLField(source='get_absolute_url')`, or may use dotted notation to traverse +attributes, such as `EmailField(source='user.email')`. -The value `source='*'` has a special meaning, and is used to indicate that the entire object should be passed through to the field. This can be useful for creating nested representations, or for fields which require access to the complete object in order to determine the output representation. +The value `source='*'` has a special meaning, and is used to indicate that the +entire object should be passed through to the field. This can be useful for +creating nested representations, or for fields which require access to the +complete object in order to determine the output representation. Defaults to the name of the field. ### `validators` -A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise `serializers.ValidationError`, but Django's built-in `ValidationError` is also supported for compatibility with validators defined in the Django codebase or third party Django packages. +A list of validator functions which should be applied to the incoming field +input, and which either raise a validation error or simply return. Validator +functions should typically raise `serializers.ValidationError`, but Django's +built-in `ValidationError` is also supported for compatibility with validators +defined in the Django codebase or third party Django packages. ### `error_messages` @@ -75,16 +111,19 @@ A dictionary of error codes to error messages. ### `label` -A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. +A short text string that may be used as the name of the field in HTML form +fields or other descriptive elements. ### `help_text` -A text string that may be used as a description of the field in HTML form fields or other descriptive elements. +A text string that may be used as a description of the field in HTML form +fields or other descriptive elements. ### `initial` -A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as -you may do with any regular Django `Field`: +A value that should be used for pre-populating the value of HTML form fields. +You may pass a callable to it, just as you may do with any regular Django +`Field`: import datetime from rest_framework import serializers @@ -93,7 +132,8 @@ you may do with any regular Django `Field`: ### `style` -A dictionary of key-value pairs that can be used to control how renderers should render the field. +A dictionary of key-value pairs that can be used to control how renderers +should render the field. Two examples here are `'input_type'` and `'base_template'`: @@ -118,7 +158,11 @@ For more details see the [HTML & Forms][html-and-forms] documentation. A boolean representation. -When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. +When using HTML encoded form input be aware that omitting a value will always +be treated as setting a field to `False`, even if it has a `default=True` +option specified. This is because HTML checkbox inputs represent the unchecked +state by omitting the value, so REST framework treats omission as if it is an +empty checkbox input. Corresponds to `django.db.models.fields.BooleanField`. @@ -138,18 +182,30 @@ Corresponds to `django.db.models.fields.NullBooleanField`. ## CharField -A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`. +A text representation. Optionally validates the text to be shorter than +`max_length` and longer than `min_length`. -Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`. +Corresponds to `django.db.models.fields.CharField` or +`django.db.models.fields.TextField`. -**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)` +**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, +trim_whitespace=True)` -- `max_length` - Validates that the input contains no more than this number of characters. -- `min_length` - Validates that the input contains no fewer than this number of characters. -- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. -- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`. +- `max_length` - Validates that the input contains no more than this number of + characters. +- `min_length` - Validates that the input contains no fewer than this number of + characters. +- `allow_blank` - If set to `True` then the empty string should be considered a + valid value. If set to `False` then the empty string is considered invalid + and will raise a validation error. Defaults to `False`. +- `trim_whitespace` - If set to `True` then leading and trailing whitespace is + trimmed. Defaults to `True`. -The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. +The `allow_null` option is also available for string fields, although its usage +is discouraged in favor of `allow_blank`. It is valid to set both +`allow_blank=True` and `allow_null=True`, but doing so means that there will be +two differing types of empty value permissible for string representations, +which can lead to data inconsistencies and subtle application bugs. ## EmailField @@ -161,13 +217,16 @@ Corresponds to `django.db.models.fields.EmailField` ## RegexField -A text representation, that validates the given value matches against a certain regular expression. +A text representation, that validates the given value matches against a certain +regular expression. Corresponds to `django.forms.fields.RegexField`. -**Signature:** `RegexField(regex, max_length=None, min_length=None, allow_blank=False)` +**Signature:** `RegexField(regex, max_length=None, min_length=None, +allow_blank=False)` -The mandatory `regex` argument may either be a string, or a compiled python regular expression object. +The mandatory `regex` argument may either be a string, or a compiled python +regular expression object. Uses Django's `django.core.validators.RegexValidator` for validation. @@ -181,15 +240,19 @@ Corresponds to `django.db.models.fields.SlugField`. ## URLField -A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http:///`. +A `RegexField` that validates the input against a URL matching pattern. Expects +fully qualified URLs of the form `http:///`. -Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. +Corresponds to `django.db.models.fields.URLField`. Uses Django's +`django.core.validators.URLValidator` for validation. **Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)` ## UUIDField -A field that ensures the input is a valid UUID string. The `to_internal_value` method will return a `uuid.UUID` instance. On output the field will return a string in the canonical hyphenated format, for example: +A field that ensures the input is a valid UUID string. The `to_internal_value` +method will return a `uuid.UUID` instance. On output the field will return a +string in the canonical hyphenated format, for example: "de305d54-75b4-431b-adb2-eb6b9e546013" @@ -210,11 +273,16 @@ Corresponds to `django.forms.fields.FilePathField`. **Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)` -- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice. -- `match` - A regular expression, as a string, that FilePathField will use to filter filenames. -- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`. -- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`. -- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. +- `path` - The absolute filesystem path to a directory from which this + FilePathField should get its choice. +- `match` - A regular expression, as a string, that FilePathField will use to + filter filenames. +- `recursive` - Specifies whether all subdirectories of path should be + included. Default is `False`. +- `allow_files` - Specifies whether files in the specified location should be + included. Default is `True`. Either this or `allow_folders` must be `True`. +- `allow_folders` - Specifies whether folders in the specified location should + be included. Default is `False`. Either this or `allow_files` must be `True`. ## IPAddressField @@ -224,8 +292,11 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen **Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)` -- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. -- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. +- `protocol` Limits valid inputs to the specified protocol. Accepted values are + 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. +- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this + option is enabled that address would be unpacked to 192.0.2.1. Default is + disabled. Can only be used when protocol is set to 'both'. --- @@ -235,7 +306,10 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen An integer representation. -Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`. +Corresponds to `django.db.models.fields.IntegerField`, +`django.db.models.fields.SmallIntegerField`, +`django.db.models.fields.PositiveIntegerField` and +`django.db.models.fields.PositiveSmallIntegerField`. **Signature**: `IntegerField(max_value=None, min_value=None)` @@ -261,12 +335,21 @@ Corresponds to `django.db.models.fields.DecimalField`. **Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)` -- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places. +- `max_digits` The maximum number of digits allowed in the number. Note that + this number must be greater than or equal to decimal_places. - `decimal_places` The number of decimal places to store with the number. -- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`. +- `coerce_to_string` Set to `True` if string values should be returned for the + representation, or `False` if `Decimal` objects should be returned. Defaults + to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will + be `True` unless overridden. If `Decimal` objects are returned by the + serializer, then the final output format will be determined by the renderer. + Note that setting `localize` will force the value to `True`. - `max_value` Validate that the number provided is no greater than this value. - `min_value` Validate that the number provided is no less than this value. -- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file. +- `localize` Set to `True` to enable localization of input and output based on + the current locale. This will also force `coerce_to_string` to `True`. + Defaults to `False`. Note that data formatting is enabled if you have set + `USE_L10N=True` in your settings file. #### Example usage @@ -294,22 +377,41 @@ Corresponds to `django.db.models.fields.DateTimeField`. **Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None)` -* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer. -* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. +* `format` - A string representing the output format. If not specified, this + defaults to the same value as the `DATETIME_FORMAT` settings key, which will + be `'iso-8601'` unless set. Setting to a format string indicates that + `to_representation` return values should be coerced to string output. Format + strings are described below. Setting this value to `None` indicates that + Python `datetime` objects should be returned by `to_representation`. In this + case the datetime encoding will be determined by the renderer. +* `input_formats` - A list of strings representing the input formats which may + be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` + setting will be used, which defaults to `['iso-8601']`. #### `DateTimeField` format strings. -Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`) +Format strings may either be [Python strftime formats][strftime] which +explicitly specify the format, or the special string `'iso-8601'`, which +indicates that [ISO 8601][iso8601] style datetimes should be used. (eg +`'2013-01-29T12:34:56.000000Z'`) -When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will determined by the renderer class. +When a value of `None` is used for the format `datetime` objects will be +returned by `to_representation` and the final output representation will +determined by the renderer class. -In the case of JSON this means the default datetime representation uses the [ECMA 262 date time string specification][ecma262]. This is a subset of ISO 8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC timezone, for example: `2013-01-29T12:34:56.123Z`. +In the case of JSON this means the default datetime representation uses the +[ECMA 262 date time string specification][ecma262]. This is a subset of ISO +8601 which uses millisecond precision, and includes the 'Z' suffix for the UTC +timezone, for example: `2013-01-29T12:34:56.123Z`. #### `auto_now` and `auto_now_add` model fields. -When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default. +When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any +model fields with `auto_now=True` or `auto_now_add=True` will use serializer +fields that are `read_only=True` by default. -If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example: +If you want to override this behavior, you'll need to declare the +`DateTimeField` explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer): created = serializers.DateTimeField() @@ -325,12 +427,23 @@ Corresponds to `django.db.models.fields.DateField` **Signature:** `DateField(format=api_settings.DATE_FORMAT, input_formats=None)` -* `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer. -* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. +* `format` - A string representing the output format. If not specified, this + defaults to the same value as the `DATE_FORMAT` settings key, which will be + `'iso-8601'` unless set. Setting to a format string indicates that + `to_representation` return values should be coerced to string output. Format + strings are described below. Setting this value to `None` indicates that + Python `date` objects should be returned by `to_representation`. In this case + the date encoding will be determined by the renderer. +* `input_formats` - A list of strings representing the input formats which may + be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` + setting will be used, which defaults to `['iso-8601']`. #### `DateField` format strings -Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) +Format strings may either be [Python strftime formats][strftime] which +explicitly specify the format, or the special string `'iso-8601'`, which +indicates that [ISO 8601][iso8601] style dates should be used. (eg +`'2013-01-29'`) ## TimeField @@ -340,12 +453,23 @@ Corresponds to `django.db.models.fields.TimeField` **Signature:** `TimeField(format=api_settings.TIME_FORMAT, input_formats=None)` -* `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer. -* `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. +* `format` - A string representing the output format. If not specified, this + defaults to the same value as the `TIME_FORMAT` settings key, which will be + `'iso-8601'` unless set. Setting to a format string indicates that + `to_representation` return values should be coerced to string output. Format + strings are described below. Setting this value to `None` indicates that + Python `time` objects should be returned by `to_representation`. In this case + the time encoding will be determined by the renderer. +* `input_formats` - A list of strings representing the input formats which may + be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` + setting will be used, which defaults to `['iso-8601']`. #### `TimeField` format strings -Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) +Format strings may either be [Python strftime formats][strftime] which +explicitly specify the format, or the special string `'iso-8601'`, which +indicates that [ISO 8601][iso8601] style times should be used. (eg +`'12:34:56.000000'`) ## DurationField @@ -371,25 +495,49 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding **Signature:** `ChoiceField(choices)` -- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. -- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. -- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. -- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` +- `choices` - A list of valid values, or a list of `(key, display_name)` + tuples. +- `allow_blank` - If set to `True` then the empty string should be considered a + valid value. If set to `False` then the empty string is considered invalid + and will raise a validation error. Defaults to `False`. +- `html_cutoff` - If set this will be the maximum number of choices that will + be displayed by a HTML select drop down. Can be used to ensure that + automatically generated ChoiceFields with very large possible selections do + not prevent a template from rendering. Defaults to `None`. +- `html_cutoff_text` - If set this will display a textual indicator if the + maximum number of items have been cutoff in an HTML select drop down. + Defaults to `"More than {count} items…"` -Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. +Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, +although it is highly recommended that you only use one and not both. +`allow_blank` should be preferred for textual choices, and `allow_null` should +be preferred for numeric or other non-textual choices. ## MultipleChoiceField -A field that can accept a set of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_value` returns a `set` containing the selected values. +A field that can accept a set of zero, one or many values, chosen from a +limited set of choices. Takes a single mandatory argument. `to_internal_value` +returns a `set` containing the selected values. **Signature:** `MultipleChoiceField(choices)` -- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. -- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. -- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. -- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` +- `choices` - A list of valid values, or a list of `(key, display_name)` + tuples. +- `allow_blank` - If set to `True` then the empty string should be considered a + valid value. If set to `False` then the empty string is considered invalid + and will raise a validation error. Defaults to `False`. +- `html_cutoff` - If set this will be the maximum number of choices that will + be displayed by a HTML select drop down. Can be used to ensure that + automatically generated ChoiceFields with very large possible selections do + not prevent a template from rendering. Defaults to `None`. +- `html_cutoff_text` - If set this will display a textual indicator if the + maximum number of items have been cutoff in an HTML select drop down. + Defaults to `"More than {count} items…"` -As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. +As with `ChoiceField`, both the `allow_blank` and `allow_null` options are +valid, although it is highly recommended that you only use one and not both. +`allow_blank` should be preferred for textual choices, and `allow_null` should +be preferred for numeric or other non-textual choices. --- @@ -397,8 +545,10 @@ As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid #### Parsers and file uploads. -The `FileField` and `ImageField` classes are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads. -Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. +The `FileField` and `ImageField` classes are only suitable for use with +`MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't +support file uploads. Django's regular [FILE_UPLOAD_HANDLERS] are used for +handling uploaded files. ## FileField @@ -406,25 +556,35 @@ A file representation. Performs Django's standard FileField validation. Corresponds to `django.forms.fields.FileField`. -**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` +**Signature:** `FileField(max_length=None, allow_empty_file=False, +use_url=UPLOADED_FILES_USE_URL)` - `max_length` - Designates the maximum length for the file name. - `allow_empty_file` - Designates if empty files are allowed. -- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. +- `use_url` - If set to `True` then URL string values will be used for the + output representation. If set to `False` then filename string values will be + used for the output representation. Defaults to the value of the + `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. ## ImageField -An image representation. Validates the uploaded file content as matching a known image format. +An image representation. Validates the uploaded file content as matching a +known image format. Corresponds to `django.forms.fields.ImageField`. -**Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` +**Signature:** `ImageField(max_length=None, allow_empty_file=False, +use_url=UPLOADED_FILES_USE_URL)` - `max_length` - Designates the maximum length for the file name. - `allow_empty_file` - Designates if empty files are allowed. -- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. +- `use_url` - If set to `True` then URL string values will be used for the + output representation. If set to `False` then filename string values will be + used for the output representation. Defaults to the value of the + `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. -Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained. +Requires either the `Pillow` package or `PIL` package. The `Pillow` package is +recommended, as `PIL` is no longer actively maintained. --- @@ -436,30 +596,39 @@ A field class that validates a list of objects. **Signature**: `ListField(child)` -- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. +- `child` - A field instance that should be used for validating the objects in + the list. If this argument is not provided then objects in the list will not + be validated. -For example, to validate a list of integers you might use something like the following: +For example, to validate a list of integers you might use something like the +following: scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) -The `ListField` class also supports a declarative style that allows you to write reusable list field classes. +The `ListField` class also supports a declarative style that allows you to +write reusable list field classes. class StringListField(serializers.ListField): child = serializers.CharField() -We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it. +We can now reuse our custom `StringListField` class throughout our application, +without having to provide a `child` argument to it. ## DictField -A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values. +A field class that validates a dictionary of objects. The keys in `DictField` +are always assumed to be string values. **Signature**: `DictField(child)` -- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. +- `child` - A field instance that should be used for validating the values in + the dictionary. If this argument is not provided then values in the mapping + will not be validated. -For example, to create a field that validates a mapping of strings to strings, you would write something like this: +For example, to create a field that validates a mapping of strings to strings, +you would write something like this: document = DictField(child=CharField()) @@ -470,11 +639,14 @@ You can also use the declarative style, as with `ListField`. For example: ## JSONField -A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. +A field class that validates that the incoming data structure consists of valid +JSON primitives. In its alternate binary mode, it will represent and validate +JSON-encoded binary strings. **Signature**: `JSONField(binary)` -- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`. +- `binary` - If set to `True` then the field will output and validate a JSON + encoded string, rather than a primitive data structure. Defaults to `False`. --- @@ -484,11 +656,13 @@ A field class that validates that the incoming data structure consists of valid A field class that simply returns the value of the field without modification. -This field is used by default with `ModelSerializer` when including field names that relate to an attribute rather than a model field. +This field is used by default with `ModelSerializer` when including field names +that relate to an attribute rather than a model field. **Signature**: `ReadOnlyField()` -For example, if `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`: +For example, if `has_expired` was a property on the `Account` model, then the +following serializer would automatically generate it as a `ReadOnlyField`: class AccountSerializer(serializers.ModelSerializer): class Meta: @@ -497,37 +671,54 @@ For example, if `has_expired` was a property on the `Account` model, then the fo ## HiddenField -A field class that does not take a value based on user input, but instead takes its value from a default value or callable. +A field class that does not take a value based on user input, but instead takes +its value from a default value or callable. **Signature**: `HiddenField()` -For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following: +For example, to include a field that always provides the current time as part +of the serializer validated data, you would use the following: modified = serializers.HiddenField(default=timezone.now) -The `HiddenField` class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user. +The `HiddenField` class is usually only needed if you have some validation that +needs to run based on some pre-provided field values, but you do not want to +expose all of those fields to the end user. For further examples on `HiddenField` see the [validators](validators.md) documentation. ## ModelField -A generic field that can be tied to any arbitrary model field. The `ModelField` class delegates the task of serialization/deserialization to its associated model field. This field can be used to create serializer fields for custom model fields, without having to create a new custom serializer field. +A generic field that can be tied to any arbitrary model field. The `ModelField` +class delegates the task of serialization/deserialization to its associated +model field. This field can be used to create serializer fields for custom +model fields, without having to create a new custom serializer field. -This field is used by `ModelSerializer` to correspond to custom model field classes. +This field is used by `ModelSerializer` to correspond to custom model field +classes. **Signature:** `ModelField(model_field=)` -The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` +The `ModelField` class is generally intended for internal use, but can be used +by your API if needed. In order to properly instantiate a `ModelField`, it +must be passed a field that is attached to an instantiated model. For example: +`ModelField(model_field=MyModel()._meta.get_field('custom_field'))` ## SerializerMethodField -This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. +This is a read-only field. It gets its value by calling a method on the +serializer class it is attached to. It can be used to add any sort of data to +the serialized representation of your object. **Signature**: `SerializerMethodField(method_name=None)` -- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. +- `method_name` - The name of the method on the serializer to be called. If not + included this defaults to `get_`. -The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: +The serializer method referred to by the `method_name` argument should accept a +single argument (in addition to `self`), which is the object being serialized. +It should return whatever you want to be included in the serialized +representation of the object. For example: from django.contrib.auth.models import User from django.utils.timezone import now @@ -546,17 +737,30 @@ The serializer method referred to by the `method_name` argument should accept a # Custom fields -If you want to create a custom field, you'll need to subclass `Field` and then override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, `date`/`time`/`datetime` or `None`. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using. +If you want to create a custom field, you'll need to subclass `Field` and then +override either one or both of the `.to_representation()` and +`.to_internal_value()` methods. These two methods are used to convert between +the initial datatype, and a primitive, serializable datatype. Primitive +datatypes will typically be any of a number, string, boolean, +`date`/`time`/`datetime` or `None`. They may also be any list or dictionary +like object that only contains other primitive objects. Other types might be +supported, depending on the renderer that you are using. -The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype. +The `.to_representation()` method is called to convert the initial datatype +into a primitive, serializable datatype. -The `to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid. +The `to_internal_value()` method is called to restore a primitive datatype into +its internal python representation. This method should raise a +`serializers.ValidationError` if the data is invalid. -Note that the `WritableField` class that was present in version 2.x no longer exists. You should subclass `Field` and override `to_internal_value()` if the field supports data input. +Note that the `WritableField` class that was present in version 2.x no longer +exists. You should subclass `Field` and override `to_internal_value()` if the +field supports data input. ## Examples -Let's look at an example of serializing a class that represents an RGB color value: +Let's look at an example of serializing a class that represents an RGB color +value: class Color(object): """ @@ -579,9 +783,12 @@ Let's look at an example of serializing a class that represents an RGB color val red, green, blue = [int(col) for col in data.split(',')] return Color(red, green, blue) -By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.get_attribute()` and/or `.get_value()`. +By default field values are treated as mapping to an attribute on the object. +If you need to customize how the field value is accessed and set you need to +override `.get_attribute()` and/or `.get_value()`. -As an example, let's create a field that can be used to represent the class name of the object being serialized: +As an example, let's create a field that can be used to represent the class +name of the object being serialized: class ClassNameField(serializers.Field): def get_attribute(self, obj): @@ -616,7 +823,8 @@ To indicate invalid data, we should raise a `serializers.ValidationError`, like return Color(red, green, blue) -The `.fail()` method is a shortcut for raising `ValidationError` that takes a message string from the `error_messages` dictionary. For example: +The `.fail()` method is a shortcut for raising `ValidationError` that takes a +message string from the `error_messages` dictionary. For example: default_error_messages = { 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}', @@ -640,7 +848,8 @@ The `.fail()` method is a shortcut for raising `ValidationError` that takes a me return Color(red, green, blue) -This style keeps you error messages more cleanly separated from your code, and should be preferred. +This style keeps you error messages more cleanly separated from your code, and +should be preferred. # Third party packages @@ -648,23 +857,35 @@ The following third party packages are also available. ## DRF Compound Fields -The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. +The [drf-compound-fields][drf-compound-fields] package provides "compound" +serializer fields, such as lists of simple values, which can be described by +other fields rather than serializers with the `many=True` option. Also provided +are fields for typed dictionaries and values that can be either a specific type +or a list of items of that type. ## DRF Extra Fields -The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes. +The [drf-extra-fields][drf-extra-fields] package provides extra serializer +fields for REST framework, including `Base64ImageField` and `PointField` +classes. ## djangrestframework-recursive -the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures +the [djangorestframework-recursive][djangorestframework-recursive] package +provides a `RecursiveField` for serializing and deserializing recursive +structures ## django-rest-framework-gis -The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. +The [django-rest-framework-gis][django-rest-framework-gis] package provides +geographic addons for django rest framework like a `GeometryField` field and a +GeoJSON serializer. ## django-rest-framework-hstore -The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreField` to support [django-hstore][django-hstore] `DictionaryField` model field. +The [django-rest-framework-hstore][django-rest-framework-hstore] package +provides an `HStoreField` to support [django-hstore][django-hstore] +`DictionaryField` model field. [cite]: https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.cleaned_data [html-and-forms]: ../topics/html-and-forms.md diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 0ccd51dd3..c7b7b9e9d 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -2,19 +2,26 @@ source: filters.py # Filtering -> The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. +> The root QuerySet provided by the Manager describes all objects in the +> database table. Usually, though, you'll need to select only a subset of the +> complete set of objects. > > — [Django documentation][cite] -The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset. +The default behavior of REST framework's generic list views is to return the +entire queryset for a model manager. Often you will want your API to restrict +the items that are returned by the queryset. -The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method. +The simplest way to filter the queryset of any view that subclasses +`GenericAPIView` is to override the `.get_queryset()` method. -Overriding this method allows you to customize the queryset returned by the view in a number of different ways. +Overriding this method allows you to customize the queryset returned by the +view in a number of different ways. ## Filtering against the current user -You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned. +You might want to filter the queryset to ensure that only results relevant to +the currently authenticated user making the request are returned. You can do so by filtering based on the value of `request.user`. @@ -38,13 +45,15 @@ For example: ## Filtering against the URL -Another style of filtering might involve restricting the queryset based on some part of the URL. +Another style of filtering might involve restricting the queryset based on some +part of the URL. For example if your URL config contained an entry like this: url('^purchases/(?P.+)/$', PurchaseList.as_view()), -You could then write a view that returned a purchase queryset filtered by the username portion of the URL: +You could then write a view that returned a purchase queryset filtered by the +username portion of the URL: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer @@ -59,9 +68,12 @@ You could then write a view that returned a purchase queryset filtered by the us ## Filtering against query parameters -A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url. +A final example of filtering the initial queryset would be to determine the +initial queryset based on query parameters in the url. -We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL: +We can override `.get_queryset()` to deal with URLs such as +`http://example.com/api/purchases?username=denvercoder9`, and filter the +queryset only if the `username` parameter is included in the URL: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer @@ -81,9 +93,12 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/ # Generic Filtering -As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters. +As well as being able to override the default queryset, REST framework also +includes support for generic filtering backends that allow you to easily +construct complex searches and filters. -Generic filters can also present themselves as HTML controls in the browsable API and admin API. +Generic filters can also present themselves as HTML controls in the browsable +API and admin API. ![Filter Example](../img/filter-controls.png) @@ -110,15 +125,23 @@ using the `GenericAPIView` class-based views. ## Filtering and object lookups -Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. +Note that if a filter backend is configured for a view, then as well as being +used to filter list views, it will also be used to filter the querysets used +for returning a single object. -For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance: +For instance, given the previous example, and a product with an id of `4675`, +the following URL would either return the corresponding object, or return a 404 +response, depending on if the filtering conditions were met by the given +product instance: http://example.com/api/products/4675/?category=clothing&max_price=10.00 ## Overriding the initial queryset -Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this: +Note that you can use both an overridden `.get_queryset()` and generic +filtering together, and everything will work as expected. For example, if +`Product` had a many-to-many relationship with `User`, named `purchase`, you +might want to write a view like this: class PurchasedProductsList(generics.ListAPIView): """ @@ -139,23 +162,30 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering ## DjangoFilterBackend -The `DjangoFilterBackend` class supports highly customizable field filtering, using the [django-filter package][django-filter]. +The `DjangoFilterBackend` class supports highly customizable field filtering, +using the [django-filter package][django-filter]. To use REST framework's `DjangoFilterBackend`, first install `django-filter`. pip install django-filter -If you are using the browsable API or admin API you may also want to install `django-crispy-forms`, which will enhance the presentation of the filter forms in HTML views, by allowing them to render Bootstrap 3 HTML. +If you are using the browsable API or admin API you may also want to install +`django-crispy-forms`, which will enhance the presentation of the filter forms +in HTML views, by allowing them to render Bootstrap 3 HTML. pip install django-crispy-forms -With crispy forms installed and added to Django's `INSTALLED_APPS`, the browsable API will present a filtering control for `DjangoFilterBackend`, like so: +With crispy forms installed and added to Django's `INSTALLED_APPS`, the +browsable API will present a filtering control for `DjangoFilterBackend`, like +so: ![Django Filter](../img/django-filter.png) #### Specifying filter fields -If all you need is simple equality-based filtering, you can set a `filter_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against. +If all you need is simple equality-based filtering, you can set a +`filter_fields` attribute on the view, or viewset, listing the set of fields +you wish to filter against. class ProductList(generics.ListAPIView): queryset = Product.objects.all() @@ -213,7 +243,9 @@ This enables us to make queries like: http://example.com/api/products?manufacturer__name=foo -This is nice, but it exposes the Django's double underscore convention as part of the API. If you instead want to explicitly name the filter argument you can instead explicitly include it on the `FilterSet` class: +This is nice, but it exposes the Django's double underscore convention as part +of the API. If you instead want to explicitly name the filter argument you can +instead explicitly include it on the `FilterSet` class: import django_filters from myapp.models import Product @@ -238,21 +270,31 @@ For more details on using filter sets see the [django-filter documentation][djan **Hints & Tips** -* By default filtering is not enabled. If you want to use `DjangoFilterBackend` remember to make sure it is installed by using the `'DEFAULT_FILTER_BACKENDS'` setting. -* When using boolean fields, you should use the values `True` and `False` in the URL query parameters, rather than `0`, `1`, `true` or `false`. (The allowed boolean values are currently hardwired in Django's [NullBooleanSelect implementation][nullbooleanselect].) -* `django-filter` supports filtering across relationships, using Django's double-underscore syntax. +* By default filtering is not enabled. If you want to use + `DjangoFilterBackend` remember to make sure it is installed by using the + `'DEFAULT_FILTER_BACKENDS'` setting. +* When using boolean fields, you should use the values `True` and `False` in + the URL query parameters, rather than `0`, `1`, `true` or `false`. (The + allowed boolean values are currently hardwired in Django's [NullBooleanSelect + implementation][nullbooleanselect].) +* `django-filter` supports filtering across relationships, using Django's + double-underscore syntax. --- ## SearchFilter -The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin]. +The `SearchFilter` class supports simple single query parameter based +searching, and is based on the [Django admin's search +functionality][search-django-admin]. When in use, the browsable API will include a `SearchFilter` control: ![Search Filter](../img/search-filter.png) -The `SearchFilter` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`. +The `SearchFilter` class will only be applied if the view has a `search_fields` +attribute set. The `search_fields` attribute should be a list of names of text +type fields on the model, such as `CharField` or `TextField`. class UserListView(generics.ListAPIView): queryset = User.objects.all() @@ -260,17 +302,23 @@ The `SearchFilter` class will only be applied if the view has a `search_fields` filter_backends = (filters.SearchFilter,) search_fields = ('username', 'email') -This will allow the client to filter the items in the list by making queries such as: +This will allow the client to filter the items in the list by making queries +such as: http://example.com/api/users?search=russell -You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: +You can also perform a related lookup on a ForeignKey or ManyToManyField with +the lookup API double-underscore notation: search_fields = ('username', 'email', 'profile__profession') -By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. +By default, searches will use case-insensitive partial matches. The search +parameter may contain multiple search terms, which should be whitespace and/or +comma separated. If multiple search terms are used then objects will be +returned in the list only if all the provided terms are matched. -The search behavior may be restricted by prepending various characters to the `search_fields`. +The search behavior may be restricted by prepending various characters to the +`search_fields`. * '^' Starts-with search. * '=' Exact matches. @@ -309,7 +357,9 @@ Multiple orderings may also be specified: ### Specifying which fields may be ordered against -It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so: +It's recommended that you explicitly specify which fields the API should +allowing in the ordering filter. You can do this by setting an +`ordering_fields` attribute on the view, like so: class UserListView(generics.ListAPIView): queryset = User.objects.all() @@ -317,11 +367,17 @@ It's recommended that you explicitly specify which fields the API should allowin filter_backends = (filters.OrderingFilter,) ordering_fields = ('username', 'email') -This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data. +This helps prevent unexpected data leakage, such as allowing users to order +against a password hash field or other sensitive data. -If you *don't* specify an `ordering_fields` attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the `serializer_class` attribute. +If you *don't* specify an `ordering_fields` attribute on the view, the filter +class will default to allowing the user to filter on any readable fields on the +serializer specified by the `serializer_class` attribute. -If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on *any* model field or queryset aggregate, by using the special value `'__all__'`. +If you are confident that the queryset being used by the view doesn't contain +any sensitive data, you can also explicitly specify that a view should allow +ordering on *any* model field or queryset aggregate, by using the special value +`'__all__'`. class BookingsListView(generics.ListAPIView): queryset = Booking.objects.all() @@ -331,9 +387,14 @@ If you are confident that the queryset being used by the view doesn't contain an ### Specifying a default ordering -If an `ordering` attribute is set on the view, this will be used as the default ordering. +If an `ordering` attribute is set on the view, this will be used as the default +ordering. -Typically you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results. +Typically you'd instead control this by setting `order_by` on the initial +queryset, but using the `ordering` parameter on the view allows you to specify +the ordering in a way that it can then be passed automatically as context to a +rendered template. This makes it possible to automatically render column +headers differently if they are being used to order the results. class UserListView(generics.ListAPIView): queryset = User.objects.all() @@ -348,11 +409,19 @@ The `ordering` attribute may be either a string or a list/tuple of strings. ## DjangoObjectPermissionsFilter -The `DjangoObjectPermissionsFilter` is intended to be used together with the [`django-guardian`][guardian] package, with custom `'view'` permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission. +The `DjangoObjectPermissionsFilter` is intended to be used together with the +[`django-guardian`][guardian] package, with custom `'view'` permissions added. +The filter will ensure that querysets only returns objects for which the user +has the appropriate view permission. -If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass `DjangoObjectPermissions` and add `'view'` permissions to the `perms_map` attribute. +If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to +add an appropriate object permissions class, to ensure that users can only +operate on instances if they have the appropriate object permissions. The +easiest way to do this is to subclass `DjangoObjectPermissions` and add +`'view'` permissions to the `perms_map` attribute. -A complete example using both `DjangoObjectPermissionsFilter` and `DjangoObjectPermissions` might look something like this. +A complete example using both `DjangoObjectPermissionsFilter` and +`DjangoObjectPermissions` might look something like this. **permissions.py**: @@ -389,11 +458,16 @@ For more information on adding `'view'` permissions for models, see the [relevan # Custom generic filtering -You can also provide your own generic filtering backend, or write an installable app for other developers to use. +You can also provide your own generic filtering backend, or write an +installable app for other developers to use. -To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset. +To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, +request, queryset, view)` method. The method should return a new, filtered +queryset. -As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user. +As well as allowing clients to perform searches and filtering, generic filter +backends can be useful for restricting which objects should be visible to any +given request or user. ## Example @@ -406,11 +480,15 @@ For example, you might need to restrict users to only being able to see objects def filter_queryset(self, request, queryset, view): return queryset.filter(owner=request.user) -We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API. +We could achieve the same behavior by overriding `get_queryset()` on the views, +but using a filter backend allows you to more easily add this restriction to +multiple views, or to apply it across the entire API. ## Customizing the interface -Generic filters may also present an interface in the browsable API. To do so you should implement a `to_html()` method which returns a rendered HTML representation of the filter. This method should have the following signature: +Generic filters may also present an interface in the browsable API. To do so +you should implement a `to_html()` method which returns a rendered HTML +representation of the filter. This method should have the following signature: `to_html(self, request, queryset, view)` @@ -422,15 +500,25 @@ The following third party packages provide additional filter implementations. ## Django REST framework filters package -The [django-rest-framework-filters package][django-rest-framework-filters] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field. +The [django-rest-framework-filters package][django-rest-framework-filters] +works together with the `DjangoFilterBackend` class, and allows you to easily +create filters across relationships, or create multiple filter lookup types for +a given field. ## Django REST framework full word search filter -The [djangorestframework-word-filter][django-rest-framework-word-search-filter] developed as alternative to `filters.SearchFilter` which will search full word in text, or exact match. +The [djangorestframework-word-filter][django-rest-framework-word-search-filter] +developed as alternative to `filters.SearchFilter` which will search full word +in text, or exact match. ## Django URL Filter -[django-url-filter][django-url-filter] provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django `QuerySet`s. +[django-url-filter][django-url-filter] provides a safe way to filter data via +human-friendly URLs. It works very similar to DRF serializers and fields in a +sense that they can be nested except they are called filtersets and filters. +That provides easy way to filter related data. Also this library is +generic-purpose so it can be used to filter other sources of data and not only +Django `QuerySet`s. [cite]: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters [django-filter]: https://github.com/alex/django-filter diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index 05dde47f2..1c05a6aef 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -7,21 +7,30 @@ used all the time. > > — Roy Fielding, [REST discuss mailing list][cite] -A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. +A common pattern for Web APIs is to use filename extensions on URLs to provide +an endpoint for a given media type. For example, +'http://example.com/api/users.json' to serve a JSON representation. -Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf. +Adding format-suffix patterns to each individual entry in the URLconf for your +API is error-prone and non-DRY, so REST framework provides a shortcut to adding +these patterns to your URLConf. ## format_suffix_patterns -**Signature**: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None) +**Signature**: format_suffix_patterns(urlpatterns, suffix_required=False, +allowed=None) -Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided. +Returns a URL pattern list which includes format suffix patterns appended to +each of the URL patterns provided. Arguments: * **urlpatterns**: Required. A URL pattern list. -* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default. -* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. +* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs + should be optional or mandatory. Defaults to `False`, meaning that suffixes + are optional by default. +* **allowed**: Optional. A list or tuple of valid format suffixes. If not + provided, a wildcard format suffix pattern will be used. Example: @@ -36,7 +45,8 @@ Example: urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) -When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example: +When using `format_suffix_patterns`, you must make sure to add the `'format'` +keyword argument to the corresponding views. For example: @api_view(('GET', 'POST')) def comment_list(request, format=None): @@ -51,13 +61,17 @@ Or with class-based views: def post(self, request, format=None): # do stuff... -The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting. +The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` +setting. -Also note that `format_suffix_patterns` does not support descending into `include` URL patterns. +Also note that `format_suffix_patterns` does not support descending into +`include` URL patterns. ### Using with `i18n_patterns` -If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example: +If using the `i18n_patterns` function provided by Django, as well as +`format_suffix_patterns` you should make sure that the `i18n_patterns` function +is applied as the final, or outermost function. For example: url patterns = [ … @@ -71,23 +85,34 @@ If using the `i18n_patterns` function provided by Django, as well as `format_suf ## Query parameter formats -An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations. +An alternative to the format suffixes is to include the requested format in a +query parameter. REST framework provides this option by default, and it is used +in the browsable API to switch between differing available representations. -To select a representation using its short format, use the `format` query parameter. For example: `http://example.com/organizations/?format=csv`. +To select a representation using its short format, use the `format` query +parameter. For example: `http://example.com/organizations/?format=csv`. -The name of this query parameter can be modified using the `URL_FORMAT_OVERRIDE` setting. Set the value to `None` to disable this behavior. +The name of this query parameter can be modified using the +`URL_FORMAT_OVERRIDE` setting. Set the value to `None` to disable this +behavior. --- ## Accept headers vs. format suffixes -There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead. +There seems to be a view among some of the Web community that filename +extensions are not a RESTful pattern, and that `HTTP Accept` headers should +always be used instead. -It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: +It is actually a misconception. For example, take the following quote from Roy +Fielding discussing the relative merits of query parameter media-type +indicators vs. file extension media-type indicators: -“That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2] +“That's why I always prefer extensions. Neither choice has anything to +do with REST.” — Roy Fielding, [REST discuss mailing list][cite2] -The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern. +The quote does not mention Accept headers, but it does make it clear that +format suffixes should be considered an acceptable pattern. [cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857 [cite2]: http://tech.groups.yahoo.com/group/rest-discuss/message/14844 diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index d7dc30ce1..f0182f57e 100644 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -7,15 +7,21 @@ source: mixins.py > > — [Django Documentation][cite] -One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns. +One of the key benefits of class-based views is the way they allow you to +compose bits of reusable behavior. REST framework takes advantage of this by +providing a number of pre-built views that provide for commonly used patterns. -The generic views provided by REST framework allow you to quickly build API views that map closely to your database models. +The generic views provided by REST framework allow you to quickly build API +views that map closely to your database models. -If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views. +If the generic views don't suit the needs of your API, you can drop down to +using the regular `APIView` class, or reuse the mixins and base classes used by +the generic views to compose your own set of reusable generic views. ## Examples -Typically when using the generic views, you'll override the view, and set several class attributes. +Typically when using the generic views, you'll override the view, and set +several class attributes. from django.contrib.auth.models import User from myapp.serializers import UserSerializer @@ -27,7 +33,8 @@ Typically when using the generic views, you'll override the view, and set severa serializer_class = UserSerializer permission_classes = (IsAdminUser,) -For more complex cases you might also want to override various methods on the view class. For example. +For more complex cases you might also want to override various methods on the +view class. For example. class UserList(generics.ListCreateAPIView): queryset = User.objects.all() @@ -40,7 +47,9 @@ For more complex cases you might also want to override various methods on the vi serializer = UserSerializer(queryset, many=True) return Response(serializer.data) -For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry: +For very simple cases you might want to pass through any class attributes using +the `.as_view()` method. For example, your URLconf might include something +like the following entry: url(r'^/users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list') @@ -50,9 +59,11 @@ For very simple cases you might want to pass through any class attributes using ## GenericAPIView -This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views. +This class extends REST framework's `APIView` class, adding commonly required +behavior for standard list and detail views. -Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes. +Each of the concrete generic views provided is built by combining +`GenericAPIView`, with one or more mixin classes. ### Attributes @@ -60,20 +71,38 @@ Each of the concrete generic views provided is built by combining `GenericAPIVie The following attributes control the basic view behavior. -* `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests. -* `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method. -* `lookup_field` - The model field that should be used to for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value. -* `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`. +* `queryset` - The queryset that should be used for returning objects from this + view. Typically, you must either set this attribute, or override the + `get_queryset()` method. If you are overriding a view method, it is important + that you call `get_queryset()` instead of accessing this property directly, + as `queryset` will get evaluated once, and those results will be cached for + all subsequent requests. +* `serializer_class` - The serializer class that should be used for validating + and deserializing input, and for serializing output. Typically, you must + either set this attribute, or override the `get_serializer_class()` method. +* `lookup_field` - The model field that should be used to for performing object + lookup of individual model instances. Defaults to `'pk'`. Note that when + using hyperlinked APIs you'll need to ensure that *both* the API views *and* + the serializer classes set the lookup fields if you need to use a custom + value. +* `lookup_url_kwarg` - The URL keyword argument that should be used for object + lookup. The URL conf should include a keyword argument corresponding to this + value. If unset this defaults to using the same value as `lookup_field`. **Pagination**: -The following attributes are used to control pagination when used with list views. +The following attributes are used to control pagination when used with list +views. -* `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`. +* `pagination_class` - The pagination class that should be used when paginating + list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` + setting, which is `'rest_framework.pagination.PageNumberPagination'`. **Filtering**: -* `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting. +* `filter_backends` - A list of filter backend classes that should be used for + filtering the queryset. Defaults to the same value as the + `DEFAULT_FILTER_BACKENDS` setting. ### Methods @@ -81,11 +110,16 @@ The following attributes are used to control pagination when used with list view #### `get_queryset(self)` -Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute. +Returns the queryset that should be used for list views, and that should be +used as the base for lookups in detail views. Defaults to returning the +queryset specified by the `queryset` attribute. -This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. +This method should always be used rather than accessing `self.queryset` +directly, as `self.queryset` gets evaluated only once, and those results are +cached for all subsequent requests. -May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request. +May be overridden to provide dynamic behavior, such as returning a queryset, +that is specific to the user making the request. For example: @@ -95,9 +129,11 @@ For example: #### `get_object(self)` -Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset. +Returns an object instance that should be used for detail views. Defaults to +using the `lookup_field` parameter to filter the base queryset. -May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg. +May be overridden to provide more complex behavior, such as object lookups +based on more than one URL kwarg. For example: @@ -111,13 +147,16 @@ For example: self.check_object_permissions(self.request, obj) return obj -Note that if your API doesn't include any object level permissions, you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup. +Note that if your API doesn't include any object level permissions, you may +optionally exclude the `self.check_object_permissions`, and simply return the +object from the `get_object_or_404` lookup. -#### `filter_queryset(self, queryset)` +#### `filter_queryset(self, queryset)` -Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. +Given a queryset, filter it with whichever filter backends are in use, +returning a new queryset. -For example: +For example: def filter_queryset(self, queryset): filter_backends = (CategoryFilter,) @@ -134,9 +173,12 @@ For example: #### `get_serializer_class(self)` -Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute. +Returns the class that should be used for the serializer. Defaults to +returning the `serializer_class` attribute. -May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users. +May be overridden to provide dynamic behavior, such as using different +serializers for read and write operations, or providing different serializers +to different types of users. For example: @@ -147,24 +189,32 @@ For example: **Save and deletion hooks**: -The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior. +The following methods are provided by the mixin classes, and provide easy +overriding of the object save or deletion behavior. * `perform_create(self, serializer)` - Called by `CreateModelMixin` when saving a new object instance. * `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance. * `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when deleting an object instance. -These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument. +These hooks are particularly useful for setting attributes that are implicit in +the request, but are not part of the request data. For instance, you might set +an attribute on the object based on the request user, or based on a URL keyword +argument. def perform_create(self, serializer): serializer.save(user=self.request.user) -These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update. +These override points are also particularly useful for adding behavior that +occurs before or after saving an object, such as emailing a confirmation, or +logging the update. def perform_update(self, serializer): instance = serializer.save() send_email_confirmation(user=self.request.user, modified=instance) -You can also use these hooks to provide additional validation, by raising a `ValidationError()`. This can be useful if you need some validation logic to apply at the point of database save. For example: +You can also use these hooks to provide additional validation, by raising a +`ValidationError()`. This can be useful if you need some validation logic to +apply at the point of database save. For example: def perform_create(self, serializer): queryset = SignupRequest.objects.filter(user=self.request.user) @@ -172,69 +222,106 @@ You can also use these hooks to provide additional validation, by raising a `Val raise ValidationError('You have already signed up') serializer.save(user=self.request.user) -**Note**: These methods replace the old-style version 2.x `pre_save`, `post_save`, `pre_delete` and `post_delete` methods, which are no longer available. +**Note**: These methods replace the old-style version 2.x `pre_save`, +`post_save`, `pre_delete` and `post_delete` methods, which are no longer +available. **Other methods**: -You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`. +You won't typically need to override the following methods, although you might +need to call into them if you're writing custom views using `GenericAPIView`. -* `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. -* `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance. -* `get_paginated_response(self, data)` - Returns a paginated style `Response` object. -* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. -* `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. +* `get_serializer_context(self)` - Returns a dictionary containing any extra + context that should be supplied to the serializer. Defaults to including + `'request'`, `'view'` and `'format'` keys. +* `get_serializer(self, instance=None, data=None, many=False, partial=False)` - + Returns a serializer instance. +* `get_paginated_response(self, data)` - Returns a paginated style `Response` + object. +* `paginate_queryset(self, queryset)` - Paginate a queryset if required, either + returning a page object, or `None` if pagination is not configured for this + view. +* `filter_queryset(self, queryset)` - Given a queryset, filter it with + whichever filter backends are in use, returning a new queryset. --- # Mixins -The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as `.get()` and `.post()`, directly. This allows for more flexible composition of behavior. +The mixin classes provide the actions that are used to provide the basic view +behavior. Note that the mixin classes provide action methods rather than +defining the handler methods, such as `.get()` and `.post()`, directly. This +allows for more flexible composition of behavior. The mixin classes can be imported from `rest_framework.mixins`. ## ListModelMixin -Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset. +Provides a `.list(request, *args, **kwargs)` method, that implements listing a +queryset. -If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. +If the queryset is populated, this returns a `200 OK` response, with a +serialized representation of the queryset as the body of the response. The +response data may optionally be paginated. ## CreateModelMixin -Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance. +Provides a `.create(request, *args, **kwargs)` method, that implements creating +and saving a new model instance. -If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value. +If an object is created this returns a `201 Created` response, with a +serialized representation of the object as the body of the response. If the +representation contains a key named `url`, then the `Location` header of the +response will be populated with that value. -If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. +If the request data provided for creating the object was invalid, a `400 Bad +Request` response will be returned, with the error details as the body of the +response. ## RetrieveModelMixin -Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response. +Provides a `.retrieve(request, *args, **kwargs)` method, that implements +returning an existing model instance in a response. -If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise it will return a `404 Not Found`. +If an object can be retrieved this returns a `200 OK` response, with a +serialized representation of the object as the body of the response. Otherwise +it will return a `404 Not Found`. ## UpdateModelMixin -Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. +Provides a `.update(request, *args, **kwargs)` method, that implements updating +and saving an existing model instance. -Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests. +Also provides a `.partial_update(request, *args, **kwargs)` method, which is +similar to the `update` method, except that all fields for the update will be +optional. This allows support for HTTP `PATCH` requests. -If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response. +If an object is updated this returns a `200 OK` response, with a serialized +representation of the object as the body of the response. -If an object is created, for example when making a `DELETE` request followed by a `PUT` request to the same URL, this returns a `201 Created` response, with a serialized representation of the object as the body of the response. +If an object is created, for example when making a `DELETE` request followed by +a `PUT` request to the same URL, this returns a `201 Created` response, with a +serialized representation of the object as the body of the response. -If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. +If the request data provided for updating the object was invalid, a `400 Bad +Request` response will be returned, with the error details as the body of the +response. ## DestroyModelMixin -Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance. +Provides a `.destroy(request, *args, **kwargs)` method, that implements +deletion of an existing model instance. -If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`. +If an object is deleted this returns a `204 No Content` response, otherwise it +will return a `404 Not Found`. --- # Concrete View Classes -The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. +The following classes are the concrete generic views. If you're using generic +views this is normally the level you'll be working at unless you need heavily +customized behavior. The view classes can be imported from `rest_framework.generics`. @@ -248,7 +335,8 @@ Extends: [GenericAPIView], [CreateModelMixin] ## ListAPIView -Used for **read-only** endpoints to represent a **collection of model instances**. +Used for **read-only** endpoints to represent a **collection of model +instances**. Provides a `get` method handler. @@ -280,7 +368,8 @@ Extends: [GenericAPIView], [UpdateModelMixin] ## ListCreateAPIView -Used for **read-write** endpoints to represent a **collection of model instances**. +Used for **read-write** endpoints to represent a **collection of model +instances**. Provides `get` and `post` method handlers. @@ -304,21 +393,27 @@ Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin] ## RetrieveUpdateDestroyAPIView -Used for **read-write-delete** endpoints to represent a **single model instance**. +Used for **read-write-delete** endpoints to represent a **single model +instance**. Provides `get`, `put`, `patch` and `delete` method handlers. -Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] +Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], +[DestroyModelMixin] --- # Customizing the generic views -Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed. +Often you'll want to use the existing generic views, but use some slightly +customized behavior. If you find yourself reusing some bit of customized +behavior in multiple places, you might want to refactor the behavior into a +common class that you can then just apply to any view or viewset as needed. ## Creating custom mixins -For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following: +For example, if you need to lookup objects based on multiple fields in the URL +conf, you could create a mixin class like the following: class MultipleFieldLookupMixin(object): """ @@ -344,7 +439,9 @@ Using custom mixins is a good option if you have custom behavior that needs to b ## Creating custom base classes -If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example: +If you are using a mixin across multiple views, you can take this a step +further and create your own set of base views that can then be used throughout +your project. For example: class BaseRetrieveView(MultipleFieldLookupMixin, generics.RetrieveAPIView): @@ -354,33 +451,50 @@ If you are using a mixin across multiple views, you can take this a step further generics.RetrieveUpdateDestroyAPIView): pass -Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project. +Using custom base classes is a good option if you have custom behavior that +consistently needs to be repeated across a large number of views throughout +your project. --- # PUT as create -Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not. +Prior to version 3.0 the REST framework mixins treated `PUT` as either an +update or a create operation, depending on if the object already existed or +not. -Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. +Allowing `PUT` as create operations is problematic, as it necessarily exposes +information about the existence or non-existence of objects. It's also not +obvious that transparently allowing re-creating of previously deleted instances +is necessarily a better default behavior than simply returning `404` responses. -Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. +Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different +circumstances, but from version 3.0 onwards we now use 404 behavior as the +default, due to it being simpler and more obvious. -If you need to generic PUT-as-create behavior you may want to include something like [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views. +If you need to generic PUT-as-create behavior you may want to include something +like [this `AllowPUTAsCreateMixin` +class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to +your views. --- # Third party packages -The following third party packages provide additional generic view implementations. +The following third party packages provide additional generic view +implementations. ## Django REST Framework bulk -The [django-rest-framework-bulk package][django-rest-framework-bulk] implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests. +The [django-rest-framework-bulk package][django-rest-framework-bulk] implements +generic view mixins as well as some common concrete generic views to allow to +apply bulk operations via API requests. ## Django Rest Multiple Models -[Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request. +[Django Rest Multiple Models][django-rest-multiple-models] provides a generic +view (and mixin) for sending multiple serialized models and/or querysets via a +single API request. [cite]: https://docs.djangoproject.com/en/dev/ref/class-based-views/#base-vs-generic-views diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md index e12aeb7fd..30208ac3d 100644 --- a/docs/api-guide/metadata.md +++ b/docs/api-guide/metadata.md @@ -2,15 +2,22 @@ source: metadata.py # Metadata -> [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. +> [The `OPTIONS`] method allows a client to determine the options and/or +> requirements associated with a resource, or the capabilities of a server, +> without implying a resource action or initiating a resource retrieval. > > — [RFC7231, Section 4.3.7.][cite] -REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information. +REST framework includes a configurable mechanism for determining how your API +should respond to `OPTIONS` requests. This allows you to return API schema or +other resource information. -There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information. +There are not currently any widely adopted conventions for exactly what style +of response should be returned for HTTP `OPTIONS` requests, so we provide an +ad-hoc style that returns some useful information. -Here's an example response that demonstrates the information that is returned by default. +Here's an example response that demonstrates the information that is returned +by default. HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS @@ -59,13 +66,18 @@ Or you can set the metadata class individually for a view: ... }) -The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class. +The REST framework package only includes a single metadata class +implementation, named `SimpleMetadata`. If you want to use an alternative style +you'll need to implement a custom metadata class. ## Creating schema endpoints -If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider re-using the metadata API for doing so. +If you have specific requirements for creating schema endpoints that are +accessed with regular `GET` requests, you might consider re-using the metadata +API for doing so. -For example, the following additional route could be used on a viewset to provide a linkable schema endpoint. +For example, the following additional route could be used on a viewset to +provide a linkable schema endpoint. @list_route(methods=['GET']) def schema(self, request): @@ -73,15 +85,20 @@ For example, the following additional route could be used on a viewset to provid data = meta.determine_metadata(request, self) return Response(data) -There are a couple of reasons that you might choose to take this approach, including that `OPTIONS` responses [are not cacheable][no-options]. +There are a couple of reasons that you might choose to take this approach, +including that `OPTIONS` responses [are not cacheable][no-options]. --- # Custom metadata classes -If you want to provide a custom metadata class you should override `BaseMetadata` and implement the `determine_metadata(self, request, view)` method. +If you want to provide a custom metadata class you should override +`BaseMetadata` and implement the `determine_metadata(self, request, view)` +method. -Useful things that you might want to do could include returning schema information, using a format such as [JSON schema][json-schema], or returning debug information to admin users. +Useful things that you might want to do could include returning schema +information, using a format such as [JSON schema][json-schema], or returning +debug information to admin users. ## Example diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index 088e07184..b6ffb35ad 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -2,39 +2,55 @@ source: pagination.py # Pagination -> Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. +> Django provides a few classes that help you manage paginated data – that is, +> data that’s split across several pages, with “Previous/Next” links. > > — [Django documentation][cite] -REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data. +REST framework includes support for customizable pagination styles. This allows +you to modify how large result sets are split into individual pages of data. The pagination API can support either: * Pagination links that are provided as part of the content of the response. -* Pagination links that are included in response headers, such as `Content-Range` or `Link`. +* Pagination links that are included in response headers, such as + `Content-Range` or `Link`. -The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API. +The built-in styles currently all use links included as part of the content of +the response. This style is more accessible when using the browsable API. -Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` classes for an example. +Pagination is only performed automatically if you're using the generic views or +viewsets. If you're using a regular `APIView`, you'll need to call into the +pagination API yourself to ensure you return a paginated response. See the +source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` +classes for an example. Pagination can be turned off by setting the pagination class to `None`. ## Setting the pagination style -The default pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use the built-in limit/offset pagination, you would do something like this: +The default pagination style may be set globally, using the +`DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use +the built-in limit/offset pagination, you would do something like this: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } -Note that you need to set both the pagination class, and the page size that should be used. +Note that you need to set both the pagination class, and the page size that +should be used. -You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis. +You can also set the pagination class on an individual view by using the +`pagination_class` attribute. Typically you'll want to use the same pagination +style throughout your API, although you might want to vary individual aspects +of the pagination, such as default or maximum page size, on a per-view basis. ## Modifying the pagination style -If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change. +If you want to modify particular aspects of the pagination style, you'll want +to override one of the pagination classes, and set the attributes that you want +to change. class LargeResultsSetPagination(PageNumberPagination): page_size = 1000 @@ -85,35 +101,56 @@ This pagination style accepts a single number page number in the request query p #### Setup -To enable the `PageNumberPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired: +To enable the `PageNumberPagination` style globally, use the following +configuration, modifying the `PAGE_SIZE` as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } -On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `PageNumberPagination` on a per-view basis. +On `GenericAPIView` subclasses you may also set the `pagination_class` +attribute to select `PageNumberPagination` on a per-view basis. #### Configuration -The `PageNumberPagination` class includes a number of attributes that may be overridden to modify the pagination style. +The `PageNumberPagination` class includes a number of attributes that may be +overridden to modify the pagination style. -To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above. +To set these attributes you should override the `PageNumberPagination` class, +and then enable your custom pagination class as above. -* `django_paginator_class` - The Django Paginator class to use. Default is `django.core.paginator.Paginator`, which should be fine for most use cases. -* `page_size` - A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key. -* `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control. -* `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size. -* `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set. -* `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)` -* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`. +* `django_paginator_class` - The Django Paginator class to use. Default is + `django.core.paginator.Paginator`, which should be fine for most use cases. +* `page_size` - A numeric value indicating the page size. If set, this + overrides the `PAGE_SIZE` setting. Defaults to the same value as the + `PAGE_SIZE` settings key. +* `page_query_param` - A string value indicating the name of the query + parameter to use for the pagination control. +* `page_size_query_param` - If set, this is a string value indicating the name + of a query parameter that allows the client to set the page size on a + per-request basis. Defaults to `None`, indicating that the client may not + control the requested page size. +* `max_page_size` - If set, this is a numeric value indicating the maximum + allowable requested page size. This attribute is only valid if + `page_size_query_param` is also set. +* `last_page_strings` - A list or tuple of string values indicating values that + may be used with the `page_query_param` to request the final page in the set. + Defaults to `('last',)` +* `template` - The name of a template to use when rendering pagination controls + in the browsable API. May be overridden to modify the rendering style, or set + to `None` to disable HTML pagination controls completely. Defaults to + `"rest_framework/pagination/numbers.html"`. --- ## LimitOffsetPagination -This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an -"offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. +This pagination style mirrors the syntax used when looking up multiple database +records. The client includes both a "limit" and an "offset" query parameter. +The limit indicates the maximum number of items to return, and is equivalent to +the `page_size` in other styles. The offset indicates the starting position of +the query in relation to the complete set of unpaginated items. **Request**: @@ -139,88 +176,150 @@ To enable the `LimitOffsetPagination` style globally, use the following configur 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' } -Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client. +Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is +also used then the `limit` query parameter will be optional, and may be omitted +by the client. -On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `LimitOffsetPagination` on a per-view basis. +On `GenericAPIView` subclasses you may also set the `pagination_class` +attribute to select `LimitOffsetPagination` on a per-view basis. #### Configuration -The `LimitOffsetPagination` class includes a number of attributes that may be overridden to modify the pagination style. +The `LimitOffsetPagination` class includes a number of attributes that may be +overridden to modify the pagination style. -To set these attributes you should override the `LimitOffsetPagination` class, and then enable your custom pagination class as above. +To set these attributes you should override the `LimitOffsetPagination` class, +and then enable your custom pagination class as above. -* `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `PAGE_SIZE` settings key. -* `limit_query_param` - A string value indicating the name of the "limit" query parameter. Defaults to `'limit'`. -* `offset_query_param` - A string value indicating the name of the "offset" query parameter. Defaults to `'offset'`. -* `max_limit` - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to `None`. -* `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`. +* `default_limit` - A numeric value indicating the limit to use if one is not + provided by the client in a query parameter. Defaults to the same value as + the `PAGE_SIZE` settings key. +* `limit_query_param` - A string value indicating the name of the "limit" query + parameter. Defaults to `'limit'`. +* `offset_query_param` - A string value indicating the name of the "offset" + query parameter. Defaults to `'offset'`. +* `max_limit` - If set this is a numeric value indicating the maximum allowable + limit that may be requested by the client. Defaults to `None`. +* `template` - The name of a template to use when rendering pagination controls + in the browsable API. May be overridden to modify the rendering style, or set + to `None` to disable HTML pagination controls completely. Defaults to + `"rest_framework/pagination/numbers.html"`. --- ## CursorPagination -The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. +The cursor-based pagination presents an opaque "cursor" indicator that the +client may use to page through the result set. This pagination style only +presents forward and reverse controls, and does not allow the client to +navigate to arbitrary positions. -Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. +Cursor based pagination requires that there is a unique, unchanging ordering of +items in the result set. This ordering might typically be a creation timestamp +on the records, as this presents a consistent ordering to paginate against. -Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: +Cursor based pagination is more complex than other schemes. It also requires +that the result set presents a fixed ordering, and does not allow the client to +arbitrarily index into the result set. However it does provide the following +benefits: -* Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. -* Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases. +* Provides a consistent pagination view. When used properly `CursorPagination` + ensures that the client will never see the same item twice when paging + through records, even when new items are being inserted by other clients + during the pagination process. +* Supports usage with very large datasets. With extremely large datasets + pagination using offset-based pagination styles may become inefficient or + unusable. Cursor based pagination schemes instead have fixed-time properties, + and do not slow down as the dataset size increases. #### Details and limitations -Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first. +Proper use of cursor based pagination requires a little attention to detail. +You'll need to think about what ordering you want the scheme to be applied +against. The default is to order by `"-created"`. This assumes that **there +must be a 'created' timestamp field** on the model instances, and will present +a "timeline" style paginated view, with the most recently added items first. -You can modify the ordering by overriding the `'ordering'` attribute on the pagination class, or by using the `OrderingFilter` filter class together with `CursorPagination`. When used with `OrderingFilter` you should strongly consider restricting the fields that the user may order by. +You can modify the ordering by overriding the `'ordering'` attribute on the +pagination class, or by using the `OrderingFilter` filter class together with +`CursorPagination`. When used with `OrderingFilter` you should strongly +consider restricting the fields that the user may order by. -Proper usage of cursor pagination should have an ordering field that satisfies the following: +Proper usage of cursor pagination should have an ordering field that satisfies +the following: -* Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. -* Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. +* Should be an unchanging value, such as a timestamp, slug, or other field that + is only set once, on creation. +* Should be unique, or nearly unique. Millisecond precision timestamps are a + good example. This implementation of cursor pagination uses a smart "position + plus offset" style that allows it to properly support not-strictly-unique + values as the ordering. * Should be a non-nullable value that can be coerced to a string. * The field should have a database index. -Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination. +Using an ordering field that does not satisfy these constraints will generally +still work, but you'll be losing some of the benefits of cursor pagination. -For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach. +For more technical details on the implementation we use for cursor pagination, +the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives +a good overview of the basic approach. #### Setup -To enable the `CursorPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired: +To enable the `CursorPagination` style globally, use the following +configuration, modifying the `PAGE_SIZE` as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 'PAGE_SIZE': 100 } -On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `CursorPagination` on a per-view basis. +On `GenericAPIView` subclasses you may also set the `pagination_class` +attribute to select `CursorPagination` on a per-view basis. #### Configuration -The `CursorPagination` class includes a number of attributes that may be overridden to modify the pagination style. +The `CursorPagination` class includes a number of attributes that may be +overridden to modify the pagination style. -To set these attributes you should override the `CursorPagination` class, and then enable your custom pagination class as above. +To set these attributes you should override the `CursorPagination` class, and +then enable your custom pagination class as above. -* `page_size` = A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key. -* `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`. -* `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'slug'`. Defaults to `-created`. This value may also be overridden by using `OrderingFilter` on the view. -* `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`. +* `page_size` = A numeric value indicating the page size. If set, this + overrides the `PAGE_SIZE` setting. Defaults to the same value as the + `PAGE_SIZE` settings key. +* `cursor_query_param` = A string value indicating the name of the "cursor" + query parameter. Defaults to `'cursor'`. +* `ordering` = This should be a string, or list of strings, indicating the + field against which the cursor based pagination will be applied. For example: + `ordering = 'slug'`. Defaults to `-created`. This value may also be + overridden by using `OrderingFilter` on the view. +* `template` = The name of a template to use when rendering pagination controls + in the browsable API. May be overridden to modify the rendering style, or set + to `None` to disable HTML pagination controls completely. Defaults to + `"rest_framework/pagination/previous_and_next.html"`. --- # Custom pagination styles -To create a custom pagination serializer class you should subclass `pagination.BasePagination` and override the `paginate_queryset(self, queryset, request, view=None)` and `get_paginated_response(self, data)` methods: +To create a custom pagination serializer class you should subclass +`pagination.BasePagination` and override the `paginate_queryset(self, queryset, +request, view=None)` and `get_paginated_response(self, data)` methods: -* The `paginate_queryset` method is passed the initial queryset and should return an iterable object that contains only the data in the requested page. -* The `get_paginated_response` method is passed the serialized page data and should return a `Response` instance. +* The `paginate_queryset` method is passed the initial queryset and should + return an iterable object that contains only the data in the requested page. +* The `get_paginated_response` method is passed the serialized page data and + should return a `Response` instance. -Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method. +Note that the `paginate_queryset` method may set state on the pagination +instance, that may later be used by the `get_paginated_response` method. ## Example -Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: +Suppose we want to replace the default pagination output style with a modified +format that includes the next and previous links under in a nested 'links' +key. We could specify a custom pagination class like so: class CustomPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): @@ -240,11 +339,15 @@ We'd then need to setup the custom class in our configuration: 'PAGE_SIZE': 100 } -Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an `OrderedDict` when constructing the body of paginated responses, but this is optional. +Note that if you care about how the ordering of keys is displayed in responses +in the browsable API you might choose to use an `OrderedDict` when constructing +the body of paginated responses, but this is optional. ## Header based pagination -Let's modify the built-in `PageNumberPagination` style, so that instead of include the pagination links in the body of the response, we'll instead include a `Link` header, in a [similar style to the GitHub API][github-link-pagination]. +Let's modify the built-in `PageNumberPagination` style, so that instead of +include the pagination links in the body of the response, we'll instead include +a `Link` header, in a [similar style to the GitHub API][github-link-pagination]. class LinkHeaderPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): @@ -274,7 +377,9 @@ To have your custom pagination class be used by default, use the `DEFAULT_PAGINA 'PAGE_SIZE': 100 } -API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example: +API responses for list endpoints will now include a `Link` header, instead of +including the pagination links as part of the body of the response, for +example: --- @@ -286,24 +391,40 @@ API responses for list endpoints will now include a `Link` header, instead of in # HTML pagination controls -By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The `PageNumberPagination` and `LimitOffsetPagination` classes display a list of page numbers with previous and next controls. The `CursorPagination` class displays a simpler style that only displays a previous and next control. +By default using the pagination classes will cause HTML pagination controls to +be displayed in the browsable API. There are two built-in display styles. The +`PageNumberPagination` and `LimitOffsetPagination` classes display a list of +page numbers with previous and next controls. The `CursorPagination` class +displays a simpler style that only displays a previous and next control. ## Customizing the controls -You can override the templates that render the HTML pagination controls. The two built-in styles are: +You can override the templates that render the HTML pagination controls. The +two built-in styles are: * `rest_framework/pagination/numbers.html` * `rest_framework/pagination/previous_and_next.html` -Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. +Providing a template with either of these paths in a global template directory +will override the default rendering for the relevant pagination classes. -Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting `template = None` as an attribute on the class. You'll then need to configure your `DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default pagination style. +Alternatively you can disable HTML pagination controls completely by +subclassing on of the existing classes, setting `template = None` as an +attribute on the class. You'll then need to configure your +`DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default +pagination style. #### Low-level API -The low-level API for determining if a pagination class should display the controls or not is exposed as a `display_page_controls` attribute on the pagination instance. Custom pagination classes should be set to `True` in the `paginate_queryset` method if they require the HTML pagination controls to be displayed. +The low-level API for determining if a pagination class should display the +controls or not is exposed as a `display_page_controls` attribute on the +pagination instance. Custom pagination classes should be set to `True` in the +`paginate_queryset` method if they require the HTML pagination controls to be +displayed. -The `.to_html()` and `.get_html_context()` methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered. +The `.to_html()` and `.get_html_context()` methods may also be overridden in a +custom pagination class in order to further customize how the controls are +rendered. --- @@ -313,7 +434,9 @@ The following third party packages are also available. ## DRF-extensions -The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size. +The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` +mixin class][paginate-by-max-mixin] that allows your API clients to specify +`?page_size=max` to obtain the maximum allowed page size. [cite]: https://docs.djangoproject.com/en/dev/topics/pagination/ [github-link-pagination]: https://developer.github.com/guides/traversing-with-pagination/ diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index ef2859fe1..dbbb968e1 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -8,25 +8,38 @@ sending more complex data than simple forms > > — Malcom Tredinnick, [Django developers group][cite] -REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts. +REST framework includes a number of built in Parser classes, that allow you to +accept requests with various media types. There is also support for defining +your own custom parsers, which gives you the flexibility to design the media +types that your API accepts. ## How the parser is determined -The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. +The set of valid parsers for a view is always defined as a list of classes. +When `request.data` is accessed, REST framework will examine the +`Content-Type` header on the incoming request, and determine which parser to +use to parse the request content. --- -**Note**: When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request. +**Note**: When developing client applications always remember to make sure +you're setting the `Content-Type` header when sending data in an HTTP request. -If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you wanted. +If you don't set the content type, most clients will default to using +`'application/x-www-form-urlencoded'`, which may not be what you wanted. -As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting. +As an example, if you are sending `json` encoded data using jQuery with the +[.ajax() method][jquery-ajax], you should make sure to include the +`contentType: 'application/json'` setting. --- ## Setting the parsers -The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow only requests with `JSON` content, instead of the default of JSON or form data. +The default set of parsers may be set globally, using the +`DEFAULT_PARSER_CLASSES` setting. For example, the following settings would +allow only requests with `JSON` content, instead of the default of JSON or form +data. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': ( @@ -34,8 +47,8 @@ The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSE ) } -You can also set the parsers used for an individual view, or viewset, -using the `APIView` class-based views. +You can also set the parsers used for an individual view, or viewset, using the +`APIView` class-based views. from rest_framework.parsers import JSONParser from rest_framework.response import Response @@ -77,33 +90,46 @@ Parses `JSON` request content. Parses HTML form content. `request.data` will be populated with a `QueryDict` of data. -You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. +You will typically want to use both `FormParser` and `MultiPartParser` together +in order to fully support HTML form data. **.media_type**: `application/x-www-form-urlencoded` ## MultiPartParser -Parses multipart HTML form content, which supports file uploads. Both `request.data` will be populated with a `QueryDict`. +Parses multipart HTML form content, which supports file uploads. Both +`request.data` will be populated with a `QueryDict`. -You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. +You will typically want to use both `FormParser` and `MultiPartParser` together +in order to fully support HTML form data. **.media_type**: `multipart/form-data` ## FileUploadParser -Parses raw file upload content. The `request.data` property will be a dictionary with a single key `'file'` containing the uploaded file. +Parses raw file upload content. The `request.data` property will be a +dictionary with a single key `'file'` containing the uploaded file. -If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename. +If the view used with `FileUploadParser` is called with a `filename` URL +keyword argument, then that argument will be used as the filename. -If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`. +If it is called without a `filename` URL keyword argument, then the client must +set the filename in the `Content-Disposition` HTTP header. For example +`Content-Disposition: attachment; filename=upload.jpg`. **.media_type**: `*/*` ##### Notes: -* The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` parser instead. -* Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view. -* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details. +* The `FileUploadParser` is for usage with native clients that can upload the + file as a raw data request. For web-based uploads, or for native clients + with multipart upload support, you should use the `MultiPartParser` parser + instead. +* Since this parser's `media_type` matches any content type, `FileUploadParser` + should generally be the only parser set on an API view. +* `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, + and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] + for more details. ##### Basic usage example: @@ -128,9 +154,12 @@ If it is called without a `filename` URL keyword argument, then the client must # Custom parsers -To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method. +To implement a custom parser, you should override `BaseParser`, set the +`.media_type` property, and implement the `.parse(self, stream, media_type, +parser_context)` method. -The method should return the data that will be used to populate the `request.data` property. +The method should return the data that will be used to populate the +`request.data` property. The arguments passed to `.parse()` are: @@ -142,17 +171,22 @@ A stream-like object representing the body of the request. Optional. If provided, this is the media type of the incoming request content. -Depending on the request's `Content-Type:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"text/plain; charset=utf-8"`. +Depending on the request's `Content-Type:` header, this may be more specific +than the renderer's `media_type` attribute, and may include media type +parameters. For example `"text/plain; charset=utf-8"`. ### parser_context -Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. +Optional. If supplied, this argument will be a dictionary containing any +additional context that may be required to parse the request content. -By default this will include the following keys: `view`, `request`, `args`, `kwargs`. +By default this will include the following keys: `view`, `request`, `args`, +`kwargs`. ## Example -The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. +The following is an example plaintext parser that will populate the +`request.data` property with a string representing the body of the request. class PlainTextParser(BaseParser): """ @@ -174,7 +208,9 @@ The following third party packages are also available. ## YAML -[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. +[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and +rendering support. It was previously included directly in the REST framework +package, and is now instead supported as a third-party package. #### Installation & configuration @@ -195,7 +231,9 @@ Modify your REST framework settings. ## XML -[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. +[REST Framework XML][rest-framework-xml] provides a simple informal XML format. +It was previously included directly in the REST framework package, and is now +instead supported as a third-party package. #### Installation & configuration @@ -216,11 +254,17 @@ Modify your REST framework settings. ## MessagePack -[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]. +[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 diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 7cdb59531..1d2a54e8c 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -2,44 +2,72 @@ source: permissions.py # Permissions -> Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization. +> Authentication or identification by itself is not usually sufficient to gain +> access to information or code. For that, the entity requesting access must +> have authorization. > > — [Apple Developer Documentation][cite] -Together with [authentication] and [throttling], permissions determine whether a request should be granted or denied access. +Together with [authentication] and [throttling], permissions determine whether +a request should be granted or denied access. -Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted. +Permission checks are always run at the very start of the view, before any +other code is allowed to proceed. Permission checks will typically use the +authentication information in the `request.user` and `request.auth` properties +to determine if the incoming request should be permitted. -Permissions are used to grant or deny access different classes of users to different parts of the API. +Permissions are used to grant or deny access different classes of users to +different parts of the API. -The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds the `IsAuthenticated` class in REST framework. +The simplest style of permission would be to allow access to any authenticated +user, and deny access to any unauthenticated user. This corresponds the +`IsAuthenticated` class in REST framework. -A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework. +A slightly less strict style of permission would be to allow full access to +authenticated users, but allow read-only access to unauthenticated users. This +corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework. ## How permissions are determined -Permissions in REST framework are always defined as a list of permission classes. +Permissions in REST framework are always defined as a list of permission +classes. -Before running the main body of the view each permission in the list is checked. -If any permission check fails an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run. +Before running the main body of the view each permission in the list is +checked. If any permission check fails an `exceptions.PermissionDenied` or +`exceptions.NotAuthenticated` exception will be raised, and the main body of +the view will not run. -When the permissions checks fail either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules: +When the permissions checks fail either a "403 Forbidden" or a "401 +Unauthorized" response will be returned, according to the following rules: -* The request was successfully authenticated, but permission was denied. *— An HTTP 403 Forbidden response will be returned.* -* The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *— An HTTP 403 Forbidden response will be returned.* -* The request was not successfully authenticated, and the highest priority authentication class *does* use `WWW-Authenticate` headers. *— An HTTP 401 Unauthorized response, with an appropriate `WWW-Authenticate` header will be returned.* +* The request was successfully authenticated, but permission was denied. + *— An HTTP 403 Forbidden response will be returned.* +* The request was not successfully authenticated, and the highest priority + authentication class *does not* use `WWW-Authenticate` headers. *— An + HTTP 403 Forbidden response will be returned.* +* The request was not successfully authenticated, and the highest priority + authentication class *does* use `WWW-Authenticate` headers. *— An HTTP + 401 Unauthorized response, with an appropriate `WWW-Authenticate` header will + be returned.* ## Object level permissions -REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. +REST framework permissions also support object-level permissioning. Object +level permissions are used to determine if a user should be allowed to act on a +particular object, which will typically be a model instance. -Object level permissions are run by REST framework's generic views when `.get_object()` is called. -As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. +Object level permissions are run by REST framework's generic views when +`.get_object()` is called. As with view level permissions, an +`exceptions.PermissionDenied` exception will be raised if the user is not +allowed to act on the given object. If you're writing your own views and want to enforce object level permissions, -or if you override the `get_object` method on a generic view, then you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object. +or if you override the `get_object` method on a generic view, then you'll need +to explicitly call the `.check_object_permissions(request, obj)` method on the +view at the point at which you've retrieved the object. -This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropriate permissions. +This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or +simply return if the view has the appropriate permissions. For example: @@ -50,9 +78,13 @@ For example: #### Limitations of object level permissions -For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. +For performance reasons the generic views will not automatically apply object +level permissions to each instance in a queryset when returning a list of +objects. -Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view. +Often when you're using object level permissions you'll also want to [filter +the queryset][filtering] appropriately, to ensure that users only have +visibility onto instances that they are permitted to view. ## Setting the permission policy @@ -100,7 +132,9 @@ Or, if you're using the `@api_view` decorator with function based views. } return Response(content) -__Note:__ when you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the __settings.py__ file. +__Note:__ when you set new permission classes through class attribute or +decorators you're telling the view to ignore the default list set over the +__settings.py__ file. --- @@ -108,67 +142,102 @@ __Note:__ when you set new permission classes through class attribute or decorat ## AllowAny -The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**. +The `AllowAny` permission class will allow unrestricted access, **regardless of +if the request was authenticated or unauthenticated**. -This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit. +This permission is not strictly required, since you can achieve the same result +by using an empty list or tuple for the permissions setting, but you may find +it useful to specify this class because it makes the intention explicit. ## IsAuthenticated -The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise. +The `IsAuthenticated` permission class will deny permission to any +unauthenticated user, and allow permission otherwise. -This permission is suitable if you want your API to only be accessible to registered users. +This permission is suitable if you want your API to only be accessible to +registered users. ## IsAdminUser -The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed. +The `IsAdminUser` permission class will deny permission to any user, unless +`user.is_staff` is `True` in which case permission will be allowed. -This permission is suitable if you want your API to only be accessible to a subset of trusted administrators. +This permission is suitable if you want your API to only be accessible to a +subset of trusted administrators. ## IsAuthenticatedOrReadOnly -The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`. +The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any +request. Requests for unauthorised users will only be permitted if the request +method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`. -This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users. +This permission is suitable if you want to your API to allow read permissions +to anonymous users, and only allow write permissions to authenticated users. ## DjangoModelPermissions -This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property set. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. +This permission class ties into Django's standard `django.contrib.auth` [model +permissions][contribauth]. This permission must only be applied to views that +have a `.queryset` property set. Authorization will only be granted if the user +*is authenticated* and has the *relevant model permissions* assigned. * `POST` requests require the user to have the `add` permission on the model. -* `PUT` and `PATCH` requests require the user to have the `change` permission on the model. -* `DELETE` requests require the user to have the `delete` permission on the model. +* `PUT` and `PATCH` requests require the user to have the `change` permission + on the model. +* `DELETE` requests require the user to have the `delete` permission on the + model. -The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests. +The default behaviour can also be overridden to support custom model +permissions. For example, you might want to include a `view` model permission +for `GET` requests. -To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. +To use custom model permissions, override `DjangoModelPermissions` and set the +`.perms_map` property. Refer to the source code for details. #### Using with views that do not include a `queryset` attribute. -If you're using this permission with a view that uses an overridden `get_queryset()` method there may not be a `queryset` attribute on the view. In this case we suggest also marking the view with a sentinel queryset, so that this class can determine the required permissions. For example: +If you're using this permission with a view that uses an overridden +`get_queryset()` method there may not be a `queryset` attribute on the view. In +this case we suggest also marking the view with a sentinel queryset, so that +this class can determine the required permissions. For example: queryset = User.objects.none() # Required for DjangoModelPermissions ## DjangoModelPermissionsOrAnonReadOnly -Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. +Similar to `DjangoModelPermissions`, but also allows unauthenticated users to +have read-only access to the API. ## DjangoObjectPermissions -This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian]. +This permission class ties into Django's standard [object permissions +framework][objectpermissions] that allows per-object permissions on models. In +order to use this permission class, you'll also need to add a permission +backend that supports object-level permissions, such as +[django-guardian][guardian]. -As with `DjangoModelPermissions`, this permission must only be applied to views that have a `.queryset` property or `.get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned. +As with `DjangoModelPermissions`, this permission must only be applied to views +that have a `.queryset` property or `.get_queryset()` method. Authorization +will only be granted if the user *is authenticated* and has the *relevant +per-object permissions* and *relevant model permissions* assigned. * `POST` requests require the user to have the `add` permission on the model instance. * `PUT` and `PATCH` requests require the user to have the `change` permission on the model instance. * `DELETE` requests require the user to have the `delete` permission on the model instance. -Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well. +Note that `DjangoObjectPermissions` **does not** require the `django-guardian` +package, and should support other object-level backends equally well. -As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoModelPermissions` and setting the `.perms_map` property. Refer to the source code for details. +As with `DjangoModelPermissions` you can use custom model permissions by +overriding `DjangoModelPermissions` and setting the `.perms_map` property. +Refer to the source code for details. --- -**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests, you'll want to consider also adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions. +**Note**: If you need object level `view` permissions for `GET`, `HEAD` and +`OPTIONS` requests, you'll want to consider also adding the +`DjangoObjectPermissionsFilter` class to ensure that list endpoints only return +results including objects for which the user has appropriate view permissions. --- @@ -176,14 +245,17 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid # Custom permissions -To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods: +To implement a custom permission, override `BasePermission` and implement +either, or both, of the following methods: * `.has_permission(self, request, view)` * `.has_object_permission(self, request, view, obj)` The methods should return `True` if the request should be granted access, and `False` otherwise. -If you need to test if a request is a read operation or a write operation, you should check the request method against the constant `SAFE_METHODS`, which is a tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example: +If you need to test if a request is a read operation or a write operation, you +should check the request method against the constant `SAFE_METHODS`, which is a +tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example: if request.method in permissions.SAFE_METHODS: # Check permissions for read-only request @@ -192,23 +264,32 @@ If you need to test if a request is a read operation or a write operation, you s --- -**Note**: The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. +**Note**: The instance-level `has_object_permission` method will only be called +if the view-level `has_permission` checks have already passed. Also note that +in order for the instance-level checks to run, the view code should +explicitly call `.check_object_permissions(request, obj)`. If you are +using the generic views then this will be handled for you by default. --- -Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used. - +Custom permissions will raise a `PermissionDenied` exception if the test fails. +To change the error message associated with the exception, implement a +`message` attribute directly on your custom permission. Otherwise the +`default_detail` attribute from `PermissionDenied` will be used. + from rest_framework import permissions class CustomerAccessPermission(permissions.BasePermission): message = 'Adding customers not allowed.' - + def has_permission(self, request, view): ... - + ## Examples -The following is an example of a permission class that checks the incoming request's IP address against a blacklist, and denies the request if the IP has been blacklisted. +The following is an example of a permission class that checks the incoming +request's IP address against a blacklist, and denies the request if the IP has +been blacklisted. from rest_framework import permissions @@ -222,7 +303,9 @@ The following is an example of a permission class that checks the incoming reque blacklisted = Blacklist.objects.filter(ip_addr=ip_addr).exists() return not blacklisted -As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example: +As well as global permissions, that are run against all incoming requests, you +can also create object-level permissions, that are only run against operations +that affect a particular object instance. For example: class IsOwnerOrReadOnly(permissions.BasePermission): """ @@ -239,9 +322,17 @@ As well as global permissions, that are run against all incoming requests, you c # Instance must have an attribute named `owner`. return obj.owner == request.user -Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling `self.check_object_permissions(request, obj)` from the view once you have the object instance. This call will raise an appropriate `APIException` if any object-level permission checks fail, and will otherwise simply return. +Note that the generic views will check the appropriate object level +permissions, but if you're writing your own custom views, you'll need to make +sure you check the object level permission checks yourself. You can do so by +calling `self.check_object_permissions(request, obj)` from the view once you +have the object instance. This call will raise an appropriate `APIException` +if any object-level permission checks fail, and will otherwise simply return. -Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details. +Also note that the generic views will only check the object-level permissions +for views that retrieve a single model instance. If you require object-level +filtering of list views, you'll need to filter the queryset separately. +See the [filtering documentation][filtering] for more details. --- @@ -251,19 +342,30 @@ The following third party packages are also available. ## Composed Permissions -The [Composed Permissions][composed-permissions] package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components. +The [Composed Permissions][composed-permissions] package provides a simple way +to define complex and multi-depth (with logic operators) permission objects, +using small and reusable components. ## REST Condition -The [REST Condition][rest-condition] package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators. +The [REST Condition][rest-condition] package is another extension for building +complex permissions in a simple and convenient way. The extension allows you +to combine permissions with logical operators. ## DRY Rest Permissions -The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrive per user. +The [DRY Rest Permissions][dry-rest-permissions] package provides the ability +to define different permissions for individual default and custom actions. This +package is made for apps with permissions that are derived from relationships +defined in the app's data model. It also supports permission checks being +returned to a client app through the API's serializer. Additionally it supports +adding permissions to the default and custom list actions to restrict the data +they retrive per user. ## Django Rest Framework Roles -The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users. +The [Django Rest Framework Roles][django-rest-framework-roles] package makes it +easier to parameterize your API over multiple types of users. [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 8695b2c1e..525852774 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -8,19 +8,29 @@ source: relations.py > — [Linus Torvalds][cite] -Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`. +Relational fields are used to represent model relationships. They can be +applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, +as well as to reverse relationships, and custom relationships such as +`GenericForeignKey`. --- -**Note:** The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.`. +**Note:** The relational fields are declared in `relations.py`, but by +convention you should import them from the `serializers` module, using `from +rest_framework import serializers` and refer to fields as +`serializers.`. --- #### Inspecting relationships. -When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style. +When using the `ModelSerializer` class, serializer fields and relationships +will be automatically generated for you. Inspecting these automatically +generated fields can be a useful tool for determining how to customize the +relationship style. -To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation… +To do so, open the Django shell, using `python manage.py shell`, then import +the serializer class, instantiate it, and print the object representation… >>> from myapp.serializers import AccountSerializer >>> serializer = AccountSerializer() @@ -32,7 +42,9 @@ To do so, open the Django shell, using `python manage.py shell`, then import the # API Reference -In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. +In order to explain the various types of relational fields, we'll use a couple +of simple models for our examples. Our models will be for music albums, and +the tracks listed on each album. class Album(models.Model): album_name = models.CharField(max_length=100) @@ -53,7 +65,8 @@ In order to explain the various types of relational fields, we'll use a couple o ## StringRelatedField -`StringRelatedField` may be used to represent the target of the relationship using its `__unicode__` method. +`StringRelatedField` may be used to represent the target of the relationship +using its `__unicode__` method. For example, the following serializer. @@ -113,15 +126,22 @@ By default this field is read-write, although you can change this behavior using **Arguments**: -* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. -* `many` - If applied to a to-many relationship, you should set this argument to `True`. -* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. -* `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation. +* `queryset` - The queryset used for model instance lookups when validating the + field input. Relationships must either set a queryset explicitly, or set + `read_only=True`. +* `many` - If applied to a to-many relationship, you should set this argument + to `True`. +* `allow_null` - If set to `True`, the field will accept values of `None` or + the empty string for nullable relationships. Defaults to `False`. +* `pk_field` - Set to a field to control serialization/deserialization of the + primary key's value. For example, `pk_field=UUIDField(format='hex')` would + serialize a UUID primary key into its compact hex representation. ## HyperlinkedRelatedField -`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink. +`HyperlinkedRelatedField` may be used to represent the target of the +relationship using a hyperlink. For example, the following serializer: @@ -153,27 +173,45 @@ By default this field is read-write, although you can change this behavior using --- -**Note**: This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments. +**Note**: This field is designed for objects that map to a URL that accepts a +single URL keyword argument, as set using the `lookup_field` and +`lookup_url_kwarg` arguments. -This is suitable for URLs that contain a single primary key or slug argument as part of the URL. +This is suitable for URLs that contain a single primary key or slug argument as +part of the URL. -If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below. +If you require more complex hyperlinked representation you'll need to customize +the field, as described in the [custom hyperlinked +fields](#custom-hyperlinked-fields) section, below. --- **Arguments**: -* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**. -* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. -* `many` - If applied to a to-many relationship, you should set this argument to `True`. -* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. -* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. -* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`. -* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. +* `view_name` - The view name that should be used as the target of the + relationship. If you're using [the standard router classes][routers] this + will be a string with the format `-detail`. **required**. +* `queryset` - The queryset used for model instance lookups when validating the + field input. Relationships must either set a queryset explicitly, or set + `read_only=True`. +* `many` - If applied to a to-many relationship, you should set this argument + to `True`. +* `allow_null` - If set to `True`, the field will accept values of `None` or + the empty string for nullable relationships. Defaults to `False`. +* `lookup_field` - The field on the target that should be used for the lookup. + Should correspond to a URL keyword argument on the referenced view. Default + is `'pk'`. +* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf + that corresponds to the lookup field. Defaults to using the same value as + `lookup_field`. +* `format` - If using format suffixes, hyperlinked fields will use the same + format suffix for the target unless overridden by using the `format` + argument. ## SlugRelatedField -`SlugRelatedField` may be used to represent the target of the relationship using a field on the target. +`SlugRelatedField` may be used to represent the target of the relationship +using a field on the target. For example, the following serializer: @@ -201,20 +239,30 @@ Would serialize to a representation like this: ] } -By default this field is read-write, although you can change this behavior using the `read_only` flag. +By default this field is read-write, although you can change this behavior +using the `read_only` flag. -When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`. +When using `SlugRelatedField` as a read-write field, you will normally want to +ensure that the slug field corresponds to a model field with `unique=True`. **Arguments**: -* `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required** -* `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. -* `many` - If applied to a to-many relationship, you should set this argument to `True`. -* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. +* `slug_field` - The field on the target that should be used to represent it. + This should be a field that uniquely identifies any given instance. For + example, `username`. **required** +* `queryset` - The queryset used for model instance lookups when validating the + field input. Relationships must either set a queryset explicitly, or set + `read_only=True`. +* `many` - If applied to a to-many relationship, you should set this argument + to `True`. +* `allow_null` - If set to `True`, the field will accept values of `None` or + the empty string for nullable relationships. Defaults to `False`. ## HyperlinkedIdentityField -This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: +This field can be applied as an identity relationship, such as the `'url'` +field on a HyperlinkedModelSerializer. It can also be used for an attribute +on the object. For example, the following serializer: class AlbumSerializer(serializers.HyperlinkedModelSerializer): track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') @@ -235,10 +283,18 @@ This field is always read-only. **Arguments**: -* `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**. -* `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. -* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`. -* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. +* `view_name` - The view name that should be used as the target of the + relationship. If you're using [the standard router classes][routers] this + will be a string with the format `-detail`. **required**. +* `lookup_field` - The field on the target that should be used for the lookup. + Should correspond to a URL keyword argument on the referenced view. Default + is `'pk'`. +* `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf + that corresponds to the lookup field. Defaults to using the same value as + `lookup_field`. +* `format` - If using format suffixes, hyperlinked fields will use the same + format suffix for the target unless overridden by using the `format` + argument. --- @@ -246,7 +302,8 @@ This field is always read-only. Nested relationships can be expressed by using serializers as fields. -If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. +If the field is used to represent a to-many relationship, you should add the +`many=True` flag to the serializer field. ## Example @@ -288,7 +345,10 @@ Would serialize to a nested representation like this: # Writable nested serializers -By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved. +By default nested serializers are read-only. If you want to support +write-operations to a nested serializer field you'll need to create `create()` +and/or `update()` methods in order to explicitly specify how the child +relationships should be saved. class TrackSerializer(serializers.ModelSerializer): class Meta: @@ -326,15 +386,23 @@ By default nested serializers are read-only. If you want to support write-operat # Custom relational fields -To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance. +To implement a custom relational field, you should override `RelatedField`, and +implement the `.to_representation(self, value)` method. This method takes the +target of the field as the `value` argument, and should return the +representation that should be used to serialize the target. The `value` +argument will typically be a model instance. -If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method. +If you want to implement a read-write relational field, you must also implement +the `.to_internal_value(self, data)` method. -To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field. +To provide a dynamic queryset based on the `context`, you can also override +`.get_queryset(self)` instead of specifying `.queryset` on the class or when +initializing the field. ## Example -For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration. +For example, we could define a relational field to serialize a track to a +custom string representation, using its ordering, title, and duration. import time @@ -367,22 +435,29 @@ This custom field would then serialize to the following representation. # Custom hyperlinked fields -In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field. +In some cases you may need to customize the behavior of a hyperlinked field, in +order to represent URLs that require more than a single lookup field. -You can achieve this by overriding `HyperlinkedRelatedField`. There are two methods that may be overridden: +You can achieve this by overriding `HyperlinkedRelatedField`. There are two +methods that may be overridden: **get_url(self, obj, view_name, request, format)** -The `get_url` method is used to map the object instance to its URL representation. +The `get_url` method is used to map the object instance to its URL +representation. -May raise a `NoReverseMatch` if the `view_name` and `lookup_field` -attributes are not configured to correctly match the URL conf. +May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes +are not configured to correctly match the URL conf. **get_object(self, queryset, view_name, view_args, view_kwargs)** -If you want to support a writable hyperlinked field then you'll also want to override `get_object`, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method. +If you want to support a writable hyperlinked field then you'll also want to +override `get_object`, in order to map incoming URLs back to the object they +represent. For read-only hyperlinked fields there is no need to override this +method. -The return value of this method should the object that corresponds to the matched URL conf arguments. +The return value of this method should the object that corresponds to the +matched URL conf arguments. May raise an `ObjectDoesNotExist` exception. @@ -418,9 +493,12 @@ In this case we'd need to override `HyperlinkedRelatedField` to get the behavior } return self.get_queryset().get(**lookup_kwargs) -Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior. +Note that if you wanted to use this style together with the generic views then +you'd also need to override `.get_object` on the view in order to get the +correct lookup behavior. -Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation. +Generally we recommend a flat style for API representations where possible, but +the nested URL style can also be reasonable when used in moderation. --- @@ -428,19 +506,31 @@ Generally we recommend a flat style for API representations where possible, but ## The `queryset` argument -The `queryset` argument is only ever required for *writable* relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance. +The `queryset` argument is only ever required for *writable* relationship +field, in which case it is used for performing the model instance lookup, that +maps from the primitive user input, into a model instance. -In version 2.x a serializer class could *sometimes* automatically determine the `queryset` argument *if* a `ModelSerializer` class was being used. +In version 2.x a serializer class could *sometimes* automatically determine the +`queryset` argument *if* a `ModelSerializer` class was being used. -This behavior is now replaced with *always* using an explicit `queryset` argument for writable relational fields. +This behavior is now replaced with *always* using an explicit `queryset` +argument for writable relational fields. -Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes. +Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, +makes the behavior of the field more clear, and ensures that it is trivial to +move between using the `ModelSerializer` shortcut, or using fully explicit +`Serializer` classes. ## Customizing the HTML display -The built-in `__str__` method of the model will be used to generate string representations of the objects used to populate the `choices` property. These choices are used to populate select HTML inputs in the browsable API. +The built-in `__str__` method of the model will be used to generate string +representations of the objects used to populate the `choices` property. These +choices are used to populate select HTML inputs in the browsable API. -To provide customized representations for such inputs, override `display_value()` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example: +To provide customized representations for such inputs, override +`display_value()` of a `RelatedField` subclass. This method will receive a +model object, and should return a string suitable for representing it. For +example: class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def display_value(self, instance): @@ -448,16 +538,26 @@ To provide customized representations for such inputs, override `display_value() ## Select field cutoffs -When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed. +When rendered in the browsable API relational fields will default to only +displaying a maximum of 1000 selectable items. If more items are present then a +disabled option with "More than 1000 items…" will be displayed. -This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed. +This behavior is intended to prevent a template from being unable to render in +an acceptable timespan due to a very large number of relationships being +displayed. There are two keyword arguments you can use to control this behavior: -- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`. -- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` +- `html_cutoff` - If set this will be the maximum number of choices that will + be displayed by a HTML select drop down. Set to `None` to disable any + limiting. Defaults to `1000`. +- `html_cutoff_text` - If set this will display a textual indicator if the + maximum number of items have been cutoff in an HTML select drop down. + Defaults to `"More than {count} items…"` -In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the `style` keyword argument. For example: +In cases where the cutoff is being enforced you may want to instead use a plain +input field in the HTML form. You can do so using the `style` keyword argument. +For example: assigned_to = serializers.SlugRelatedField( queryset=User.objects.all(), @@ -467,31 +567,41 @@ In cases where the cutoff is being enforced you may want to instead use a plain ## Reverse relations -Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example: +Note that reverse relationships are not automatically included by the +`ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a +reverse relationship, you must explicitly add it to the fields list. For +example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ('tracks', ...) -You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example: +You'll normally want to ensure that you've set an appropriate `related_name` +argument on the relationship, that you can use as the field name. For example: class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') ... -If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example: +If you have not set a related name for the reverse relationship, you'll need to +use the automatically generated related name in the `fields` argument. For +example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ('track_set', ...) -See the Django documentation on [reverse relationships][reverse-relationships] for more details. +See the Django documentation on [reverse relationships][reverse-relationships] +for more details. ## Generic relationships -If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship. +If you want to serialize a generic foreign key, you need to define a custom +field, to determine explicitly how you want to serialize the targets of the +relationship. -For example, given the following model for a tag, which has a generic relationship with other arbitrary models: +For example, given the following model for a tag, which has a generic +relationship with other arbitrary models: class TaggedItem(models.Model): """ @@ -524,7 +634,9 @@ And the following two models, which may have associated tags: text = models.CharField(max_length=1000) tags = GenericRelation(TaggedItem) -We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized. +We could define a custom field that could be used to serialize tagged +instances, using the type of each instance to determine how it should be +serialized. class TaggedObjectRelatedField(serializers.RelatedField): """ @@ -541,7 +653,8 @@ We could define a custom field that could be used to serialize tagged instances, return 'Note: ' + value.text raise Exception('Unexpected type of tagged object') -If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_representation()` method: +If you need the target of the relationship to have a nested representation, you +can use the required serializers inside the `.to_representation()` method: def to_representation(self, value): """ @@ -557,7 +670,9 @@ If you need the target of the relationship to have a nested representation, you return serializer.data -Note that reverse generic keys, expressed using the `GenericRelation` field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. +Note that reverse generic keys, expressed using the `GenericRelation` field, +can be serialized using the regular relational field types, since the type of +the target in the relationship is always known. For more information see [the Django documentation on generic relations][generic-relations]. @@ -578,11 +693,13 @@ 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. +The [drf-nested-routers package][drf-nested-routers] provides routers and +relationship fields for working with nested resources. ## Rest Framework Generic Relations -The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys. +The [rest-framework-generic-relations][drf-nested-relations] library provides +read/write serialization for generic foreign keys. [cite]: http://lwn.net/Articles/193245/ [reverse-relationships]: https://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index a95778350..8466aa824 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -2,23 +2,39 @@ source: renderers.py # Renderers -> Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. +> Before a TemplateResponse instance can be returned to the client, it must be +> rendered. The rendering process takes the intermediate representation of +> template and context, and turns it into the final byte stream that can be +> served to the client. > > — [Django documentation][cite] -REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types. +REST framework includes a number of built in Renderer classes, that allow you +to return responses with various media types. There is also support for +defining your own custom renderers, which gives you the flexibility to design +your own media types. ## How the renderer is determined -The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request. +The set of valid renderers for a view is always defined as a list of classes. +When a view is entered REST framework will perform content negotiation on the +incoming request, and determine the most appropriate renderer to satisfy the +request. -The basic process of content negotiation involves examining the request's `Accept` header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data. +The basic process of content negotiation involves examining the request's +`Accept` header, to determine which media types it expects in the response. +Optionally, format suffixes on the URL may be used to explicitly request a +particular representation. For example the URL +`http://example.com/api/users_count.json` might be an endpoint that always +returns JSON data. For more information see the documentation on [content negotiation][conneg]. ## Setting the renderers -The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` as the main media type and also include the self describing API. +The default set of renderers may be set globally, using the +`DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would +use `JSON` as the main media type and also include the self describing API. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( @@ -60,11 +76,20 @@ Or, if you're using the `@api_view` decorator with function based views. ## Ordering of renderer classes -It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response. +It's important when specifying the renderer classes for your API to think about +what priority you want to assign to each media type. If a client +underspecifies the representations it can accept, such as sending an `Accept: +*/*` header, or not including an `Accept` header at all, then REST framework +will select the first renderer in the list to use for the response. -For example if your API serves JSON responses and the HTML browsable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header. +For example if your API serves JSON responses and the HTML browsable API, you +might want to make `JSONRenderer` your default renderer, in order to send +`JSON` responses to clients that do not specify an `Accept` header. -If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers]. +If your API includes views that can serve both regular webpages and API +responses depending on the request, then you might consider making +`TemplateHTMLRenderer` your default renderer, in order to play nicely with +older browsers that send [broken accept headers][browser-accept-headers]. --- @@ -74,18 +99,22 @@ If your API includes views that can serve both regular webpages and API response Renders the request data into `JSON`, using utf-8 encoding. -Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace: +Note that the default style is to include unicode characters, and render the +response using a compact style with no unnecessary whitespace: {"unicode black star":"★","value":999} -The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. +The client may additionally include an `'indent'` media type parameter, in +which case the returned `JSON` will be indented. For example `Accept: +application/json; indent=4`. { "unicode black star": "★", "value": 999 } -The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys. +The default JSON encoding style can be altered using the `UNICODE_JSON` and +`COMPACT_JSON` settings keys. **.media_type**: `application/json` @@ -95,10 +124,14 @@ The default JSON encoding style can be altered using the `UNICODE_JSON` and `COM ## TemplateHTMLRenderer -Renders data to HTML, using Django's standard template rendering. -Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`. +Renders data to HTML, using Django's standard template rendering. Unlike other +renderers, the data passed to the `Response` does not need to be serialized. +Also, unlike other renderers, you may want to include a `template_name` +argument when creating the `Response`. -The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context. +The TemplateHTMLRenderer will create a `RequestContext`, using the +`response.data` as the context dict, and determine a template name to use to +render the context. The template name is determined by (in order of preference): @@ -119,9 +152,14 @@ An example of a view that uses `TemplateHTMLRenderer`: self.object = self.get_object() return Response({'user': self.object}, template_name='user_detail.html') -You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. +You can use `TemplateHTMLRenderer` either to return regular HTML pages using +REST framework, or to return both HTML and API responses from a single +endpoint. -If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritised first even for browsers that send poorly formed `ACCEPT:` headers. +If you're building websites that use `TemplateHTMLRenderer` along with other +renderer classes, you should consider listing `TemplateHTMLRenderer` as the +first class in the `renderer_classes` list, so that it will be prioritised +first even for browsers that send poorly formed `ACCEPT:` headers. **.media_type**: `text/html` @@ -133,7 +171,9 @@ See also: `StaticHTMLRenderer` ## StaticHTMLRenderer -A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned. +A simple renderer that simply returns pre-rendered HTML. Unlike other +renderers, the data passed to the response object should be a string +representing the content to be returned. An example of a view that uses `StaticHTMLRenderer`: @@ -143,7 +183,8 @@ An example of a view that uses `StaticHTMLRenderer`: data = '

Hello, world

' return Response(data) -You can use `StaticHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. +You can use `StaticHTMLRenderer` either to return regular HTML pages using REST +framework, or to return both HTML and API responses from a single endpoint. **.media_type**: `text/html` @@ -159,7 +200,8 @@ Renders data into HTML for the Browsable API: ![The BrowsableAPIRenderer](../img/quickstart.png) -This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. +This renderer will determine which other renderer would have been given highest +priority, and use that to display an API style response within the HTML page. **.media_type**: `text/html` @@ -171,7 +213,11 @@ This renderer will determine which other renderer would have been given highest #### Customizing BrowsableAPIRenderer -By default the response content will be rendered with the highest priority renderer apart from `BrowsableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example: +By default the response content will be rendered with the highest priority +renderer apart from `BrowsableAPIRenderer`. If you need to customize this +behavior, for example to use HTML as the default return format, but use JSON in +the browsable API, you can do so by overriding the `get_default_renderer()` +method. For example: class CustomBrowsableAPIRenderer(BrowsableAPIRenderer): def get_default_renderer(self, view): @@ -183,9 +229,12 @@ Renders data into HTML for an admin-like display: ![The AdminRender view](../img/admin.png) -This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data. +This renderer is suitable for CRUD-style web APIs that should also present a +user-friendly interface for managing the data. -Note that views that have nested or list serializers for their input won't work well with the `AdminRenderer`, as the HTML forms are unable to properly support them. +Note that views that have nested or list serializers for their input won't work +well with the `AdminRenderer`, as the HTML forms are unable to properly support +them. **Note**: The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly. For example here we use models `get_absolute_url` method: @@ -206,9 +255,12 @@ Note that views that have nested or list serializers for their input won't work ## HTMLFormRenderer -Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `
` tags, a hidden CSRF input or any submit buttons. +Renders data returned by a serializer into an HTML form. The output of this +renderer does not include the enclosing `` tags, a hidden CSRF input or +any submit buttons. -This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the `render_form` template tag. +This renderer is not intended to be used directly, but can instead be used in +templates by passing a serializer instance to the `render_form` template tag. {% load rest_framework %} @@ -230,7 +282,10 @@ For more information see the [HTML & Forms][html-and-forms] documentation. ## MultiPartRenderer -This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing]. +This renderer is used for rendering HTML multipart form data. **It is not +suitable as a response renderer**, but is instead used for creating test +requests, using REST framework's [test client and test request +factory][testing]. **.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg` @@ -242,9 +297,12 @@ This renderer is used for rendering HTML multipart form data. **It is not suita # Custom renderers -To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, media_type=None, renderer_context=None)` method. +To implement a custom renderer, you should override `BaseRenderer`, set the +`.media_type` and `.format` properties, and implement the `.render(self, data, +media_type=None, renderer_context=None)` method. -The method should return a bytestring, which will be used as the body of the HTTP response. +The method should return a bytestring, which will be used as the body of the +HTTP response. The arguments passed to the `.render()` method are: @@ -254,19 +312,25 @@ The request data, as set by the `Response()` instantiation. ### `media_type=None` -Optional. If provided, this is the accepted media type, as determined by the content negotiation stage. +Optional. If provided, this is the accepted media type, as determined by the +content negotiation stage. -Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`. +Depending on the client's `Accept:` header, this may be more specific than the +renderer's `media_type` attribute, and may include media type parameters. For +example `"application/json; nested=true"`. ### `renderer_context=None` -Optional. If provided, this is a dictionary of contextual information provided by the view. +Optional. If provided, this is a dictionary of contextual information provided +by the view. -By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`. +By default this will include the following keys: `view`, `request`, `response`, +`args`, `kwargs`. ## Example -The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response. +The following is an example plaintext renderer that will return a response with +the `data` parameter as the content of the response. from django.utils.encoding import smart_unicode from rest_framework import renderers @@ -281,7 +345,8 @@ The following is an example plaintext renderer that will return a response with ## Setting the character set -By default renderer classes are assumed to be using the `UTF-8` encoding. To use a different encoding, set the `charset` attribute on the renderer. +By default renderer classes are assumed to be using the `UTF-8` encoding. To +use a different encoding, set the `charset` attribute on the renderer. class PlainTextRenderer(renderers.BaseRenderer): media_type = 'text/plain' @@ -291,11 +356,17 @@ By default renderer classes are assumed to be using the `UTF-8` encoding. To us def render(self, data, media_type=None, renderer_context=None): return data.encode(self.charset) -Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding. +Note that if a renderer class returns a unicode string, then the response +content will be coerced into a bytestring by the `Response` class, with the +`charset` attribute set on the renderer used to determine the encoding. -If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set. +If the renderer returns a bytestring representing raw binary content, you +should set a charset value of `None`, which will ensure the `Content-Type` +header of the response will not have a `charset` value set. -In some cases you may also want to set the `render_style` attribute to `'binary'`. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string. +In some cases you may also want to set the `render_style` attribute to +`'binary'`. Doing so will also ensure that the browsable API will not attempt +to display the binary content as a string. class JPEGRenderer(renderers.BaseRenderer): media_type = 'image/jpeg' @@ -312,14 +383,20 @@ In some cases you may also want to set the `render_style` attribute to `'binary' You can do some pretty flexible things using REST framework's renderers. Some examples... -* Provide either flat or nested representations from the same endpoint, depending on the requested media type. -* Serve both regular HTML webpages, and JSON based API responses from the same endpoints. +* Provide either flat or nested representations from the same endpoint, + depending on the requested media type. +* Serve both regular HTML webpages, and JSON based API responses from the same + endpoints. * Specify multiple types of HTML representation for API clients to use. -* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, and use the `Accept` header to vary the encoding of the response. +* Underspecify a renderer's media type, such as using `media_type = 'image/*'`, + and use the `Accept` header to vary the encoding of the response. ## Varying behaviour by media type -In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response. +In some cases you might want your view to use different serialization styles +depending on the accepted media type. If you need to do this you can access +`request.accepted_renderer` to determine the negotiated renderer that will be +used for the response. For example: @@ -346,36 +423,55 @@ For example: ## Underspecifying the media type -In some cases you might want a renderer to serve a range of media types. -In this case you can underspecify the media types it should respond to, by using a `media_type` value such as `image/*`, or `*/*`. +In some cases you might want a renderer to serve a range of media types. In +this case you can underspecify the media types it should respond to, by using a +`media_type` value such as `image/*`, or `*/*`. -If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the `content_type` attribute. For example: +If you underspecify the renderer's media type, you should make sure to specify +the media type explicitly when you return the response, using the +`content_type` attribute. For example: return Response(data, content_type='image/png') ## Designing your media types -For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll need to consider the design and usage of your media types in more detail. +For the purposes of many Web APIs, simple `JSON` responses with hyperlinked +relations may be sufficient. If you want to fully embrace RESTful design and +[HATEOAS] you'll need to consider the design and usage of your media types in +more detail. -In [the words of Roy Fielding][quote], "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.". +In [the words of Roy Fielding][quote], "A REST API should spend almost all of +its descriptive effort in defining the media type(s) used for representing +resources and driving application state, or in defining extended relation names +and/or hypertext-enabled mark-up for existing standard media types.". -For good examples of custom media types, see GitHub's use of a custom [application/vnd.github+json] media type, and Mike Amundsen's IANA approved [application/vnd.collection+json] JSON-based hypermedia. +For good examples of custom media types, see GitHub's use of a custom +[application/vnd.github+json] media type, and Mike Amundsen's IANA approved +[application/vnd.collection+json] JSON-based hypermedia. ## HTML error views -Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an `Http404` or `PermissionDenied` exception, or a subclass of `APIException`. +Typically a renderer will behave the same regardless of if it's dealing with a +regular response, or with a response caused by an exception being raised, such +as an `Http404` or `PermissionDenied` exception, or a subclass of +`APIException`. -If you're using either the `TemplateHTMLRenderer` or the `StaticHTMLRenderer` and an exception is raised, the behavior is slightly different, and mirrors [Django's default handling of error views][django-error-views]. +If you're using either the `TemplateHTMLRenderer` or the `StaticHTMLRenderer` +and an exception is raised, the behavior is slightly different, and mirrors +[Django's default handling of error views][django-error-views]. -Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence. +Exceptions raised and handled by an HTML renderer will attempt to render using +one of the following methods, by order of precedence. * Load and render a template named `{status_code}.html`. * Load and render a template named `api_exception.html`. * Render the HTTP status code and text, for example "404 Not Found". -Templates will render with a `RequestContext` which includes the `status_code` and `details` keys. +Templates will render with a `RequestContext` which includes the `status_code` +and `details` keys. -**Note**: If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text. +**Note**: If `DEBUG=True`, Django's standard traceback error page will be +displayed instead of rendering the HTTP status code and text. --- @@ -385,7 +481,9 @@ The following third party packages are also available. ## YAML -[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. +[REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and +rendering support. It was previously included directly in the REST framework +package, and is now instead supported as a third-party package. #### Installation & configuration @@ -406,7 +504,9 @@ Modify your REST framework settings. ## XML -[REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. +[REST Framework XML][rest-framework-xml] provides a simple informal XML format. +It was previously included directly in the REST framework package, and is now +instead supported as a third-party package. #### Installation & configuration @@ -427,13 +527,19 @@ Modify your REST framework settings. ## JSONP -[REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. +[REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. +It was previously included directly in the REST framework package, and is now +instead supported as a third-party package. --- -**Warning**: If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details. +**Warning**: If you require cross-domain AJAX requests, you should generally be +using the more modern approach of [CORS][cors] as an alternative to `JSONP`. +See the [CORS documentation][cors-docs] for more details. -The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions. +The `jsonp` approach is essentially a browser hack, and is [only appropriate +for globally readable API endpoints][jsonp-security], where `GET` requests are +unauthenticated and do not require any user permissions. --- @@ -453,27 +559,44 @@ Modify your REST framework settings. ## MessagePack -[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. ## CSV -Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework. +Comma-separated values are a plain-text tabular data format, that can be easily +imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the +[djangorestframework-csv][djangorestframework-csv] package which provides CSV +renderer support for REST framework. ## UltraJSON -[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]. +[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]. ## Pandas (CSV, Excel, PNG) -[Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq]. +[Django REST Pandas] provides a serializer and renderers that support +additional data processing and output via the [Pandas] DataFrame API. Django +REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks +(both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by +[S. Andrew Sheppard][sheppard] as part of the [wq Project][wq]. ## LaTeX -[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble]. +[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It +is maintained by [Pebble (S/F Software)][mypebble]. [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index 393b1ab9a..4fd173e46 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -6,21 +6,29 @@ source: request.py > > — Malcom Tredinnick, [Django developers group][cite] -REST framework's `Request` class extends the standard `HttpRequest`, adding support for REST framework's flexible request parsing and request authentication. +REST framework's `Request` class extends the standard `HttpRequest`, adding +support for REST framework's flexible request parsing and request +authentication. --- # Request parsing -REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data. +REST framework's Request objects provide flexible request parsing that allows +you to treat requests with JSON data or other media types in the same way that +you would normally deal with form data. ## .data -`request.data` returns the parsed content of the request body. This is similar to the standard `request.POST` and `request.FILES` attributes except that: +`request.data` returns the parsed content of the request body. This is similar +to the standard `request.POST` and `request.FILES` attributes except that: * It includes all parsed content, including *file and non-file* inputs. -* It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests. -* It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming JSON data in the same way that you handle incoming form data. +* It supports parsing the content of HTTP methods other than `POST`, meaning + that you can access the content of `PUT` and `PATCH` requests. +* It supports REST framework's flexible request parsing, rather than just + supporting form data. For example you can handle incoming JSON data in the + same way that you handle incoming form data. For more details see the [parsers documentation]. @@ -28,25 +36,38 @@ For more details see the [parsers documentation]. `request.query_params` is a more correctly named synonym for `request.GET`. -For clarity inside your code, we recommend using `request.query_params` instead of the Django's standard `request.GET`. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just `GET` requests. +For clarity inside your code, we recommend using `request.query_params` instead +of the Django's standard `request.GET`. Doing so will help keep your codebase +more correct and obvious - any HTTP method type may include query parameters, +not just `GET` requests. ## .parsers -The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Parser` instances, based on the `parser_classes` set on the view or based on the `DEFAULT_PARSER_CLASSES` setting. +The `APIView` class or `@api_view` decorator will ensure that this property is +automatically set to a list of `Parser` instances, based on the +`parser_classes` set on the view or based on the `DEFAULT_PARSER_CLASSES` +setting. You won't typically need to access this property. --- -**Note:** If a client sends malformed content, then accessing `request.data` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response. +**Note:** If a client sends malformed content, then accessing `request.data` +may raise a `ParseError`. By default REST framework's `APIView` class or +`@api_view` decorator will catch the error and return a `400 Bad Request` +response. -If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response. +If a client sends a request with a content-type that cannot be parsed then a +`UnsupportedMediaType` exception will be raised, which by default will be +caught and return a `415 Unsupported Media Type` response. --- # Content negotiation -The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behaviour such as selecting a different serialisation schemes for different media types. +The request exposes some properties that allow you to determine the result of +the content negotiation stage. This allows you to implement behaviour such as +selecting a different serialisation schemes for different media types. ## .accepted_renderer @@ -54,13 +75,15 @@ The renderer instance what was selected by the content negotiation stage. ## .accepted_media_type -A string representing the media type that was accepted by the content negotiation stage. +A string representing the media type that was accepted by the content +negotiation stage. --- # Authentication -REST framework provides flexible, per-request authentication, that gives you the ability to: +REST framework provides flexible, per-request authentication, that gives you +the ability to: * Use different authentication policies for different parts of your API. * Support the use of multiple authentication policies. @@ -68,23 +91,33 @@ REST framework provides flexible, per-request authentication, that gives you the ## .user -`request.user` typically returns an instance of `django.contrib.auth.models.User`, although the behavior depends on the authentication policy being used. +`request.user` typically returns an instance of +`django.contrib.auth.models.User`, although the behavior depends on the +authentication policy being used. -If the request is unauthenticated the default value of `request.user` is an instance of `django.contrib.auth.models.AnonymousUser`. +If the request is unauthenticated the default value of `request.user` is an +instance of `django.contrib.auth.models.AnonymousUser`. For more details see the [authentication documentation]. ## .auth -`request.auth` returns any additional authentication context. The exact behavior of `request.auth` depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against. +`request.auth` returns any additional authentication context. The exact +behavior of `request.auth` depends on the authentication policy being used, but +it may typically be an instance of the token that the request was authenticated +against. -If the request is unauthenticated, or if no additional context is present, the default value of `request.auth` is `None`. +If the request is unauthenticated, or if no additional context is present, the +default value of `request.auth` is `None`. For more details see the [authentication documentation]. ## .authenticators -The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Authentication` instances, based on the `authentication_classes` set on the view or based on the `DEFAULT_AUTHENTICATORS` setting. +The `APIView` class or `@api_view` decorator will ensure that this property is +automatically set to a list of `Authentication` instances, based on the +`authentication_classes` set on the view or based on the +`DEFAULT_AUTHENTICATORS` setting. You won't typically need to access this property. @@ -92,11 +125,13 @@ You won't typically need to access this property. # Browser enhancements -REST framework supports a few browser enhancements such as browser-based `PUT`, `PATCH` and `DELETE` forms. +REST framework supports a few browser enhancements such as browser-based `PUT`, +`PATCH` and `DELETE` forms. ## .method -`request.method` returns the **uppercased** string representation of the request's HTTP method. +`request.method` returns the **uppercased** string representation of the +request's HTTP method. Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported. @@ -104,11 +139,16 @@ For more information see the [browser enhancements documentation]. ## .content_type -`request.content_type`, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided. +`request.content_type`, returns a string object representing the media type of +the HTTP request's body, or an empty string if no media type was provided. -You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior. +You won't typically need to directly access the request's content type, as +you'll normally rely on REST framework's default request parsing behavior. -If you do need to access the content type of the request you should use the `.content_type` property in preference to using `request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for browser-based non-form content. +If you do need to access the content type of the request you should use the +`.content_type` property in preference to using +`request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for +browser-based non-form content. For more information see the [browser enhancements documentation]. @@ -116,15 +156,19 @@ For more information see the [browser enhancements documentation]. `request.stream` returns a stream representing the content of the request body. -You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior. +You won't typically need to directly access the request's content, as you'll +normally rely on REST framework's default request parsing behavior. --- # Standard HttpRequest attributes -As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` and `request.session` dictionaries are available as normal. +As REST framework's `Request` extends Django's `HttpRequest`, all the other +standard attributes and methods are also available. For example the +`request.META` and `request.session` dictionaries are available as normal. -Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition. +Note that due to implementation reasons the `Request` class does not inherit +from `HttpRequest` class, but instead extends the class using composition. [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md index 97f312710..4be6cfb57 100644 --- a/docs/api-guide/responses.md +++ b/docs/api-guide/responses.md @@ -2,17 +2,33 @@ source: response.py # Responses -> Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. +> Unlike basic HttpResponse objects, TemplateResponse objects retain the +> details of the context that was provided by the view to compute the response. +> The final output of the response is not computed until it is needed, later in +> the response process. > > — [Django documentation][cite] -REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request. +REST framework supports HTTP content negotiation by providing a `Response` +class which allows you to return content that can be rendered into multiple +content types, depending on the client request. -The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialised with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. +The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` +objects are initialised with data, which should consist of native Python +primitives. REST framework then uses standard HTTP content negotiation to +determine how it should render the final response content. -There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` or `StreamingHttpResponse` objects from your views if required. Using the `Response` class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats. +There's no requirement for you to use the `Response` class, you can also return +regular `HttpResponse` or `StreamingHttpResponse` objects from your views if +required. Using the `Response` class simply provides a nicer interface for +returning content-negotiated Web API responses, that can be rendered to +multiple formats. -Unless you want to heavily customize REST framework for some reason, you should always use an `APIView` class or `@api_view` function for views that return `Response` objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view. +Unless you want to heavily customize REST framework for some reason, you should +always use an `APIView` class or `@api_view` function for views that return +`Response` objects. Doing so ensures that the view can perform content +negotiation and select the appropriate renderer for the response, before it is +returned from the view. --- @@ -20,21 +36,31 @@ Unless you want to heavily customize REST framework for some reason, you should ## Response() -**Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)` +**Signature:** `Response(data, status=None, template_name=None, headers=None, +content_type=None)` -Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives. +Unlike regular `HttpResponse` objects, you do not instantiate `Response` +objects with rendered content. Instead you pass in unrendered data, which may +consist of any Python primitives. -The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the `Response` object. +The renderers used by the `Response` class cannot natively handle complex +datatypes such as Django model instances, so you need to serialize the data +into primitive datatypes before creating the `Response` object. -You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization. +You can use REST framework's `Serializer` classes to perform this data +serialization, or use your own custom serialization. Arguments: * `data`: The serialized data for the response. -* `status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes]. +* `status`: A status code for the response. Defaults to 200. + See also [status codes][statuscodes]. * `template_name`: A template name to use if `HTMLRenderer` is selected. * `headers`: A dictionary of HTTP headers to use in the response. -* `content_type`: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly. +* `content_type`: The content type of the response. Typically, this will be + set automatically by the renderer as determined by content negotiation, but + there may be some cases where you need to specify the content type + explicitly. --- @@ -50,35 +76,43 @@ The numeric status code of the HTTP response. ## .content -The rendered content of the response. The `.render()` method must have been called before `.content` can be accessed. +The rendered content of the response. The `.render()` method must have been +called before `.content` can be accessed. ## .template_name -The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the response. +The `template_name`, if supplied. Only required if `HTMLRenderer` or some +other custom template renderer is the accepted renderer for the response. ## .accepted_renderer The renderer instance that will be used to render the response. -Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view. +Set automatically by the `APIView` or `@api_view` immediately before the +response is returned from the view. ## .accepted_media_type The media type that was selected by the content negotiation stage. -Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view. +Set automatically by the `APIView` or `@api_view` immediately before the +response is returned from the view. ## .renderer_context -A dictionary of additional context information that will be passed to the renderer's `.render()` method. +A dictionary of additional context information that will be passed to the +renderer's `.render()` method. -Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view. +Set automatically by the `APIView` or `@api_view` immediately before the +response is returned from the view. --- # Standard HttpResponse attributes -The `Response` class extends `SimpleTemplateResponse`, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way: +The `Response` class extends `SimpleTemplateResponse`, and all the usual +attributes and methods are also available on the response. For example you can +set headers on the response in the standard way: response = Response() response['Cache-Control'] = 'no-cache' @@ -87,9 +121,14 @@ The `Response` class extends `SimpleTemplateResponse`, and all the usual attribu **Signature:** `.render()` -As with any other `TemplateResponse`, this method is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type, renderer_context)` method on the `accepted_renderer` instance. +As with any other `TemplateResponse`, this method is called to render the +serialized data of the response into the final response content. When +`.render()` is called, the response content will be set to the result of +calling the `.render(data, accepted_media_type, renderer_context)` method on +the `accepted_renderer` instance. -You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle. +You won't typically need to call `.render()` yourself, as it's handled by +Django's standard response cycle. [cite]: https://docs.djangoproject.com/en/dev/ref/template-response/ [statuscodes]: status-codes.md diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md index 71fb83f9e..8a3f70ee8 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -2,30 +2,43 @@ source: reverse.py # Returning URLs -> The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components. +> The central feature that distinguishes the REST architectural style from +> other network-based styles is its emphasis on a uniform interface between +> components. > -> — Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite] +> — Roy Fielding, [Architectural Styles and the Design of Network-based +> Software Architectures][cite] -As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`. +As a rule, it's probably better practice to return absolute URIs from your Web +APIs, such as `http://example.com/foobar`, rather than returning relative URIs, +such as `/foobar`. The advantages of doing so are: * It's more explicit. * It leaves less work for your API clients. -* There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type. -* It makes it easy to do things like markup HTML representations with hyperlinks. +* There's no ambiguity about the meaning of the string when it's found in + representations such as JSON that do not have a native URI type. +* It makes it easy to do things like markup HTML representations with + hyperlinks. -REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API. +REST framework provides two utility functions to make it more simple to return +absolute URIs from your Web API. -There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier. +There's no requirement for you to use them, but if you do then the +self-describing API will be able to automatically hyperlink its output for you, +which makes browsing the API much easier. ## reverse **Signature:** `reverse(viewname, *args, **kwargs)` -Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port. +Has the same behavior as [`django.core.urlresolvers.reverse`][reverse], except +that it returns a fully qualified URL, using the request to determine the host +and port. -You should **include the request as a keyword argument** to the function, for example: +You should **include the request as a keyword argument** to the function, for +example: from rest_framework.reverse import reverse from rest_framework.views import APIView @@ -44,9 +57,12 @@ You should **include the request as a keyword argument** to the function, for ex **Signature:** `reverse_lazy(viewname, *args, **kwargs)` -Has the same behavior as [`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port. +Has the same behavior as +[`django.core.urlresolvers.reverse_lazy`][reverse-lazy], except that it returns +a fully qualified URL, using the request to determine the host and port. -As with the `reverse` function, you should **include the request as a keyword argument** to the function, for example: +As with the `reverse` function, you should **include the request as a keyword +argument** to the function, for example: api_root = reverse_lazy('api-root', request=request) diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 10a86bdf0..3928a25cc 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -2,13 +2,19 @@ source: routers.py # Routers -> Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. +> Resource routing allows you to quickly declare all of the common routes for a +> given resourceful controller. Instead of declaring separate routes for your +> index... a resourceful route declares them in a single line of code. > > — [Ruby on Rails Documentation][cite] -Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. +Some Web frameworks such as Rails provide functionality for automatically +determining how the URLs for an application should be mapped to the logic that +deals with handling incoming requests. -REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. +REST framework adds support for automatic URL routing to Django, and provides +you with a simple, quick and consistent way of wiring your view logic to a set +of URLs. ## Usage @@ -28,7 +34,11 @@ There are two mandatory arguments to the `register()` method: Optionally, you may also specify an additional argument: -* `base_name` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `base_name` when registering the viewset. +* `base_name` - The base to use for the URL names that are created. If unset + the basename will be automatically generated based on the `queryset` + attribute of the viewset, if it has one. Note that if the viewset does not + include a `queryset` attribute then you must set `base_name` when registering + the viewset. The example above would generate the following URL patterns: @@ -39,30 +49,39 @@ The example above would generate the following URL patterns: --- -**Note**: The `base_name` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part. +**Note**: The `base_name` argument is used to specify the initial part of the +view name pattern. In the example above, that's the `user` or `account` part. -Typically you won't *need* to specify the `base_name` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this: +Typically you won't *need* to specify the `base_name` argument, but if you have +a viewset where you've defined a custom `get_queryset` method, then the viewset +may not have a `.queryset` attribute set. If you try to register that viewset +you'll see an error like this: - 'base_name' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. + 'base_name' argument not specified, and could not automatically determine + the name from the viewset, as it does not have a '.queryset' attribute. -This means you'll need to explicitly set the `base_name` argument when registering the viewset, as it could not be automatically determined from the model name. +This means you'll need to explicitly set the `base_name` argument when +registering the viewset, as it could not be automatically determined from the +model name. --- ### Using `include` with routers -The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs. +The `.urls` attribute on a router instance is simply a standard list of URL +patterns. There are a number of different styles for how you can include these +URLs. For example, you can append `router.urls` to a list of existing views… router = routers.SimpleRouter() router.register(r'users', UserViewSet) router.register(r'accounts', AccountViewSet) - + urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), ] - + urlpatterns += router.urls Alternatively you can use Django's `include` function, like so… @@ -79,12 +98,17 @@ Router URL patterns can also be namespaces. url(r'^api/', include(router.urls, namespace='api')), ] -If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters on the serializers correctly reflect the namespace. In the example above you'd need to include a parameter such as `view_name='api:user-detail'` for serializer fields hyperlinked to the user detail view. +If using namespacing with hyperlinked serializers you'll also need to ensure +that any `view_name` parameters on the serializers correctly reflect the +namespace. In the example above you'd need to include a parameter such as +`view_name='api:user-detail'` for serializer fields hyperlinked to the user +detail view. ### Extra link and actions -Any methods on the viewset decorated with `@detail_route` or `@list_route` will also be routed. -For example, given a method like this on the `UserViewSet` class: +Any methods on the viewset decorated with `@detail_route` or `@list_route` will +also be routed. For example, given a method like this on the `UserViewSet` +class: from myapp.permissions import IsAdminOrIsSelf from rest_framework.decorators import detail_route @@ -100,16 +124,18 @@ The following URL pattern would additionally be generated: * URL pattern: `^users/{pk}/set_password/$` Name: `'user-set-password'` -If you do not want to use the default URL generated for your custom action, you can instead use the url_path parameter to customize it. +If you do not want to use the default URL generated for your custom action, you +can instead use the url_path parameter to customize it. -For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write: +For example, if you want to change the URL for our custom action to +`^users/{pk}/change-password/$`, you could write: from myapp.permissions import IsAdminOrIsSelf from rest_framework.decorators import detail_route - + class UserViewSet(ModelViewSet): ... - + @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf], url_path='change-password') def set_password(self, request, pk=None): ... @@ -124,7 +150,10 @@ For more information see the viewset documentation on [marking extra actions for ## SimpleRouter -This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@detail_route` or `@list_route` decorators. +This router includes routes for the standard set of `list`, `create`, +`retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can +also mark additional methods to be routed, using the `@detail_route` or +`@list_route` decorators. @@ -138,14 +167,21 @@ This router includes routes for the standard set of `list`, `create`, `retrieve`
URL StyleHTTP MethodActionURL Name
{prefix}/{lookup}/{methodname}/GET, or as specified by `methods` argument`@detail_route` decorated method{basename}-{methodname}
-By default the URLs created by `SimpleRouter` are appended with a trailing slash. -This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example: +By default the URLs created by `SimpleRouter` are appended with a trailing +slash. This behavior can be modified by setting the `trailing_slash` argument +to `False` when instantiating the router. For example: router = SimpleRouter(trailing_slash=False) -Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style. +Trailing slashes are conventional in Django, but are not used by default in +some other frameworks such as Rails. Which style you choose to use is largely +a matter of preference, although some javascript frameworks may expect a +particular routing style. -The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs: +The router will match lookup values containing any characters except slashes +and period characters. For a more restrictive (or lenient) lookup pattern, set +the `lookup_value_regex` attribute on the viewset. For example, you can limit +the lookup to valid UUIDs: class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): lookup_field = 'my_model_id' @@ -153,7 +189,10 @@ The router will match lookup values containing any characters except slashes and ## DefaultRouter -This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes. +This router is similar to `SimpleRouter` as above, but additionally includes a +default API root view, that returns a response containing hyperlinks to all the +list views. It also generates routes for optional `.json` style format +suffixes. @@ -168,48 +207,70 @@ This router is similar to `SimpleRouter` as above, but additionally includes a d
URL StyleHTTP MethodActionURL Name
{prefix}/{lookup}/{methodname}/[.format]GET, or as specified by `methods` argument`@detail_route` decorated method{basename}-{methodname}
-As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router. +As with `SimpleRouter` the trailing slashes on the URL routes can be removed by +setting the `trailing_slash` argument to `False` when instantiating the router. router = DefaultRouter(trailing_slash=False) # Custom Routers -Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the your URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. +Implementing a custom router isn't something you'd need to do very often, but +it can be useful if you have specific requirements about how the your URLs for +your API are structured. Doing so allows you to encapsulate the URL structure +in a reusable way that ensures you don't have to write your URL patterns +explicitly for each new view. -The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. The `.routes` attribute is a list of `Route` named tuples. +The simplest way to implement a custom router is to subclass one of the +existing router classes. The `.routes` attribute is used to template the URL +patterns that will be mapped to each viewset. The `.routes` attribute is a list +of `Route` named tuples. The arguments to the `Route` named tuple are: -**url**: A string representing the URL to be routed. May include the following format strings: +**url**: A string representing the URL to be routed. May include the following +format strings: * `{prefix}` - The URL prefix to use for this set of routes. * `{lookup}` - The lookup field used to match against a single instance. -* `{trailing_slash}` - Either a '/' or an empty string, depending on the `trailing_slash` argument. +* `{trailing_slash}` - Either a '/' or an empty string, depending on the + `trailing_slash` argument. **mapping**: A mapping of HTTP method names to the view methods -**name**: The name of the URL as used in `reverse` calls. May include the following format string: +**name**: The name of the URL as used in `reverse` calls. May include the +following format string: * `{basename}` - The base to use for the URL names that are created. -**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `suffix` argument is reserved for identifying the viewset type, used when generating the view name and breadcrumb links. +**initkwargs**: A dictionary of any additional arguments that should be passed +when instantiating the view. Note that the `suffix` argument is reserved for +identifying the viewset type, used when generating the view name and breadcrumb +links. ## Customizing dynamic routes -You can also customize how the `@list_route` and `@detail_route` decorators are routed. -To route either or both of these decorators, include a `DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes` list. +You can also customize how the `@list_route` and `@detail_route` decorators are +routed. To route either or both of these decorators, include a +`DynamicListRoute` and/or `DynamicDetailRoute` named tuple in the `.routes` +list. The arguments to `DynamicListRoute` and `DynamicDetailRoute` are: -**url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{methodname}` and `{methodnamehyphen}` format strings. +**url**: A string representing the URL to be routed. May include the same +format strings as `Route`, and additionally accepts the `{methodname}` and +`{methodnamehyphen}` format strings. -**name**: The name of the URL as used in `reverse` calls. May include the following format strings: `{basename}`, `{methodname}` and `{methodnamehyphen}`. +**name**: The name of the URL as used in `reverse` calls. May include the +following format strings: `{basename}`, `{methodname}` and +`{methodnamehyphen}`. -**initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. +**initkwargs**: A dictionary of any additional arguments that should be passed +when instantiating the view. ## Example -The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention. +The following example will only route to the `list` and `retrieve` actions, and +does not use the trailing slash convention. from rest_framework.routers import Route, DynamicDetailRoute, SimpleRouter @@ -278,9 +339,15 @@ For another example of setting the `.routes` attribute, see the source code for ## Advanced custom routers -If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. +If you want to provide totally custom behavior, you can override `BaseRouter` +and override the `get_urls(self)` method. The method should inspect the +registered viewsets and return a list of URL patterns. The registered prefix, +viewset and basename tuples may be inspected by accessing the `self.registry` +attribute. -You may also want to override the `get_default_base_name(self, viewset)` method, or else always explicitly set the `base_name` argument when registering your viewsets with the router. +You may also want to override the `get_default_base_name(self, viewset)` +method, or else always explicitly set the `base_name` argument when registering +your viewsets with the router. # Third Party Packages @@ -288,11 +355,17 @@ 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. +The [drf-nested-routers package][drf-nested-routers] provides routers and +relationship fields for working with nested resources. ## ModelRouter (wq.db.rest) -The [wq.db package][wq.db] provides an advanced [ModelRouter][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 `rest.router.register_model` is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration. +The [wq.db package][wq.db] provides an advanced [ModelRouter][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 `rest.router.register_model` is a model class. Reasonable +defaults for a url prefix, serializer, and viewset will be inferred from the +model and global configuration. from wq.db import rest from myapp.models import MyModel @@ -301,7 +374,11 @@ The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] clas ## DRF-extensions -The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names]. +The [`DRF-extensions` package][drf-extensions] provides +[routers][drf-extensions-routers] for creating [nested +viewsets][drf-extensions-nested-viewsets], [collection level +controllers][drf-extensions-collection-level-controllers] with [customizable +endpoint names][drf-extensions-customizable-endpoint-names]. [cite]: http://guides.rubyonrails.org/routing.html [route-decorators]: viewsets.md#marking-extra-actions-for-routing diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index 7f8af723e..74cc2d9cb 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -2,7 +2,9 @@ source: schemas.py # Schemas -> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support. +> A machine-readable [schema] describes what resources are available via the +> API, what their URLs are, how they are represented and what operations they +> support. > > — Heroku, [JSON Schema for the Heroku Platform API][cite] @@ -281,9 +283,12 @@ Typically you'll instantiate `SchemaGenerator` with a single argument, like so: Arguments: * `title` - The name of the API. **required** -* `url` - The root URL of the API schema. This option is not required unless the schema is included under path prefix. -* `patterns` - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf. -* `urlconf` - A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`. +* `url` - The root URL of the API schema. This option is not required unless + the schema is included under path prefix. +* `patterns` - A list of URLs to inspect when generating the schema. Defaults + to the project's URL conf. +* `urlconf` - A URL conf module name to use when generating the schema. + Defaults to `settings.ROOT_URLCONF`. ### get_schema() @@ -382,27 +387,37 @@ the following strings: **"path"** -Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`. +Included in a templated URI. For example a `url` value of +`/products/{product_code}/` could be used together with a `"path"` field, to +handle API inputs in a URL path such as `/products/slim-fit-jeans/`. -These fields will normally correspond with [named arguments in the project URL conf][named-arguments]. +These fields will normally correspond with [named arguments in the project URL +conf][named-arguments]. **"query"** -Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests. +Included as a URL query parameter. For example `?search=sale`. Typically for +`GET` requests. -These fields will normally correspond with pagination and filtering controls on a view. +These fields will normally correspond with pagination and filtering controls on +a view. **"form"** -Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link. +Included in the request body, as a single item of a JSON object or HTML form. +For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` +requests. Multiple `"form"` fields may be included on a single link. These fields will normally correspond with serializer fields on a view. **"body"** -Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields. +Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` +requests. No more than one `"body"` field may exist on a link. May not be used +together with `"form"` fields. -These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views. +These fields will normally correspond with views that use `ListSerializer` to +validate the request input, or with file upload views. #### `encoding` diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 70fab448c..4001eb6e5 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -8,9 +8,17 @@ will take some serious design work. > > — Russell Keith-Magee, [Django users group][cite] -Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into `JSON`, `XML` or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. +Serializers allow complex data such as querysets and model instances to be +converted to native Python datatypes that can then be easily rendered into +`JSON`, `XML` or other content types. Serializers also provide +deserialization, allowing parsed data to be converted back into complex types, +after first validating the incoming data. -The serializers in REST framework work very similarly to Django's `Form` and `ModelForm` classes. We provide a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets. +The serializers in REST framework work very similarly to Django's `Form` and +`ModelForm` classes. We provide a `Serializer` class which gives you a +powerful, generic way to control the output of your responses, as well as a +`ModelSerializer` class which provides a useful shortcut for creating +serializers that deal with model instances and querysets. ## Declaring Serializers @@ -26,7 +34,8 @@ Let's start by creating a simple object we can use for example purposes: comment = Comment(email='leila@example.com', content='foo bar') -We'll declare a serializer that we can use to serialize and deserialize data that corresponds to `Comment` objects. +We'll declare a serializer that we can use to serialize and deserialize data +that corresponds to `Comment` objects. Declaring a serializer looks very similar to declaring a form: @@ -39,13 +48,15 @@ Declaring a serializer looks very similar to declaring a form: ## Serializing objects -We can now use `CommentSerializer` to serialize a comment, or list of comments. Again, using the `Serializer` class looks a lot like using a `Form` class. +We can now use `CommentSerializer` to serialize a comment, or list of comments. +Again, using the `Serializer` class looks a lot like using a `Form` class. serializer = CommentSerializer(comment) serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} -At this point we've translated the model instance into Python native datatypes. To finalise the serialization process we render the data into `json`. +At this point we've translated the model instance into Python native datatypes. +To finalise the serialization process we render the data into `json`. from rest_framework.renderers import JSONRenderer @@ -55,7 +66,8 @@ At this point we've translated the model instance into Python native datatypes. ## Deserializing objects -Deserialization is similar. First we parse a stream into Python native datatypes... +Deserialization is similar. First we parse a stream into Python native +datatypes... from django.utils.six import BytesIO from rest_framework.parsers import JSONParser @@ -73,7 +85,9 @@ Deserialization is similar. First we parse a stream into Python native datatypes ## Saving instances -If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `update()` methods. For example: +If we want to be able to return complete object instances based on the +validated data we need to implement one or both of the `.create()` and +`update()` methods. For example: class CommentSerializer(serializers.Serializer): email = serializers.EmailField() @@ -89,7 +103,9 @@ If we want to be able to return complete object instances based on the validated instance.created = validated_data.get('created', instance.created) return instance -If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if `Comment` was a Django model, the methods might look like this: +If your object instances correspond to Django models you'll also want to ensure +that these methods save the object to the database. For example, if `Comment` +was a Django model, the methods might look like this: def create(self, validated_data): return Comment.objects.create(**validated_data) @@ -101,11 +117,14 @@ If your object instances correspond to Django models you'll also want to ensure instance.save() return instance -Now when deserializing data, we can call `.save()` to return an object instance, based on the validated data. +Now when deserializing data, we can call `.save()` to return an object +instance, based on the validated data. comment = serializer.save() -Calling `.save()` will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: +Calling `.save()` will either create a new instance, or update an existing +instance, depending on if an existing instance was passed when instantiating +the serializer class: # .save() will create a new instance. serializer = CommentSerializer(data=data) @@ -113,23 +132,33 @@ Calling `.save()` will either create a new instance, or update an existing insta # .save() will update the existing `comment` instance. serializer = CommentSerializer(comment, data=data) -Both the `.create()` and `.update()` methods are optional. You can implement either neither, one, or both of them, depending on the use-case for your serializer class. +Both the `.create()` and `.update()` methods are optional. You can implement +either neither, one, or both of them, depending on the use-case for your +serializer class. #### Passing additional attributes to `.save()` -Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data. +Sometimes you'll want your view code to be able to inject additional data at +the point of saving the instance. This additional data might include +information like the current user, the current time, or anything else that is +not part of the request data. -You can do so by including additional keyword arguments when calling `.save()`. For example: +You can do so by including additional keyword arguments when calling `.save()`. +For example: serializer.save(owner=request.user) -Any additional keyword arguments will be included in the `validated_data` argument when `.create()` or `.update()` are called. +Any additional keyword arguments will be included in the `validated_data` +argument when `.create()` or `.update()` are called. #### Overriding `.save()` directly. -In some cases the `.create()` and `.update()` method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message. +In some cases the `.create()` and `.update()` method names may not be +meaningful. For example, in a contact form we may not be creating new +instances, but instead sending an email or other message. -In these cases you might instead choose to override `.save()` directly, as being more readable and meaningful. +In these cases you might instead choose to override `.save()` directly, as +being more readable and meaningful. For example: @@ -142,11 +171,15 @@ For example: message = self.validated_data['message'] send_email(from=email, message=message) -Note that in the case above we're now having to access the serializer `.validated_data` property directly. +Note that in the case above we're now having to access the serializer +`.validated_data` property directly. ## Validation -When deserializing data, you always need to call `is_valid()` before attempting to access the validated data, or save an object instance. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example: +When deserializing data, you always need to call `is_valid()` before attempting +to access the validated data, or save an object instance. If any validation +errors occur, the `.errors` property will contain a dictionary representing the +resulting error messages. For example: serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) serializer.is_valid() @@ -154,26 +187,39 @@ When deserializing data, you always need to call `is_valid()` before attempting serializer.errors # {'email': [u'Enter a valid e-mail address.'], 'created': [u'This field is required.']} -Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting. +Each key in the dictionary will be the field name, and the values will be lists +of strings of any error messages corresponding to that field. The +`non_field_errors` key may also be present, and will list any general +validation errors. The name of the `non_field_errors` key may be customized +using the `NON_FIELD_ERRORS_KEY` REST framework setting. -When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items. +When deserializing a list of items, errors will be returned as a list of +dictionaries representing each of the deserialized items. #### Raising an exception on invalid data -The `.is_valid()` method takes an optional `raise_exception` flag that will cause it to raise a `serializers.ValidationError` exception if there are validation errors. +The `.is_valid()` method takes an optional `raise_exception` flag that will +cause it to raise a `serializers.ValidationError` exception if there are +validation errors. -These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return `HTTP 400 Bad Request` responses by default. +These exceptions are automatically dealt with by the default exception handler +that REST framework provides, and will return `HTTP 400 Bad Request` responses +by default. # Return a 400 response if the data was invalid. serializer.is_valid(raise_exception=True) #### Field-level validation -You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are similar to the `.clean_` methods on Django forms. +You can specify custom field-level validation by adding +`.validate_` methods to your `Serializer` subclass. These are +similar to the `.clean_` methods on Django forms. -These methods take a single argument, which is the field value that requires validation. +These methods take a single argument, which is the field value that requires +validation. -Your `validate_` methods should return the validated value or raise a `serializers.ValidationError`. For example: +Your `validate_` methods should return the validated value or raise +a `serializers.ValidationError`. For example: from rest_framework import serializers @@ -191,13 +237,19 @@ Your `validate_` methods should return the validated value or raise --- -**Note:** If your `` is declared on your serializer with the parameter `required=False` then this validation step will not take place if the field is not included. +**Note:** If your `` is declared on your serializer with the +parameter `required=False` then this validation step will not take place if the +field is not included. --- #### Object-level validation -To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `ValidationError` if necessary, or just return the validated values. For example: +To do any other validation that requires access to multiple fields, add a +method called `.validate()` to your `Serializer` subclass. This method takes a +single argument, which is a dictionary of field values. It should raise a +`ValidationError` if necessary, or just return the validated values. For +example: from rest_framework import serializers @@ -226,7 +278,9 @@ Individual fields on a serializer can include validators, by declaring them on t score = IntegerField(validators=[multiple_of_ten]) ... -Serializer classes can also include reusable validators that are applied to the complete set of field data. These validators are included by declaring them on an inner `Meta` class, like so: +Serializer classes can also include reusable validators that are applied to the +complete set of field data. These validators are included by declaring them on +an inner `Meta` class, like so: class EventSerializer(serializers.Serializer): name = serializers.CharField() @@ -244,9 +298,13 @@ For more information see the [validators documentation](validators.md). ## Accessing the initial data and instance -When passing an initial object or queryset to a serializer instance, the object will be made available as `.instance`. If no initial object is passed then the `.instance` attribute will be `None`. +When passing an initial object or queryset to a serializer instance, the object +will be made available as `.instance`. If no initial object is passed then the +`.instance` attribute will be `None`. -When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the data keyword argument is not passed then the `.initial_data` attribute will not exist. +When passing data to a serializer instance, the unmodified data will be made +available as `.initial_data`. If the data keyword argument is not passed then +the `.initial_data` attribute will not exist. ## Partial updates @@ -257,9 +315,13 @@ By default, serializers must be passed values for all required fields or they wi ## Dealing with nested objects -The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. +The previous examples are fine for dealing with objects that only have simple +datatypes, but sometimes we also need to be able to represent more complex +objects, where some of the attributes of an object might not be simple +datatypes such as strings, dates or integers. -The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another. +The `Serializer` class is itself a type of `Field`, and can be used to +represent relationships where one object type is nested inside another. class UserSerializer(serializers.Serializer): email = serializers.EmailField() @@ -270,14 +332,16 @@ The `Serializer` class is itself a type of `Field`, and can be used to represent content = serializers.CharField(max_length=200) created = serializers.DateTimeField() -If a nested representation may optionally accept the `None` value you should pass the `required=False` flag to the nested serializer. +If a nested representation may optionally accept the `None` value you should +pass the `required=False` flag to the nested serializer. class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False) # May be an anonymous user. content = serializers.CharField(max_length=200) created = serializers.DateTimeField() -Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serialized. +Similarly if a nested representation should be a list of items, you should pass +the `many=True` flag to the nested serialized. class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False) @@ -287,7 +351,9 @@ Similarly if a nested representation should be a list of items, you should pass ## Writable nested representations -When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object. +When dealing with nested representations that support deserializing the data, +any errors with nested objects will be nested under the field name of the +nested object. serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'}) serializer.is_valid() @@ -299,9 +365,11 @@ Similarly, the `.validated_data` property will include nested data structures. #### Writing `.create()` methods for nested representations -If you're supporting writable nested representations you'll need to write `.create()` or `.update()` methods that handle saving multiple objects. +If you're supporting writable nested representations you'll need to write +`.create()` or `.update()` methods that handle saving multiple objects. -The following example demonstrates how you might handle creating a user with a nested profile object. +The following example demonstrates how you might handle creating a user with a +nested profile object. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() @@ -318,14 +386,17 @@ The following example demonstrates how you might handle creating a user with a n #### Writing `.update()` methods for nested representations -For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is `None`, or not provided, which of the following should occur? +For updates you'll want to think carefully about how to handle updates to +relationships. For example if the data for the relationship is `None`, or not +provided, which of the following should occur? * Set the relationship to `NULL` in the database. * Delete the associated instance. * Ignore the data and leave the instance as it is. * Raise a validation error. -Here's an example for an `update()` method on our previous `UserSerializer` class. +Here's an example for an `update()` method on our previous `UserSerializer` +class. def update(self, instance, validated_data): profile_data = validated_data.pop('profile') @@ -350,15 +421,24 @@ Here's an example for an `update()` method on our previous `UserSerializer` clas return instance -Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default `ModelSerializer` `.create()` and `.update()` methods do not include support for writable nested representations. +Because the behavior of nested creates and updates can be ambiguous, and may +require complex dependencies between related models, REST framework 3 requires +you to always write these methods explicitly. The default `ModelSerializer` +`.create()` and `.update()` methods do not include support for writable nested +representations. -It is possible that a third party package, providing automatic support some kinds of automatic writable nested representations may be released alongside the 3.1 release. +It is possible that a third party package, providing automatic support some +kinds of automatic writable nested representations may be released alongside +the 3.1 release. #### Handling saving related instances in model manager classes -An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances. +An alternative to saving multiple related instances in the serializer is to +write custom model manager classes that handle creating the correct instances. -For example, suppose we wanted to ensure that `User` instances and `Profile` instances are always created together as a pair. We might write a custom manager class that looks something like this: +For example, suppose we wanted to ensure that `User` instances and `Profile` +instances are always created together as a pair. We might write a custom +manager class that looks something like this: class UserManager(models.Manager): ... @@ -374,7 +454,9 @@ For example, suppose we wanted to ensure that `User` instances and `Profile` ins profile.save() return user -This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our `.create()` method on the serializer class can now be re-written to use the new manager method. +This manager class now more nicely encapsulates that user instances and profile +instances are always created at the same time. Our `.create()` method on the +serializer class can now be re-written to use the new manager method. def create(self, validated_data): return User.objects.create( @@ -384,7 +466,9 @@ This manager class now more nicely encapsulates that user instances and profile has_support_contract=validated_data['profile']['has_support_contract'] ) -For more details on this approach see the Django documentation on [model managers][model-managers], and [this blogpost on using model and manager classes][encapsulation-blogpost]. +For more details on this approach see the Django documentation on [model +managers][model-managers], and [this blogpost on using model and manager +classes][encapsulation-blogpost]. ## Dealing with multiple objects @@ -392,7 +476,9 @@ The `Serializer` class can also handle serializing or deserializing lists of obj #### Serializing multiple objects -To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized. +To serialize a queryset or list of objects instead of a single object instance, +you should pass the `many=True` flag when instantiating the serializer. You +can then pass a queryset or list of objects to be serialized. queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) @@ -405,32 +491,46 @@ To serialize a queryset or list of objects instead of a single object instance, #### Deserializing multiple objects -The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#listserializer) documentation below. +The default behavior for deserializing multiple objects is to support multiple +object creation, but not support multiple object updates. For more information +on how to support or customize either of these cases, see the +[ListSerializer](#listserializer) documentation below. ## Including extra context -There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs. +There are some cases where you need to provide extra context to the serializer +in addition to the object being serialized. One common case is if you're using +a serializer that includes hyperlinked relations, which requires the serializer +to have access to the current request so that it can properly generate fully +qualified URLs. -You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example: +You can provide arbitrary additional context by passing a `context` argument +when instantiating the serializer. For example: serializer = AccountSerializer(account, context={'request': request}) serializer.data # {'id': 6, 'owner': u'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'} -The context dictionary can be used within any serializer field logic, such as a custom `.to_representation()` method, by accessing the `self.context` attribute. +The context dictionary can be used within any serializer field logic, such as a +custom `.to_representation()` method, by accessing the `self.context` +attribute. --- # ModelSerializer -Often you'll want serializer classes that map closely to Django model definitions. +Often you'll want serializer classes that map closely to Django model +definitions. -The `ModelSerializer` class provides a shortcut that lets you automatically create a `Serializer` class with fields that correspond to the Model fields. +The `ModelSerializer` class provides a shortcut that lets you automatically +create a `Serializer` class with fields that correspond to the Model fields. -**The `ModelSerializer` class is the same as a regular `Serializer` class, except that**: +**The `ModelSerializer` class is the same as a regular `Serializer` class, +except that**: * It will automatically generate a set of fields for you, based on the model. -* It will automatically generate validators for the serializer, such as unique_together validators. +* It will automatically generate validators for the serializer, such as + unique_together validators. * It includes simple default implementations of `.create()` and `.update()`. Declaring a `ModelSerializer` looks like this: @@ -440,15 +540,22 @@ Declaring a `ModelSerializer` looks like this: model = Account fields = ('id', 'account_name', 'users', 'created') -By default, all the model fields on the class will be mapped to a corresponding serializer fields. +By default, all the model fields on the class will be mapped to a corresponding +serializer fields. -Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Reverse relationships are not included by default unless explicitly included as described below. +Any relationships such as foreign keys on the model will be mapped to +`PrimaryKeyRelatedField`. Reverse relationships are not included by default +unless explicitly included as described below. #### Inspecting a `ModelSerializer` -Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with `ModelSerializers` where you want to determine what set of fields and validators are being automatically created for you. +Serializer classes generate helpful verbose representation strings, that allow +you to fully inspect the state of their fields. This is particularly useful +when working with `ModelSerializers` where you want to determine what set of +fields and validators are being automatically created for you. -To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation… +To do so, open the Django shell, using `python manage.py shell`, then import +the serializer class, instantiate it, and print the object representation… >>> from myapp.serializers import AccountSerializer >>> serializer = AccountSerializer() @@ -460,7 +567,12 @@ To do so, open the Django shell, using `python manage.py shell`, then import the ## Specifying which fields to include -If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. It is strongly recommended that you explicitly set all fields that should be serialized using the `fields` attribute. This will make it less likely to result in unintentionally exposing data when your models change. +If you only want a subset of the default fields to be used in a model +serializer, you can do so using `fields` or `exclude` options, just as you +would with a `ModelForm`. It is strongly recommended that you explicitly set +all fields that should be serialized using the `fields` attribute. This will +make it less likely to result in unintentionally exposing data when your models +change. For example: @@ -469,7 +581,8 @@ For example: model = Account fields = ('id', 'account_name', 'users', 'created') -You can also set the `fields` attribute to the special value `'__all__'` to indicate that all fields in the model should be used. +You can also set the `fields` attribute to the special value `'__all__'` to +indicate that all fields in the model should be used. For example: @@ -487,15 +600,20 @@ For example: model = Account exclude = ('users',) -In the example above, if the `Account` model had 3 fields `account_name`, `users`, and `created`, this will result in the fields `account_name` and `created` to be serialized. +In the example above, if the `Account` model had 3 fields `account_name`, +`users`, and `created`, this will result in the fields `account_name` and +`created` to be serialized. -The names in the `fields` and `exclude` attributes will normally map to model fields on the model class. +The names in the `fields` and `exclude` attributes will normally map to model +fields on the model class. -Alternatively names in the `fields` options can map to properties or methods which take no arguments that exist on the model class. +Alternatively names in the `fields` options can map to properties or methods +which take no arguments that exist on the model class. ## Specifying nested serialization -The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: +The default `ModelSerializer` uses primary keys for relationships, but you can +also easily generate nested representations using the `depth` option: class AccountSerializer(serializers.ModelSerializer): class Meta: @@ -503,13 +621,17 @@ The default `ModelSerializer` uses primary keys for relationships, but you can a fields = ('id', 'account_name', 'users', 'created') depth = 1 -The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. +The `depth` option should be set to an integer value that indicates the depth +of relationships that should be traversed before reverting to a flat +representation. -If you want to customize the way the serialization is done you'll need to define the field yourself. +If you want to customize the way the serialization is done you'll need to +define the field yourself. ## Specifying fields explicitly -You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. +You can add extra fields to a `ModelSerializer` or override the default fields +by declaring fields on the class, just as you would for a `Serializer` class. class AccountSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) @@ -522,9 +644,12 @@ Extra fields can correspond to any property or callable on the model. ## Specifying read only fields -You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the shortcut Meta option, `read_only_fields`. +You may wish to specify multiple fields as read-only. Instead of adding each +field explicitly with the `read_only=True` attribute, you may use the shortcut +Meta option, `read_only_fields`. -This option should be a list or tuple of field names, and is declared as follows: +This option should be a list or tuple of field names, and is declared as +follows: class AccountSerializer(serializers.ModelSerializer): class Meta: @@ -532,15 +657,24 @@ This option should be a list or tuple of field names, and is declared as follows fields = ('id', 'account_name', 'users', 'created') read_only_fields = ('account_name',) -Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option. +Model fields which have `editable=False` set, and `AutoField` fields will be +set to read-only by default, and do not need to be added to the +`read_only_fields` option. --- -**Note**: There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user. +**Note**: There is a special-case where a read-only field is part of a +`unique_together` constraint at the model level. In this case the field is +required by the serializer class in order to validate the constraint, but +should also not be editable by the user. -The right way to deal with this is to specify the field explicitly on the serializer, providing both the `read_only=True` and `default=…` keyword arguments. +The right way to deal with this is to specify the field explicitly on the +serializer, providing both the `read_only=True` and `default=…` keyword +arguments. -One example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so: +One example of this is a read-only relation to the currently authenticated +`User` which is `unique_together` with another identifier. In this case you +would declare the user field like so: user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) @@ -551,9 +685,13 @@ Please review the [Validators Documentation](/api-guide/validators/) for details ## Additional keyword arguments -There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. As in the case of `read_only_fields`, this means you do not need to explicitly declare the field on the serializer. +There is also a shortcut allowing you to specify arbitrary additional keyword +arguments on fields, using the `extra_kwargs` option. As in the case of +`read_only_fields`, this means you do not need to explicitly declare the field +on the serializer. -This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example: +This option is a dictionary, mapping field names to a dictionary of keyword +arguments. For example: class CreateUserSerializer(serializers.ModelSerializer): class Meta: @@ -572,106 +710,143 @@ This option is a dictionary, mapping field names to a dictionary of keyword argu ## Relational fields -When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances. +When serializing model instances, there are a number of different ways you +might choose to represent relationships. The default representation for +`ModelSerializer` is to use the primary keys of the related instances. -Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation. +Alternative representations include serializing using hyperlinks, serializing +complete nested representations, or serializing with a custom representation. For full details see the [serializer relations][relations] documentation. ## Inheritance of the 'Meta' class -The inner `Meta` class on serializers is not inherited from parent classes by default. This is the same behavior as with Django's `Model` and `ModelForm` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example: +The inner `Meta` class on serializers is not inherited from parent classes by +default. This is the same behavior as with Django's `Model` and `ModelForm` +classes. If you want the `Meta` class to inherit from a parent class you must +do so explicitly. For example: class AccountSerializer(MyBaseSerializer): class Meta(MyBaseSerializer.Meta): model = Account -Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly. +Typically we would recommend *not* using inheritance on inner Meta classes, but +instead declaring all options explicitly. ## Customizing field mappings -The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer. +The ModelSerializer class also exposes an API that you can override in order to +alter how serializer fields are automatically determined when instantiating the +serializer. -Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model. +Normally if a `ModelSerializer` does not generate the fields you need by +default then you should either add them to the class explicitly, or simply use +a regular `Serializer` class instead. However in some cases you may want to +create a new base class that defines how the serializer fields are created for +any given model. ### `.serializer_field_mapping` -A mapping of Django model classes to REST framework serializer classes. You can override this mapping to alter the default serializer classes that should be used for each model class. +A mapping of Django model classes to REST framework serializer classes. You can +override this mapping to alter the default serializer classes that should be +used for each model class. ### `.serializer_related_field` -This property should be the serializer field class, that is used for relational fields by default. +This property should be the serializer field class, that is used for relational +fields by default. For `ModelSerializer` this defaults to `PrimaryKeyRelatedField`. -For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`. +For `HyperlinkedModelSerializer` this defaults to +`serializers.HyperlinkedRelatedField`. ### `serializer_url_field` -The serializer field class that should be used for any `url` field on the serializer. +The serializer field class that should be used for any `url` field on the +serializer. Defaults to `serializers.HyperlinkedIdentityField` ### `serializer_choice_field` -The serializer field class that should be used for any choice fields on the serializer. +The serializer field class that should be used for any choice fields on the +serializer. Defaults to `serializers.ChoiceField` ### The field_class and field_kwargs API -The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`. +The following methods are called to determine the class and keyword arguments +for each field that should be automatically included on the serializer. Each of + these methods should return a two tuple of `(field_class, + field_kwargs)`. ### `.build_standard_field(self, field_name, model_field)` Called to generate a serializer field that maps to a standard model field. -The default implementation returns a serializer class based on the `serializer_field_mapping` attribute. +The default implementation returns a serializer class based on the +`serializer_field_mapping` attribute. ### `.build_relational_field(self, field_name, relation_info)` Called to generate a serializer field that maps to a relational model field. -The default implementation returns a serializer class based on the `serializer_relational_field` attribute. +The default implementation returns a serializer class based on the +`serializer_relational_field` attribute. -The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. +The `relation_info` argument is a named tuple, that contains `model_field`, +`related_model`, `to_many` and `has_through_model` properties. ### `.build_nested_field(self, field_name, relation_info, nested_depth)` -Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set. +Called to generate a serializer field that maps to a relational model field, +when the `depth` option has been set. -The default implementation dynamically creates a nested serializer class based on either `ModelSerializer` or `HyperlinkedModelSerializer`. +The default implementation dynamically creates a nested serializer class based +on either `ModelSerializer` or `HyperlinkedModelSerializer`. The `nested_depth` will be the value of the `depth` option, minus one. -The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. +The `relation_info` argument is a named tuple, that contains `model_field`, +`related_model`, `to_many` and `has_through_model` properties. ### `.build_property_field(self, field_name, model_class)` -Called to generate a serializer field that maps to a property or zero-argument method on the model class. +Called to generate a serializer field that maps to a property or zero-argument +method on the model class. The default implementation returns a `ReadOnlyField` class. ### `.build_url_field(self, field_name, model_class)` -Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class. +Called to generate a serializer field for the serializer's own `url` field. The +default implementation returns a `HyperlinkedIdentityField` class. ### `.build_unknown_field(self, field_name, model_class)` Called when the field name did not map to any model field or model property. -The default implementation raises an error, although subclasses may customize this behavior. +The default implementation raises an error, although subclasses may customize +this behavior. --- # HyperlinkedModelSerializer -The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys. +The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` +class except that it uses hyperlinks to represent relationships, rather than +primary keys. -By default the serializer will include a `url` field instead of a primary key field. +By default the serializer will include a `url` field instead of a primary key +field. -The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field. +The url field will be represented using a `HyperlinkedIdentityField` serializer +field, and any relationships on the model will be represented using a +`HyperlinkedRelatedField` serializer field. -You can explicitly include the primary key by adding it to the `fields` option, for example: +You can explicitly include the primary key by adding it to the `fields` option, +for example: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: @@ -694,16 +869,21 @@ Rather than relative URLs, such as: /accounts/1/ -If you *do* want to use relative URLs, you should explicitly pass `{'request': None}` -in the serializer context. +If you *do* want to use relative URLs, you should explicitly pass `{'request': +None}` in the serializer context. ## How hyperlinked views are determined -There needs to be a way of determining which views should be used for hyperlinking to model instances. +There needs to be a way of determining which views should be used for +hyperlinking to model instances. -By default hyperlinks are expected to correspond to a view name that matches the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword argument. +By default hyperlinks are expected to correspond to a view name that matches +the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword +argument. -You can override a URL field view name and lookup field by using either, or both of, the `view_name` and `lookup_field` options in the `extra_kwargs` setting, like so: +You can override a URL field view name and lookup field by using either, or +both of, the `view_name` and `lookup_field` options in the `extra_kwargs` +setting, like so: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: @@ -734,36 +914,52 @@ Alternatively you can set the fields on the serializer explicitly. For example: --- -**Tip**: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the `repr` of a `HyperlinkedModelSerializer` instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too. +**Tip**: Properly matching together hyperlinked representations and your URL +conf can sometimes be a bit fiddly. Printing the `repr` of a +`HyperlinkedModelSerializer` instance is a particularly useful way to inspect +exactly which view names and lookup fields the relationships are expected to +map too. --- ## Changing the URL field name -The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting. +The name of the URL field defaults to 'url'. You can override this globally, +by using the `URL_FIELD_NAME` setting. --- # ListSerializer -The `ListSerializer` class provides the behavior for serializing and validating multiple objects at once. You won't *typically* need to use `ListSerializer` directly, but should instead simply pass `many=True` when instantiating a serializer. +The `ListSerializer` class provides the behavior for serializing and validating +multiple objects at once. You won't *typically* need to use `ListSerializer` +directly, but should instead simply pass `many=True` when instantiating a +serializer. -When a serializer is instantiated and `many=True` is passed, a `ListSerializer` instance will be created. The serializer class then becomes a child of the parent `ListSerializer` +When a serializer is instantiated and `many=True` is passed, a `ListSerializer` +instance will be created. The serializer class then becomes a child of the +parent `ListSerializer` -The following argument can also be passed to a `ListSerializer` field or a serializer that is passed `many=True`: +The following argument can also be passed to a `ListSerializer` field or a +serializer that is passed `many=True`: ### `allow_empty` -This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input. +This is `True` by default, but can be set to `False` if you want to disallow +empty lists as valid input. ### Customizing `ListSerializer` behavior -There *are* a few use cases when you might want to customize the `ListSerializer` behavior. For example: +There *are* a few use cases when you might want to customize the +`ListSerializer` behavior. For example: -* You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list. +* You want to provide particular validation of the lists, such as checking that + one element does not conflict with another element in a list. * You want to customize the create or update behavior of multiple objects. -For these cases you can modify the class that is used when `many=True` is passed, by using the `list_serializer_class` option on the serializer `Meta` class. +For these cases you can modify the class that is used when `many=True` is +passed, by using the `list_serializer_class` option on the serializer `Meta` +class. For example: @@ -777,7 +973,10 @@ For example: #### Customizing multiple create -The default implementation for multiple object creation is to simply call `.create()` for each item in the list. If you want to customize this behavior, you'll need to customize the `.create()` method on `ListSerializer` class that is used when `many=True` is passed. +The default implementation for multiple object creation is to simply call +`.create()` for each item in the list. If you want to customize this behavior, +you'll need to customize the `.create()` method on `ListSerializer` class that +is used when `many=True` is passed. For example: @@ -793,16 +992,26 @@ For example: #### Customizing multiple update -By default the `ListSerializer` class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous. +By default the `ListSerializer` class does not support multiple updates. This +is because the behavior that should be expected for insertions and deletions is +ambiguous. -To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind: +To support multiple updates you'll need to do so explicitly. When writing your +multiple update code make sure to keep the following in mind: -* How do you determine which instance should be updated for each item in the list of data? -* How should insertions be handled? Are they invalid, or do they create new objects? -* How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid? -* How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? +* How do you determine which instance should be updated for each item in the + list of data? +* How should insertions be handled? Are they invalid, or do they create new + objects? +* How should removals be handled? Do they imply object deletion, or removing a + relationship? Should they be silently ignored, or are they invalid? +* How should ordering be handled? Does changing the position of two items imply + any state change or is it ignored? -You will need to add an explicit `id` field to the instance serializer. The default implicitly-generated `id` field is marked as `read_only`. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's `update` method. +You will need to add an explicit `id` field to the instance serializer. The +default implicitly-generated `id` field is marked as `read_only`. This causes +it to be removed on updates. Once you declare it explicitly, it will be +available in the list serializer's `update` method. Here's an example of how you might choose to implement multiple updates: @@ -839,15 +1048,25 @@ Here's an example of how you might choose to implement multiple updates: class Meta: list_serializer_class = BookListSerializer -It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the `allow_add_remove` behavior that was present in REST framework 2. +It is possible that a third party package may be included alongside the 3.1 +release that provides some automatic support for multiple update operations, +similar to the `allow_add_remove` behavior that was present in REST framework +2. #### Customizing ListSerializer initialization -When a serializer with `many=True` is instantiated, we need to determine which arguments and keyword arguments should be passed to the `.__init__()` method for both the child `Serializer` class, and for the parent `ListSerializer` class. +When a serializer with `many=True` is instantiated, we need to determine which +arguments and keyword arguments should be passed to the `.__init__()` method +for both the child `Serializer` class, and for the parent `ListSerializer` + class. -The default implementation is to pass all arguments to both classes, except for `validators`, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class. +The default implementation is to pass all arguments to both classes, except for +`validators`, and any custom keyword arguments, both of which are assumed to be +intended for the child serializer class. -Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when `many=True` is passed. You can do so by using the `many_init` class method. +Occasionally you might need to explicitly specify how the child and parent +classes should be instantiated when `many=True` is passed. You can do so by +using the `many_init` class method. @classmethod def many_init(cls, *args, **kwargs): @@ -876,20 +1095,28 @@ There are four methods that can be overridden, depending on what functionality y * `.to_internal_value()` - Override this to support deserialization, for write operations. * `.create()` and `.update()` - Override either or both of these to support saving instances. -Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`. +Because this class provides the same interface as the `Serializer` class, you +can use it with the existing generic class-based views exactly as you would for +a regular `Serializer` or `ModelSerializer`. -The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input. +The only difference you'll notice when doing so is the `BaseSerializer` classes +will not generate HTML forms in the browsable API. This is because the data +they return does not include all the field information that would allow each +field to be rendered into a suitable HTML input. ##### Read-only `BaseSerializer` classes -To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: +To implement a read-only serializer using the `BaseSerializer` class, we just +need to override the `.to_representation()` method. Let's take a look at an +example using a simple Django model: class HighScore(models.Model): created = models.DateTimeField(auto_now_add=True) player_name = models.CharField(max_length=10) score = models.IntegerField() -It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types. +It's simple to create a read-only serializer for converting `HighScore` +instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer): def to_representation(self, obj): @@ -916,13 +1143,20 @@ Or use it to serialize multiple instances: ##### Read-write `BaseSerializer` classes -To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `ValidationError` if the supplied data is in an incorrect format. +To create a read-write serializer we first need to implement a +`.to_internal_value()` method. This method returns the validated values that +will be used to construct the object instance, and may raise a +`ValidationError` if the supplied data is in an incorrect format. -Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`. +Once you've implemented `.to_internal_value()`, the basic validation API will +be available on the serializer, and you will be able to use `.is_valid()`, +`.validated_data` and `.errors`. -If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods. +If you want to also support `.save()` you'll need to also implement either or +both of the `.create()` and `.update()` methods. -Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations. +Here's a complete example of our previous `HighScoreSerializer`, that's been +updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer): def to_internal_value(self, data): @@ -961,9 +1195,12 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd #### Creating new base classes -The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. +The `BaseSerializer` class is also useful if you want to implement new generic +serializer classes for dealing with particular serialization styles, or for +integrating with alternative storage backends. -The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. +The following class is an example of a generic serializer that can handle +coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer): """ @@ -1003,37 +1240,56 @@ The following class is an example of a generic serializer that can handle coerci ## Overriding serialization and deserialization behavior -If you need to alter the serialization, deserialization or validation of a serializer class you can do so by overriding the `.to_representation()` or `.to_internal_value()` methods. +If you need to alter the serialization, deserialization or validation of a +serializer class you can do so by overriding the `.to_representation()` or +`.to_internal_value()` methods. Some reasons this might be useful include... * Adding new behavior for new serializer base classes. * Modifying the behavior slightly for an existing class. -* Improving serialization performance for a frequently accessed API endpoint that returns lots of data. +* Improving serialization performance for a frequently accessed API endpoint + that returns lots of data. The signatures for these methods are as follows: #### `.to_representation(self, obj)` -Takes the object instance that requires serialization, and should return a primitive representation. Typically this means returning a structure of built-in Python datatypes. The exact types that can be handled will depend on the render classes you have configured for your API. +Takes the object instance that requires serialization, and should return a +primitive representation. Typically this means returning a structure of +built-in Python datatypes. The exact types that can be handled will depend on +the render classes you have configured for your API. #### ``.to_internal_value(self, data)`` -Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class. +Takes the unvalidated incoming data as input and should return the validated +data that will be made available as `serializer.validated_data`. The return +value will also be passed to the `.create()` or `.update()` methods if +`.save()` is called on the serializer class. -If any of the validation fails, then the method should raise a `serializers.ValidationError(errors)`. Typically the `errors` argument here will be a dictionary mapping field names to error messages. +If any of the validation fails, then the method should raise a +`serializers.ValidationError(errors)`. Typically the `errors` argument here +will be a dictionary mapping field names to error messages. -The `data` argument passed to this method will normally be the value of `request.data`, so the datatype it provides will depend on the parser classes you have configured for your API. +The `data` argument passed to this method will normally be the value of +`request.data`, so the datatype it provides will depend on the parser classes +you have configured for your API. ## Dynamically modifying fields -Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the `.fields` attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer. +Once a serializer has been initialized, the dictionary of fields that are set +on the serializer may be accessed using the `.fields` attribute. Accessing and +modifying this attribute allows you to dynamically modify the serializer. -Modifying the `fields` argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer. +Modifying the `fields` argument directly allows you to do interesting things +such as changing the arguments on serializer fields at runtime, rather than at +the point of declaring the serializer. ### Example -For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so: +For example, if you wanted to be able to set which fields should be used by a +serializer at the point of initializing it, you could create a serializer class +like so: class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ @@ -1070,13 +1326,18 @@ This would then allow you to do the following: ## Customizing the default fields -REST framework 2 provided an API to allow developers to override how a `ModelSerializer` class would automatically generate the default set of fields. +REST framework 2 provided an API to allow developers to override how a +`ModelSerializer` class would automatically generate the default set of fields. This API included the `.get_field()`, `.get_pk_field()` and other methods. -Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change. +Because the serializers have been fundamentally redesigned with 3.0 this API no +longer exists. You can still modify the fields that get created but you'll need +to refer to the source code, and be aware that if the changes you make are +against private bits of API then they may be subject to change. -A new interface for controlling this behavior is currently planned for REST framework 3.1. +A new interface for controlling this behavior is currently planned for REST +framework 3.1. --- @@ -1086,29 +1347,49 @@ The following third party packages are also available. ## Django REST marshmallow -The [django-rest-marshmallow][django-rest-marshmallow] package provides an alternative implementation for serializers, using the python [marshmallow][marshmallow] library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases. +The [django-rest-marshmallow][django-rest-marshmallow] package provides an +alternative implementation for serializers, using the python +[marshmallow][marshmallow] library. It exposes the same API as the REST +framework serializers, and can be used as a drop-in replacement in some +use-cases. ## Serpy -The [serpy][serpy] package is an alternative implementation for serializers that is built for speed. [Serpy][serpy] serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed. +The [serpy][serpy] package is an alternative implementation for serializers +that is built for speed. [Serpy][serpy] serializes complex datatypes to simple +native types. The native types can be easily converted to JSON or any other +format needed. ## MongoengineModelSerializer -The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEngineModelSerializer` serializer class that supports using MongoDB as the storage layer for Django REST framework. +The [django-rest-framework-mongoengine][mongoengine] package provides a +`MongoEngineModelSerializer` serializer class that supports using MongoDB as +the storage layer for Django REST framework. ## GeoFeatureModelSerializer -The [django-rest-framework-gis][django-rest-framework-gis] package provides a `GeoFeatureModelSerializer` serializer class that supports GeoJSON both for read and write operations. +The [django-rest-framework-gis][django-rest-framework-gis] package provides a +`GeoFeatureModelSerializer` serializer class that supports GeoJSON both for +read and write operations. ## HStoreSerializer -The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreSerializer` to support [django-hstore][django-hstore] `DictionaryField` model field and its `schema-mode` feature. +The [django-rest-framework-hstore][django-rest-framework-hstore] package +provides an `HStoreSerializer` to support [django-hstore][django-hstore] +`DictionaryField` model field and its `schema-mode` feature. ## Dynamic REST -The [dynamic-rest][dynamic-rest] package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers. +The [dynamic-rest][dynamic-rest] package extends the ModelSerializer and +ModelViewSet interfaces, adding API query parameters for filtering, sorting, +and including / excluding all fields and relationships defined by your +serializers. -## HTML JSON Forms -The [html-json-forms][html-json-forms] package provides an algorithm and serializer for processing `` submissions per the (inactive) [HTML JSON Form specification][json-form-spec]. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, `` will be interpreted as `{"items": [{"id": "5"}]}`. +## HTML JSON Forms The [html-json-forms][html-json-forms] package provides an +algorithm and serializer for processing `` submissions per the (inactive) +[HTML JSON Form specification][json-form-spec]. The serializer facilitates +processing of arbitrarily nested JSON structures within HTML. For example, +`` will be interpreted as `{"items": +[{"id": "5"}]}`. [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion [relations]: relations.md diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index ea018053f..f189ee37f 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -6,9 +6,11 @@ source: settings.py > > — [The Zen of Python][cite] -Configuration for REST framework is all namespaced inside a single Django setting, named `REST_FRAMEWORK`. +Configuration for REST framework is all namespaced inside a single Django +setting, named `REST_FRAMEWORK`. -For example your project's `settings.py` file might include something like this: +For example your project's `settings.py` file might include something like +this: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( @@ -21,14 +23,17 @@ For example your project's `settings.py` file might include something like this: ## Accessing settings -If you need to access the values of REST framework's API settings in your project, -you should use the `api_settings` object. For example. +If you need to access the values of REST framework's API settings in your +project, you should use the `api_settings` object. For example. from rest_framework.settings import api_settings print api_settings.DEFAULT_AUTHENTICATION_CLASSES -The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal. +The `api_settings` object will check for any user-defined settings, and +otherwise fall back to the default values. Any setting that uses string import +paths to refer to a class will automatically import and return the referenced +class, instead of the string literal. --- @@ -36,11 +41,13 @@ The `api_settings` object will check for any user-defined settings, and otherwis ## API policy settings -*The following settings control the basic API policies, and are applied to every `APIView` class-based view, or `@api_view` function based view.* +*The following settings control the basic API policies, and are applied to +every `APIView` class-based view, or `@api_view` function based view.* #### DEFAULT_RENDERER_CLASSES -A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object. +A list or tuple of renderer classes, that determines the default set of +renderers that may be used when returning a `Response` object. Default: @@ -51,7 +58,8 @@ Default: #### DEFAULT_PARSER_CLASSES -A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.data` property. +A list or tuple of parser classes, that determines the default set of parsers +used when accessing the `request.data` property. Default: @@ -63,7 +71,9 @@ Default: #### DEFAULT_AUTHENTICATION_CLASSES -A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties. +A list or tuple of authentication classes, that determines the default set of +authenticators used when accessing the `request.user` or `request.auth` +properties. Default: @@ -74,7 +84,9 @@ Default: #### DEFAULT_PERMISSION_CLASSES -A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list. +A list or tuple of permission classes, that determines the default set of +permissions checked at the start of a view. Permission must be granted by every +class in the list. Default: @@ -84,13 +96,15 @@ Default: #### DEFAULT_THROTTLE_CLASSES -A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view. +A list or tuple of throttle classes, that determines the default set of +throttles checked at the start of a view. Default: `()` #### DEFAULT_CONTENT_NEGOTIATION_CLASS -A content negotiation class, that determines how a renderer is selected for the response, given an incoming request. +A content negotiation class, that determines how a renderer is selected for the +response, given an incoming request. Default: `'rest_framework.negotiation.DefaultContentNegotiation'` @@ -123,13 +137,15 @@ If set to `None` then generic filtering is disabled. **This setting has been removed.** -See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style). +See the pagination documentation for further guidance on [setting the +pagination style](pagination.md#modifying-the-pagination-style). --- #### PAGE_SIZE -The default page size to use for pagination. If set to `None`, pagination is disabled by default. +The default page size to use for pagination. If set to `None`, pagination is +disabled by default. Default: `None` @@ -139,7 +155,8 @@ Default: `None` **This setting has been removed.** -See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style). +See the pagination documentation for further guidance on [setting the +pagination style](pagination.md#modifying-the-pagination-style). --- @@ -149,19 +166,22 @@ See the pagination documentation for further guidance on [setting the pagination **This setting is pending deprecation.** -See the pagination documentation for further guidance on [setting the pagination style](pagination.md#modifying-the-pagination-style). +See the pagination documentation for further guidance on [setting the +pagination style](pagination.md#modifying-the-pagination-style). --- ### SEARCH_PARAM -The name of a query parameter, which can be used to specify the search term used by `SearchFilter`. +The name of a query parameter, which can be used to specify the search term +used by `SearchFilter`. Default: `search` #### ORDERING_PARAM -The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`. +The name of a query parameter, which can be used to specify the ordering of +results returned by `OrderingFilter`. Default: `ordering` @@ -171,19 +191,23 @@ Default: `ordering` #### DEFAULT_VERSION -The value that should be used for `request.version` when no versioning information is present. +The value that should be used for `request.version` when no versioning +information is present. Default: `None` #### ALLOWED_VERSIONS -If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. +If set, this value will restrict the set of versions that may be returned by +the versioning scheme, and will raise an error if the provided version if not +in this set. Default: `None` #### VERSION_PARAM -The string that should used for any versioning parameters, such as in the media type or URL query parameters. +The string that should used for any versioning parameters, such as in the media +type or URL query parameters. Default: `'version'` @@ -195,13 +219,15 @@ Default: `'version'` #### UNAUTHENTICATED_USER -The class that should be used to initialize `request.user` for unauthenticated requests. +The class that should be used to initialize `request.user` for unauthenticated +requests. Default: `django.contrib.auth.models.AnonymousUser` #### UNAUTHENTICATED_TOKEN -The class that should be used to initialize `request.auth` for unauthenticated requests. +The class that should be used to initialize `request.auth` for unauthenticated +requests. Default: `None` @@ -223,7 +249,9 @@ Default: `'multipart'` The renderer classes that are supported when building test requests. -The format of any of these renderer classes may be used when constructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')` +The format of any of these renderer classes may be used when constructing a +test request, for example: `client.post('/users', {'username': 'jamie'}, +format='json')` Default: @@ -238,7 +266,9 @@ Default: #### URL_FORMAT_OVERRIDE -The name of a URL parameter that may be used to override the default content negotiation `Accept` header behavior, by using a `format=…` query parameter in the request URL. +The name of a URL parameter that may be used to override the default content +negotiation `Accept` header behavior, by using a `format=…` query parameter in +the request URL. For example: `http://example.com/organizations/?format=csv` @@ -248,7 +278,9 @@ Default: `'format'` #### FORMAT_SUFFIX_KWARG -The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using `format_suffix_patterns` to include suffixed URL patterns. +The name of a parameter in the URL conf that may be used to provide a format +suffix. This setting is applied when using `format_suffix_patterns` to include +suffixed URL patterns. For example: `http://example.com/organizations.csv/` @@ -258,11 +290,15 @@ Default: `'format'` ## Date and time formatting -*The following settings are used to control how date and time representations may be parsed and rendered.* +*The following settings are used to control how date and time representations +may be parsed and rendered.* #### DATETIME_FORMAT -A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return Python `datetime` objects, and the datetime encoding will be determined by the renderer. +A format string that should be used by default for rendering the output of +`DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer +fields will return Python `datetime` objects, and the datetime encoding will be +determined by the renderer. May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. @@ -270,41 +306,55 @@ Default: `'iso-8601'` #### DATETIME_INPUT_FORMATS -A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields. +A list of format strings that should be used by default for parsing inputs to +`DateTimeField` serializer fields. -May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings. +May be a list including the string `'iso-8601'` or Python [strftime +format][strftime] strings. Default: `['iso-8601']` #### DATE_FORMAT -A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return Python `date` objects, and the date encoding will be determined by the renderer. +A format string that should be used by default for rendering the output of +`DateField` serializer fields. If `None`, then `DateField` serializer fields +will return Python `date` objects, and the date encoding will be determined by +the renderer. -May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. +May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] +string. Default: `'iso-8601'` #### DATE_INPUT_FORMATS -A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields. +A list of format strings that should be used by default for parsing inputs to +`DateField` serializer fields. -May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings. +May be a list including the string `'iso-8601'` or Python [strftime +format][strftime] strings. Default: `['iso-8601']` #### TIME_FORMAT -A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return Python `time` objects, and the time encoding will be determined by the renderer. +A format string that should be used by default for rendering the output of +`TimeField` serializer fields. If `None`, then `TimeField` serializer fields +will return Python `time` objects, and the time encoding will be determined by +the renderer. -May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. +May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] +string. Default: `'iso-8601'` #### TIME_INPUT_FORMATS -A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields. +A list of format strings that should be used by default for parsing inputs to +`TimeField` serializer fields. -May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings. +May be a list including the string `'iso-8601'` or Python [strftime +format][strftime] strings. Default: `['iso-8601']` @@ -322,29 +372,39 @@ When set to `False`, JSON responses will escape non-ascii characters, like so: {"unicode black star":"\u2605"} -Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses. +Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. +The unicode style is preferred as being more user-friendly when inspecting API +responses. Default: `True` #### COMPACT_JSON -When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example: +When set to `True`, JSON responses will return compact representations, with no +spacing after `':'` and `','` characters. For example: {"is_admin":false,"email":"jane@example"} -When set to `False`, JSON responses will return slightly more verbose representations, like so: +When set to `False`, JSON responses will return slightly more verbose +representations, like so: {"is_admin": false, "email": "jane@example"} -The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json]. +The default style is to return minified responses, in line with [Heroku's API +design guidelines][heroku-minified-json]. Default: `True` #### COERCE_DECIMAL_TO_STRING -When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations. +When returning decimal objects in API representations that do not support a +native decimal type, it is normally best to return the value as a string. This +avoids the loss of precision that occurs with binary floating point +implementations. -When set to `True`, the serializer `DecimalField` class will return strings instead of `Decimal` objects. When set to `False`, serializers will return `Decimal` objects, which the default JSON encoder will return as floats. +When set to `True`, the serializer `DecimalField` class will return strings +instead of `Decimal` objects. When set to `False`, serializers will return +`Decimal` objects, which the default JSON encoder will return as floats. Default: `True` @@ -352,7 +412,8 @@ Default: `True` ## View names and descriptions -**The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.** +**The following settings are used to generate the view names and descriptions, +as used in responses to `OPTIONS` requests, and as used in the browsable API.** #### VIEW_NAME_FUNCTION @@ -362,23 +423,31 @@ This should be a function with the following signature: view_name(cls, suffix=None) -* `cls`: The view class. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `cls.__name__`. -* `suffix`: The optional suffix used when differentiating individual views in a viewset. +* `cls`: The view class. Typically the name function would inspect the name of + the class when generating a descriptive name, by accessing `cls.__name__`. +* `suffix`: The optional suffix used when differentiating individual views in a + viewset. Default: `'rest_framework.views.get_view_name'` #### VIEW_DESCRIPTION_FUNCTION -A string representing the function that should be used when generating view descriptions. +A string representing the function that should be used when generating view +descriptions. -This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support `rst` markup in your view docstrings being output in the browsable API. +This setting can be changed to support markup styles other than the default +markdown. For example, you can use it to support `rst` markup in your view +docstrings being output in the browsable API. This should be a function with the following signature: view_description(cls, html=False) -* `cls`: The view class. Typically the description function would inspect the docstring of the class when generating a description, by accessing `cls.__doc__` -* `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses. +* `cls`: The view class. Typically the description function would inspect the + docstring of the class when generating a description, by accessing + `cls.__doc__` +* `html`: A boolean indicating if HTML output is required. `True` when used in + the browsable API, and `False` when used in generating `OPTIONS` responses. Default: `'rest_framework.views.get_view_description'` @@ -388,9 +457,13 @@ Default: `'rest_framework.views.get_view_description'` #### EXCEPTION_HANDLER -A string representing the function that should be used when returning a response for any given exception. If the function returns `None`, a 500 error will be raised. +A string representing the function that should be used when returning a +response for any given exception. If the function returns `None`, a 500 error +will be raised. -This setting can be changed to support error responses other than the default `{"detail": "Failure..."}` responses. For example, you can use it to provide API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`. +This setting can be changed to support error responses other than the default +`{"detail": "Failure..."}` responses. For example, you can use it to provide +API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`. This should be a function with the following signature: @@ -402,19 +475,24 @@ Default: `'rest_framework.views.exception_handler'` #### NON_FIELD_ERRORS_KEY -A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors. +A string representing the key that should be used for serializer errors that do +not refer to a specific field, but are instead general errors. Default: `'non_field_errors'` #### URL_FIELD_NAME -A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`. +A string representing the key that should be used for the URL fields generated +by `HyperlinkedModelSerializer`. Default: `'url'` #### NUM_PROXIES -An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes. +An integer of 0 or more, that may be used to specify the number of application +proxies that the API runs behind. This allows throttling to more accurately +identify client IP addresses. If set to `None` then less strict IP matching +will be used by the throttle classes. Default: `None` diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index f6ec3598f..b03b5a013 100644 --- a/docs/api-guide/status-codes.md +++ b/docs/api-guide/status-codes.md @@ -2,11 +2,15 @@ source: status.py # Status Codes -> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. +> 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in +> the error code "418 I'm a teapot". The resulting entity body MAY be short +> and stout. > > — [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol -Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make more code more obvious and readable. +Using bare status codes in your responses isn't recommended. REST framework +includes a set of named constants that you can use to make more code more +obvious and readable. from rest_framework import status from rest_framework.response import Response @@ -15,9 +19,11 @@ Using bare status codes in your responses isn't recommended. REST framework inc content = {'please move along': 'nothing to see here'} return Response(content, status=status.HTTP_404_NOT_FOUND) -The full set of HTTP status codes included in the `status` module is listed below. +The full set of HTTP status codes included in the `status` module is listed +below. -The module also includes a set of helper functions for testing if a status code is in a given range. +The module also includes a set of helper functions for testing if a status code +is in a given range. from rest_framework import status from rest_framework.test import APITestCase @@ -34,14 +40,16 @@ and [RFC 6585][rfc6585]. ## Informational - 1xx -This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default. +This class of status code indicates a provisional response. There are no 1xx +status codes used in REST framework by default. HTTP_100_CONTINUE HTTP_101_SWITCHING_PROTOCOLS ## Successful - 2xx -This class of status code indicates that the client's request was successfully received, understood, and accepted. +This class of status code indicates that the client's request was successfully +received, understood, and accepted. HTTP_200_OK HTTP_201_CREATED @@ -54,7 +62,8 @@ This class of status code indicates that the client's request was successfully r ## Redirection - 3xx -This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. +This class of status code indicates that further action needs to be taken by +the user agent in order to fulfill the request. HTTP_300_MULTIPLE_CHOICES HTTP_301_MOVED_PERMANENTLY @@ -67,7 +76,10 @@ This class of status code indicates that further action needs to be taken by the ## Client Error - 4xx -The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. +The 4xx class of status code is intended for cases in which the client seems to +have erred. Except when responding to a HEAD request, the server SHOULD +include an entity containing an explanation of the error situation, and whether +it is a temporary or permanent condition. HTTP_400_BAD_REQUEST HTTP_401_UNAUTHORIZED @@ -97,7 +109,11 @@ The 4xx class of status code is intended for cases in which the client seems to ## Server Error - 5xx -Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. +Response status codes beginning with the digit "5" indicate cases in which the +server is aware that it has erred or is incapable of performing the request. +Except when responding to a HEAD request, the server SHOULD include an entity +containing an explanation of the error situation, and whether it is a temporary +or permanent condition. HTTP_500_INTERNAL_SERVER_ERROR HTTP_501_NOT_IMPLEMENTED @@ -110,7 +126,8 @@ Response status codes beginning with the digit "5" indicate cases in which the s ## Helper functions -The following helper functions are available for identifying the category of the response code. +The following helper functions are available for identifying the category of +the response code. is_informational() # 1xx is_success() # 2xx diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 69da7d105..2cf0c2178 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -6,7 +6,8 @@ source: test.py > > — [Jacob Kaplan-Moss][cite] -REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests. +REST framework includes a few helper classes that extend Django's existing test +framework, and improve support for making API requests. # APIRequestFactory @@ -14,7 +15,10 @@ Extends [Django's existing `RequestFactory` class][requestfactory]. ## Creating test requests -The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. +The `APIRequestFactory` class supports an almost identical API to Django's +standard `RequestFactory` class. This means that the standard `.get()`, +`.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` +methods are all available. from rest_framework.test import APIRequestFactory @@ -24,32 +28,41 @@ The `APIRequestFactory` class supports an almost identical API to Django's stand #### Using the `format` argument -Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a content type other than multipart form data. For example: +Methods which create a request body, such as `post`, `put` and `patch`, include +a `format` argument, which make it easy to generate requests using a content +type other than multipart form data. For example: # Create a JSON POST request factory = APIRequestFactory() request = factory.post('/notes/', {'title': 'new idea'}, format='json') -By default the available formats are `'multipart'` and `'json'`. For compatibility with Django's existing `RequestFactory` the default format is `'multipart'`. +By default the available formats are `'multipart'` and `'json'`. For +compatibility with Django's existing `RequestFactory` the default format is +`'multipart'`. -To support a wider set of request formats, or change the default format, [see the configuration section][configuration]. +To support a wider set of request formats, or change the default format, [see +the configuration section][configuration]. #### Explicitly encoding the request body -If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example: +If you need to explicitly encode the request body, you can do so by setting the +`content_type` flag. For example: request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json') #### PUT and PATCH with form data -One difference worth noting between Django's `RequestFactory` and REST framework's `APIRequestFactory` is that multipart form data will be encoded for methods other than just `.post()`. +One difference worth noting between Django's `RequestFactory` and REST +framework's `APIRequestFactory` is that multipart form data will be encoded for +methods other than just `.post()`. For example, using `APIRequestFactory`, you can make a form PUT request like so: factory = APIRequestFactory() request = factory.put('/notes/547/', {'title': 'remember to email dave'}) -Using Django's `RequestFactory`, you'd need to explicitly encode the data yourself: +Using Django's `RequestFactory`, you'd need to explicitly encode the data +yourself: from django.test.client import encode_multipart, RequestFactory @@ -61,7 +74,9 @@ Using Django's `RequestFactory`, you'd need to explicitly encode the data yourse ## Forcing authentication -When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials. +When testing views directly using a request factory, it's often convenient to +be able to directly authenticate the request, rather than having to construct +the correct authentication credentials. To forcibly authenticate a request, use the `force_authenticate()` method. @@ -76,9 +91,12 @@ To forcibly authenticate a request, use the `force_authenticate()` method. force_authenticate(request, user=user) response = view(request) -The signature for the method is `force_authenticate(request, user=None, token=None)`. When making the call, either or both of the user and token may be set. +The signature for the method is `force_authenticate(request, user=None, +token=None)`. When making the call, either or both of the user and token may +be set. -For example, when forcibly authenticating using a token, you might do something like the following: +For example, when forcibly authenticating using a token, you might do something +like the following: user = User.objects.get(username='olivia') request = factory.get('/accounts/django-superstars/') @@ -86,9 +104,14 @@ For example, when forcibly authenticating using a token, you might do something --- -**Note**: When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called. +**Note**: When using `APIRequestFactory`, the object that is returned is +Django's standard `HttpRequest`, and not REST framework's `Request` object, +which is only generated once the view is called. -This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used. +This means that setting attributes directly on the request object may not +always have the effect you expect. For example, setting `.token` directly will +have no effect, and setting `.user` directly will only work if session +authentication is being used. # Request will only authenticate if `SessionAuthentication` is in use. request = factory.get('/accounts/django-superstars/') @@ -99,13 +122,20 @@ This means that setting attributes directly on the request object may not always ## Forcing CSRF validation -By default, requests created with `APIRequestFactory` will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the `enforce_csrf_checks` flag when instantiating the factory. +By default, requests created with `APIRequestFactory` will not have CSRF +validation applied when passed to a REST framework view. If you need to +explicitly turn CSRF validation on, you can do so by setting the +`enforce_csrf_checks` flag when instantiating the factory. factory = APIRequestFactory(enforce_csrf_checks=True) --- -**Note**: It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks. +**Note**: It's worth noting that Django's standard `RequestFactory` doesn't +need to include this option, because when using regular Django the CSRF +validation takes place in middleware, which is not run when testing views +directly. When using REST framework, CSRF validation takes place inside the +view, so the request factory needs to disable view-level CSRF checks. --- @@ -115,20 +145,26 @@ Extends [Django's existing `Client` class][client]. ## Making requests -The `APIClient` class supports the same request interface as Django's standard `Client` class. This means the that standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example: +The `APIClient` class supports the same request interface as Django's standard +`Client` class. This means the that standard `.get()`, `.post()`, `.put()`, +`.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. +For example: from rest_framework.test import APIClient client = APIClient() client.post('/notes/', {'title': 'new idea'}, format='json') -To support a wider set of request formats, or change the default format, [see the configuration section][configuration]. +To support a wider set of request formats, or change the default format, [see +the configuration section][configuration]. ## Authenticating #### .login(**kwargs) -The `login` method functions exactly as it does with Django's regular `Client` class. This allows you to authenticate requests against any views which include `SessionAuthentication`. +The `login` method functions exactly as it does with Django's regular `Client` +class. This allows you to authenticate requests against any views which +include `SessionAuthentication`. # Make all requests in the context of a logged in session. client = APIClient() @@ -139,11 +175,14 @@ To logout, call the `logout` method as usual. # Log out client.logout() -The `login` method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API. +The `login` method is appropriate for testing APIs that use session +authentication, for example web sites which include AJAX interaction with the +API. #### .credentials(**kwargs) -The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client. +The `credentials` method can be used to set headers that will then be included +on all subsequent requests by the test client. from rest_framework.authtoken.models import Token from rest_framework.test import APIClient @@ -153,40 +192,53 @@ The `credentials` method can be used to set headers that will then be included o client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) -Note that calling `credentials` a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments. +Note that calling `credentials` a second time overwrites any existing +credentials. You can unset any existing credentials by calling the method with +no arguments. # Stop including any credentials client.credentials() -The `credentials` method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes. +The `credentials` method is appropriate for testing APIs that require +authentication headers, such as basic authentication, OAuth1a and OAuth2 +authentication, and simple token authentication schemes. #### .force_authenticate(user=None, token=None) -Sometimes you may want to bypass authentication, and simple force all requests by the test client to be automatically treated as authenticated. +Sometimes you may want to bypass authentication, and simple force all requests +by the test client to be automatically treated as authenticated. -This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests. +This can be a useful shortcut if you're testing the API but don't want to have +to construct valid authentication credentials in order to make test requests. user = User.objects.get(username='lauren') client = APIClient() client.force_authenticate(user=user) -To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`. +To unauthenticate subsequent requests, call `force_authenticate` setting the +user and/or token to `None`. client.force_authenticate(user=None) ## CSRF validation -By default CSRF validation is not applied when using `APIClient`. If you need to explicitly enable CSRF validation, you can do so by setting the `enforce_csrf_checks` flag when instantiating the client. +By default CSRF validation is not applied when using `APIClient`. If you need +to explicitly enable CSRF validation, you can do so by setting the +`enforce_csrf_checks` flag when instantiating the client. client = APIClient(enforce_csrf_checks=True) -As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling `login()`. +As usual CSRF validation will only apply to any session authenticated views. +This means CSRF validation will only occur if the client has been logged in by +calling `login()`. --- # Test cases -REST framework includes the following test case classes, that mirror the existing Django test case classes, but use `APIClient` instead of Django's default `Client`. +REST framework includes the following test case classes, that mirror the +existing Django test case classes, but use `APIClient` instead of Django's +default `Client`. * `APISimpleTestCase` * `APITransactionTestCase` @@ -195,7 +247,9 @@ REST framework includes the following test case classes, that mirror the existin ## Example -You can use any of REST framework's test case classes as you would for the regular Django test case classes. The `self.client` attribute will be an `APIClient` instance. +You can use any of REST framework's test case classes as you would for the +regular Django test case classes. The `self.client` attribute will be an +`APIClient` instance. from django.core.urlresolvers import reverse from rest_framework import status @@ -220,7 +274,9 @@ You can use any of REST framework's test case classes as you would for the regul ## Checking the response data -When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response. +When checking the validity of test responses it's often more convenient to +inspect the data that the response was created with, rather than inspecting the +fully rendered response. For example, it's easier to inspect `response.data`: @@ -234,7 +290,10 @@ Instead of inspecting the result of parsing `response.content`: ## Rendering responses -If you're testing views directly using `APIRequestFactory`, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access `response.content`, you'll first need to render the response. +If you're testing views directly using `APIRequestFactory`, the responses that +are returned will not yet be rendered, as rendering of template responses is +performed by Django's internal request-response cycle. In order to access +`response.content`, you'll first need to render the response. view = UserDetail.as_view() request = factory.get('/users/4') @@ -248,7 +307,10 @@ If you're testing views directly using `APIRequestFactory`, the responses that a ## Setting the default format -The default format used to make test requests may be set using the `TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your `settings.py` file: +The default format used to make test requests may be set using the +`TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for +test requests by default instead of standard multipart form requests, set the +following in your `settings.py` file: REST_FRAMEWORK = { ... @@ -257,9 +319,11 @@ The default format used to make test requests may be set using the `TEST_REQUEST ## Setting the available formats -If you need to test requests using something other than multipart or json requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting. +If you need to test requests using something other than multipart or json +requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting. -For example, to add support for using `format='html'` in test requests, you might have something like this in your `settings.py` file. +For example, to add support for using `format='html'` in test requests, you +might have something like this in your `settings.py` file. REST_FRAMEWORK = { ... diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index da4d5f725..ded7d7401 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -6,26 +6,40 @@ source: throttling.py > > [Twitter API rate limiting response][cite] -Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API. +Throttling is similar to [permissions], in that it determines if a request +should be authorized. Throttles indicate a temporary state, and are used to +control the rate of requests that clients can make to an API. -As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests. +As with permissions, multiple throttles may be used. Your API might have a +restrictive throttle for unauthenticated requests, and a less restrictive +throttle for authenticated requests. -Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive. +Another scenario where you might want to use multiple throttles would be if you +need to impose different constraints on different parts of the API, due to some +services being particularly resource-intensive. -Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day. +Multiple throttles can also be used if you want to impose both burst throttling +rates, and sustained throttling rates. For example, you might want to limit a +user to a maximum of 60 requests per minute, and 1000 requests per day. -Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed. +Throttles do not necessarily only refer to rate-limiting requests. For example +a storage service might also need to throttle against bandwidth, and a paid +data service might want to throttle against a certain number of a records being +accessed. ## How throttling is determined -As with permissions and authentication, throttling in REST framework is always defined as a list of classes. +As with permissions and authentication, throttling in REST framework is always +defined as a list of classes. Before running the main body of the view each throttle in the list is checked. -If any throttle check fails an `exceptions.Throttled` exception will be raised, and the main body of the view will not run. +If any throttle check fails an `exceptions.Throttled` exception will be raised, +and the main body of the view will not run. ## Setting the throttling policy -The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example. +The default throttling policy may be set globally, using the +`DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example. REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( @@ -38,7 +52,8 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C } } -The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. +The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, +`minute`, `hour` or `day` as the throttle period. You can also set the throttling policy on a per-view or per-viewset basis, using the `APIView` class-based views. @@ -68,24 +83,44 @@ Or, if you're using the `@api_view` decorator with function based views. ## How clients are identified -The `X-Forwarded-For` and `Remote-Addr` HTTP headers are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `Remote-Addr` header will be used. +The `X-Forwarded-For` and `Remote-Addr` HTTP headers are used to uniquely +identify client IP addresses for throttling. If the `X-Forwarded-For` header +is present then it will be used, otherwise the value of the `Remote-Addr` +header will be used. -If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `Remote-Addr` header will always be used as the identifying IP address. +If you need to strictly identify unique client IP addresses, you'll need to +first configure the number of application proxies that the API runs behind by +setting the `NUM_PROXIES` setting. This setting should be an integer of zero +or more. If set to non-zero then the client IP will be identified as being the +last IP address in the `X-Forwarded-For` header, once any application proxy IP +addresses have first been excluded. If set to zero, then the `Remote-Addr` +header will always be used as the identifying IP address. -It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. +It is important to understand that if you configure the `NUM_PROXIES` setting, +then all clients behind a unique +[NAT'd](http://en.wikipedia.org/wiki/Network_address_translation) gateway will +be treated as a single client. -Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifing-clients]. +Further context on how the `X-Forwarded-For` header works, and identifying a +remote client IP can be [found here][identifing-clients]. ## Setting up the cache -The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details. +The throttle classes provided by REST framework use Django's cache backend. +You should make sure that you've set appropriate [cache +settings][cache-setting]. The default value of `LocMemCache` backend should be +okay for simple setups. See Django's [cache documentation][cache-docs] for +more details. -If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example: +If you need to use a cache other than `'default'`, you can do so by creating a +custom throttle class and setting the `cache` attribute. For example: class CustomAnonRateThrottle(AnonRateThrottle): cache = get_cache('alternate') -You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. +You'll need to remember to also set your custom throttle class in the +`'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view +attribute. --- @@ -93,27 +128,39 @@ You'll need to remember to also set your custom throttle class in the `'DEFAULT_ ## AnonRateThrottle -The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against. +The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP +address of the incoming request is used to generate a unique key to throttle +against. -The allowed request rate is determined from one of the following (in order of preference). +The allowed request rate is determined from one of the following (in order of +preference). -* The `rate` property on the class, which may be provided by overriding `AnonRateThrottle` and setting the property. +* The `rate` property on the class, which may be provided by overriding + `AnonRateThrottle` and setting the property. * The `DEFAULT_THROTTLE_RATES['anon']` setting. -`AnonRateThrottle` is suitable if you want to restrict the rate of requests from unknown sources. +`AnonRateThrottle` is suitable if you want to restrict the rate of requests +from unknown sources. ## UserRateThrottle -The `UserRateThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against. +The `UserRateThrottle` will throttle users to a given rate of requests across +the API. The user id is used to generate a unique key to throttle against. +Unauthenticated requests will fall back to using the IP address of the incoming +request to generate a unique key to throttle against. -The allowed request rate is determined from one of the following (in order of preference). +The allowed request rate is determined from one of the following (in order of +preference). -* The `rate` property on the class, which may be provided by overriding `UserRateThrottle` and setting the property. +* The `rate` property on the class, which may be provided by overriding + `UserRateThrottle` and setting the property. * The `DEFAULT_THROTTLE_RATES['user']` setting. -An API may have multiple `UserRateThrottles` in place at the same time. To do so, override `UserRateThrottle` and set a unique "scope" for each class. +An API may have multiple `UserRateThrottles` in place at the same time. To do +so, override `UserRateThrottle` and set a unique "scope" for each class. -For example, multiple user throttle rates could be implemented by using the following classes... +For example, multiple user throttle rates could be implemented by using the +following classes... class BurstRateThrottle(UserRateThrottle): scope = 'burst' @@ -138,9 +185,14 @@ For example, multiple user throttle rates could be implemented by using the foll ## ScopedRateThrottle -The `ScopedRateThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address. +The `ScopedRateThrottle` class can be used to restrict access to specific parts +of the API. This throttle will only be applied if the view that is being +accessed includes a `.throttle_scope` property. The unique throttle key will +then be formed by concatenating the "scope" of the request with the unique user +id or IP address. -The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope". +The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting +using a key from the request "scope". For example, given the following views... @@ -168,21 +220,30 @@ For example, given the following views... } } -User requests to either `ContactListView` or `ContactDetailView` would be restricted to a total of 1000 requests per-day. User requests to `UploadView` would be restricted to 20 requests per day. +User requests to either `ContactListView` or `ContactDetailView` would be +restricted to a total of 1000 requests per-day. User requests to `UploadView` +would be restricted to 20 requests per day. --- # Custom throttles -To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise. +To create a custom throttle, override `BaseThrottle` and implement +`.allow_request(self, request, view)`. The method should return `True` if the +request should be allowed, and `False` otherwise. -Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`. +Optionally you may also override the `.wait()` method. If implemented, +`.wait()` should return a recommended number of seconds to wait before +attempting the next request, or `None`. The `.wait()` method will only be +called if `.allow_request()` has previously returned `False`. -If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response. +If the `.wait()` method is implemented and the request is throttled, then a +`Retry-After` header will be included in the response. ## Example -The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests. +The following is an example of a rate throttle, that will randomly throttle 1 +in every 10 requests. import random diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index f04c74c3c..be3398271 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -6,32 +6,49 @@ source: validators.py > > — [Django documentation][cite] -Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes. +Most of the time you're dealing with validation in REST framework you'll simply +be relying on the default field validation, or writing explicit validation +methods on serializer or field classes. -However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. +However, sometimes you'll want to place your validation logic into reusable +components, so that it can easily be reused throughout your codebase. This can +be achieved by using validator functions and validator classes. ## Validation in REST framework -Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class. +Validation in Django REST framework serializers is handled a little differently +to how validation works in Django's `ModelForm` class. -With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: +With `ModelForm` the validation is performed partially on the form, and +partially on the model instance. With REST framework the validation is +performed entirely on the serializer class. This is advantageous for the +following reasons: -* It introduces a proper separation of concerns, making your code behavior more obvious. -* It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate. -* Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance. +* It introduces a proper separation of concerns, making your code behavior more + obvious. +* It is easy to switch between using shortcut `ModelSerializer` classes and + using explicit `Serializer` classes. Any validation behavior being used for + `ModelSerializer` is simple to replicate. +* Printing the `repr` of a serializer instance will show you exactly what + validation rules it applies. There's no extra hidden validation behavior + being called on the model instance. -When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using a `Serializer` classes instead, then you need to define the validation rules explicitly. +When you're using `ModelSerializer` all of this is handled automatically for +you. If you want to drop down to using a `Serializer` classes instead, then you +need to define the validation rules explicitly. #### Example -As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint. +As an example of how REST framework uses explicit validation, we'll take a +simple model class that has a field with a uniqueness constraint. class CustomerReportRecord(models.Model): time_raised = models.DateTimeField(default=timezone.now, editable=False) reference = models.CharField(unique=True, max_length=20) description = models.TextField() -Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`: +Here's a basic `ModelSerializer` that we can use for creating or updating +instances of `CustomerReportRecord`: class CustomerReportSerializer(serializers.ModelSerializer): class Meta: @@ -48,9 +65,13 @@ If we open up the Django shell using `manage.py shell` we can now reference = CharField(max_length=20, validators=[]) description = CharField(style={'type': 'textarea'}) -The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field. +The interesting bit here is the `reference` field. We can see that the +uniqueness constraint is being explicitly enforced by a validator on the +serializer field. -Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. +Because of this more explicit style REST framework includes a few validator +classes that are not available in core Django. These classes are detailed +below. --- @@ -76,14 +97,16 @@ This validator should be applied to *serializer fields*, like so: This validator can be used to enforce `unique_together` constraints on model instances. It has two required arguments, and a single optional `messages` argument: -* `queryset` *required* - This is the queryset against which uniqueness should be enforced. -* `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class. +* `queryset` *required* - This is the queryset against which uniqueness should + be enforced. +* `fields` *required* - A list or tuple of field names which should make a + unique set. These must exist as fields on the serializer class. * `message` - The error message that should be used when validation fails. The validator should be applied to *serializer classes*, like so: from rest_framework.validators import UniqueTogetherValidator - + class ExampleSerializer(serializers.Serializer): # ... class Meta: @@ -99,7 +122,10 @@ The validator should be applied to *serializer classes*, like so: --- -**Note**: The `UniqueTogetherValidation` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. +**Note**: The `UniqueTogetherValidation` class always imposes an implicit +constraint that all the fields it applies to are always treated as required. +Fields with `default` values are an exception to this as they always supply a +value even when omitted from user input. --- @@ -109,11 +135,17 @@ The validator should be applied to *serializer classes*, like so: ## UniqueForYearValidator -These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments: +These validators can be used to enforce the `unique_for_date`, +`unique_for_month` and `unique_for_year` constraints on model instances. They +take the following arguments: -* `queryset` *required* - This is the queryset against which uniqueness should be enforced. -* `field` *required* - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class. -* `date_field` *required* - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class. +* `queryset` *required* - This is the queryset against which uniqueness should + be enforced. +* `field` *required* - A field name against which uniqueness in the given date + range will be validated. This must exist as a field on the serializer class. +* `date_field` *required* - A field name which will be used to determine date + range for the uniqueness constrain. This must exist as a field on the + serializer class. * `message` - The error message that should be used when validation fails. The validator should be applied to *serializer classes*, like so: @@ -132,50 +164,74 @@ The validator should be applied to *serializer classes*, like so: ) ] -The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class `default=...`, because the value being used for the default wouldn't be generated until after the validation has run. +The date field that is used for the validation is always required to be present +on the serializer class. You can't simply rely on a model class `default=...`, +because the value being used for the default wouldn't be generated until after +the validation has run. -There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using `ModelSerializer` you'll probably simply rely on the defaults that REST framework generates for you, but if you are using `Serializer` or simply want more explicit control, use on of the styles demonstrated below. +There are a couple of styles you may want to use for this depending on how you +want your API to behave. If you're using `ModelSerializer` you'll probably +simply rely on the defaults that REST framework generates for you, but if you +are using `Serializer` or simply want more explicit control, use on of the +styles demonstrated below. #### Using with a writable date field. -If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a `default` argument, or by setting `required=True`. +If you want the date field to be writable the only thing worth noting is that +you should ensure that it is always available in the input data, either by +setting a `default` argument, or by setting `required=True`. published = serializers.DateTimeField(required=True) #### Using with a read-only date field. -If you want the date field to be visible, but not editable by the user, then set `read_only=True` and additionally set a `default=...` argument. +If you want the date field to be visible, but not editable by the user, then +set `read_only=True` and additionally set a `default=...` argument. published = serializers.DateTimeField(read_only=True, default=timezone.now) -The field will not be writable to the user, but the default value will still be passed through to the `validated_data`. +The field will not be writable to the user, but the default value will still be +passed through to the `validated_data`. #### Using with a hidden date field. -If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns it's default value to the `validated_data` in the serializer. +If you want the date field to be entirely hidden from the user, then use +`HiddenField`. This field type does not accept user input, but instead always +returns it's default value to the `validated_data` in the serializer. published = serializers.HiddenField(default=timezone.now) --- -**Note**: The `UniqueForValidation` classes always imposes an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. +**Note**: The `UniqueForValidation` classes always imposes an implicit +constraint that the fields they are applied to are always treated as required. +Fields with `default` values are an exception to this as they always supply a +value even when omitted from user input. --- # Advanced field defaults -Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator. +Validators that are applied across multiple fields in the serializer can +sometimes require a field input that should not be provided by the API client, +but that *is* available as input to the validator. Two patterns that you may want to use for this sort of validation include: -* Using `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation. -* Using a standard field with `read_only=True`, but that also includes a `default=…` argument. This field *will* be used in the serializer output representation, but cannot be set directly by the user. +* Using `HiddenField`. This field will be present in `validated_data` but *will + not* be used in the serializer output representation. +* Using a standard field with `read_only=True`, but that also includes a + `default=…` argument. This field *will* be used in the serializer output + representation, but cannot be set directly by the user. -REST framework includes a couple of defaults that may be useful in this context. +REST framework includes a couple of defaults that may be useful in this +context. #### CurrentUserDefault -A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer. +A default class that can be used to represent the current user. In order to use +this, the 'request' must have been provided as part of the context dictionary +when instantiating the serializer. owner = serializers.HiddenField( default=serializers.CurrentUserDefault() @@ -183,9 +239,11 @@ A default class that can be used to represent the current user. In order to use #### CreateOnlyDefault -A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted. +A default class that can be used to *only set a default argument during create +operations*. During updates the field is omitted. -It takes a single argument, which is the default value or callable that should be used during create operations. +It takes a single argument, which is the default value or callable that should +be used during create operations. created_at = serializers.DateTimeField( read_only=True, @@ -273,7 +331,8 @@ A validator may be any callable that raises a `serializers.ValidationError` on f ## Class-based -To write a class-based validator, use the `__call__` method. Class-based validators are useful as they allow you to parameterize and reuse behavior. +To write a class-based validator, use the `__call__` method. Class-based +validators are useful as they allow you to parameterize and reuse behavior. class MultipleOf(object): def __init__(self, base): @@ -286,7 +345,9 @@ To write a class-based validator, use the `__call__` method. Class-based validat #### Using `set_context()` -In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by declaring a `set_context` method on a class-based validator. +In some advanced cases you might want a validator to be passed the serializer +field it is being used with as additional context. You can do so by declaring a +`set_context` method on a class-based validator. def set_context(self, serializer_field): # Determine if this is an update or a create operation. diff --git a/docs/api-guide/versioning.md b/docs/api-guide/versioning.md index 29672c96e..256b429ec 100644 --- a/docs/api-guide/versioning.md +++ b/docs/api-guide/versioning.md @@ -6,21 +6,31 @@ source: versioning.py > > — [Roy Fielding][cite]. -API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes. +API versioning allows you to alter behavior between different clients. REST +framework provides for a number of different versioning schemes. -Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers. +Versioning is determined by the incoming client request, and may either be +based on the request URL, or based on the request headers. -There are a number of valid approaches to approaching versioning. [Non-versioned systems can also be appropriate][roy-fielding-on-versioning], particularly if you're engineering for very long-term systems with multiple clients outside of your control. +There are a number of valid approaches to approaching versioning. +[Non-versioned systems can also be appropriate][roy-fielding-on-versioning], +particularly if you're engineering for very long-term systems with multiple +clients outside of your control. ## Versioning with REST framework -When API versioning is enabled, the `request.version` attribute will contain a string that corresponds to the version requested in the incoming client request. +When API versioning is enabled, the `request.version` attribute will contain a +string that corresponds to the version requested in the incoming client +request. -By default, versioning is not enabled, and `request.version` will always return `None`. +By default, versioning is not enabled, and `request.version` will always return +`None`. #### Varying behavior based on the version -How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example: +How you vary the API behavior is up to you, but one example you might typically +want is to switch to a different serialization style in a newer version. For +example: def get_serializer_class(self): if self.request.version == 'v1': @@ -29,20 +39,29 @@ How you vary the API behavior is up to you, but one example you might typically #### Reversing URLs for versioned APIs -The `reverse` function included by REST framework ties in with the versioning scheme. You need to make sure to include the current `request` as a keyword argument, like so. +The `reverse` function included by REST framework ties in with the versioning +scheme. You need to make sure to include the current `request` as a keyword +argument, like so. from rest_framework.reverse import reverse reverse('bookings-list', request=request) -The above function will apply any URL transformations appropriate to the request version. For example: +The above function will apply any URL transformations appropriate to the +request version. For example: -* If `NamespacedVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`. -* If `QueryParameterVersioning` was being used, and the API version was `1.0`, then the returned URL might be something like `http://example.org/bookings/?version=1.0` +* If `NamespacedVersioning` was being used, and the API version was 'v1', then + the URL lookup used would be `'v1:bookings-list'`, which might resolve to a + URL like `http://example.org/v1/bookings/`. +* If `QueryParameterVersioning` was being used, and the API version was `1.0`, + then the returned URL might be something like + `http://example.org/bookings/?version=1.0` #### Versioned APIs and hyperlinked serializers -When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer. +When using hyperlinked serialization styles together with a URL based +versioning scheme make sure to include the request as context to the +serializer. def get(self, request): queryset = Booking.objects.all() @@ -59,9 +78,13 @@ The versioning scheme is defined by the `DEFAULT_VERSIONING_CLASS` settings key. 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning' } -Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be `None`. In this case the `request.version` attribute will always return `None`. +Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be +`None`. In this case the `request.version` attribute will always return `None`. -You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the `versioning_class` attribute. +You can also set the versioning scheme on an individual view. Typically you +won't need to do this, as it makes more sense to have a single versioning +scheme used globally. If you do need to do so, use the `versioning_class` +attribute. class ProfileList(APIView): versioning_class = versioning.QueryParameterVersioning @@ -70,11 +93,21 @@ You can also set the versioning scheme on an individual view. Typically you won' The following settings keys are also used to control versioning: -* `DEFAULT_VERSION`. The value that should be used for `request.version` when no versioning information is present. Defaults to `None`. -* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the `DEFAULT_VERSION` setting is always considered to be part of the `ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`. -* `VERSION_PARAM`. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`. +* `DEFAULT_VERSION`. The value that should be used for `request.version` when + no versioning information is present. Defaults to `None`. +* `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that + may be returned by the versioning scheme, and will raise an error if the + provided version is not in this set. Note that the value used for the + `DEFAULT_VERSION` setting is always considered to be part of the + `ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`. +* `VERSION_PARAM`. The string that should be used for any versioning + parameters, such as in the media type or URL query parameters. Defaults to + `'version'`. -You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the `default_version`, `allowed_versions` and `version_param` class variables. For example, if you want to use `URLPathVersioning`: +You can also set your versioning class plus those three values on a per-view or +a per-viewset basis by defining your own versioning scheme and using the +`default_version`, `allowed_versions` and `version_param` class variables. For +example, if you want to use `URLPathVersioning`: from rest_framework.versioning import URLPathVersioning from rest_framework.views import APIView @@ -93,7 +126,9 @@ You can also set your versioning class plus those three values on a per-view or ## AcceptHeaderVersioning -This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type. +This scheme requires the client to specify the version as part of the media +type in the `Accept` header. The version is included as a media type parameter, +that supplements the main media type. Here's an example HTTP request using the accept header versioning style. @@ -101,9 +136,12 @@ Here's an example HTTP request using the accept header versioning style. Host: example.com Accept: application/json; version=1.0 -In the example request above `request.version` attribute would return the string `'1.0'`. +In the example request above `request.version` attribute would return the +string `'1.0'`. -Versioning based on accept headers is [generally considered][klabnik-guidelines] as [best practice][heroku-guidelines], although other styles may be suitable depending on your client requirements. +Versioning based on accept headers is [generally +considered][klabnik-guidelines] as [best practice][heroku-guidelines], although +other styles may be suitable depending on your client requirements. #### Using accept headers with vendor media types @@ -126,7 +164,9 @@ This scheme requires the client to specify the version as part of the URL path. Host: example.com Accept: application/json -Your URL conf must include a pattern that matches the version with a `'version'` keyword argument, so that this information is available to the versioning scheme. +Your URL conf must include a pattern that matches the version with a +`'version'` keyword argument, so that this information is available to the +versioning scheme. urlpatterns = [ url( @@ -143,15 +183,19 @@ Your URL conf must include a pattern that matches the version with a `'version'` ## NamespaceVersioning -To the client, this scheme is the same as `URLPathVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments. +To the client, this scheme is the same as `URLPathVersioning`. The only +difference is how it is configured in your Django application, as it uses URL +namespacing, instead of URL keyword arguments. GET /v1/something/ HTTP/1.1 Host: example.com Accept: application/json -With this scheme the `request.version` attribute is determined based on the `namespace` that matches the incoming request path. +With this scheme the `request.version` attribute is determined based on the +`namespace` that matches the incoming request path. -In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace: +In the following example we're giving a set of views two different possible URL +prefixes, each under a different namespace: # bookings/urls.py urlpatterns = [ @@ -165,13 +209,18 @@ In the following example we're giving a set of views two different possible URL url(r'^v2/bookings/', include('bookings.urls', namespace='v2')) ] -Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLPathVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects. +Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just +need a simple versioning scheme. The `URLPathVersioning` approach might be +better suitable for small ad-hoc projects, and the `NamespaceVersioning` is +probably easier to manage for larger projects. ## HostNameVersioning -The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL. +The hostname versioning scheme requires the client to specify the requested +version as part of the hostname in the URL. -For example the following is an HTTP request to the `http://v1.example.com/bookings/` URL: +For example the following is an HTTP request to the +`http://v1.example.com/bookings/` URL: GET /bookings/ HTTP/1.1 Host: v1.example.com @@ -181,11 +230,17 @@ By default this implementation expects the hostname to match this simple regular ^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$ -Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname. +Note that the first group is enclosed in brackets, indicating that this is the +matched portion of the hostname. -The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online services which you to [access localhost with a custom subdomain][lvh] which you may find helpful in this case. +The `HostNameVersioning` scheme can be awkward to use in debug mode as you will +typically be accessing a raw IP address such as `127.0.0.1`. There are various +online services which you to [access localhost with a custom subdomain][lvh] +which you may find helpful in this case. -Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions. +Hostname based versioning can be particularly useful if you have requirements +to route incoming requests to different servers based on the version, as you +can configure different DNS records for different API versions. ## QueryParameterVersioning @@ -199,17 +254,21 @@ This scheme is a simple style that includes the version as a query parameter in # Custom versioning schemes -To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method. +To implement a custom versioning scheme, subclass `BaseVersioning` and override +the `.determine_version` method. ## Example -The following example uses a custom `X-API-Version` header to determine the requested version. +The following example uses a custom `X-API-Version` header to determine the +requested version. class XAPIVersionScheme(versioning.BaseVersioning): def determine_version(self, request, *args, **kwargs): return request.META.get('HTTP_X_API_VERSION', None) -If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples. +If your versioning scheme is based on the request URL, you will also want to +alter how versioned URLs are determined. In order to do so you should override +the `.reverse()` method on the class. See the source code for examples. [cite]: http://www.slideshare.net/evolve_conference/201308-fielding-evolve/31 [roy-fielding-on-versioning]: http://www.infoq.com/articles/roy-fielding-on-versioning diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 62f14087f..91938e9e7 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -7,16 +7,27 @@ source: decorators.py > > — [Reinout van Rees][cite] -REST framework provides an `APIView` class, which subclasses Django's `View` class. +REST framework provides an `APIView` class, which subclasses Django's `View` +class. -`APIView` classes are different from regular `View` classes in the following ways: +`APIView` classes are different from regular `View` classes in the following +ways: -* Requests passed to the handler methods will be REST framework's `Request` instances, not Django's `HttpRequest` instances. -* Handler methods may return REST framework's `Response`, instead of Django's `HttpResponse`. The view will manage content negotiation and setting the correct renderer on the response. -* Any `APIException` exceptions will be caught and mediated into appropriate responses. -* Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method. +* Requests passed to the handler methods will be REST framework's `Request` + instances, not Django's `HttpRequest` instances. +* Handler methods may return REST framework's `Response`, instead of Django's + `HttpResponse`. The view will manage content negotiation and setting the + correct renderer on the response. +* Any `APIException` exceptions will be caught and mediated into appropriate + responses. +* Incoming requests will be authenticated and appropriate permission and/or + throttle checks will be run before dispatching the request to the handler + method. -Using the `APIView` class is pretty much the same as using a regular `View` class, as usual, the incoming request is dispatched to an appropriate handler method such as `.get()` or `.post()`. Additionally, a number of attributes may be set on the class that control various aspects of the API policy. +Using the `APIView` class is pretty much the same as using a regular `View` +class, as usual, the incoming request is dispatched to an appropriate handler +method such as `.get()` or `.post()`. Additionally, a number of attributes may +be set on the class that control various aspects of the API policy. For example: @@ -59,7 +70,8 @@ The following attributes control the pluggable aspects of API views. ## API policy instantiation methods -The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods. +The following methods are used by REST framework to instantiate the various +pluggable API policies. You won't typically need to override these methods. ### .get_renderers(self) @@ -86,32 +98,42 @@ The following methods are called before dispatching to the handler method. ## Dispatch methods The following methods are called directly by the view's `.dispatch()` method. -These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()`, `patch()` and `.delete()`. +These perform any actions that need to occur before or after calling the +handler methods such as `.get()`, `.post()`, `put()`, `patch()` and +`.delete()`. ### .initial(self, request, \*args, **kwargs) Performs any actions that need to occur before the handler method gets called. -This method is used to enforce permissions and throttling, and perform content negotiation. +This method is used to enforce permissions and throttling, and perform content +negotiation. You won't typically need to override this method. ### .handle_exception(self, exc) -Any exception thrown by the handler method will be passed to this method, which either returns a `Response` instance, or re-raises the exception. +Any exception thrown by the handler method will be passed to this method, which +either returns a `Response` instance, or re-raises the exception. -The default implementation handles any subclass of `rest_framework.exceptions.APIException`, as well as Django's `Http404` and `PermissionDenied` exceptions, and returns an appropriate error response. +The default implementation handles any subclass of +`rest_framework.exceptions.APIException`, as well as Django's `Http404` and +`PermissionDenied` exceptions, and returns an appropriate error response. -If you need to customize the error responses your API returns you should subclass this method. +If you need to customize the error responses your API returns you should +subclass this method. ### .initialize_request(self, request, \*args, **kwargs) -Ensures that the request object that is passed to the handler method is an instance of `Request`, rather than the usual Django `HttpRequest`. +Ensures that the request object that is passed to the handler method is an +instance of `Request`, rather than the usual Django `HttpRequest`. You won't typically need to override this method. ### .finalize_response(self, request, response, \*args, **kwargs) -Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation. +Ensures that any `Response` object returned from the handler method will be +rendered into the correct content type, as determined by the content +negotiation. You won't typically need to override this method. @@ -123,13 +145,19 @@ You won't typically need to override this method. > > — [Nick Coghlan][cite2] -REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed. +REST framework also allows you to work with regular function based views. It +provides a set of simple decorators that wrap your function based views to +ensure they receive an instance of `Request` (rather than the usual Django +`HttpRequest`) and allows them to return a `Response` (instead of a Django +`HttpResponse`), and allow you to configure how the request is processed. ## @api_view() **Signature:** `@api_view(http_method_names=['GET'])` -The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: +The core of this functionality is the `api_view` decorator, which takes a list +of HTTP methods that your view should respond to. For example, this is how you +would write a very simple view that just manually returns some data: from rest_framework.decorators import api_view @@ -137,9 +165,12 @@ The core of this functionality is the `api_view` decorator, which takes a list o def hello_world(request): return Response({"message": "Hello, world!"}) -This view will use the default renderers, parsers, authentication classes etc specified in the [settings]. +This view will use the default renderers, parsers, authentication classes etc +specified in the [settings]. -By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so: +By default only `GET` methods will be accepted. Other methods will respond with +"405 Method Not Allowed". To alter this behavior, specify which methods the +view allows, like so: @api_view(['GET', 'POST']) def hello_world(request): @@ -149,7 +180,12 @@ By default only `GET` methods will be accepted. Other methods will respond with ## API policy decorators -To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: +To override the default settings, REST framework provides a set of additional +decorators which can be added to your views. These must come *after* (below) +the `@api_view` decorator. For example, to create a view that uses a +[throttle][throttling] to ensure it can only be called once per day by a +particular user, use the `@throttle_classes` decorator, passing a list of +throttle classes: from rest_framework.decorators import api_view, throttle_classes from rest_framework.throttling import UserRateThrottle @@ -162,7 +198,8 @@ To override the default settings, REST framework provides a set of additional de def view(request): return Response({"message": "Hello for today! See you tomorrow!"}) -These decorators correspond to the attributes set on `APIView` subclasses, described above. +These decorators correspond to the attributes set on `APIView` subclasses, +described above. The available decorators are: @@ -172,7 +209,8 @@ The available decorators are: * `@throttle_classes(...)` * `@permission_classes(...)` -Each of these decorators takes a single argument which must be a list or tuple of classes. +Each of these decorators takes a single argument which must be a list or tuple +of classes. [cite]: http://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html [cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index e6df17f51..10d8ff286 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -2,18 +2,28 @@ source: viewsets.py # ViewSets -> After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. +> After routing has determined which controller to use for a request, your +> controller is responsible for making sense of the request and producing the +> appropriate output. > > — [Ruby on Rails Documentation][cite] -Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. +Django REST framework allows you to combine the logic for a set of related +views in a single class, called a `ViewSet`. In other frameworks you may also +find conceptually similar implementations named something like 'Resources' or +'Controllers'. -A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. +A `ViewSet` class is simply **a type of class-based View, that does not provide +any method handlers** such as `.get()` or `.post()`, and instead provides +actions such as `.list()` and `.create()`. -The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. +The method handlers for a `ViewSet` are only bound to the corresponding actions +at the point of finalizing the view, using the `.as_view()` method. -Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. +Typically, rather than explicitly registering the views in a viewset in the +urlconf, you'll register the viewset with a router class, that automatically +determines the urlconf for you. ## Example @@ -45,7 +55,8 @@ If we need to, we can bind this viewset into two separate views, like so: user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) -Typically we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. +Typically we wouldn't do this, but would instead register the viewset with a +router, and allow the urlconf to be automatically generated. from myapp.views import UserViewSet from rest_framework.routers import DefaultRouter @@ -54,7 +65,8 @@ Typically we wouldn't do this, but would instead register the viewset with a rou router.register(r'users', UserViewSet) urlpatterns = router.urls -Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: +Rather than writing your own viewsets, you'll often want to use the existing +base classes that provide a default set of behavior. For example: class UserViewSet(viewsets.ModelViewSet): """ @@ -63,16 +75,25 @@ Rather than writing your own viewsets, you'll often want to use the existing bas serializer_class = UserSerializer queryset = User.objects.all() -There are two main advantages of using a `ViewSet` class over using a `View` class. +There are two main advantages of using a `ViewSet` class over using a `View` +class. -* Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. -* By using routers, we no longer need to deal with wiring up the URL conf ourselves. +* Repeated logic can be combined into a single class. In the above example, we + only need to specify the `queryset` once, and it'll be used across multiple + views. +* By using routers, we no longer need to deal with wiring up the URL conf + ourselves. -Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. +Both of these come with a trade-off. Using regular views and URL confs is more +explicit and gives you more control. ViewSets are helpful if you want to get +up and running quickly, or when you have a large API and you want to enforce a +consistent URL configuration throughout. ## Marking extra actions for routing -The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style operations, as shown below: +The default routers included with REST framework will provide routes for a +standard set of create/retrieve/update/destroy style operations, as shown +below: class UserViewSet(viewsets.ViewSet): """ @@ -101,9 +122,12 @@ The default routers included with REST framework will provide routes for a stand def destroy(self, request, pk=None): pass -If you have ad-hoc methods that you need to be routed to, you can mark them as requiring routing using the `@detail_route` or `@list_route` decorators. +If you have ad-hoc methods that you need to be routed to, you can mark them as +requiring routing using the `@detail_route` or `@list_route` decorators. -The `@detail_route` decorator contains `pk` in its URL pattern and is intended for methods which require a single instance. The `@list_route` decorator is intended for methods which operate on a list of objects. +The `@detail_route` decorator contains `pk` in its URL pattern and is intended +for methods which require a single instance. The `@list_route` decorator is +intended for methods which operate on a list of objects. For example: @@ -145,13 +169,15 @@ For example: serializer = self.get_serializer(recent_users, many=True) return Response(serializer.data) -The decorators can additionally take extra arguments that will be set for the routed view only. For example... +The decorators can additionally take extra arguments that will be set for the +routed view only. For example... @detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... -These decorators will route `GET` requests by default, but may also accept other HTTP methods, by using the `methods` argument. For example: +These decorators will route `GET` requests by default, but may also accept +other HTTP methods, by using the `methods` argument. For example: @detail_route(methods=['post', 'delete']) def unset_password(self, request, pk=None): @@ -165,25 +191,38 @@ The two new actions will then be available at the urls `^users/{pk}/set_password ## ViewSet -The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset. +The `ViewSet` class inherits from `APIView`. You can use any of the standard +attributes such as `permission_classes`, `authentication_classes` in order to +control the API policy on the viewset. -The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. +The `ViewSet` class does not provide any implementations of actions. In order +to use a `ViewSet` class you'll override the class and define the action +implementations explicitly. ## GenericViewSet -The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default. +The `GenericViewSet` class inherits from `GenericAPIView`, and provides the +default set of `get_object`, `get_queryset` methods and other generic view base +behavior, but does not include any actions by default. -In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly. +In order to use a `GenericViewSet` class you'll override the class and either +mixin the required mixin classes, or define the action implementations +explicitly. ## ModelViewSet -The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes. +The `ModelViewSet` class inherits from `GenericAPIView` and includes +implementations for various actions, by mixing in the behavior of the various +mixin classes. -The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`. +The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, +`.create()`, `.update()`, `.partial_update()`, and `.destroy()`. #### Example -Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: +Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to +provide at least the `queryset` and `serializer_class` attributes. For +example: class AccountViewSet(viewsets.ModelViewSet): """ @@ -193,7 +232,9 @@ Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] -Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this: +Note that you can use any of the standard attributes or method overrides +provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically +determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet): """ @@ -206,17 +247,26 @@ Note that you can use any of the standard attributes or method overrides provide def get_queryset(self): return self.request.user.accounts.all() -Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the base_name of your Model automatically, and so you will have to specify the `base_name` kwarg as part of your [router registration][routers]. +Note however that upon removal of the `queryset` property from your `ViewSet`, +any associated [router][routers] will be unable to derive the base_name of your +Model automatically, and so you will have to specify the `base_name` kwarg as +part of your [router registration][routers]. -Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. +Also note that although this class provides the complete set of +create/list/retrieve/update/destroy actions by default, you can restrict the +available operations by using the standard permission classes. ## ReadOnlyModelViewSet -The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. +The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with +`ModelViewSet` it also includes implementations for various actions, but unlike +`ModelViewSet` only provides the 'read-only' actions, `.list()` and +`.retrieve()`. #### Example -As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: +As with `ModelViewSet`, you'll normally need to provide at least the `queryset` +and `serializer_class` attributes. For example: class AccountViewSet(viewsets.ReadOnlyModelViewSet): """ @@ -225,15 +275,18 @@ As with `ModelViewSet`, you'll normally need to provide at least the `queryset` queryset = Account.objects.all() serializer_class = AccountSerializer -Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`. +Again, as with `ModelViewSet`, you can use any of the standard attributes and +method overrides available to `GenericAPIView`. # Custom ViewSet base classes -You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way. +You may need to provide custom `ViewSet` classes that do not have the full set +of `ModelViewSet` actions, or that customize the behavior in some other way. ## Example -To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions: +To create a base viewset class that provides `create`, `list` and `retrieve` +operations, inherit from `GenericViewSet`, and mixin the required actions: class CreateListRetrieveViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, @@ -247,7 +300,8 @@ To create a base viewset class that provides `create`, `list` and `retrieve` ope """ pass -By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API. +By creating your own base `ViewSet` classes, you can provide common behavior +that can be reused in multiple viewsets across your API. [cite]: http://guides.rubyonrails.org/routing.html [routers]: routers.md diff --git a/docs/index.md b/docs/index.md index 3019467ed..3866bc0f0 100644 --- a/docs/index.md +++ b/docs/index.md @@ -31,7 +31,8 @@ --- -**Note**: This is the documentation for the **version 3** of REST framework. Documentation for [version 2](http://tomchristie.github.io/rest-framework-2-docs/) is also available. +**Note**: This is the documentation for the **version 3** of REST framework. +Documentation for [version 2](http://tomchristie.github.io/rest-framework-2-docs/) is also available. --- @@ -116,14 +117,18 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting. 'rest_framework', ) -If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file. +If you're intending to use the browsable API you'll probably also want to add +REST framework's login and logout views. Add the following to your root +`urls.py` file. urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -Note that the URL path can be whatever you want, but you must include `'rest_framework.urls'` with the `'rest_framework'` namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you. +Note that the URL path can be whatever you want, but you must include +`'rest_framework.urls'` with the `'rest_framework'` namespace. You may leave +out the namespace in Django 1.9+, and REST framework will set it for you. ## Example @@ -131,7 +136,9 @@ Let's take a look at a quick example of using REST framework to build a simple m We'll create a read-write API for accessing information on the users of our project. -Any global settings for a REST framework API are kept in a single configuration dictionary named `REST_FRAMEWORK`. Start off by adding the following to your `settings.py` module: +Any global settings for a REST framework API are kept in a single configuration +dictionary named `REST_FRAMEWORK`. Start off by adding the following to your +`settings.py` module: REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, @@ -172,15 +179,22 @@ Here's our project's root `urls.py` module: url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -You can now open the API in your browser at [http://127.0.0.1:8000/](http://127.0.0.1:8000/), and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system. +You can now open the API in your browser at +[http://127.0.0.1:8000/](http://127.0.0.1:8000/), and view your new 'users' +API. If you use the login control in the top right corner you'll also be able +to add, create and delete users from the system. ## Quickstart -Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework. +Can't wait to get started? The [quickstart guide][quickstart] is the fastest +way to get up and running, and building APIs with REST framework. ## Tutorial -The tutorial will walk you through the building blocks that make up REST framework. It'll take a little while to get through, but it'll give you a comprehensive understanding of how everything fits together, and is highly recommended reading. +The tutorial will walk you through the building blocks that make up REST +framework. It'll take a little while to get through, but it'll give you a +comprehensive understanding of how everything fits together, and is highly +recommended reading. * [1 - Serialization][tut-1] * [2 - Requests & Responses][tut-2] @@ -257,20 +271,32 @@ Framework. ## Support -For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.freenode.net`, search [the IRC archives][botbot], or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag. +For support please see the [REST framework discussion group][group], try the +`#restframework` channel on `irc.freenode.net`, search [the IRC +archives][botbot], or raise a question on [Stack Overflow][stack-overflow], +making sure to include the ['django-rest-framework'][django-rest-framework-tag] +tag. -[Paid support is available][paid-support] from [DabApps][dabapps], and can include work on REST framework core, or support with building your REST framework API. Please [contact DabApps][contact-dabapps] if you'd like to discuss commercial support options. +[Paid support is available][paid-support] from [DabApps][dabapps], and can +include work on REST framework core, or support with building your REST +framework API. Please [contact DabApps][contact-dabapps] if you'd like to +discuss commercial support options. -For updates on REST framework development, you may also want to follow [the author][twitter] on Twitter. +For updates on REST framework development, you may also want to follow [the +author][twitter] on Twitter. ## Security -If you believe you’ve found something in Django REST framework which has security implications, please **do not raise the issue in a public forum**. +If you believe you’ve found something in Django REST framework which has +security implications, please **do not raise the issue in a public forum**. -Send a description of the issue via email to [rest-framework-security@googlegroups.com][security-mail]. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure. +Send a description of the issue via email to +[rest-framework-security@googlegroups.com][security-mail]. The project +maintainers will then work with you to resolve any issues where required, prior +to any public disclosure. ## License diff --git a/docs/topics/2.2-announcement.md b/docs/topics/2.2-announcement.md index e6220f427..b4a3ff10e 100644 --- a/docs/topics/2.2-announcement.md +++ b/docs/topics/2.2-announcement.md @@ -1,48 +1,80 @@ # Django REST framework 2.2 -The 2.2 release represents an important point for REST framework, with the addition of Python 3 support, and the introduction of an official deprecation policy. +The 2.2 release represents an important point for REST framework, with the +addition of Python 3 support, and the introduction of an official deprecation +policy. ## Python 3 support -Thanks to some fantastic work from [Xavier Ordoquy][xordoquy], Django REST framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and it's worth keeping in mind that Django's Python 3 support is currently [considered experimental][django-python-3]. +Thanks to some fantastic work from [Xavier Ordoquy][xordoquy], Django REST +framework 2.2 now supports Python 3. You'll need to be running Django 1.5, and +it's worth keeping in mind that Django's Python 3 support is currently +[considered experimental][django-python-3]. -Django 1.6's Python 3 support is expected to be officially labeled as 'production-ready'. +Django 1.6's Python 3 support is expected to be officially labeled as +'production-ready'. -If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation. +If you want to start ensuring that your own projects are Python 3 ready, we can +highly recommend Django's [Porting to Python 3][porting-python-3] +documentation. -Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with [Django 1.5's Python compatibility][python-compat]. +Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line +with [Django 1.5's Python compatibility][python-compat]. ## Deprecation policy -We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework. +We've now introduced an official deprecation policy, which is in line with +[Django's deprecation policy][django-deprecation-policy]. This policy will +make it easy for you to continue to track the latest, greatest version of REST +framework. The timeline for deprecation works as follows: -* Version 2.2 introduces some API changes as detailed in the release notes. It remains fully backwards compatible with 2.1, but will raise `PendingDeprecationWarning` warnings if you use bits of API that are due to be deprecated. These warnings are silent by default, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make. +* Version 2.2 introduces some API changes as detailed in the release notes. It + remains fully backwards compatible with 2.1, but will raise + `PendingDeprecationWarning` warnings if you use bits of API that are due to + be deprecated. These warnings are silent by default, but can be explicitly + enabled when you're ready to start migrating any required changes. For + example if you start running your tests using `python -Wd manage.py test`, + you'll be warned of any API changes you need to make. -* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is loud by default. +* Version 2.3 will escalate these warnings to `DeprecationWarning`, which is + loud by default. * Version 2.4 will remove the deprecated bits of API entirely. -Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change. +Note that in line with Django's policy, any parts of the framework not +mentioned in the documentation should generally be considered private API, and +may be subject to change. ## Community -As of the 2.2 merge, we've also hit an impressive milestone. The number of committers listed in [the credits][credits], is now at over **one hundred individuals**. Each name on that list represents at least one merged pull request, however large or small. +As of the 2.2 merge, we've also hit an impressive milestone. The number of +committers listed in [the credits][credits], is now at over **one hundred +individuals**. Each name on that list represents at least one merged pull +request, however large or small. -Our [mailing list][mailing-list] and #restframework IRC channel are also very active, and we've got a really impressive rate of development both on REST framework itself, and on third party packages such as the great [django-rest-framework-docs][django-rest-framework-docs] package from [Marc Gibbons][marcgibbons]. +Our [mailing list][mailing-list] and #restframework IRC channel are also very +active, and we've got a really impressive rate of development both on REST +framework itself, and on third party packages such as the great +[django-rest-framework-docs][django-rest-framework-docs] package from [Marc +Gibbons][marcgibbons]. --- ## API changes -The 2.2 release makes a few changes to the API, in order to make it more consistent, simple, and easier to use. +The 2.2 release makes a few changes to the API, in order to make it more +consistent, simple, and easier to use. ### Cleaner to-many related fields -The `ManyRelatedField()` style is being deprecated in favor of a new `RelatedField(many=True)` syntax. +The `ManyRelatedField()` style is being deprecated in favor of a new +`RelatedField(many=True)` syntax. -For example, if a user is associated with multiple questions, which we want to represent using a primary key relationship, we might use something like the following: +For example, if a user is associated with multiple questions, which we want to +represent using a primary key relationship, we might use something like the +following: class UserSerializer(serializers.HyperlinkedModelSerializer): questions = serializers.PrimaryKeyRelatedField(many=True) @@ -50,9 +82,14 @@ For example, if a user is associated with multiple questions, which we want to r class Meta: fields = ('username', 'questions') -The new syntax is cleaner and more obvious, and the change will also make the documentation cleaner, simplify the internal API, and make writing custom relational fields easier. +The new syntax is cleaner and more obvious, and the change will also make the +documentation cleaner, simplify the internal API, and make writing custom +relational fields easier. -The change also applies to serializers. If you have a nested serializer, you should start using `many=True` for to-many relationships. For example, a serializer representation of an Album that can contain many Tracks might look something like this: +The change also applies to serializers. If you have a nested serializer, you +should start using `many=True` for to-many relationships. For example, a +serializer representation of an Album that can contain many Tracks might look +something like this: class TrackSerializer(serializer.ModelSerializer): class Meta: @@ -66,49 +103,80 @@ The change also applies to serializers. If you have a nested serializer, you sh model = Album fields = ('album_name', 'artist', 'tracks') -Additionally, the change also applies when serializing or deserializing data. For example to serialize a queryset of models you should now use the `many=True` flag. +Additionally, the change also applies when serializing or deserializing data. +For example to serialize a queryset of models you should now use the +`many=True` flag. serializer = SnippetSerializer(Snippet.objects.all(), many=True) serializer.data -This more explicit behavior on serializing and deserializing data [makes integration with non-ORM backends such as MongoDB easier][564], as instances to be serialized can include the `__iter__` method, without incorrectly triggering list-based serialization, or requiring workarounds. +This more explicit behavior on serializing and deserializing data [makes +integration with non-ORM backends such as MongoDB easier][564], as instances to +be serialized can include the `__iter__` method, without incorrectly triggering +list-based serialization, or requiring workarounds. -The implicit to-many behavior on serializers, and the `ManyRelatedField` style classes will continue to function, but will raise a `PendingDeprecationWarning`, which can be made visible using the `-Wd` flag. +The implicit to-many behavior on serializers, and the `ManyRelatedField` style +classes will continue to function, but will raise a +`PendingDeprecationWarning`, which can be made visible using the `-Wd` flag. -**Note**: If you need to forcibly turn off the implicit "`many=True` for `__iter__` objects" behavior, you can now do so by specifying `many=False`. This will become the default (instead of the current default of `None`) once the deprecation of the implicit behavior is finalised in version 2.4. +**Note**: If you need to forcibly turn off the implicit "`many=True` for +`__iter__` objects" behavior, you can now do so by specifying `many=False`. +This will become the default (instead of the current default of `None`) once +the deprecation of the implicit behavior is finalised in version 2.4. ### Cleaner optional relationships -Serializer relationships for nullable Foreign Keys will change from using the current `null=True` flag, to instead using `required=False`. +Serializer relationships for nullable Foreign Keys will change from using the +current `null=True` flag, to instead using `required=False`. -For example, is a user account has an optional foreign key to a company, that you want to express using a hyperlink, you might use the following field in a `Serializer` class: +For example, is a user account has an optional foreign key to a company, that +you want to express using a hyperlink, you might use the following field in a +`Serializer` class: current_company = serializers.HyperlinkedRelatedField(required=False) -This is in line both with the rest of the serializer fields API, and with Django's `Form` and `ModelForm` API. +This is in line both with the rest of the serializer fields API, and with +Django's `Form` and `ModelForm` API. -Using `required` throughout the serializers API means you won't need to consider if a particular field should take `blank` or `null` arguments instead of `required`, and also means there will be more consistent behavior for how fields are treated when they are not present in the incoming data. +Using `required` throughout the serializers API means you won't need to +consider if a particular field should take `blank` or `null` arguments instead +of `required`, and also means there will be more consistent behavior for how +fields are treated when they are not present in the incoming data. -The `null=True` argument will continue to function, and will imply `required=False`, but will raise a `PendingDeprecationWarning`. +The `null=True` argument will continue to function, and will imply +`required=False`, but will raise a `PendingDeprecationWarning`. ### Cleaner CharField syntax -The `CharField` API previously took an optional `blank=True` argument, which was intended to differentiate between null CharField input, and blank CharField input. +The `CharField` API previously took an optional `blank=True` argument, which +was intended to differentiate between null CharField input, and blank CharField +input. -In keeping with Django's CharField API, REST framework's `CharField` will only ever return the empty string, for missing or `None` inputs. The `blank` flag will no longer be in use, and you should instead just use the `required=` flag. For example: +In keeping with Django's CharField API, REST framework's `CharField` will only +ever return the empty string, for missing or `None` inputs. The `blank` flag +will no longer be in use, and you should instead just use the `required=` +flag. For example: extra_details = CharField(required=False) -The `blank` keyword argument will continue to function, but will raise a `PendingDeprecationWarning`. +The `blank` keyword argument will continue to function, but will raise a +`PendingDeprecationWarning`. ### Simpler object-level permissions -Custom permissions classes previously used the signature `.has_permission(self, request, view, obj=None)`. This method would be called twice, firstly for the global permissions check, with the `obj` parameter set to `None`, and again for the object-level permissions check when appropriate, with the `obj` parameter set to the relevant model instance. +Custom permissions classes previously used the signature `.has_permission(self, +request, view, obj=None)`. This method would be called twice, firstly for the +global permissions check, with the `obj` parameter set to `None`, and again for +the object-level permissions check when appropriate, with the `obj` parameter +set to the relevant model instance. -The global permissions check and object-level permissions check are now separated into two separate methods, which gives a cleaner, more obvious API. +The global permissions check and object-level permissions check are now +separated into two separate methods, which gives a cleaner, more obvious API. -* Global permission checks now use the `.has_permission(self, request, view)` signature. -* Object-level permission checks use a new method `.has_object_permission(self, request, view, obj)`. +* Global permission checks now use the `.has_permission(self, request, view)` + signature. +* Object-level permission checks use a new method `.has_object_permission(self, + request, view, obj)`. For example, the following custom permission class: @@ -136,15 +204,27 @@ Now becomes: def has_object_permission(self, request, view, obj): return obj.owner == request.user -If you're overriding the `BasePermission` class, the old-style signature will continue to function, and will correctly handle both global and object-level permissions checks, but its use will raise a `PendingDeprecationWarning`. +If you're overriding the `BasePermission` class, the old-style signature will +continue to function, and will correctly handle both global and object-level +permissions checks, but its use will raise a `PendingDeprecationWarning`. -Note also that the usage of the internal APIs for permission checking on the `View` class has been cleaned up slightly, and is now documented and subject to the deprecation policy in all future versions. +Note also that the usage of the internal APIs for permission checking on the +`View` class has been cleaned up slightly, and is now documented and subject to +the deprecation policy in all future versions. ### More explicit hyperlink relations behavior -When using a serializer with a `HyperlinkedRelatedField` or `HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs if the serializer context included a `'request'` key, and fall back to using relative URLs otherwise. This could lead to non-obvious behavior, as it might not be clear why some serializers generated absolute URLs, and others do not. +When using a serializer with a `HyperlinkedRelatedField` or +`HyperlinkedIdentityField`, the hyperlinks would previously use absolute URLs +if the serializer context included a `'request'` key, and fall back to using + relative URLs otherwise. This could lead to non-obvious behavior, as + it might not be clear why some serializers generated absolute URLs, and + others do not. -From version 2.2 onwards, serializers with hyperlinked relationships *always* require a `'request'` key to be supplied in the context dictionary. The implicit behavior will continue to function, but its use will raise a `PendingDeprecationWarning`. +From version 2.2 onwards, serializers with hyperlinked relationships *always* +require a `'request'` key to be supplied in the context dictionary. The +implicit behavior will continue to function, but its use will raise a +`PendingDeprecationWarning`. [xordoquy]: https://github.com/xordoquy [django-python-3]: https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3 diff --git a/docs/topics/2.3-announcement.md b/docs/topics/2.3-announcement.md index d9bab39dc..6edcd167b 100644 --- a/docs/topics/2.3-announcement.md +++ b/docs/topics/2.3-announcement.md @@ -6,11 +6,14 @@ REST framework 2.3 makes it even quicker and easier to build your Web APIs. The 2.3 release introduces the [ViewSet][viewset] and [Router][router] classes. -A viewset is simply a type of class-based view that allows you to group multiple views into a single common class. +A viewset is simply a type of class-based view that allows you to group +multiple views into a single common class. -Routers allow you to automatically determine the URLconf for your viewset classes. +Routers allow you to automatically determine the URLconf for your viewset +classes. -As an example of just how simple REST framework APIs can now be, here's an API written in a single `urls.py` module: +As an example of just how simple REST framework APIs can now be, here's an API +written in a single `urls.py` module: """ A REST framework API for viewing and editing users and groups. @@ -41,21 +44,33 @@ As an example of just how simple REST framework APIs can now be, here's an API w url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] -The best place to get started with ViewSets and Routers is to take a look at the [newest section in the tutorial][part-6], which demonstrates their usage. +The best place to get started with ViewSets and Routers is to take a look at +the [newest section in the tutorial][part-6], which demonstrates their usage. ## Simpler views -This release rationalises the API and implementation of the generic views, dropping the dependency on Django's `SingleObjectMixin` and `MultipleObjectMixin` classes, removing a number of unneeded attributes, and generally making the implementation more obvious and easy to work with. +This release rationalises the API and implementation of the generic views, +dropping the dependency on Django's `SingleObjectMixin` and +`MultipleObjectMixin` classes, removing a number of unneeded attributes, and +generally making the implementation more obvious and easy to work with. -This improvement is reflected in improved documentation for the `GenericAPIView` base class, and should make it easier to determine how to override methods on the base class if you need to write customized subclasses. +This improvement is reflected in improved documentation for the +`GenericAPIView` base class, and should make it easier to determine how to +override methods on the base class if you need to write customized subclasses. ## Easier Serializers -REST framework lets you be totally explicit regarding how you want to represent relationships, allowing you to choose between styles such as hyperlinking or primary key relationships. +REST framework lets you be totally explicit regarding how you want to represent +relationships, allowing you to choose between styles such as hyperlinking or +primary key relationships. -The ability to specify exactly how you want to represent relationships is powerful, but it also introduces complexity. In order to keep things more simple, REST framework now allows you to include reverse relationships simply by including the field name in the `fields` metadata of the serializer class. +The ability to specify exactly how you want to represent relationships is +powerful, but it also introduces complexity. In order to keep things more +simple, REST framework now allows you to include reverse relationships simply +by including the field name in the `fields` metadata of the serializer class. -For example, in REST framework 2.2, reverse relationships needed to be included explicitly on a serializer class. +For example, in REST framework 2.2, reverse relationships needed to be included +explicitly on a serializer class. class BlogSerializer(serializers.ModelSerializer): comments = serializers.PrimaryKeyRelatedField(many=True) @@ -64,7 +79,8 @@ For example, in REST framework 2.2, reverse relationships needed to be included model = Blog fields = ('id', 'title', 'created', 'comments') -As of 2.3, you can simply include the field name, and the appropriate serializer field will automatically be used for the relationship. +As of 2.3, you can simply include the field name, and the appropriate +serializer field will automatically be used for the relationship. class BlogSerializer(serializers.ModelSerializer): """ @@ -74,7 +90,8 @@ As of 2.3, you can simply include the field name, and the appropriate serializer model = Blog fields = ('id', 'title', 'created', 'comments') -Similarly, you can now easily include the primary key in hyperlinked relationships, simply by adding the field name to the metadata. +Similarly, you can now easily include the primary key in hyperlinked +relationships, simply by adding the field name to the metadata. class BlogSerializer(serializers.HyperlinkedModelSerializer): """ @@ -88,11 +105,16 @@ Similarly, you can now easily include the primary key in hyperlinked relationshi ## More flexible filtering -The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a `DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend classes, instead of a single filter backend class. +The `FILTER_BACKEND` setting has moved to pending deprecation, in favor of a +`DEFAULT_FILTER_BACKENDS` setting that takes a *list* of filter backend +classes, instead of a single filter backend class. -The generic view `filter_backend` attribute has also been moved to pending deprecation in favor of a `filter_backends` setting. +The generic view `filter_backend` attribute has also been moved to pending +deprecation in favor of a `filter_backends` setting. -Being able to specify multiple filters will allow for more flexible, powerful behavior. New filter classes to handle searching and ordering of results are planned to be released shortly. +Being able to specify multiple filters will allow for more flexible, powerful +behavior. New filter classes to handle searching and ordering of results are +planned to be released shortly. --- @@ -100,44 +122,69 @@ Being able to specify multiple filters will allow for more flexible, powerful be ## Simplified generic view classes -The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` base classes has now been moved into the base class `GenericAPIView`. The implementation of this base class is simple enough that providing subclasses for the base classes of detail and list views is somewhat unnecessary. +The functionality provided by `SingleObjectAPIView` and `MultipleObjectAPIView` +base classes has now been moved into the base class `GenericAPIView`. The +implementation of this base class is simple enough that providing subclasses +for the base classes of detail and list views is somewhat unnecessary. -Additionally the base generic view no longer inherits from Django's `SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the implementation, and meaning you don't need to cross-reference across to Django's codebase. +Additionally the base generic view no longer inherits from Django's +`SingleObjectMixin` or `MultipleObjectMixin` classes, simplifying the +implementation, and meaning you don't need to cross-reference across to +Django's codebase. -Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes continues to be supported, but will raise a `PendingDeprecationWarning`. You should instead simply use `GenericAPIView` as the base for any generic view subclasses. +Using the `SingleObjectAPIView` and `MultipleObjectAPIView` base classes +continues to be supported, but will raise a `PendingDeprecationWarning`. You +should instead simply use `GenericAPIView` as the base for any generic view +subclasses. ### Removed attributes -The following attributes and methods, were previously present as part of Django's generic view implementations, but were unneeded and unused and have now been entirely removed. +The following attributes and methods, were previously present as part of +Django's generic view implementations, but were unneeded and unused and have +now been entirely removed. * context_object_name * get_context_data() * get_context_object_name() -The following attributes and methods, which were previously present as part of Django's generic view implementations have also been entirely removed. +The following attributes and methods, which were previously present as part of +Django's generic view implementations have also been entirely removed. * paginator_class * get_paginator() * get_allow_empty() * get_slug_field() -There may be cases when removing these bits of API might mean you need to write a little more code if your view has highly customized behavior, but generally we believe that providing a coarser-grained API will make the views easier to work with, and is the right trade-off to make for the vast majority of cases. +There may be cases when removing these bits of API might mean you need to write +a little more code if your view has highly customized behavior, but generally +we believe that providing a coarser-grained API will make the views easier to +work with, and is the right trade-off to make for the vast majority of cases. -Note that the listed attributes and methods have never been a documented part of the REST framework API, and as such are not covered by the deprecation policy. +Note that the listed attributes and methods have never been a documented part +of the REST framework API, and as such are not covered by the deprecation +policy. ### Simplified methods -The `get_object` and `get_paginate_by` methods no longer take an optional queryset argument. This makes overridden these methods more obvious, and a little more simple. +The `get_object` and `get_paginate_by` methods no longer take an optional +queryset argument. This makes overridden these methods more obvious, and a +little more simple. -Using an optional queryset with these methods continues to be supported, but will raise a `PendingDeprecationWarning`. +Using an optional queryset with these methods continues to be supported, but +will raise a `PendingDeprecationWarning`. -The `paginate_queryset` method no longer takes a `page_size` argument, or returns a four-tuple of pagination information. Instead it simply takes a queryset argument, and either returns a `page` object with an appropriate page size, or returns `None`, if pagination is not configured for the view. +The `paginate_queryset` method no longer takes a `page_size` argument, or +returns a four-tuple of pagination information. Instead it simply takes a +queryset argument, and either returns a `page` object with an appropriate page +size, or returns `None`, if pagination is not configured for the view. -Using the `page_size` argument is still supported and will trigger the old-style return type, but will raise a `PendingDeprecationWarning`. +Using the `page_size` argument is still supported and will trigger the +old-style return type, but will raise a `PendingDeprecationWarning`. ### Deprecated attributes -The following attributes are used to control queryset lookup, and have all been moved into a pending deprecation state. +The following attributes are used to control queryset lookup, and have all been +moved into a pending deprecation state. * pk_url_kwarg = 'pk' * slug_url_kwarg = 'slug' @@ -147,7 +194,11 @@ Their usage is replaced with a single attribute: * lookup_field = 'pk' -This attribute is used both as the regex keyword argument in the URL conf, and as the model field to filter against when looking up a model instance. To use non-pk based lookup, simply set the `lookup_field` argument to an alternative field, and ensure that the keyword argument in the url conf matches the field name. +This attribute is used both as the regex keyword argument in the URL conf, and +as the model field to filter against when looking up a model instance. To use +non-pk based lookup, simply set the `lookup_field` argument to an alternative +field, and ensure that the keyword argument in the url conf matches the field +name. For example, a view with 'username' based lookup might look like this: @@ -160,9 +211,12 @@ And would have the following entry in the urlconf: url(r'^users/(?P\w+)/$', UserDetail.as_view()), -Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`. +Usage of the old-style attributes continues to be supported, but will raise a +`PendingDeprecationWarning`. -The `allow_empty` attribute is also deprecated. To use `allow_empty=False` style behavior you should explicitly override `get_queryset` and raise an `Http404` on empty querysets. +The `allow_empty` attribute is also deprecated. To use `allow_empty=False` +style behavior you should explicitly override `get_queryset` and raise an +`Http404` on empty querysets. For example: @@ -173,45 +227,68 @@ For example: raise Http404 return queryset -In our opinion removing lesser-used attributes like `allow_empty` helps us move towards simpler generic view implementations, making them more obvious to use and override, and re-enforcing the preferred style of developers writing their own base classes and mixins for custom behavior rather than relying on the configurability of the generic views. +In our opinion removing lesser-used attributes like `allow_empty` helps us move +towards simpler generic view implementations, making them more obvious to use +and override, and re-enforcing the preferred style of developers writing their +own base classes and mixins for custom behavior rather than relying on the +configurability of the generic views. ## Simpler URL lookups -The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` arguments. +The `HyperlinkedRelatedField` class now takes a single optional `lookup_field` +argument, that replaces the `pk_url_kwarg`, `slug_url_kwarg`, and `slug_field` +arguments. -For example, you might have a field that references it's relationship by a hyperlink based on a slug field: +For example, you might have a field that references it's relationship by a +hyperlink based on a slug field: account = HyperlinkedRelatedField(read_only=True, lookup_field='slug', view_name='account-detail') -Usage of the old-style attributes continues to be supported, but will raise a `PendingDeprecationWarning`. +Usage of the old-style attributes continues to be supported, but will raise a +`PendingDeprecationWarning`. ## FileUploadParser -2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in addition to the existing multipart upload support. +2.3 adds a `FileUploadParser` parser class, that supports raw file uploads, in +addition to the existing multipart upload support. ## DecimalField -2.3 introduces a `DecimalField` serializer field, which returns `Decimal` instances. +2.3 introduces a `DecimalField` serializer field, which returns `Decimal` +instances. -For most cases APIs using model fields will behave as previously, however if you are using a custom renderer, not provided by REST framework, then you may now need to add support for rendering `Decimal` instances to your renderer implementation. +For most cases APIs using model fields will behave as previously, however if +you are using a custom renderer, not provided by REST framework, then you may +now need to add support for rendering `Decimal` instances to your renderer +implementation. ## ModelSerializers and reverse relationships -The support for adding reverse relationships to the `fields` option on a `ModelSerializer` class means that the `get_related_field` and `get_nested_field` method signatures have now changed. +The support for adding reverse relationships to the `fields` option on a +`ModelSerializer` class means that the `get_related_field` and +`get_nested_field` method signatures have now changed. -In the unlikely event that you're providing a custom serializer class, and implementing these methods you should note the new call signature for both methods is now `(self, model_field, related_model, to_many)`. For reverse relationships `model_field` will be `None`. +In the unlikely event that you're providing a custom serializer class, and +implementing these methods you should note the new call signature for both +methods is now `(self, model_field, related_model, to_many)`. For reverse +relationships `model_field` will be `None`. -The old-style signature will continue to function but will raise a `PendingDeprecationWarning`. +The old-style signature will continue to function but will raise a +`PendingDeprecationWarning`. ## View names and descriptions -The mechanics of how the names and descriptions used in the browsable API are generated has been modified and cleaned up somewhat. +The mechanics of how the names and descriptions used in the browsable API are +generated has been modified and cleaned up somewhat. -If you've been customizing this behavior, for example perhaps to use `rst` markup for the browsable API, then you'll need to take a look at the implementation to see what updates you need to make. +If you've been customizing this behavior, for example perhaps to use `rst` +markup for the browsable API, then you'll need to take a look at the +implementation to see what updates you need to make. -Note that the relevant methods have always been private APIs, and the docstrings called them out as intended to be deprecated. +Note that the relevant methods have always been private APIs, and the +docstrings called them out as intended to be deprecated. --- @@ -219,7 +296,9 @@ Note that the relevant methods have always been private APIs, and the docstrings ## More explicit style -The usage of `model` attribute in generic Views is still supported, but it's usage is generally being discouraged throughout the documentation, in favour of the setting the more explicit `queryset` and `serializer_class` attributes. +The usage of `model` attribute in generic Views is still supported, but it's +usage is generally being discouraged throughout the documentation, in favour of +the setting the more explicit `queryset` and `serializer_class` attributes. For example, the following is now the recommended style for using generic views: @@ -227,9 +306,11 @@ For example, the following is now the recommended style for using generic views: queryset = MyModel.objects.all() serializer_class = MyModelSerializer -Using an explicit `queryset` and `serializer_class` attributes makes the functioning of the view more clear than using the shortcut `model` attribute. +Using an explicit `queryset` and `serializer_class` attributes makes the +functioning of the view more clear than using the shortcut `model` attribute. -It also makes the usage of the `get_queryset()` or `get_serializer_class()` methods more obvious. +It also makes the usage of the `get_queryset()` or `get_serializer_class()` +methods more obvious. class AccountListView(generics.RetrieveAPIView): serializer_class = MyModelSerializer @@ -246,18 +327,23 @@ It also makes the usage of the `get_queryset()` or `get_serializer_class()` meth ## Django 1.3 support -The 2.3.x release series will be the last series to provide compatibility with Django 1.3. +The 2.3.x release series will be the last series to provide compatibility with +Django 1.3. ## Version 2.2 API changes -All API changes in 2.2 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default. +All API changes in 2.2 that previously raised `PendingDeprecationWarning` will +now raise a `DeprecationWarning`, which is loud by default. ## What comes next? -* Support for read-write nested serializers is almost complete, and due to be released in the next few weeks. -* Extra filter backends for searching and ordering of results are planned to be added shortly. +* Support for read-write nested serializers is almost complete, and due to be + released in the next few weeks. +* Extra filter backends for searching and ordering of results are planned to be + added shortly. -The next few months should see a renewed focus on addressing outstanding tickets. The 2.4 release is currently planned for around August-September. +The next few months should see a renewed focus on addressing outstanding +tickets. The 2.4 release is currently planned for around August-September. [viewset]: ../api-guide/viewsets.md [router]: ../api-guide/routers.md diff --git a/docs/topics/2.4-announcement.md b/docs/topics/2.4-announcement.md index 3009daa49..69df4903e 100644 --- a/docs/topics/2.4-announcement.md +++ b/docs/topics/2.4-announcement.md @@ -1,35 +1,49 @@ # Django REST framework 2.4 -The 2.4 release is largely an intermediate step, tying up some outstanding issues prior to the 3.x series. +The 2.4 release is largely an intermediate step, tying up some outstanding +issues prior to the 3.x series. ## Version requirements -Support for Django 1.3 has been dropped. -The lowest supported version of Django is now 1.4.2. +Support for Django 1.3 has been dropped. The lowest supported version of +Django is now 1.4.2. -The current plan is for REST framework to remain in lockstep with [Django's long-term support policy][lts-releases]. +The current plan is for REST framework to remain in lockstep with [Django's +long-term support policy][lts-releases]. ## Django 1.7 support -The optional authtoken application now includes support for *both* Django 1.7 schema migrations, *and* for old-style `south` migrations. +The optional authtoken application now includes support for *both* Django 1.7 +schema migrations, *and* for old-style `south` migrations. -**If you are using authtoken, and you want to continue using `south`, you must upgrade your `south` package to version 1.0.** +**If you are using authtoken, and you want to continue using `south`, you must +upgrade your `south` package to version 1.0.** ## Deprecation of `.model` view attribute -The `.model` attribute on view classes is an optional shortcut for either or both of `.serializer_class` and `.queryset`. Its usage results in more implicit, less obvious behavior. +The `.model` attribute on view classes is an optional shortcut for either or +both of `.serializer_class` and `.queryset`. Its usage results in more +implicit, less obvious behavior. -The documentation has previously stated that usage of the more explicit style is prefered, and we're now taking that one step further and deprecating the usage of the `.model` shortcut. +The documentation has previously stated that usage of the more explicit style +is prefered, and we're now taking that one step further and deprecating the +usage of the `.model` shortcut. -Doing so will mean that there are cases of API code where you'll now need to include a serializer class where you previously were just using the `.model` shortcut. However we firmly believe that it is the right trade-off to make. +Doing so will mean that there are cases of API code where you'll now need to +include a serializer class where you previously were just using the `.model` +shortcut. However we firmly believe that it is the right trade-off to make. -Removing the shortcut takes away an unnecessary layer of abstraction, and makes your codebase more explicit without any significant extra complexity. It also results in better consistency, as there's now only one way to set the serializer class and queryset attributes for the view, instead of two. +Removing the shortcut takes away an unnecessary layer of abstraction, and makes +your codebase more explicit without any significant extra complexity. It also +results in better consistency, as there's now only one way to set the +serializer class and queryset attributes for the view, instead of two. The `DEFAULT_MODEL_SERIALIZER_CLASS` API setting is now also deprecated. ## Updated test runner -We now have a new test runner for developing against the project,, that uses the excellent [py.test](http://pytest.org) library. +We now have a new test runner for developing against the project,, that uses +the excellent [py.test](http://pytest.org) library. To use it make sure you have first installed the test requirements. @@ -39,7 +53,8 @@ Then run the `runtests.py` script. ./runtests.py -The new test runner also includes [flake8](https://flake8.readthedocs.io) code linting, which should help keep our coding style consistent. +The new test runner also includes [flake8](https://flake8.readthedocs.io) code +linting, which should help keep our coding style consistent. #### Test runner flags @@ -71,15 +86,24 @@ Shorter form to run the tests for a given test method. ./runtests test_this_method -Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. +Note: The test case and test method matching is fuzzy and will sometimes run +other tests that contain a partial string match to the given command line +input. ## Improved viewset routing -The `@action` and `@link` decorators were inflexible in that they only allowed additional routes to be added against instance style URLs, not against list style URLs. +The `@action` and `@link` decorators were inflexible in that they only allowed +additional routes to be added against instance style URLs, not against list +style URLs. -The `@action` and `@link` decorators have now been moved to pending deprecation, and the `@list_route` and `@detail_route` decorators have been introduced. +The `@action` and `@link` decorators have now been moved to pending +deprecation, and the `@list_route` and `@detail_route` decorators have been +introduced. -Here's an example of using the new decorators. Firstly we have a detail-type route named "set_password" that acts on a single instance, and takes a `pk` argument in the URL. Secondly we have a list-type route named "recent_users" that acts on a queryset, and does not take any arguments in the URL. +Here's an example of using the new decorators. Firstly we have a detail-type +route named "set_password" that acts on a single instance, and takes a `pk` +argument in the URL. Secondly we have a list-type route named "recent_users" +that acts on a queryset, and does not take any arguments in the URL. class UserViewSet(viewsets.ModelViewSet): """ @@ -111,40 +135,58 @@ For more details, see the [viewsets documentation](../api-guide/viewsets.md). ## Throttle behavior -There's one bugfix in 2.4 that's worth calling out, as it will *invalidate existing throttle caches* when you upgrade. +There's one bugfix in 2.4 that's worth calling out, as it will *invalidate +existing throttle caches* when you upgrade. -We've now fixed a typo on the `cache_format` attribute. Previously this was named `"throtte_%(scope)s_%(ident)s"`, it is now `"throttle_%(scope)s_%(ident)s"`. +We've now fixed a typo on the `cache_format` attribute. Previously this was +named `"throtte_%(scope)s_%(ident)s"`, it is now +`"throttle_%(scope)s_%(ident)s"`. If you're concerned about the invalidation you have two options. * Manually pre-populate your cache with the fixed version. -* Set the `cache_format` attribute on your throttle class in order to retain the previous incorrect spelling. +* Set the `cache_format` attribute on your throttle class in order to retain + the previous incorrect spelling. ## Other features -There are also a number of other features and bugfixes as [listed in the release notes][2-4-release-notes]. In particular these include: +There are also a number of other features and bugfixes as [listed in the +release notes][2-4-release-notes]. In particular these include: -[Customizable view name and description functions][view-name-and-description-settings] for use with the browsable API, by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings. +[Customizable view name and description +functions][view-name-and-description-settings] for use with the browsable API, +by using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings. -Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting. +Smarter [client IP identification for throttling][client-ip-identification], +with the addition of the `NUM_PROXIES` setting. -Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](http://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Throttle-Wait-Seconds` header which will be fully deprecated in 3.0. +Added the standardized `Retry-After` header to throttled responses, as per [RFC +6585](http://tools.ietf.org/html/rfc6585). This should now be used in +preference to the custom `X-Throttle-Wait-Seconds` header which will be fully +deprecated in 3.0. ## Deprecations -All API changes in 2.3 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default. +All API changes in 2.3 that previously raised `PendingDeprecationWarning` will +now raise a `DeprecationWarning`, which is loud by default. -All API changes in 2.3 that previously raised `DeprecationWarning` have now been removed entirely. +All API changes in 2.3 that previously raised `DeprecationWarning` have now +been removed entirely. -Furter details on these deprecations is available in the [2.3 announcement][2-3-announcement]. +Furter details on these deprecations is available in the [2.3 +announcement][2-3-announcement]. ## Labels and milestones -Although not strictly part of the 2.4 release it's also worth noting here that we've been working hard towards improving our triage process. +Although not strictly part of the 2.4 release it's also worth noting here that +we've been working hard towards improving our triage process. -The [labels that we use in GitHub][github-labels] have been cleaned up, and all existing tickets triaged. Any given ticket should have one and only one label, indicating its current state. +The [labels that we use in GitHub][github-labels] have been cleaned up, and all +existing tickets triaged. Any given ticket should have one and only one label, +indicating its current state. -We've also [started using milestones][github-milestones] in order to track tickets against particular releases. +We've also [started using milestones][github-milestones] in order to track +tickets against particular releases. --- @@ -154,13 +196,16 @@ We've also [started using milestones][github-milestones] in order to track ticke --- -We hope both of these changes will help make the management process more clear and obvious and help keep tickets well-organised and relevant. +We hope both of these changes will help make the management process more clear +and obvious and help keep tickets well-organised and relevant. ## Next steps -The next planned release will be 3.0, featuring an improved and simplified serializer implementation. +The next planned release will be 3.0, featuring an improved and simplified +serializer implementation. -Once again, many thanks to all the generous [backers and sponsors][kickstarter-sponsors] who've helped make this possible! +Once again, many thanks to all the generous [backers and +sponsors][kickstarter-sponsors] who've helped make this possible! [lts-releases]: https://docs.djangoproject.com/en/dev/internals/release-process/#long-term-support-lts-releases [2-4-release-notes]: release-notes#240 diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md index e6cbf7238..a493e8a64 100644 --- a/docs/topics/3.0-announcement.md +++ b/docs/topics/3.0-announcement.md @@ -1,14 +1,22 @@ # Django REST framework 3.0 -The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views. +The 3.0 release of Django REST framework is the result of almost four years of +iteration and refinement. It comprehensively addresses some of the previous +remaining design issues in serializers, fields and the generic views. -**This release is incremental in nature. There *are* some breaking API changes, and upgrading *will* require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.** +**This release is incremental in nature. There *are* some breaking API changes, +and upgrading *will* require you to read the release notes carefully, but the +migration path should otherwise be relatively straightforward.** -The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier. +The difference in quality of the REST framework API and implementation should +make writing, maintaining and debugging your application far easier. -3.0 is the first of three releases that have been funded by our recent [Kickstarter campaign][kickstarter]. +3.0 is the first of three releases that have been funded by our recent +[Kickstarter campaign][kickstarter]. -As ever, a huge thank you to our many [wonderful sponsors][sponsors]. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring. +As ever, a huge thank you to our many [wonderful sponsors][sponsors]. If you're +looking for a Django gig, and want to work with smart community-minded folks, +you should probably check out that list and see who's hiring. --- @@ -16,15 +24,23 @@ As ever, a huge thank you to our many [wonderful sponsors][sponsors]. If you're Notable features of this new release include: -* Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. -* Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit `ModelSerializer` class and the explicit `Serializer` class. -* A new `BaseSerializer` class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. -* A cleaner fields API including new classes such as `ListField` and `MultipleChoiceField`. +* Printable representations on serializers that allow you to inspect exactly + what fields are present on the instance. +* Simple model serializers that are vastly easier to understand and debug, and + that make it easy to switch between the implicit `ModelSerializer` class and + the explicit `Serializer` class. +* A new `BaseSerializer` class, making it easier to write serializers for + alternative storage backends, or to completely customize your serialization + and validation logic. +* A cleaner fields API including new classes such as `ListField` and + `MultipleChoiceField`. * [Super simple default implementations][mixins.py] for the generic views. * Support for overriding how validation errors are handled by your API. -* A metadata API that allows you to customize how `OPTIONS` requests are handled by your API. +* A metadata API that allows you to customize how `OPTIONS` requests are + handled by your API. * A more compact JSON output with unicode style encoding turned on by default. -* Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release. +* Templated based HTML form rendering for serializers. This will be finalized + as public API in the upcoming 3.1 release. Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release. @@ -32,7 +48,9 @@ Significant new functionality continues to be planned for the 3.1 and 3.2 releas #### REST framework: Under the hood. -This talk from the [Django: Under the Hood](http://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0. +This talk from the [Django: Under the Hood](http://www.djangounderthehood.com/) +event in Amsterdam, Nov 2014, gives some good background context on the design +decisions behind 3.0. @@ -44,11 +62,15 @@ This talk from the [Django: Under the Hood](http://www.djangounderthehood.com/) #### The `.data` and `.query_params` properties. -The usage of `request.DATA` and `request.FILES` is now pending deprecation in favor of a single `request.data` attribute that contains *all* the parsed data. +The usage of `request.DATA` and `request.FILES` is now pending deprecation in +favor of a single `request.data` attribute that contains *all* the parsed data. -Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports. +Having separate attributes is reasonable for web applications that only ever +parse url-encoded or multipart requests, but makes less sense for the +general-purpose request parsing that REST framework supports. -You may now pass all the request data to a serializer class in a single argument: +You may now pass all the request data to a serializer class in a single +argument: # Do this... ExampleSerializer(data=request.data) @@ -59,7 +81,8 @@ Instead of passing the files argument separately: ExampleSerializer(data=request.DATA, files=request.FILES) -The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`. +The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the +lowercased `request.query_params`. --- @@ -69,14 +92,25 @@ The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the l Previously the serializers used a two-step object creation, as follows: -1. Validating the data would create an object instance. This instance would be available as `serializer.object`. -2. Calling `serializer.save()` would then save the object instance to the database. +1. Validating the data would create an object instance. This instance would be + available as `serializer.object`. +2. Calling `serializer.save()` would then save the object instance to the + database. -This style is in-line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: +This style is in-line with how the `ModelForm` class works in Django, but is +problematic for a number of reasons: -* Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. -* Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. -* The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save? +* Some data, such as many-to-many relationships, cannot be added to the object + instance until after it has been saved. This type of data needed to be hidden + in some undocumented state on the object instance, or kept as state on the + serializer instance so that it could be used when `.save()` is called. +* Instantiating model instances directly means that you cannot use model + manager classes for instance creation, e.g. + `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at + which to enforce business logic and application-level data constraints. +* The two step process makes it unclear where to put deserialization logic. For + example, should extra attributes such as the current user get added to the + instance during object creation or during object save? We now use single-step object creation, like so: @@ -87,13 +121,19 @@ The resulting API changes are further detailed below. #### The `.create()` and `.update()` methods. -The `.restore_object()` method is now removed, and we instead have two separate methods, `.create()` and `.update()`. These methods work slightly different to the previous `.restore_object()`. +The `.restore_object()` method is now removed, and we instead have two separate +methods, `.create()` and `.update()`. These methods work slightly different to +the previous `.restore_object()`. -When using the `.create()` and `.update()` methods you should both create *and save* the object instance. This is in contrast to the previous `.restore_object()` behavior that would instantiate the object but not save it. +When using the `.create()` and `.update()` methods you should both create *and +save* the object instance. This is in contrast to the previous +`.restore_object()` behavior that would instantiate the object but not save it. -These methods also replace the optional `.save_object()` method, which no longer exists. +These methods also replace the optional `.save_object()` method, which no +longer exists. -The following example from the tutorial previously used `restore_object()` to handle both creating and updating object instances. +The following example from the tutorial previously used `restore_object()` to +handle both creating and updating object instances. def restore_object(self, attrs, instance=None): if instance: @@ -126,7 +166,9 @@ Note that these methods should return the newly created object instance. #### Use `.validated_data` instead of `.object`. -You must now use the `.validated_data` attribute if you need to inspect the data before saving, rather than using the `.object` attribute, which no longer exists. +You must now use the `.validated_data` attribute if you need to inspect the +data before saving, rather than using the `.object` attribute, which no longer +exists. For example the following code *is no longer valid*: @@ -136,7 +178,10 @@ For example the following code *is no longer valid*: serializer.object.user = request.user # Include the user when saving. serializer.save() -Instead of using `.object` to inspect a partially constructed instance, you would now use `.validated_data` to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the `.save()` method as keyword arguments. +Instead of using `.object` to inspect a partially constructed instance, you +would now use `.validated_data` to inspect the cleaned incoming values. Also +you can't set extra attributes on the instance directly, but instead pass them +to the `.save()` method as keyword arguments. The corresponding code would now look like this: @@ -149,59 +194,87 @@ The corresponding code would now look like this: The `.is_valid()` method now takes an optional boolean flag, `raise_exception`. -Calling `.is_valid(raise_exception=True)` will cause a `ValidationError` to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code. +Calling `.is_valid(raise_exception=True)` will cause a `ValidationError` to be +raised if the serializer data contains validation errors. This error will be +handled by REST framework's default exception handler, allowing you to remove +error response handling from your view code. -The handling and formatting of error responses may be altered globally by using the `EXCEPTION_HANDLER` settings key. +The handling and formatting of error responses may be altered globally by using +the `EXCEPTION_HANDLER` settings key. -This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides. +This change also means it's now possible to alter the style of error responses +used by the built-in generic views, without having to include mixin classes or +other overrides. #### Using `serializers.ValidationError`. -Previously `serializers.ValidationError` error was simply a synonym for `django.core.exceptions.ValidationError`. This has now been altered so that it inherits from the standard `APIException` base class. +Previously `serializers.ValidationError` error was simply a synonym for +`django.core.exceptions.ValidationError`. This has now been altered so that it +inherits from the standard `APIException` base class. -The reason behind this is that Django's `ValidationError` class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers. +The reason behind this is that Django's `ValidationError` class is intended for +use with HTML forms and its API makes using it slightly awkward with nested +validation errors that can occur in serializers. -For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the `serializers.ValidationError` exception class, and not Django's built-in exception. +For most users this change shouldn't require any updates to your codebase, but +it is worth ensuring that whenever raising validation errors you should prefer +using the `serializers.ValidationError` exception class, and not Django's +built-in exception. -We strongly recommend that you use the namespaced import style of `import serializers` and not `from serializers import ValidationError` in order to avoid any potential confusion. +We strongly recommend that you use the namespaced import style of `import +serializers` and not `from serializers import ValidationError` in order to +avoid any potential confusion. #### Change to `validate_`. -The `validate_` method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field: +The `validate_` method hooks that can be attached to serializer +classes change their signature slightly and return type. Previously these would +take a dictionary of all incoming data, and a key representing the field name, +and would return a dictionary including the validated data for that field: def validate_score(self, attrs, source): if attrs['score'] % 10 != 0: raise serializers.ValidationError('This field should be a multiple of ten.') return attrs -This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value. +This is now simplified slightly, and the method hooks simply take the value to +be validated, and return the validated value. def validate_score(self, value): if value % 10 != 0: raise serializers.ValidationError('This field should be a multiple of ten.') return value -Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual. +Any ad-hoc validation that applies to more than one field should go in the +`.validate(self, attrs)` method as usual. -Because `.validate_` would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use `.validate()` instead. +Because `.validate_` would previously accept the complete +dictionary of attributes, it could be used to validate a field depending on the +input in another field. Now if you need to do this you should use `.validate()` +instead. -You can either return `non_field_errors` from the validate method by raising a simple `ValidationError` +You can either return `non_field_errors` from the validate method by raising a +simple `ValidationError` def validate(self, attrs): # serializer.errors == {'non_field_errors': ['A non field error']} raise serializers.ValidationError('A non field error') -Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the `ValidationError`, like so: +Alternatively if you want the errors to be against a specific field, use a +dictionary of when instantiating the `ValidationError`, like so: def validate(self, attrs): # serializer.errors == {'my_field': ['A field error']} raise serializers.ValidationError({'my_field': 'A field error'}) -This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field. +This ensures you can still write validation that compares all the input fields, +but that marks the error against a particular field. #### Removal of `transform_`. -The under-used `transform_` on serializer classes is no longer provided. Instead you should just override `to_representation()` if you need to apply any modifications to the representation style. +The under-used `transform_` on serializer classes is no longer +provided. Instead you should just override `to_representation()` if you need to +apply any modifications to the representation style. For example: @@ -210,9 +283,13 @@ For example: ret['username'] = ret['username'].lower() return ret -Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches. +Dropping the extra point of API means there's now only one right way to do +things. This helps with repetition and reinforcement of the core API, rather +than having multiple differing approaches. -If you absolutely need to preserve `transform_` behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example: +If you absolutely need to preserve `transform_` behavior, for +example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, +or serializer base class that add the behavior back in. For example: class BaseModelSerializer(ModelSerializer): """ @@ -228,32 +305,54 @@ If you absolutely need to preserve `transform_` behavior, for exampl #### Differences between ModelSerializer validation and ModelForm. -This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. +This change also means that we no longer use the `.full_clean()` method on +model instances, but instead perform all validation explicitly on the +serializer. This gives a cleaner separation, and ensures that there's no +automatic validation behavior on `ModelSerializer` classes that can't also be +easily replicated on regular `Serializer` classes. -For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different. +For the most part this change should be transparent. Field validation and +uniqueness checks will still be run as normal, but the implementation is a +little different. -The one difference that you do need to note is that the `.clean()` method will not be called as part of serializer validation, as it would be if using a `ModelForm`. Use the serializer `.validate()` method to perform a final validation step on incoming data where required. +The one difference that you do need to note is that the `.clean()` method will +not be called as part of serializer validation, as it would be if using a +`ModelForm`. Use the serializer `.validate()` method to perform a final +validation step on incoming data where required. -There may be some cases where you really do need to keep validation logic in the model `.clean()` method, and cannot instead separate it into the serializer `.validate()`. You can do so by explicitly instantiating a model instance in the `.validate()` method. +There may be some cases where you really do need to keep validation logic in +the model `.clean()` method, and cannot instead separate it into the serializer +`.validate()`. You can do so by explicitly instantiating a model instance in +the `.validate()` method. def validate(self, attrs): instance = ExampleModel(**attrs) instance.clean() return attrs -Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path. +Again, you really should look at properly separating the validation logic out +of the model method if possible, but the above might be useful in some +backwards compatibility cases, or for an easy migration path. #### Writable nested serialization. -REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic: +REST framework 2.x attempted to automatically support writable nested +serialization, but the behavior was complex and non-obvious. Attempting to +automatically handle these case is problematic: -* There can be complex dependencies involved in order of saving multiple related model instances. -* It's unclear what behavior the user should expect when related models are passed `None` data. -* It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. +* There can be complex dependencies involved in order of saving multiple + related model instances. +* It's unclear what behavior the user should expect when related models are + passed `None` data. +* It's unclear how the user should expect to-many relationships to handle + updates, creations and deletions of multiple records. -Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default. +Using the `depth` option on `ModelSerializer` will now create **read-only +nested serializers** by default. -If you try to use a writable nested serializer without writing a custom `create()` and/or `update()` method you'll see an assertion error when you attempt to save the serializer. For example: +If you try to use a writable nested serializer without writing a custom +`create()` and/or `update()` method you'll see an assertion error when you +attempt to save the serializer. For example: >>> class ProfileSerializer(serializers.ModelSerializer): >>> class Meta: @@ -276,7 +375,9 @@ If you try to use a writable nested serializer without writing a custom `create( >>> serializer.save() AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields. -To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly. +To use writable nested serialization you'll want to declare a nested field on +the serializer class, and write the `create()` and/or `update()` methods +explicitly. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() @@ -291,11 +392,13 @@ To use writable nested serialization you'll want to declare a nested field on th Profile.objects.create(user=user, **profile_data) return user -The single-step object creation makes this far simpler and more obvious than the previous `.restore_object()` behavior. +The single-step object creation makes this far simpler and more obvious than +the previous `.restore_object()` behavior. #### Printable serializer representations. -Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. +Serializer instances now support a printable representation that allows you to +inspect the fields present on the instance. For instance, given the following example model: @@ -310,7 +413,8 @@ Let's create a simple `ModelSerializer` class corresponding to the `LocationRati class Meta: model = LocationRating -We can now inspect the serializer representation in the Django shell, using `python manage.py shell`... +We can now inspect the serializer representation in the Django shell, using +`python manage.py shell`... >>> serializer = LocationRatingSerializer() >>> print(serializer) # Or use `print serializer` in Python 2.x @@ -322,7 +426,8 @@ We can now inspect the serializer representation in the Django shell, using `pyt #### The `extra_kwargs` option. -The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDeprecation` and replaced with a more generic `extra_kwargs`. +The `write_only_fields` option on `ModelSerializer` has been moved to +`PendingDeprecation` and replaced with a more generic `extra_kwargs`. class MySerializer(serializer.ModelSerializer): class Meta: @@ -345,7 +450,9 @@ The `read_only_fields` option remains as a convenient shortcut for the more comm #### Changes to `HyperlinkedModelSerializer`. -The `view_name` and `lookup_field` options have been moved to `PendingDeprecation`. They are no longer required, as you can use the `extra_kwargs` argument instead: +The `view_name` and `lookup_field` options have been moved to +`PendingDeprecation`. They are no longer required, as you can use the +`extra_kwargs` argument instead: class MySerializer(serializer.HyperlinkedModelSerializer): class Meta: @@ -369,7 +476,9 @@ Alternatively, specify the field explicitly on the serializer class: #### Fields for model methods and properties. -With `ModelSerializer` you can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model: +With `ModelSerializer` you can now specify field names in the `fields` option +that refer to model methods or properties. For example, suppose you have the +following model: class Invitation(models.Model): created = models.DateTimeField() @@ -397,20 +506,30 @@ These fields will be mapped to `serializers.ReadOnlyField()` instances. #### The `ListSerializer` class. -The `ListSerializer` class has now been added, and allows you to create base serializer classes for only accepting multiple inputs. +The `ListSerializer` class has now been added, and allows you to create base +serializer classes for only accepting multiple inputs. class MultipleUserSerializer(ListSerializer): child = UserSerializer() -You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. +You can also still use the `many=True` argument to serializer classes. It's +worth noting that `many=True` argument transparently creates a `ListSerializer` +instance, allowing the validation logic for list and non-list data to be +cleanly separated in the REST framework codebase. -You will typically want to *continue to use the existing `many=True` flag* rather than declaring `ListSerializer` classes explicitly, but declaring the classes explicitly can be useful if you need to write custom `create` or `update` methods for bulk updates, or provide for other custom behavior. +You will typically want to *continue to use the existing `many=True` flag* +rather than declaring `ListSerializer` classes explicitly, but declaring the +classes explicitly can be useful if you need to write custom `create` or +`update` methods for bulk updates, or provide for other custom behavior. -See also the new `ListField` class, which validates input in the same way, but does not include the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on. +See also the new `ListField` class, which validates input in the same way, but +does not include the serializer interfaces of `.is_valid()`, `.data`, `.save()` +and so on. #### The `BaseSerializer` class. -REST framework now includes a simple `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles. +REST framework now includes a simple `BaseSerializer` class that can be used to +easily support alternative serialization and deserialization styles. This class implements the same basic API as the `Serializer` class: @@ -420,19 +539,27 @@ This class implements the same basic API as the `Serializer` class: * `.errors` - Returns an errors during validation. * `.save()` - Persists the validated data into an object instance. -There are four methods that can be overridden, depending on what functionality you want the serializer class to support: +There are four methods that can be overridden, depending on what functionality +you want the serializer class to support: * `.to_representation()` - Override this to support serialization, for read operations. * `.to_internal_value()` - Override this to support deserialization, for write operations. * `.create()` and `.update()` - Override either or both of these to support saving instances. -Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`. +Because this class provides the same interface as the `Serializer` class, you +can use it with the existing generic class-based views exactly as you would for +a regular `Serializer` or `ModelSerializer`. -The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input. +The only difference you'll notice when doing so is the `BaseSerializer` classes +will not generate HTML forms in the browsable API. This is because the data +they return does not include all the field information that would allow each +field to be rendered into a suitable HTML input. ##### Read-only `BaseSerializer` classes. -To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: +To implement a read-only serializer using the `BaseSerializer` class, we just +need to override the `.to_representation()` method. Let's take a look at an +example using a simple Django model: class HighScore(models.Model): created = models.DateTimeField(auto_now_add=True) @@ -466,13 +593,20 @@ Or use it to serialize multiple instances: ##### Read-write `BaseSerializer` classes. -To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `ValidationError` if the supplied data is in an incorrect format. +To create a read-write serializer we first need to implement a +`.to_internal_value()` method. This method returns the validated values that +will be used to construct the object instance, and may raise a +`ValidationError` if the supplied data is in an incorrect format. -Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`. +Once you've implemented `.to_internal_value()`, the basic validation API will +be available on the serializer, and you will be able to use `.is_valid()`, +`.validated_data` and `.errors`. -If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods. +If you want to also support `.save()` you'll need to also implement either or +both of the `.create()` and `.update()` methods. -Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations. +Here's a complete example of our previous `HighScoreSerializer`, that's been +updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer): def to_internal_value(self, data): @@ -511,9 +645,12 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd #### Creating new generic serializers with `BaseSerializer`. -The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. +The `BaseSerializer` class is also useful if you want to implement new generic +serializer classes for dealing with particular serialization styles, or for +integrating with alternative storage backends. -The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. +The following class is an example of a generic serializer that can handle +coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer): """ @@ -557,36 +694,53 @@ There are some minor tweaks to the field base classes. Previously we had these two base classes: -* `Field` as the base class for read-only fields. A default implementation was included for serializing data. +* `Field` as the base class for read-only fields. A default implementation was + included for serializing data. * `WritableField` as the base class for read-write fields. We now use the following: -* `Field` is the base class for all fields. It does not include any default implementation for either serializing or deserializing data. -* `ReadOnlyField` is a concrete implementation for read-only fields that simply returns the attribute value without modification. +* `Field` is the base class for all fields. It does not include any default + implementation for either serializing or deserializing data. +* `ReadOnlyField` is a concrete implementation for read-only fields that simply + returns the attribute value without modification. #### The `required`, `allow_null`, `allow_blank` and `default` arguments. -REST framework now has more explicit and clear control over validating empty values for fields. +REST framework now has more explicit and clear control over validating empty +values for fields. -Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None` or the empty string. +Previously the meaning of the `required=False` keyword argument was +underspecified. In practice its use meant that a field could either be not +included in the input, or it could be included, but be `None` or the empty +string. -We now have a better separation, with separate `required`, `allow_null` and `allow_blank` arguments. +We now have a better separation, with separate `required`, `allow_null` and +`allow_blank` arguments. The following set of arguments are used to control validation of empty values: -* `required=False`: The value does not need to be present in the input, and will not be passed to `.create()` or `.update()` if it is not seen. -* `default=`: The value does not need to be present in the input, and a default value will be passed to `.create()` or `.update()` if it is not seen. +* `required=False`: The value does not need to be present in the input, and + will not be passed to `.create()` or `.update()` if it is not seen. +* `default=`: The value does not need to be present in the input, and a + default value will be passed to `.create()` or `.update()` if it is not seen. * `allow_null=True`: `None` is a valid input. * `allow_blank=True`: `''` is valid input. For `CharField` and subclasses only. -Typically you'll want to use `required=False` if the corresponding model field has a default value, and additionally set either `allow_null=True` or `allow_blank=True` if required. +Typically you'll want to use `required=False` if the corresponding model field +has a default value, and additionally set either `allow_null=True` or +`allow_blank=True` if required. -The `default` argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the `required` argument when a default is specified, and doing so will result in an error. +The `default` argument is also available and always implies that the field is +not required to be in the input. It is unnecessary to use the `required` +argument when a default is specified, and doing so will result in an error. #### Coercing output types. -The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an `IntegerField` would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior. +The previous field implementations did not forcibly coerce returned values into +the correct type in many cases. For example, an `IntegerField` would return a +string output if the attribute value was a string. We now more strictly coerce +to the correct return type, leading to more constrained and expected behavior. #### Removal of `.validate()`. @@ -603,11 +757,14 @@ Previously validation errors could be raised in either `.to_native()` or `.valid #### The `ListField` class. -The `ListField` class has now been added. This field validates list input. It takes a `child` keyword argument which is used to specify the field used to validate each item in the list. For example: +The `ListField` class has now been added. This field validates list input. It +takes a `child` keyword argument which is used to specify the field used to +validate each item in the list. For example: scores = ListField(child=IntegerField(min_value=0, max_value=100)) -You can also use a declarative style to create new subclasses of `ListField`, like this: +You can also use a declarative style to create new subclasses of `ListField`, +like this: class ScoresField(ListField): child = IntegerField(min_value=0, max_value=100) @@ -616,31 +773,44 @@ We can now use the `ScoresField` class inside another serializer: scores = ScoresField() -See also the new `ListSerializer` class, which validates input in the same way, but also includes the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on. +See also the new `ListSerializer` class, which validates input in the same way, +but also includes the serializer interfaces of `.is_valid()`, `.data`, +`.save()` and so on. #### The `ChoiceField` class may now accept a flat list. -The `ChoiceField` class may now accept a list of choices in addition to the existing style of using a list of pairs of `(name, display_value)`. The following is now valid: +The `ChoiceField` class may now accept a list of choices in addition to the +existing style of using a list of pairs of `(name, display_value)`. The +following is now valid: color = ChoiceField(choices=['red', 'green', 'blue']) #### The `MultipleChoiceField` class. -The `MultipleChoiceField` class has been added. This field acts like `ChoiceField`, but returns a set, which may include none, one or many of the valid choices. +The `MultipleChoiceField` class has been added. This field acts like +`ChoiceField`, but returns a set, which may include none, one or many of the +valid choices. #### Changes to the custom field API. -The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`. +The `from_native(self, value)` and `to_native(self, data)` method names have +been replaced with the more obviously named `to_internal_value(self, data)` and +`to_representation(self, value)`. -The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example... +The `field_from_native()` and `field_to_native()` methods are removed. +Previously you could use these methods if you wanted to customise the behaviour +in a way that did not simply lookup the field value from the object. For +example... def field_to_native(self, obj, field_name): """A custom read-only field that returns the class name.""" return obj.__class__.__name__ -Now if you need to access the entire object you'll instead need to override one or both of the following: +Now if you need to access the entire object you'll instead need to override one +or both of the following: -* Use `get_attribute` to modify the attribute value passed to `to_representation()`. +* Use `get_attribute` to modify the attribute value passed to + `to_representation()`. * Use `get_value` to modify the data value passed `to_internal_value()`. For example: @@ -655,7 +825,9 @@ For example: #### Explicit `queryset` required on relational fields. -Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a `ModelSerializer`. +Previously relational fields that were explicitly declared on a serializer +class could omit the queryset argument if (and only if) they were declared on a +`ModelSerializer`. This code *would be valid* in `2.4.3`: @@ -674,8 +846,9 @@ However this code *would not be valid* in `3.0`: def restore_object(self, attrs, instance=None): # ... -The queryset argument is now always required for writable relational fields. -This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes. +The `queryset` argument is now always required for writable relational fields. +This removes some magic and makes it easier and more obvious to move between +implicit `ModelSerializer` classes and explicit `Serializer` classes. class AccountSerializer(serializers.ModelSerializer): organizations = serializers.SlugRelatedField( @@ -686,11 +859,13 @@ This removes some magic and makes it easier and more obvious to move between imp class Meta: model = Account -The `queryset` argument is only ever required for writable fields, and is not required or valid for fields with `read_only=True`. +The `queryset` argument is only ever required for writable fields, and is not +required or valid for fields with `read_only=True`. #### Optional argument to `SerializerMethodField`. -The argument to `SerializerMethodField` is now optional, and defaults to `get_`. For example the following is valid: +The argument to `SerializerMethodField` is now optional, and defaults to +`get_`. For example the following is valid: class AccountSerializer(serializers.Serializer): # `method_name='get_billing_details'` by default. @@ -699,13 +874,17 @@ The argument to `SerializerMethodField` is now optional, and defaults to `get_ "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." +> "Take a close look at possible CSRF / XSRF vulnerabilities on your own +> websites. They're the worst kind of vulnerability — very easy to +> exploit by attackers, yet not so intuitively easy to understand for software +> developers, at least until you've been bitten by one." > > — [Jeff Atwood][cite] ## Javascript clients -If you’re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers. +If you’re building a JavaScript client to interface with your Web API, you'll +need to consider if the client can use the same authentication policy that is +used by the rest of the website, and also determine if you need to use CSRF +tokens or CORS headers. -AJAX requests that are made within the same context as the API they are interacting with will typically use `SessionAuthentication`. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website. +AJAX requests that are made within the same context as the API they are +interacting with will typically use `SessionAuthentication`. This ensures that +once a user has logged in, any AJAX requests made can be authenticated using +the same session-based authentication that is used for the rest of the website. -AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`. +AJAX requests that are made on a different site from the API they are +communicating with will typically need to use a non-session-based +authentication scheme, such as `TokenAuthentication`. ## CSRF protection -[Cross Site Request Forgery][csrf] protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session. +[Cross Site Request Forgery][csrf] protection is a mechanism of guarding +against a particular type of attack, which can occur when a user has not logged +out of a web site, and continues to have a valid session. In this +circumstance a malicious site may be able to perform actions against the target +site, within the context of the logged-in session. To guard against these type of attacks, you need to do two things: -1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` cannot be used to alter any server-side state. -2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token. +1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` + cannot be used to alter any server-side state. +2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and + `DELETE`, always require a valid CSRF token. -If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations. +If you're using `SessionAuthentication` you'll need to include valid CSRF +tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations. -In order to make AJAX requests, you need to include CSRF token in the HTTP header, as [described in the Django documentation][csrf-ajax]. +In order to make AJAX requests, you need to include CSRF token in the HTTP +header, as [described in the Django documentation][csrf-ajax]. ## CORS -[Cross-Origin Resource Sharing][cors] is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed. +[Cross-Origin Resource Sharing][cors] is a mechanism for allowing clients to +interact with APIs that are hosted on a different domain. CORS works by +requiring the server to include a specific set of headers that allow a browser +to determine if and when cross-domain requests should be allowed. -The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views. +The best way to deal with CORS in REST framework is to add the required +response headers in middleware. This ensures that CORS is supported +transparently, without having to change any behavior in your views. -[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs. +[Otto Yiu][ottoyiu] maintains the [django-cors-headers] package, which is known +to work correctly with REST framework APIs. [cite]: http://www.codinghorror.com/blog/2008/10/preventing-csrf-and-xsrf-attacks.html [csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md index bc1431cfc..c8fd9acc0 100644 --- a/docs/topics/browsable-api.md +++ b/docs/topics/browsable-api.md @@ -1,25 +1,42 @@ # The Browsable API -> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them. +> It is a profoundly erroneous truism... that we should cultivate the habit of +> thinking of what we are doing. The precise opposite is the case. +> Civilization advances by extending the number of important operations which +> we can perform without thinking about them. > > — [Alfred North Whitehead][cite], An Introduction to Mathematics (1911) -API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`. +API may stand for Application *Programming* Interface, but humans have to be +able to read the APIs, too; someone has to do the programming. Django REST +Framework supports generating human-friendly HTML output for each resource when +the `HTML` format is requested. These pages allow for easy browsing of +resources, as well as forms for submitting data to the resources using `POST`, +`PUT`, and `DELETE`. ## URLs -If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose. +If you include fully-qualified URLs in your resource output, they will be +'urlized' and made clickable for easy browsing by humans. The `rest_framework` +package includes a [`reverse`][drfreverse] helper for this purpose. ## Formats -By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview]. +By default, the API will return the format specified by the headers, which in +the case of the browser is HTML. The format can be specified using `?format=` +in the request, so you can look at the raw JSON response in a browser by adding +`?format=json` to the URL. There are helpful extensions for viewing JSON in +[Firefox][ffjsonview] and [Chrome][chromejsonview]. ## Customizing -The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel. +The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), +making it easy to customize the look-and-feel. -To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example: +To customize the default style, create a template called +`rest_framework/api.html` that extends from `rest_framework/base.html`. For +example: **templates/rest_framework/api.html** @@ -29,15 +46,23 @@ To customize the default style, create a template called `rest_framework/api.htm ### Overriding the default theme -To replace the default theme, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme. +To replace the default theme, add a `bootstrap_theme` block to your `api.html` +and insert a `link` to the desired Bootstrap theme css file. This will +completely replace the included theme. {% block bootstrap_theme %} {% endblock %} -Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. +Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. +To use any of the Bootswatch themes, simply download the theme's +`bootstrap.min.css` file, add it to your project, and replace the default one +as described above. -You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style. +You can also change the navbar variant, which by default is `navbar-inverse`, +using the `bootstrap_navbar_variant` block. The empty `{% block +bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap +navbar style. Full example: @@ -86,11 +111,16 @@ All of the standard [Bootstrap components][bcomponents] are available. #### Tooltips -The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content will display a tooltip on hover events. +The browsable API makes use of the Bootstrap tooltips component. Any element +with the `js-tooltip` class and a `title` attribute has that title content will +display a tooltip on hover events. ### Login Template -To add branding and customize the look-and-feel of the login template, create a template called `login.html` and add it to your project, eg: `templates/rest_framework/login.html`. The template should extend from `rest_framework/login_base.html`. +To add branding and customize the look-and-feel of the login template, create a +template called `login.html` and add it to your project, eg: +`templates/rest_framework/login.html`. The template should extend from +`rest_framework/login_base.html`. You can add your site name or branding by including the branding block: @@ -127,13 +157,19 @@ You can override the `BrowsableAPIRenderer.get_context()` method to customise th #### Not using base.html -For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you. +For more advanced customization, such as not having a Bootstrap basis or +tighter integration with the rest of your site, you can simply choose not to +have `api.html` extend `base.html`. Then the page content and capabilities are +entirely up to you. #### Handling `ChoiceField` with large numbers of items. -When a relationship or `ChoiceField` has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. +When a relationship or `ChoiceField` has too many items, rendering the widget +containing all the options can become very slow, and cause the browsable API +rendering to perform poorly. -The simplest option in this case is to replace the select input with a standard text input. For example: +The simplest option in this case is to replace the select input with a standard +text input. For example: author = serializers.HyperlinkedRelatedField( queryset=User.objects.all(), @@ -142,9 +178,18 @@ The simplest option in this case is to replace the select input with a standard #### Autocomplete -An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself. +An alternative, but more complex option would be to replace the input with an +autocomplete widget, that only loads and renders a subset of the available +options as needed. If you need to do this you'll need to do some work to build +a custom autocomplete HTML template yourself. -There are [a variety of packages for autocomplete widgets][autocomplete-packages], such as [django-autocomplete-light][django-autocomplete-light], that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the `widget` keyword argument since it now uses templated HTML generation. +There are [a variety of packages for autocomplete +widgets][autocomplete-packages], such as +[django-autocomplete-light][django-autocomplete-light], that you may want to +refer to. Note that you will not be able to simply include these components as +standard widgets, but will need to write the HTML template explicitly. This is +because REST framework 3.0 no longer supports the `widget` keyword argument +since it now uses templated HTML generation. Better support for autocomplete inputs is planned in future versions. diff --git a/docs/topics/browser-enhancements.md b/docs/topics/browser-enhancements.md index e1977e826..82f837892 100644 --- a/docs/topics/browser-enhancements.md +++ b/docs/topics/browser-enhancements.md @@ -1,12 +1,16 @@ # Browser enhancements -> "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE" +> "There are two noncontroversial uses for overloaded POST. The first is to +> *simulate* HTTP's uniform interface for clients like web browsers that don't +> support PUT or DELETE" > > — [RESTful Web Services][cite], Leonard Richardson & Sam Ruby. -In order to allow the browsable API to function, there are a couple of browser enhancements that REST framework needs to provide. +In order to allow the browsable API to function, there are a couple of browser +enhancements that REST framework needs to provide. -As of version 3.3.0 onwards these are enabled with javascript, using the [ajax-form][ajax-form] library. +As of version 3.3.0 onwards these are enabled with javascript, using the +[ajax-form][ajax-form] library. ## Browser based PUT, DELETE, etc... @@ -19,11 +23,15 @@ After including the library, use the `data-method` attribute on the form, like s ... -Note that prior to 3.3.0, this support was server-side rather than javascript based. The method overloading style (as used in [Ruby on Rails][rails]) is no longer supported due to subtle issues that it introduces in request parsing. +Note that prior to 3.3.0, this support was server-side rather than javascript +based. The method overloading style (as used in [Ruby on Rails][rails]) is no +longer supported due to subtle issues that it introduces in request parsing. ## Browser based submission of non-form content -Browser-based submission of content types such as JSON are supported by the [AJAX form library][ajax-form], using form fields with `data-override='content-type'` and `data-override='content'` attributes. +Browser-based submission of content types such as JSON are supported by the +[AJAX form library][ajax-form], using form fields with +`data-override='content-type'` and `data-override='content'` attributes. For example: @@ -45,12 +53,14 @@ This behavior is controlled using the `URL_FORMAT_OVERRIDE` setting. ## HTTP header based method overriding -Prior to version 3.3.0 the semi extension header `X-HTTP-Method-Override` was supported for overriding the request method. This behavior is no longer in core, but can be adding if needed using middleware. +Prior to version 3.3.0 the semi extension header `X-HTTP-Method-Override` was +supported for overriding the request method. This behavior is no longer in +core, but can be adding if needed using middleware. For example: METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' - + class MethodOverrideMiddleware(object): def process_view(self, request, callback, callback_args, callback_kwargs): if request.method != 'POST': @@ -61,9 +71,13 @@ For example: ## URL based accept headers -Until version 3.3.0 REST framework included built-in support for `?accept=application/json` style URL parameters, which would allow the `Accept` header to be overridden. +Until version 3.3.0 REST framework included built-in support for +`?accept=application/json` style URL parameters, which would allow the `Accept` +header to be overridden. -Since the introduction of the content negotiation API this behavior is no longer included in core, but may be added using a custom content negotiation class, if needed. +Since the introduction of the content negotiation API this behavior is no +longer included in core, but may be added using a custom content negotiation +class, if needed. For example: diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md index c4ef0efdf..dbdc4f627 100644 --- a/docs/topics/contributing.md +++ b/docs/topics/contributing.md @@ -1,200 +1,280 @@ # Contributing to REST framework -> The world can only really be changed one piece at a time. The art is picking that piece. +> 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. +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. +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. +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 to 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 +to 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. +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. +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. +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. +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]. +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 maintenance 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. +* 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 + maintenance overhead of REST framework, so that the focus can be on continued + stability, bug fixes, 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 +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. +* 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 + 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 set up your editor to automatically indicate non-conforming styles. +Changes should broadly follow the [PEP 8][pep-8] style conventions, and we +recommend you set up your editor to automatically indicate non-conforming +styles. ## Testing To run the tests, clone the repository, and then: - # Setup the virtual environment - virtualenv env - source env/bin/activate - pip install -r requirements.txt + # Setup the virtual environment virtualenv env source env/bin/activate pip + install -r requirements.txt - # Run the tests - ./runtests.py + # Run the tests ./runtests.py ### Test options Run using a more concise output style. - ./runtests.py -q + ./runtests.py -q Run the tests using a more concise output style, no coverage, no flake8. - ./runtests.py --fast + ./runtests.py --fast Don't run the flake8 code linting. - ./runtests.py --nolint + ./runtests.py --nolint Only run the flake8 code linting, don't run the tests. - ./runtests.py --lintonly + ./runtests.py --lintonly Run the tests for a given test case. - ./runtests.py MyTestCase + ./runtests.py MyTestCase Run the tests for a given test method. - ./runtests.py MyTestCase.test_this_method + ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. - ./runtests.py test_this_method + ./runtests.py test_this_method -Note: The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. +Note: The test case and test method matching is fuzzy and will sometimes run +other tests that contain a partial string match to the given command line +input. ### Running against multiple environments -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: +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 + 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 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 separate issue without interfering with an ongoing pull requests. +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 separate 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. +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]. +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. +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 running as you'd expect. - -![Travis status][travis-status] - -*Above: Travis build notifications* +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 running as you'd expect. ## 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. +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]. +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. +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, install MkDocs with `pip install mkdocs` and then run the following command. +To build the documentation, install MkDocs with `pip install mkdocs` and then +run the following command. - mkdocs build + mkdocs build This will build the documentation into the `site` directory. -You can build the documentation and open a preview in a browser window by using the `serve` command. +You can build the documentation and open a preview in a browser window by using +the `serve` command. - mkdocs serve + mkdocs serve ## 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. +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. -* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'. +* Don't use abbreviations such as 'e.g.' but instead use + the long form, such as 'For example'. ## Markdown style -There are a couple of conventions you should follow when working on the documentation. +There are a couple of conventions you should follow when working on the +documentation. ##### 1. Headers -Headers should use the hash style. For example: +Headers should use the hash style. For example: - ### Some important topic + ### Some important topic -The underline style should not be used. **Don't do this:** +The underline style should not be used. **Don't do this:** - Some important topic - ==================== + Some important topic ==================== ##### 2. Links -Links should always use the reference style, with the referenced hyperlinks kept at the end of the document. +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]. + Here is a link to [some other thing][other-thing]. - More text... + More text... - [other-thing]: http://example.com/other/thing + [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: +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 + [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. +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: +If you want to draw attention to a note or warning, use a pair of enclosing +lines, like so: - --- + --- - **Note:** A useful documentation note. + **Note:** A useful documentation note. - --- + --- [cite]: http://www.w3.org/People/Berners-Lee/FAQ.html @@ -203,7 +283,6 @@ If you want to draw attention to a note or warning, use a pair of enclosing line [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]: ../img/travis-status.png [pull-requests]: https://help.github.com/articles/using-pull-requests [tox]: https://tox.readthedocs.io/en/latest/ [markdown]: http://daringfireball.net/projects/markdown/basics diff --git a/docs/topics/documenting-your-api.md b/docs/topics/documenting-your-api.md index e7d2cde0c..395e84359 100644 --- a/docs/topics/documenting-your-api.md +++ b/docs/topics/documenting-your-api.md @@ -1,24 +1,40 @@ # Documenting your API -> A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state. +> A REST API should spend almost all of its descriptive effort in defining the +> media type(s) used for representing resources and driving application state. > > — Roy Fielding, [REST APIs must be hypertext driven][cite] -There are a variety of approaches to API documentation. This document introduces a few of the various tools and options you might choose from. The approaches should not be considered exclusive - you may want to provide more than one documentation style for you API, such as a self describing API that also includes static documentation of the various API endpoints. +There are a variety of approaches to API documentation. This document +introduces a few of the various tools and options you might choose from. The +approaches should not be considered exclusive - you may want to provide more +than one documentation style for you API, such as a self describing API that +also includes static documentation of the various API endpoints. ## Endpoint documentation -The most common way to document Web APIs today is to produce documentation that lists the API endpoints verbatim, and describes the allowable operations on each. There are various tools that allow you to do this in an automated or semi-automated way. +The most common way to document Web APIs today is to produce documentation that +lists the API endpoints verbatim, and describes the allowable operations on +each. There are various tools that allow you to do this in an automated or +semi-automated way. --- #### DRF Docs -[DRF Docs][drfdocs-repo] allows you to document Web APIs made with Django REST Framework and it is authored by Emmanouil Konstantinidis. It's made to work out of the box and its setup should not take more than a couple of minutes. Complete documentation can be found on the [website][drfdocs-website] while there is also a [demo][drfdocs-demo] available for people to see what it looks like. **Live API Endpoints** allow you to utilize the endpoints from within the documentation in a neat way. +[DRF Docs][drfdocs-repo] allows you to document Web APIs made with Django REST +Framework and it is authored by Emmanouil Konstantinidis. It's made to work out +of the box and its setup should not take more than a couple of minutes. +Complete documentation can be found on the [website][drfdocs-website] while +there is also a [demo][drfdocs-demo] available for people to see what it looks +like. **Live API Endpoints** allow you to utilize the endpoints from within the +documentation in a neat way. -Features include customizing the template with your branding, settings for hiding the docs depending on the environment and more. +Features include customizing the template with your branding, settings for +hiding the docs depending on the environment and more. -Both this package and Django REST Swagger are fully documented, well supported, and come highly recommended. +Both this package and Django REST Swagger are fully documented, well supported, +and come highly recommended. ![Screenshot - DRF docs][image-drf-docs] @@ -26,13 +42,19 @@ Both this package and Django REST Swagger are fully documented, well supported, #### Django REST Swagger -Marc Gibbons' [Django REST Swagger][django-rest-swagger] integrates REST framework with the [Swagger][swagger] API documentation tool. The package produces well presented API documentation, and includes interactive tools for testing API endpoints. +Marc Gibbons' [Django REST Swagger][django-rest-swagger] integrates REST +framework with the [Swagger][swagger] API documentation tool. The package +produces well presented API documentation, and includes interactive tools for +testing API endpoints. Django REST Swagger supports REST framework versions 2.3 and above. -Mark is also the author of the [REST Framework Docs][rest-framework-docs] package which offers clean, simple autogenerated documentation for your API but is deprecated and has moved to Django REST Swagger. +Mark is also the author of the [REST Framework Docs][rest-framework-docs] +package which offers clean, simple autogenerated documentation for your API but +is deprecated and has moved to Django REST Swagger. -Both this package and DRF docs are fully documented, well supported, and come highly recommended. +Both this package and DRF docs are fully documented, well supported, and come +highly recommended. ![Screenshot - Django REST Swagger][image-django-rest-swagger] @@ -40,7 +62,11 @@ Both this package and DRF docs are fully documented, well supported, and come hi #### Apiary -There are various other online tools and services for providing API documentation. One notable service is [Apiary][apiary]. With Apiary, you describe your API using a simple markdown-like syntax. The generated documentation includes API interaction, a mock server for testing & prototyping, and various other tools. +There are various other online tools and services for providing API +documentation. One notable service is [Apiary][apiary]. With Apiary, you +describe your API using a simple markdown-like syntax. The generated +documentation includes API interaction, a mock server for testing & +prototyping, and various other tools. ![Screenshot - Apiary][image-apiary] @@ -48,7 +74,9 @@ There are various other online tools and services for providing API documentatio ## Self describing APIs -The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser. +The browsable API that REST framework provides makes it possible for your API +to be entirely self describing. The documentation for each API endpoint can be +provided simply by visiting the URL in your browser. ![Screenshot - Self describing API][image-self-describing-api] @@ -56,17 +84,26 @@ The browsable API that REST framework provides makes it possible for your API to #### Setting the title -The title that is used in the browsable API is generated from the view class name or function name. Any trailing `View` or `ViewSet` suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores. +The title that is used in the browsable API is generated from the view class +name or function name. Any trailing `View` or `ViewSet` suffix is stripped, +and the string is whitespace separated on uppercase/lowercase boundaries or +underscores. -For example, the view `UserListView`, will be named `User List` when presented in the browsable API. +For example, the view `UserListView`, will be named `User List` when presented +in the browsable API. -When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set `UserViewSet` will generate views named `User List` and `User Instance`. +When working with viewsets, an appropriate suffix is appended to each generated +view. For example, the view set `UserViewSet` will generate views named `User +List` and `User Instance`. #### Setting the description -The description in the browsable API is generated from the docstring of the view or viewset. +The description in the browsable API is generated from the docstring of the +view or viewset. -If the python `markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example: +If the python `markdown` library is installed, then [markdown syntax][markdown] +may be used in the docstring, and will be converted to HTML in the browsable +API. For example: class AccountListView(views.APIView): """ @@ -77,15 +114,23 @@ If the python `markdown` library is installed, then [markdown syntax][markdown] [ref]: http://example.com/activating-accounts """ -Note that one constraint of using viewsets is that any documentation be used for all generated views, so for example, you cannot have differing documentation for the generated list view and detail view. +Note that one constraint of using viewsets is that any documentation be used +for all generated views, so for example, you cannot have differing + documentation for the generated list view and detail view. #### The `OPTIONS` method -REST framework APIs also support programmatically accessible descriptions, using the `OPTIONS` HTTP method. A view will respond to an `OPTIONS` request with metadata including the name, description, and the various media types it accepts and responds with. +REST framework APIs also support programmatically accessible descriptions, +using the `OPTIONS` HTTP method. A view will respond to an `OPTIONS` request +with metadata including the name, description, and the various media types it +accepts and responds with. -When using the generic views, any `OPTIONS` requests will additionally respond with metadata regarding any `POST` or `PUT` actions available, describing which fields are on the serializer. +When using the generic views, any `OPTIONS` requests will additionally respond +with metadata regarding any `POST` or `PUT` actions available, describing which +fields are on the serializer. -You can modify the response behavior to `OPTIONS` requests by overriding the `metadata` view method. For example: +You can modify the response behavior to `OPTIONS` requests by overriding the +`metadata` view method. For example: def metadata(self, request): """ @@ -99,11 +144,20 @@ You can modify the response behavior to `OPTIONS` requests by overriding the `me ## The hypermedia approach -To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends. +To be fully RESTful an API should present its available actions as hypermedia +controls in the responses that it sends. -In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the *media types* that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document. +In this approach, rather than documenting the available API endpoints up front, +the description instead concentrates on the *media types* that are used. The +available actions that may be taken on any given URL are not strictly fixed, +but are instead made available by the presence of link and form controls in the +returned document. -To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the documentation includes pointers to background reading, as well as links to various hypermedia formats. +To implement a hypermedia API you'll need to decide on an appropriate media +type for the API, and implement a custom renderer and parser for that media +type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the +documentation includes pointers to background reading, as well as links to +various hypermedia formats. [cite]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven [drfdocs-repo]: https://github.com/ekonstantinidis/django-rest-framework-docs diff --git a/docs/topics/funding.md b/docs/topics/funding.md index 814de0a3c..523bb2ff9 100644 --- a/docs/topics/funding.md +++ b/docs/topics/funding.md @@ -97,21 +97,32 @@ form.signup { # Funding -> As a direct result of [a successful Mozilla grant application](mozilla-grant.md), I will be leaving my current role at [DabApps](http://www.dabapps.com), and attempting to secure a sustainable business model for REST framework development. I need your help in order to make this work. +> As a direct result of [a successful Mozilla grant +> application](mozilla-grant.md), I will be leaving my current role at +> [DabApps](http://www.dabapps.com), and attempting to secure a sustainable +> business model for REST framework development. I need your help in order to +> make this work. > > — Tom Christie -If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan. +If you use REST framework commercially we strongly encourage you to invest in +its continued development by signing up for a paid plan. -**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.** +**We believe that collaboratively funded software can offer outstanding returns +on investment, by encouraging our users to collectively share the cost of +development.** Signing up for a paid plan will: -* Directly contribute to faster releases, more features, and higher quality software. -* Allow more time to be invested in documentation, issue triage, and community support. +* Directly contribute to faster releases, more features, and higher quality + software. +* Allow more time to be invested in documentation, issue triage, and community + support. * Safeguard the future development of REST framework. -REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development. +REST framework continues to be open-source and permissively licensed, but we +firmly believe it is in the commercial best-interest for users of the project +to invest in its ongoing development. --- @@ -134,17 +145,22 @@ With *typical corporate fundings of just £100-£1000 per organization* we succe * The metadata APIs for handling `OPTIONS` requests and schema endpoints. * Numerous minor improvements and better quality throughout the codebase. -This incredible level of return on investment is *only possible through collaboratively funded models*, which is why we believe that supporting our paid plans is in everyone's best interest. +This incredible level of return on investment is *only possible through +collaboratively funded models*, which is why we believe that supporting our +paid plans is in everyone's best interest. -Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project. +Sign up for a paid plan today, and help ensure that REST framework becomes a +sustainable, full-time funded project. --- ## Freelancer plan -This subscription is recommended for freelancers and other individuals with an interest in seeing REST framework continue to improve. +This subscription is recommended for freelancers and other individuals with an +interest in seeing REST framework continue to improve. -If you are using REST framework as an full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans). +If you are using REST framework as an full-time employee, consider recommending +that your company takes out a [corporate plan](#corporate-plans).
@@ -188,11 +204,16 @@ If you are using REST framework as an full-time employee, consider recommending ## Corporate plans -These subscriptions are recommended for companies and organizations using REST framework either publicly or privately. +These subscriptions are recommended for companies and organizations using REST +framework either publicly or privately. -In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**. +In exchange for funding you'll also receive advertising space on our site, +allowing you to **promote your company or product to many tens of thousands of +developers worldwide**. -Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day. +Our professional and premium plans also include **priority support**. At any +time your engineers can escalate an issue or discussion group thread, and we'll +ensure it gets a guaranteed response within the next working day.
diff --git a/docs/topics/html-and-forms.md b/docs/topics/html-and-forms.md index 6660607fe..7411bad6b 100644 --- a/docs/topics/html-and-forms.md +++ b/docs/topics/html-and-forms.md @@ -1,18 +1,27 @@ # HTML & Forms -REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can used as HTML forms and rendered in templates. +REST framework is suitable for returning both API style responses, and regular +HTML pages. Additionally, serializers can used as HTML forms and rendered in +templates. ## Rendering HTML -In order to return HTML responses you'll need to either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`. +In order to return HTML responses you'll need to either `TemplateHTMLRenderer`, +or `StaticHTMLRenderer`. -The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response. +The `TemplateHTMLRenderer` class expects the response to contain a dictionary +of context data, and renders an HTML page based on a template that must be +specified either in the view or on the response. -The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content. +The `StaticHTMLRender` class expects the response to contain a string of the +pre-rendered HTML content. -Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views. +Because static HTML pages typically have different behavior from API responses +you'll probably need to write any HTML views explicitly, rather than relying on +the built-in generic views. -Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template: +Here's an example of a view that returns a list of "Profile" instances, +rendered in an HTML template: **views.py**: @@ -40,12 +49,14 @@ Here's an example of a view that returns a list of "Profile" instances, rendered {% endfor %} - + ## Rendering Forms -Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template. +Serializers may be rendered as forms by using the `render_form` template tag, +and including the serializer instance as context to the template. -The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance: +The following view demonstrates an example of using a serializer in a template +for viewing and updating a model instance: **views.py**: @@ -77,7 +88,7 @@ The following view demonstrates an example of using a serializer in a template f {% load rest_framework %} - +

Profile - {{ profile.name }}

@@ -90,9 +101,14 @@ The following view demonstrates an example of using a serializer in a template f ### Using template packs -The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields. +The `render_form` tag takes an optional `template_pack` argument, that +specifies which template directory should be used for rendering the form and +form fields. -REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS. +REST framework includes three built-in template packs, all based on Bootstrap +3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default +style is `horizontal`. To use any of these template packs you'll want to also +include the Bootstrap 3 CSS. The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS: @@ -101,9 +117,12 @@ The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS: -Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates. +Third party packages may include alternate template packs, by bundling a +template directory containing the necessary form and field templates. -Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form. +Let's take a look at how to render each of the three available template packs. +For these examples we'll use a single serializer class to present a "Login" +form. class LoginSerializer(serializers.Serializer): email = serializers.EmailField( @@ -120,7 +139,8 @@ Let's take a look at how to render each of the three available template packs. F #### `rest_framework/vertical` -Presents form labels above their corresponding control inputs, using the standard Bootstrap layout. +Presents form labels above their corresponding control inputs, using the +standard Bootstrap layout. *This is the default template pack.* @@ -180,25 +200,34 @@ A compact form style that presents all the controls inline. ## Field styles -Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used. +Serializer fields can have their rendering style customized by using the +`style` keyword argument. This argument is a dictionary of options that control +the template and layout used. -The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use. +The most common way to customize the field style is to use the `base_template` +style keyword argument to select which template in the template pack should be +use. -For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this: +For example, to render a `CharField` as an HTML textarea rather than the +default HTML input, you would use something like this: details = serializers.CharField( max_length=1000, style={'base_template': 'textarea.html'} ) -If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name: +If you instead want a field to be rendered using a custom template that is *not +part of an included template pack*, you can instead use the `template` style +option, to fully specify a template name: details = serializers.CharField( max_length=1000, style={'template': 'my-field-templates/custom-input.html'} ) -Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control. +Field templates can also use additional style properties, depending on their +type. For example, the `textarea.html` template also accepts a `rows` property +that can be used to affect the sizing of the control. details = serializers.CharField( max_length=1000, @@ -207,7 +236,7 @@ Field templates can also use additional style properties, depending on their typ The complete list of `base_template` options and their associated style options is listed below. -base_template | Valid field types | Additional style options +base_template | Valid field types | Additional style options ----|----|---- input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label textarea.html | `CharField` | rows, placeholder, hide_label diff --git a/docs/topics/internationalization.md b/docs/topics/internationalization.md index 3968e23d1..b1fe39408 100644 --- a/docs/topics/internationalization.md +++ b/docs/topics/internationalization.md @@ -4,27 +4,36 @@ > > — [Jannis Leidel, speaking at Django Under the Hood, 2015][cite]. -REST framework ships with translatable error messages. You can make these appear in your language enabling [Django's standard translation mechanisms][django-translation]. +REST framework ships with translatable error messages. You can make these +appear in your language enabling [Django's standard translation +mechanisms][django-translation]. Doing so will allow you to: -* Select a language other than English as the default, using the standard `LANGUAGE_CODE` Django setting. -* Allow clients to choose a language themselves, using the `LocaleMiddleware` included with Django. A typical usage for API clients would be to include an `Accept-Language` request header. +* Select a language other than English as the default, using the standard + `LANGUAGE_CODE` Django setting. +* Allow clients to choose a language themselves, using the `LocaleMiddleware` + included with Django. A typical usage for API clients would be to include an + `Accept-Language` request header. ## Enabling internationalized APIs -You can change the default language by using the standard Django `LANGUAGE_CODE` setting: +You can change the default language by using the standard Django +`LANGUAGE_CODE` setting: LANGUAGE_CODE = "es-es" -You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting: +You can turn on per-request language requests by adding `LocalMiddleware` to +your `MIDDLEWARE_CLASSES` setting: MIDDLEWARE_CLASSES = [ ... 'django.middleware.locale.LocaleMiddleware' ] -When per-request internationalization is enabled, client requests will respect the `Accept-Language` header where possible. For example, let's make a request for an unsupported media type: +When per-request internationalization is enabled, client requests will respect +the `Accept-Language` header where possible. For example, let's make a request +for an unsupported media type: **Request** @@ -39,19 +48,25 @@ When per-request internationalization is enabled, client requests will respect t {"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."} -REST framework includes these built-in translations both for standard exception cases, and for serializer validation errors. +REST framework includes these built-in translations both for standard exception +cases, and for serializer validation errors. -Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example `400 Bad Request` response body might look like this: +Note that the translations only apply to the error strings themselves. The +format of error messages, and the keys of field names will remain the same. An +example `400 Bad Request` response body might look like this: {"detail": {"username": ["Esse campo deve ser unico."]}} -If you want to use different string for parts of the response such as `detail` and `non_field_errors` then you can modify this behavior by using a [custom exception handler][custom-exception-handler]. +If you want to use different string for parts of the response such as `detail` +and `non_field_errors` then you can modify this behavior by using a [custom +exception handler][custom-exception-handler]. #### Specifying the set of supported languages. By default all available languages will be supported. -If you only wish to support a subset of the available languages, use Django's standard `LANGUAGES` setting: +If you only wish to support a subset of the available languages, use Django's +standard `LANGUAGES` setting: LANGUAGES = [ ('de', _('German')), @@ -60,53 +75,80 @@ If you only wish to support a subset of the available languages, use Django's st ## Adding new translations -REST framework translations are managed online using [Transifex][transifex-project]. You can use the Transifex service to add new translation languages. The maintenance team will then ensure that these translation strings are included in the REST framework package. +REST framework translations are managed online using +[Transifex][transifex-project]. You can use the Transifex service to add new +translation languages. The maintenance team will then ensure that these +translation strings are included in the REST framework package. -Sometimes you may need to add translation strings to your project locally. You may need to do this if: +Sometimes you may need to add translation strings to your project locally. You +may need to do this if: -* You want to use REST Framework in a language which has not been translated yet on Transifex. -* Your project includes custom error messages, which are not part of REST framework's default translation strings. +* You want to use REST Framework in a language which has not been translated + yet on Transifex. +* Your project includes custom error messages, which are not part of REST + framework's default translation strings. #### Translating a new language locally -This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading [Django's translation docs][django-translation]. +This guide assumes you are already familiar with how to translate a Django app. +If you're not, start by reading [Django's translation +docs][django-translation]. -If you're translating a new language you'll need to translate the existing REST framework error messages: +If you're translating a new language you'll need to translate the existing REST +framework error messages: -1. Make a new folder where you want to store the internationalization resources. Add this path to your [`LOCALE_PATHS`][django-locale-paths] setting. +1. Make a new folder where you want to store the internationalization +resources. Add this path to your [`LOCALE_PATHS`][django-locale-paths] setting. -2. Now create a subfolder for the language you want to translate. The folder should be named using [locale name][django-locale-name] notation. For example: `de`, `pt_BR`, `es_AR`. +2. Now create a subfolder for the language you want to translate. The folder +should be named using [locale name][django-locale-name] notation. For example: +`de`, `pt_BR`, `es_AR`. -3. Now copy the [base translations file][django-po-source] from the REST framework source code into your translations folder. +3. Now copy the [base translations file][django-po-source] from the REST +framework source code into your translations folder. -4. Edit the `django.po` file you've just copied, translating all the error messages. +4. Edit the `django.po` file you've just copied, translating all the error +messages. -5. Run `manage.py compilemessages -l pt_BR` to make the translations -available for Django to use. You should see a message like `processing file django.po in <...>/locale/pt_BR/LC_MESSAGES`. +5. Run `manage.py compilemessages -l pt_BR` to make the translations available +for Django to use. You should see a message like `processing file django.po in + <...>/locale/pt_BR/LC_MESSAGES`. 6. Restart your development server to see the changes take effect. -If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source `django.po` file into a `LOCALE_PATHS` folder, and can instead simply run Django's standard `makemessages` process. +If you're only translating custom error messages that exist inside your project +codebase you don't need to copy the REST framework source `django.po` file into +a `LOCALE_PATHS` folder, and can instead simply run Django's standard +`makemessages` process. ## How the language is determined -If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` setting. +If you want to allow per-request language preferences you'll need to include +`django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE_CLASSES` +setting. -You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is: +You can find more information on how the language preference is determined in +the [Django documentation][django-language-preference]. For reference, the +method is: 1. First, it looks for the language prefix in the requested URL. -2. Failing that, it looks for the `LANGUAGE_SESSION_KEY` key in the current user’s session. +2. Failing that, it looks for the `LANGUAGE_SESSION_KEY` key in the current +user’s session. 3. Failing that, it looks for a cookie. 4. Failing that, it looks at the `Accept-Language` HTTP header. 5. Failing that, it uses the global `LANGUAGE_CODE` setting. -For API clients the most appropriate of these will typically be to use the `Accept-Language` header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an `Accept-Language` header for API clients rather than using language URL prefixes. +For API clients the most appropriate of these will typically be to use the +`Accept-Language` header; Sessions and cookies will not be available unless +using session authentication, and generally better practice to prefer an +`Accept-Language` header for API clients rather than using language URL +prefixes. [cite]: http://youtu.be/Wa0VfS2q94Y [django-translation]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation [custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling [transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/ -[django-po-source]: https://raw.githubusercontent.com/tomchristie/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po +[django-po-source]: https://raw.githubusercontent.com/tomchristie/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po [django-language-preference]: https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#how-django-discovers-language-preference [django-locale-paths]: https://docs.djangoproject.com/en/1.7/ref/settings/#std:setting-LOCALE_PATHS [django-locale-name]: https://docs.djangoproject.com/en/1.7/topics/i18n/#term-locale-name diff --git a/docs/topics/kickstarter-announcement.md b/docs/topics/kickstarter-announcement.md index 78c5cce6f..21e1e5c81 100644 --- a/docs/topics/kickstarter-announcement.md +++ b/docs/topics/kickstarter-announcement.md @@ -6,11 +6,14 @@ --- -In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3. +In order to continue to drive the project forward, I'm launching a Kickstarter +campaign to help fund the development of a major new release - Django REST +framework 3. ## Project details -This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following: +This new release will allow us to comprehensively address some of the +shortcomings of the framework, and will aim to include the following: * Faster, simpler and easier-to-use serializers. * An alternative admin-style interface for the browsable API. @@ -20,9 +23,13 @@ This new release will allow us to comprehensively address some of the shortcomin * Triage of outstanding tickets. * Improving the ongoing quality and maintainability of the project. -Full details are available now on the [project page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3). +Full details are available now on the [project +page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3). -If you're interested in helping make sustainable open source development a reality please [visit the Kickstarter page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) and consider funding the project. +If you're interested in helping make sustainable open source development a +reality please [visit the Kickstarter +page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) +and consider funding the project. I can't wait to see where this takes us! @@ -34,13 +41,19 @@ Many thanks to everyone for your support so far, ## Sponsors -We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible. +We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), +meaning I'll be in a position to work on the project significantly beyond what +we'd originally planned for. I owe a huge debt of gratitude to all the +wonderful companies and individuals who have been backing the project so +generously, and making this possible. --- ### Platinum sponsors -Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough. +Our platinum sponsors have each made a hugely substantial contribution to the +future development of Django REST framework, and I simply can't thank them +enough.