aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJosé Padilla2014-11-28 12:14:40 -0400
committerJosé Padilla2014-11-28 12:14:40 -0400
commit0cc990792c63caa8fa8fea62cea53b0d28157b55 (patch)
tree7ea80a203cc8718150cd55e4403f3f4771160281
parent1aa77830955dcdf829f65a9001b6b8900dfc8755 (diff)
parent3a5b3772fefc3c2f2c0899947cbc07bfe6e6b5d2 (diff)
downloaddjango-rest-framework-0cc990792c63caa8fa8fea62cea53b0d28157b55.tar.bz2
Merge branch 'version-3.1' into oauth_as_package
Conflicts: requirements-test.txt rest_framework/compat.py tests/settings.py tox.ini
-rw-r--r--.gitignore2
-rw-r--r--.travis.yml51
-rw-r--r--CONTRIBUTING.md10
-rw-r--r--MANIFEST.in2
-rw-r--r--README.md15
-rw-r--r--docs/CNAME1
-rwxr-xr-xdocs/api-guide/authentication.md19
-rw-r--r--docs/api-guide/content-negotiation.md6
-rw-r--r--docs/api-guide/exceptions.md24
-rw-r--r--docs/api-guide/fields.md422
-rw-r--r--docs/api-guide/filtering.md24
-rw-r--r--docs/api-guide/format-suffixes.md25
-rwxr-xr-xdocs/api-guide/generic-views.md56
-rw-r--r--docs/api-guide/metadata.md109
-rw-r--r--docs/api-guide/pagination.md6
-rw-r--r--docs/api-guide/parsers.md22
-rw-r--r--docs/api-guide/permissions.md22
-rw-r--r--docs/api-guide/relations.md141
-rw-r--r--docs/api-guide/renderers.md16
-rw-r--r--docs/api-guide/requests.md49
-rw-r--r--docs/api-guide/responses.md4
-rw-r--r--docs/api-guide/reverse.md4
-rw-r--r--docs/api-guide/routers.md8
-rw-r--r--docs/api-guide/serializers.md797
-rw-r--r--docs/api-guide/settings.md18
-rw-r--r--docs/api-guide/status-codes.md6
-rw-r--r--docs/api-guide/testing.md6
-rw-r--r--docs/api-guide/throttling.md14
-rw-r--r--docs/api-guide/validators.md231
-rw-r--r--docs/api-guide/views.md7
-rw-r--r--docs/api-guide/viewsets.md4
-rw-r--r--docs/css/default.css16
-rw-r--r--docs/index.md19
-rw-r--r--docs/requirements.txt1
-rw-r--r--docs/template.html238
-rw-r--r--docs/topics/2.2-announcement.md8
-rw-r--r--docs/topics/2.3-announcement.md14
-rw-r--r--docs/topics/2.4-announcement.md6
-rw-r--r--docs/topics/3.0-announcement.md768
-rw-r--r--docs/topics/ajax-csrf-cors.md6
-rw-r--r--docs/topics/browsable-api.md33
-rw-r--r--docs/topics/contributing.md57
-rw-r--r--docs/topics/documenting-your-api.md8
-rw-r--r--docs/topics/kickstarter-announcement.md144
-rw-r--r--docs/topics/release-notes.md159
-rw-r--r--docs/topics/rest-framework-2-announcement.md4
-rw-r--r--docs/topics/rest-hypermedia-hateoas.md12
-rw-r--r--docs/topics/third-party-resources.md331
-rw-r--r--docs/topics/writable-nested-serializers.md12
-rw-r--r--docs/tutorial/1-serialization.md94
-rw-r--r--docs/tutorial/2-requests-and-responses.md21
-rw-r--r--docs/tutorial/3-class-based-views.md8
-rw-r--r--docs/tutorial/4-authentication-and-permissions.md22
-rw-r--r--docs/tutorial/5-relationships-and-hyperlinked-apis.md11
-rw-r--r--docs/tutorial/6-viewsets-and-routers.md14
-rw-r--r--docs/tutorial/quickstart.md10
-rw-r--r--docs_theme/404.html (renamed from docs/404.html)211
-rw-r--r--docs_theme/base.html196
-rw-r--r--docs_theme/nav.html47
-rwxr-xr-xmkdocs.py202
-rw-r--r--mkdocs.yml55
-rw-r--r--rest_framework/__init__.py2
-rw-r--r--rest_framework/authentication.py2
-rw-r--r--rest_framework/authtoken/serializers.py8
-rw-r--r--rest_framework/authtoken/views.py14
-rw-r--r--rest_framework/compat.py94
-rw-r--r--rest_framework/exceptions.py97
-rw-r--r--rest_framework/fields.py794
-rw-r--r--rest_framework/filters.py11
-rw-r--r--rest_framework/generics.py60
-rw-r--r--rest_framework/metadata.py131
-rw-r--r--rest_framework/mixins.py65
-rw-r--r--rest_framework/negotiation.py4
-rw-r--r--rest_framework/pagination.py1
-rw-r--r--rest_framework/parsers.py3
-rw-r--r--rest_framework/relations.py154
-rw-r--r--rest_framework/renderers.py196
-rw-r--r--rest_framework/request.py59
-rw-r--r--rest_framework/response.py4
-rw-r--r--rest_framework/reverse.py3
-rw-r--r--rest_framework/routers.py5
-rw-r--r--rest_framework/serializers.py701
-rw-r--r--rest_framework/settings.py5
-rw-r--r--rest_framework/static/rest_framework/css/bootstrap-tweaks.css24
-rw-r--r--rest_framework/static/rest_framework/css/bootstrap.min.css844
-rw-r--r--rest_framework/static/rest_framework/css/default.css7
-rw-r--r--rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.eotbin0 -> 20335 bytes
-rw-r--r--rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg229
-rw-r--r--rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.ttfbin0 -> 41280 bytes
-rw-r--r--rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.woffbin0 -> 23320 bytes
-rw-r--r--rest_framework/static/rest_framework/js/bootstrap.min.js13
-rw-r--r--rest_framework/templates/rest_framework/api_form.html8
-rw-r--r--rest_framework/templates/rest_framework/base.html80
-rw-r--r--rest_framework/templates/rest_framework/form.html15
-rw-r--r--rest_framework/templates/rest_framework/horizontal/checkbox.html16
-rw-r--r--rest_framework/templates/rest_framework/horizontal/checkbox_multiple.html30
-rw-r--r--rest_framework/templates/rest_framework/horizontal/fieldset.html13
-rw-r--r--rest_framework/templates/rest_framework/horizontal/form.html15
-rw-r--r--rest_framework/templates/rest_framework/horizontal/input.html14
-rw-r--r--rest_framework/templates/rest_framework/horizontal/list_fieldset.html16
-rw-r--r--rest_framework/templates/rest_framework/horizontal/radio.html30
-rw-r--r--rest_framework/templates/rest_framework/horizontal/select.html21
-rw-r--r--rest_framework/templates/rest_framework/horizontal/select_multiple.html18
-rw-r--r--rest_framework/templates/rest_framework/horizontal/textarea.html14
-rw-r--r--rest_framework/templates/rest_framework/inline/checkbox.html8
-rw-r--r--rest_framework/templates/rest_framework/inline/checkbox_multiple.html13
-rw-r--r--rest_framework/templates/rest_framework/inline/fieldset.html6
-rw-r--r--rest_framework/templates/rest_framework/inline/form.html11
-rw-r--r--rest_framework/templates/rest_framework/inline/input.html6
-rw-r--r--rest_framework/templates/rest_framework/inline/list_fieldset.html1
-rw-r--r--rest_framework/templates/rest_framework/inline/radio.html13
-rw-r--r--rest_framework/templates/rest_framework/inline/select.html13
-rw-r--r--rest_framework/templates/rest_framework/inline/select_multiple.html10
-rw-r--r--rest_framework/templates/rest_framework/inline/textarea.html6
-rw-r--r--rest_framework/templates/rest_framework/login_base.html9
-rw-r--r--rest_framework/templates/rest_framework/vertical/checkbox.html14
-rw-r--r--rest_framework/templates/rest_framework/vertical/checkbox_multiple.html30
-rw-r--r--rest_framework/templates/rest_framework/vertical/fieldset.html9
-rw-r--r--rest_framework/templates/rest_framework/vertical/form.html11
-rw-r--r--rest_framework/templates/rest_framework/vertical/input.html12
-rw-r--r--rest_framework/templates/rest_framework/vertical/list_fieldset.html8
-rw-r--r--rest_framework/templates/rest_framework/vertical/radio.html30
-rw-r--r--rest_framework/templates/rest_framework/vertical/select.html19
-rw-r--r--rest_framework/templates/rest_framework/vertical/select_multiple.html16
-rw-r--r--rest_framework/templates/rest_framework/vertical/textarea.html12
-rw-r--r--rest_framework/templatetags/rest_framework.py10
-rw-r--r--rest_framework/test.py46
-rw-r--r--rest_framework/utils/encoders.py21
-rw-r--r--rest_framework/utils/field_mapping.py114
-rw-r--r--rest_framework/utils/html.py8
-rw-r--r--rest_framework/utils/model_meta.py23
-rw-r--r--rest_framework/utils/representation.py10
-rw-r--r--rest_framework/utils/serializer_helpers.py102
-rw-r--r--rest_framework/validators.py254
-rw-r--r--rest_framework/views.py53
-rw-r--r--tests/accounts/__init__.py0
-rw-r--r--tests/accounts/models.py8
-rw-r--r--tests/accounts/serializers.py11
-rw-r--r--tests/conftest.py3
-rw-r--r--tests/put_as_create_workspace.txt33
-rw-r--r--tests/records/__init__.py0
-rw-r--r--tests/records/models.py6
-rw-r--r--tests/settings.py144
-rw-r--r--tests/test_authentication.py2
-rw-r--r--tests/test_bound_fields.py69
-rw-r--r--tests/test_fields.py2070
-rw-r--r--tests/test_files.py92
-rw-r--r--tests/test_genericrelations.py151
-rw-r--r--tests/test_generics.py182
-rw-r--r--tests/test_hyperlinkedserializers.py406
-rw-r--r--tests/test_metadata.py166
-rw-r--r--tests/test_model_serializer.py89
-rw-r--r--tests/test_modelinfo.py31
-rw-r--r--tests/test_nullable_fields.py39
-rw-r--r--tests/test_permissions.py106
-rw-r--r--tests/test_relations.py178
-rw-r--r--tests/test_relations_generic.py104
-rw-r--r--tests/test_relations_hyperlink.py958
-rw-r--r--tests/test_relations_nested.py326
-rw-r--r--tests/test_relations_pk.py969
-rw-r--r--tests/test_relations_slug.py525
-rw-r--r--tests/test_renderers.py9
-rw-r--r--tests/test_request.py95
-rw-r--r--tests/test_response.py4
-rw-r--r--tests/test_serializer.py2181
-rw-r--r--tests/test_serializer_bulk_update.py401
-rw-r--r--tests/test_serializer_empty.py15
-rw-r--r--tests/test_serializer_import.py19
-rw-r--r--tests/test_serializer_lists.py274
-rw-r--r--tests/test_serializer_nested.py389
-rw-r--r--tests/test_templatetags.py35
-rw-r--r--tests/test_testing.py47
-rw-r--r--tests/test_urlizer.py37
-rw-r--r--tests/test_utils.py (renamed from tests/test_breadcrumbs.py)72
-rw-r--r--tests/test_validation.py39
-rw-r--r--tests/test_validators.py273
-rw-r--r--tests/users/__init__.py0
-rw-r--r--tests/users/models.py6
-rw-r--r--tests/users/serializers.py8
-rw-r--r--tox.ini166
180 files changed, 10102 insertions, 10202 deletions
diff --git a/.gitignore b/.gitignore
index ae73f837..2bdf8f7e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,7 +3,7 @@
*~
.*
-html/
+site/
htmlcov/
coverage/
build/
diff --git a/.travis.yml b/.travis.yml
index a5b6d7d9..6191e7e2 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,28 +1,41 @@
language: python
-python: 2.7
+sudo: false
env:
- - TOX_ENV=flake8
- - TOX_ENV=py3.4-django1.7
- - TOX_ENV=py3.3-django1.7
- - TOX_ENV=py3.2-django1.7
- - TOX_ENV=py2.7-django1.7
- - TOX_ENV=py3.4-django1.6
- - TOX_ENV=py3.3-django1.6
- - TOX_ENV=py3.2-django1.6
- - TOX_ENV=py2.7-django1.6
- - TOX_ENV=py2.6-django1.6
- - TOX_ENV=py3.4-django1.5
- - TOX_ENV=py3.3-django1.5
- - TOX_ENV=py3.2-django1.5
- - TOX_ENV=py2.7-django1.5
- - TOX_ENV=py2.6-django1.5
- - TOX_ENV=py2.7-django1.4
- - TOX_ENV=py2.6-django1.4
+ - TOX_ENV=py27-flake8
+ - TOX_ENV=py27-docs
+ - TOX_ENV=py34-django17
+ - TOX_ENV=py33-django17
+ - TOX_ENV=py32-django17
+ - TOX_ENV=py27-django17
+ - TOX_ENV=py34-django16
+ - TOX_ENV=py33-django16
+ - TOX_ENV=py32-django16
+ - TOX_ENV=py27-django16
+ - TOX_ENV=py26-django16
+ - TOX_ENV=py34-django15
+ - TOX_ENV=py33-django15
+ - TOX_ENV=py32-django15
+ - TOX_ENV=py27-django15
+ - TOX_ENV=py26-django15
+ - TOX_ENV=py27-django14
+ - TOX_ENV=py26-django14
+ - TOX_ENV=py34-djangomaster
+ - TOX_ENV=py33-djangomaster
+ - TOX_ENV=py32-djangomaster
+ - TOX_ENV=py27-djangomaster
+
+matrix:
+ fast_finish: true
+ allow_failures:
+ - env: TOX_ENV=py34-djangomaster
+ - env: TOX_ENV=py33-djangomaster
+ - env: TOX_ENV=py32-djangomaster
+ - env: TOX_ENV=py27-djangomaster
install:
- - "pip install tox --download-cache $HOME/.pip-cache"
+ - pip install tox
script:
- tox -e $TOX_ENV
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index a6dd05a0..69802995 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -75,7 +75,7 @@ You can also use the excellent [`tox`][tox] testing tool to run the tests agains
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
-It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another seperate issue without interfering with an ongoing pull requests.
+It's also 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.
@@ -101,15 +101,15 @@ There are many great markdown editors that make working with the documentation r
## Building the documentation
-To build the documentation, simply run the `mkdocs.py` script.
+To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
- ./mkdocs.py
+ mkdocs build
This will build the html output into the `html` directory.
-You can build the documentation and open a preview in a browser window by using the `-p` flag.
+You can build the documentation and open a preview in a browser window by using the `serve` command.
- ./mkdocs.py -p
+ mkdocs serve
## Language style
diff --git a/MANIFEST.in b/MANIFEST.in
index d407865f..d202c86e 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,4 +1,4 @@
-recursive-include rest_framework/static *.js *.css *.png
+recursive-include rest_framework/static *.js *.css *.png *.eot *.svg *.ttf *.woff
recursive-include rest_framework/templates *.html
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
diff --git a/README.md b/README.md
index ebc83bf5..5d0306bb 100644
--- a/README.md
+++ b/README.md
@@ -1,10 +1,17 @@
# Django REST framework
[![build-status-image]][travis]
+[![pypi-version]][pypi]
**Awesome web-browseable Web APIs.**
-**Note**: Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
+Full documentation for the project is available at [http://www.django-rest-framework.org][docs].
+
+---
+
+**Note**: The incoming 3.0 version has now been merged to the `master` branch on GitHub. For the source of the currently available PyPI version, please see the `2.4.4` tag.
+
+---
# Overview
@@ -26,8 +33,8 @@ There is a live example API for testing purposes, [available here][sandbox].
# Requirements
-* Python (2.6.5+, 2.7, 3.2, 3.3)
-* Django (1.4.2+, 1.5, 1.6, 1.7)
+* Python (2.6.5+, 2.7, 3.2, 3.3, 3.4)
+* Django (1.4.11+, 1.5.5+, 1.6, 1.7)
# Installation
@@ -175,6 +182,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
[travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
+[pypi-version]: https://pypip.in/version/djangorestframework/badge.svg
+[pypi]: https://pypi.python.org/pypi/djangorestframework
[twitter]: https://twitter.com/_tomchristie
[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
[0.4]: https://github.com/tomchristie/django-rest-framework/tree/0.4.X
diff --git a/docs/CNAME b/docs/CNAME
new file mode 100644
index 00000000..4e332899
--- /dev/null
+++ b/docs/CNAME
@@ -0,0 +1 @@
+www.django-rest-framework.org
diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md
index 3d4e0f72..2074f1bf 100755
--- a/docs/api-guide/authentication.md
+++ b/docs/api-guide/authentication.md
@@ -1,4 +1,4 @@
-<a class="github" href="authentication.py"></a>
+source: authentication.py
# Authentication
@@ -168,12 +168,13 @@ The `curl` command line tool may be useful for testing token authenticated APIs.
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.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
- @receiver(post_save, sender=get_user_model())
+ @receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
@@ -190,9 +191,10 @@ If you've already created some users, you can generate tokens for all existing u
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:
- urlpatterns += patterns('',
- url(r'^api-token-auth/', 'rest_framework.authtoken.views.obtain_auth_token')
- )
+ from rest_framework.authtoken import views
+ urlpatterns += [
+ url(r'^api-token-auth/', views.obtain_auth_token)
+ ]
Note that the URL part of the pattern can be whatever you want to use.
@@ -297,7 +299,7 @@ HTTP digest authentication is a widely implemented scheme that was intended to r
## 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 excelllent [OAuthLib][oauthlib]. The package is well documented, and comes as a recommended alternative 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 comes as a recommended alternative for OAuth 2.0 support.
## Django OAuth2 Consumer
@@ -315,6 +317,10 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y
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.
+
[cite]: http://jacobian.org/writing/rest-worst-practices/
[http401]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2
[http403]: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4
@@ -349,3 +355,4 @@ HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a
[hawk]: https://github.com/hueniverse/hawk
[mohawk]: http://mohawk.readthedocs.org/en/latest/
[mac]: http://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05
+[djoser]: https://github.com/sunscrapers/djoser
diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md
index 94dd59ca..bc3b09fb 100644
--- a/docs/api-guide/content-negotiation.md
+++ b/docs/api-guide/content-negotiation.md
@@ -1,4 +1,4 @@
-<a class="github" href="negotiation.py"></a>
+source: negotiation.py
# Content negotiation
@@ -29,7 +29,7 @@ The priorities for each of the given media types would be:
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]
+For more information on the `HTTP Accept` header, see [RFC 2616][accept-header]
---
@@ -62,7 +62,7 @@ request when selecting the appropriate parser or renderer.
Select the first parser in the `.parser_classes` list.
"""
return parsers[0]
-
+
def select_renderer(self, request, renderers, format_suffix):
"""
Select the first renderer in the `.renderer_classes` list.
diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md
index e61dcfa9..467ad970 100644
--- a/docs/api-guide/exceptions.md
+++ b/docs/api-guide/exceptions.md
@@ -1,4 +1,4 @@
-<a class="github" href="exceptions.py"></a>
+source: exceptions.py
# Exceptions
@@ -100,7 +100,7 @@ For example, if your API relies on a third party service that may sometimes be u
**Signature:** `ParseError(detail=None)`
-Raised if the request contains malformed data when accessing `request.DATA` or `request.FILES`.
+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".
@@ -140,7 +140,7 @@ By default this exception results in a response with the HTTP status code "405 M
**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` or `request.FILES`.
+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".
@@ -152,5 +152,23 @@ 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".
+## ValidationError
+
+**Signature:** `ValidationError(detail)`
+
+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 `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.
+
+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 f0778318..391a52e5 100644
--- a/docs/api-guide/fields.md
+++ b/docs/api-guide/fields.md
@@ -1,4 +1,10 @@
-<a class="github" href="fields.py"></a>
+source: fields.py
+
+---
+
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
# Serializer fields
@@ -10,7 +16,7 @@ Serializer fields handle converting between primitive values and internal dataty
---
-**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.<FieldName>`.
+**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.<FieldName>`.
---
@@ -18,14 +24,6 @@ Serializer fields handle converting between primitive values and internal dataty
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:
-### `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 `Field(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `Field(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. (See the implementation of the `PaginationSerializer` class for an example.)
-
-Defaults to the name of the field.
-
### `read_only`
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.
@@ -45,25 +43,36 @@ Set to false if this field is not required to be present during deserialization.
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.
+
+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 behavior is to not populate the attribute at all.
May be set to a function or other callable, in which case the value will be evaluated each time it is used.
+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('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.
+
+Defaults to the name of the field.
+
### `validators`
-A list of Django validators that should be used to validate deserialized values.
+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`
A dictionary of error codes to error messages.
-### `widget`
-
-Used only if rendering the field to HTML.
-This argument sets the widget that should be used to render the field. For more details, and a list of available widgets, see [the Django documentation on form widgets][django-widgets].
-
### `label`
A short text string that may be used as the name of the field in HTML form fields or other descriptive elements.
@@ -72,165 +81,191 @@ A short text string that may be used as the name of the field in HTML form field
A text string that may be used as a description of the field in HTML form fields or other descriptive elements.
----
+### `initial`
-# Generic Fields
+A value that should be used for pre-populating the value of HTML form fields.
-These generic fields are used for representing arbitrary model fields or the output of model methods.
+### `style`
-## Field
+A dictionary of key-value pairs that can be used to control how renderers should render the field. The API for this should still be considered experimental, and will be formalized with the 3.1 release.
-A generic, **read-only** field. You can use this field for any attribute that does not need to support write operations.
+Two options are currently used in HTML form generation, `'input_type'` and `'base_template'`.
-For example, using the following model.
+ # Use <input type="password"> for the input.
+ password = serializers.CharField(
+ style={'input_type': 'password'}
+ )
- from django.db import models
- from django.utils.timezone import now
+ # Use a radio input instead of a select input.
+ color_channel = serializers.ChoiceField(
+ choices=['red', 'green', 'blue']
+ style = {'base_template': 'radio.html'}
+ }
- class Account(models.Model):
- owner = models.ForeignKey('auth.user')
- name = models.CharField(max_length=100)
- created = models.DateTimeField(auto_now_add=True)
- payment_expiry = models.DateTimeField()
+**Note**: The `style` argument replaces the old-style version 2.x `widget` keyword argument. Because REST framework 3 now uses templated HTML form generation, the `widget` option that was used to support Django built-in widgets can no longer be supported. Version 3.1 is planned to include public API support for customizing HTML form generation.
- def has_expired(self):
- return now() > self.payment_expiry
+---
-A serializer definition that looked like this:
+# Boolean fields
- from rest_framework import serializers
+## BooleanField
- class AccountSerializer(serializers.HyperlinkedModelSerializer):
- expired = serializers.Field(source='has_expired')
+A boolean representation.
- class Meta:
- model = Account
- fields = ('url', 'owner', 'name', 'expired')
+Corresponds to `django.db.models.fields.BooleanField`.
-Would produce output similar to:
+**Signature:** `BooleanField()`
- {
- 'url': 'http://example.com/api/accounts/3/',
- 'owner': 'http://example.com/api/users/12/',
- 'name': 'FooCorp business account',
- 'expired': True
- }
+## NullBooleanField
-By default, the `Field` class will perform a basic translation of the source value into primitive datatypes, falling back to unicode representations of complex datatypes when necessary.
+A boolean representation that also accepts `None` as a valid value.
-You can customize this behavior by overriding the `.to_native(self, value)` method.
+Corresponds to `django.db.models.fields.NullBooleanField`.
-## WritableField
+**Signature:** `NullBooleanField()`
-A field that supports both read and write operations. By itself `WritableField` does not perform any translation of input values into a given type. You won't typically use this field directly, but you may want to override it and implement the `.to_native(self, value)` and `.from_native(self, value)` methods.
+---
-## ModelField
+# String fields
-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.
+## CharField
-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'))`
+A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`.
-**Signature:** `ModelField(model_field=<Django ModelField instance>)`
+Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`.
-## SerializerMethodField
+**Signature:** `CharField(max_length=None, min_length=None, allow_blank=False)`
-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. The field's constructor accepts a single argument, which is the name of the method on the serializer to be called. The method 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:
+- `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`.
- from django.contrib.auth.models import User
- from django.utils.timezone import now
- from rest_framework import serializers
+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.
- class UserSerializer(serializers.ModelSerializer):
- days_since_joined = serializers.SerializerMethodField('get_days_since_joined')
+## EmailField
- class Meta:
- model = User
+A text representation, validates the text to be a valid e-mail address.
- def get_days_since_joined(self, obj):
- return (now() - obj.date_joined).days
+Corresponds to `django.db.models.fields.EmailField`
----
+**Signature:** `EmailField(max_length=None, min_length=None, allow_blank=False)`
-# Typed Fields
+## RegexField
-These fields represent basic datatypes, and support both reading and writing values.
+A text representation, that validates the given value matches against a certain regular expression.
-## BooleanField
+Corresponds to `django.forms.fields.RegexField`.
-A Boolean representation.
+**Signature:** `RegexField(regex, max_length=None, min_length=None, allow_blank=False)`
-Corresponds to `django.db.models.fields.BooleanField`.
+The mandatory `regex` argument may either be a string, or a compiled python regular expression object.
-## CharField
+Uses Django's `django.core.validators.RegexValidator` for validation.
+
+## SlugField
-A text representation, optionally validates the text to be shorter than `max_length` and longer than `min_length`.
-If `allow_none` is `False` (default), `None` values will be converted to an empty string.
+A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`.
-Corresponds to `django.db.models.fields.CharField`
-or `django.db.models.fields.TextField`.
+Corresponds to `django.db.models.fields.SlugField`.
-**Signature:** `CharField(max_length=None, min_length=None, allow_none=False)`
+**Signature:** `SlugField(max_length=50, min_length=None, allow_blank=False)`
## URLField
+A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http://<host>/<path>`.
+
Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation.
-**Signature:** `URLField(max_length=200, min_length=None)`
+**Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)`
-## SlugField
+---
-Corresponds to `django.db.models.fields.SlugField`.
+# Numeric fields
-**Signature:** `SlugField(max_length=50, min_length=None)`
+## IntegerField
-## ChoiceField
+An integer representation.
-A field that can accept a value out of a limited set of choices. Optionally takes a `blank_display_value` parameter that customizes the display value of an empty choice.
+Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`.
-**Signature:** `ChoiceField(choices=(), blank_display_value=None)`
+**Signature**: `IntegerField(max_value=None, min_value=None)`
-## EmailField
+- `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.
-A text representation, validates the text to be a valid e-mail address.
+## FloatField
-Corresponds to `django.db.models.fields.EmailField`
+A floating point representation.
-## RegexField
+Corresponds to `django.db.models.fields.FloatField`.
-A text representation, that validates the given value matches against a certain regular expression.
+**Signature**: `FloatField(max_value=None, min_value=None)`
-Uses Django's `django.core.validators.RegexValidator` for validation.
+- `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.
+
+## DecimalField
+
+A decimal representation, represented in Python by a `Decimal` instance.
+
+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.
+- `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.
+- `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.
+
+#### Example usage
-Corresponds to `django.forms.fields.RegexField`
+To validate numbers up to 999 with a resolution of 2 decimal places, you would use:
-**Signature:** `RegexField(regex, max_length=None, min_length=None)`
+ serializers.DecimalField(max_digits=5, decimal_places=2)
+
+And to validate numbers up to anything less than one billion with a resolution of 10 decimal places:
+
+ serializers.DecimalField(max_digits=19, decimal_places=10)
+
+This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
+
+If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
+
+---
+
+# Date and time fields
## DateTimeField
A date and time representation.
-Corresponds to `django.db.models.fields.DateTimeField`
+Corresponds to `django.db.models.fields.DateTimeField`.
-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.
+**Signature:** `DateTimeField(format=None, input_formats=None)`
-If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example:
+* `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']`.
- class CommentSerializer(serializers.ModelSerializer):
- created = serializers.DateTimeField()
+#### `DateTimeField` format strings.
- class Meta:
- model = Comment
+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'`)
-Note that by default, datetime representations are determined by the renderer in use, although this can be explicitly overridden as detailed below.
+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`.
-**Signature:** `DateTimeField(format=None, input_formats=None)`
+#### `auto_now` and `auto_now_add` model fields.
-* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that Python `datetime` objects should be returned by `to_native`. 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']`.
+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.
-DateTime 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'`)
+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()
+
+ class Meta:
+ model = Comment
## DateField
@@ -240,63 +275,58 @@ Corresponds to `django.db.models.fields.DateField`
**Signature:** `DateField(format=None, input_formats=None)`
-* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that Python `date` objects should be returned by `to_native`. In this case the date encoding will be determined by the renderer.
+* `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']`.
-Date 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'`)
+#### `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'`)
## TimeField
A time representation.
-Optionally takes `format` as parameter to replace the matching pattern.
-
Corresponds to `django.db.models.fields.TimeField`
**Signature:** `TimeField(format=None, input_formats=None)`
-* `format` - A string representing the output format. If not specified, this defaults to `None`, which indicates that Python `time` objects should be returned by `to_native`. In this case the time encoding will be determined by the renderer.
+* `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']`.
-Time 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'`)
+#### `TimeField` format strings
-## IntegerField
-
-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`
-
-## FloatField
+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'`)
-A floating point representation.
+---
-Corresponds to `django.db.models.fields.FloatField`.
+# Choice selection fields
-## DecimalField
+## ChoiceField
-A decimal representation, represented in Python by a Decimal instance.
+A field that can accept a value out of a limited set of choices.
-Has two required arguments:
+Used by `ModelSerializer` to automatically generate fields if the corresponding model field includes a `choices=…` argument.
-- `max_digits` The maximum number of digits allowed in the number. Note that this number must be greater than or equal to decimal_places.
+**Signature:** `ChoiceField(choices)`
-- `decimal_places` The number of decimal places to store with the number.
+- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
-For example, to validate numbers up to 999 with a resolution of 2 decimal places, you would use:
+## MultipleChoiceField
- serializers.DecimalField(max_digits=5, decimal_places=2)
+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_representation` returns a `set` containing the selected values.
-And to validate numbers up to anything lesss than one billion with a resolution of 10 decimal places:
+**Signature:** `MultipleChoiceField(choices)`
- serializers.DecimalField(max_digits=19, decimal_places=10)
+- `choices` - A list of valid values, or a list of `(key, display_name)` tuples.
-This field also takes an optional argument, `coerce_to_string`. If set to `True` the representation will be output as a string. If set to `False` the representation will be left as a `Decimal` instance and the final representation will be determined by the renderer.
+---
-If unset, this will default to the same value as the `COERCE_DECIMAL_TO_STRING` setting, which is `True` unless set otherwise.
+# File upload fields
-**Signature:** `DecimalField(max_digits, decimal_places, coerce_to_string=None)`
+#### Parsers and file uploads.
-Corresponds to `django.db.models.fields.DecimalField`.
+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
@@ -304,34 +334,128 @@ A file representation. Performs Django's standard FileField validation.
Corresponds to `django.forms.fields.FileField`.
-**Signature:** `FileField(max_length=None, allow_empty_file=False)`
-
- - `max_length` designates the maximum length for the file name.
+**Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)`
- - `allow_empty_file` designates if empty files are allowed.
+ - `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.
## ImageField
-An image representation.
+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)`
+
+ - `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.
+
Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained.
-Signature and validation is the same as with `FileField`.
+---
+
+# Composite fields
+
+## ListField
+
+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.
+
+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.
+
+ 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.
---
-**Note:** `FileFields` and `ImageFields` are only suitable for use with MultiPartParser, since e.g. json doesn't support file uploads.
-Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files.
+# Miscellaneous fields
+
+## ReadOnlyField
+
+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.
+
+**Signature**: `ReadOnlyField()`
+
+For example, is `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:
+ model = Account
+ fields = ('id', 'account_name', 'has_expired')
+
+## 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.
+
+**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:
+
+ modified = serializer.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.
+
+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.
+
+This field is used by `ModelSerializer` to correspond to custom model field classes.
+
+**Signature:** `ModelField(model_field=<Django ModelField instance>)`
+
+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.
+
+**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_<field_name>`.
+
+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
+ from rest_framework import serializers
+
+ class UserSerializer(serializers.ModelSerializer):
+ days_since_joined = serializers.SerializerMethodField()
+
+ class Meta:
+ model = User
+
+ def get_days_since_joined(self, obj):
+ return (now() - obj.date_joined).days
---
# Custom fields
-If you want to create a custom field, you'll probably want to override either one or both of the `.to_native()` and `.from_native()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes may be any of a number, string, date/time/datetime or None. They may also be any list or dictionary like object that only contains other primitive objects.
+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_native()` method is called to convert the initial datatype into a primitive, serializable datatype. The `from_native()` method is called to restore a primitive datatype into its initial representation.
+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.
+
+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
@@ -346,25 +470,29 @@ Let's look at an example of serializing a class that represents an RGB color val
assert(red < 256 and green < 256 and blue < 256)
self.red, self.green, self.blue = red, green, blue
- class ColourField(serializers.WritableField):
+ class ColorField(serializers.Field):
"""
Color objects are serialized into "rgb(#, #, #)" notation.
"""
- def to_native(self, obj):
+ def to_representation(self, obj):
return "rgb(%d, %d, %d)" % (obj.red, obj.green, obj.blue)
- def from_native(self, data):
+ def to_internal_value(self, data):
data = data.strip('rgb(').rstrip(')')
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 `.field_to_native()` and/or `.field_from_native()`.
+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 represent the class name of the object being serialized:
class ClassNameField(serializers.Field):
- def field_to_native(self, obj, field_name):
+ def get_attribute(self, obj):
+ # We pass the object instance onto `to_representation`,
+ # not just the field attribute.
+ return obj
+
+ def to_representation(self, obj):
"""
Serialize the object's class name.
"""
diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md
index cfeb4334..83977048 100644
--- a/docs/api-guide/filtering.md
+++ b/docs/api-guide/filtering.md
@@ -1,4 +1,4 @@
-<a class="github" href="filters.py"></a>
+source: filters.py
# Filtering
@@ -26,7 +26,7 @@ For example:
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
-
+
def get_queryset(self):
"""
This view should return a list of all the purchases
@@ -38,7 +38,7 @@ 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:
@@ -48,7 +48,7 @@ You could then write a view that returned a purchase queryset filtered by the us
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
-
+
def get_queryset(self):
"""
This view should return a list of all the purchases for
@@ -57,7 +57,7 @@ You could then write a view that returned a purchase queryset filtered by the us
username = self.kwargs['username']
return Purchase.objects.filter(purchaser__username=username)
-## Filtering against query parameters
+## 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.
@@ -65,7 +65,7 @@ We can override `.get_queryset()` to deal with URLs such as `http://example.com/
class PurchaseList(generics.ListAPIView):
serializer_class = PurchaseSerializer
-
+
def get_queryset(self):
"""
Optionally restricts the returned purchases to a given user,
@@ -113,7 +113,7 @@ For instance, given the previous example, and a product with an id of `4675`, th
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:
class PurchasedProductsList(generics.ListAPIView):
@@ -124,7 +124,7 @@ Note that you can use both an overridden `.get_queryset()` and generic filtering
model = Product
serializer_class = ProductSerializer
filter_class = ProductFilter
-
+
def get_queryset(self):
user = self.request.user
return user.purchase_set.all()
@@ -135,7 +135,7 @@ 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`.
@@ -216,7 +216,7 @@ This is nice, but it exposes the Django's double underscore convention as part o
And now you can execute:
http://example.com/api/products?manufacturer=foo
-
+
For more details on using filter sets see the [django-filter documentation][django-filter-docs].
---
@@ -224,7 +224,7 @@ 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].)
+* 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.
* For Django 1.3 support, make sure to install `django-filter` version 0.5.4, as later versions drop support for 1.3.
@@ -316,7 +316,7 @@ Typically you'd instead control this by setting `order_by` on the initial querys
queryset = User.objects.all()
serializer_class = UserSerializer
filter_backends = (filters.OrderingFilter,)
- ordering = ('username',)
+ ordering = ('username',)
The `ordering` attribute may be either a string or a list/tuple of strings.
diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md
index 529738e3..20c1e995 100644
--- a/docs/api-guide/format-suffixes.md
+++ b/docs/api-guide/format-suffixes.md
@@ -1,4 +1,4 @@
-<a class="github" href="urlpatterns.py"></a>
+source: urlpatterns.py
# Format suffixes
@@ -7,7 +7,7 @@ used all the time.
>
> &mdash; 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.
@@ -21,18 +21,19 @@ 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.
+* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used.
Example:
from rest_framework.urlpatterns import format_suffix_patterns
-
- urlpatterns = patterns('blog.views',
- url(r'^/$', 'api_root'),
- url(r'^comments/$', 'comment_list'),
- url(r'^comments/(?P<pk>[0-9]+)/$', 'comment_detail')
- )
-
+ from blog import views
+
+ urlpatterns = [
+ url(r'^/$', views.apt_root),
+ url(r'^comments/$', views.comment_list),
+ url(r'^comments/(?P<pk>[0-9]+)/$', views.comment_detail)
+ ]
+
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:
@@ -55,12 +56,12 @@ The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` se
Also note that `format_suffix_patterns` does not support descending into `include` URL patterns.
---
-
+
## 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.
-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:
&ldquo;That's why I always prefer extensions. Neither choice has anything to do with REST.&rdquo; &mdash; Roy Fielding, [REST discuss mailing list][cite2]
diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md
index 49be0cae..f5bbdfdd 100755
--- a/docs/api-guide/generic-views.md
+++ b/docs/api-guide/generic-views.md
@@ -1,5 +1,11 @@
-<a class="github" href="mixins.py"></a>
-<a class="github" href="generics.py"></a>
+source: mixins.py
+ generics.py
+
+---
+
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
# Generic views
@@ -7,7 +13,7 @@
>
> &mdash; [Django Documentation][cite]
-One of the key benefits of class based views is the way they allow you to compose bits of reusable behaviour. 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.
@@ -171,24 +177,26 @@ For example:
return 20
return 100
-**Save / deletion hooks**:
+**Save and deletion hooks**:
-The following methods are provided as placeholder interfaces. They contain empty implementations and are not called directly by `GenericAPIView`, but they are overridden and used by some of the mixin classes.
+The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior.
-* `pre_save(self, obj)` - A hook that is called before saving an object.
-* `post_save(self, obj, created=False)` - A hook that is called after saving an object.
-* `pre_delete(self, obj)` - A hook that is called before deleting an object.
-* `post_delete(self, obj)` - A hook that is called after deleting an object.
+* `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.
-The `pre_save` method in particular is a useful hook 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 pre_save(self, obj):
- """
- Set the object's owner, based on the incoming request.
- """
- obj.owner = self.request.user
+ 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.
+
+ def perform_update(self, serializer):
+ instance = serializer.save()
+ send_email_confirmation(user=self.request.user, modified=instance)
-Remember that the `pre_save()` method is not called by `GenericAPIView` itself, but it is called by `create()` and `update()` methods on the `CreateModelMixin` and `UpdateModelMixin` classes.
+**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**:
@@ -352,7 +360,7 @@ You can then simply apply this mixin to a view or viewset anytime you need to ap
serializer_class = UserSerializer
lookup_fields = ('account', 'username')
-Using custom mixins is a good option if you have custom behavior that needs to be used
+Using custom mixins is a good option if you have custom behavior that needs to be used.
## Creating custom base classes
@@ -368,6 +376,20 @@ If you are using a mixin across multiple views, you can take this a step further
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.
+
+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.
+
+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.
diff --git a/docs/api-guide/metadata.md b/docs/api-guide/metadata.md
new file mode 100644
index 00000000..c3e51148
--- /dev/null
+++ b/docs/api-guide/metadata.md
@@ -0,0 +1,109 @@
+<a class="github" href="metadata.py"></a>
+
+---
+
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
+
+# 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.
+>
+> &mdash; [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.
+
+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.
+
+ HTTP 200 OK
+ Allow: GET, POST, HEAD, OPTIONS
+ Content-Type: application/json
+
+ {
+ "name": "To Do List",
+ "description": "List existing 'To Do' items, or create a new item.",
+ "renders": [
+ "application/json",
+ "text/html"
+ ],
+ "parses": [
+ "application/json",
+ "application/x-www-form-urlencoded",
+ "multipart/form-data"
+ ],
+ "actions": {
+ "POST": {
+ "note": {
+ "type": "string",
+ "required": false,
+ "read_only": false,
+ "label": "title",
+ "max_length": 100
+ }
+ }
+ }
+ }
+
+## Setting the metadata scheme
+
+You can set the metadata class globally using the `'DEFAULT_METADATA_CLASS'` settings key:
+
+ REST_FRAMEWORK = {
+ 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
+ }
+
+Or you can set the metadata class individually for a view:
+
+ class APIRoot(APIView):
+ metadata_class = APIRootMetadata
+
+ def get(self, request, format=None):
+ return Response({
+ ...
+ })
+
+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.
+
+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):
+ meta = self.metadata_class()
+ 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].
+
+---
+
+# 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.
+
+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
+
+The following class could be used to limit the information that is returned to `OPTIONS` requests.
+
+ class MinimalMetadata(BaseMetadata):
+ """
+ Don't include field and other information for `OPTIONS` requests.
+ Just return the name and description.
+ """
+ def determine_metadata(self, request, view):
+ return {
+ 'name': view.get_view_name(),
+ 'description': view.get_view_description()
+ }
+
+[cite]: http://tools.ietf.org/html/rfc7231#section-4.3.7
+[no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS
+[json-schema]: http://json-schema.org/
diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md
index e57aed1a..9b7086c5 100644
--- a/docs/api-guide/pagination.md
+++ b/docs/api-guide/pagination.md
@@ -1,4 +1,4 @@
-<a class="github" href="pagination.py"></a>
+source: pagination.py
# Pagination
@@ -6,7 +6,7 @@
>
> &mdash; [Django documentation][cite]
-REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.
+REST framework includes a `PaginationSerializer` class that makes it easy to return paginated data in a way that can then be rendered to arbitrary media types.
## Paginating basic data
@@ -33,7 +33,7 @@ The `context` argument of the `PaginationSerializer` class may optionally includ
request = RequestFactory().get('/foobar')
serializer = PaginationSerializer(instance=page, context={'request': request})
serializer.data
- # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
+ # {'count': 4, 'next': 'http://testserver/foobar?page=2', 'previous': None, 'results': [u'john', u'paul']}
We could now return that data in a `Response` object, and it would be rendered into the correct media type.
diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md
index 72a4af64..73e3a705 100644
--- a/docs/api-guide/parsers.md
+++ b/docs/api-guide/parsers.md
@@ -1,4 +1,4 @@
-<a class="github" href="parsers.py"></a>
+source: parsers.py
# Parsers
@@ -12,7 +12,7 @@ REST framework includes a number of built in Parser classes, that allow you to a
## How the parser is determined
-The set of valid parsers for a view is always defined as a list of classes. When either `request.DATA` or `request.FILES` 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.
---
@@ -48,7 +48,7 @@ using the `APIView` class based views.
parser_classes = (YAMLParser,)
def post(self, request, format=None):
- return Response({'received data': request.DATA})
+ return Response({'received data': request.data})
Or, if you're using the `@api_view` decorator with function based views.
@@ -58,7 +58,7 @@ Or, if you're using the `@api_view` decorator with function based views.
"""
A view that can accept POST requests with YAML content.
"""
- return Response({'received data': request.DATA})
+ return Response({'received data': request.data})
---
@@ -92,7 +92,7 @@ Requires the `defusedxml` package to be installed.
## FormParser
-Parses HTML form content. `request.DATA` will be populated with a `QueryDict` of data, `request.FILES` will be populated with an empty `QueryDict` of data.
+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.
@@ -100,7 +100,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
## MultiPartParser
-Parses multipart HTML form content, which supports file uploads. Both `request.DATA` and `request.FILES` 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.
@@ -108,7 +108,7 @@ You will typically want to use both `FormParser` and `MultiPartParser` together
## FileUploadParser
-Parses raw file upload content. The `request.DATA` property will be an empty `QueryDict`, and `request.FILES` 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 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`.
@@ -126,7 +126,7 @@ If the view used with `FileUploadParser` is called with a `filename` URL keyword
parser_classes = (FileUploadParser,)
def put(self, request, filename, format=None):
- file_obj = request.FILES['file']
+ file_obj = request.data['file']
# ...
# do some staff with uploaded file
# ...
@@ -139,7 +139,7 @@ If the view used with `FileUploadParser` is called with a `filename` URL keyword
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:
@@ -161,7 +161,7 @@ By default this will include the following keys: `view`, `request`, `args`, `kwa
## 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):
"""
@@ -197,4 +197,4 @@ The following third party packages are also available.
[juanriaza]: https://github.com/juanriaza
[vbabiy]: https://github.com/vbabiy
[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
-[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case \ No newline at end of file
+[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md
index a32db4a2..7558475f 100644
--- a/docs/api-guide/permissions.md
+++ b/docs/api-guide/permissions.md
@@ -1,4 +1,4 @@
-<a class="github" href="permissions.py"></a>
+source: permissions.py
# Permissions
@@ -12,7 +12,7 @@ Permission checks are always run at the very start of the view, before any other
## 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` exception will be raised, and the main body of the view will not run.
@@ -146,7 +146,13 @@ As with `DjangoModelPermissions`, this permission must only be applied to views
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. Note that if you add a custom `view` permission for `GET`, `HEAD` and `OPTIONS` requests, you'll probably also want to consider adding the `DjangoObjectPermissionsFilter` class to ensure that list endpoints only return results including objects for which the user has appropriate view permissions.
+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.
+
+---
---
@@ -168,11 +174,7 @@ If you need to test if a request is a read operation or a write operation, you s
---
-**Note**: In versions 2.0 and 2.1, the signature for the permission checks always included an optional `obj` parameter, like so: `.has_permission(self, request, view, obj=None)`. The method would be called twice, first for the global permission checks, with no object supplied, and second for the object-level check when required.
-
-As of version 2.2 this signature has now been replaced with two separate method calls, which is more explicit and obvious. The old style signature continues to work, but its use will result in a `PendingDeprecationWarning`, which is silent by default. In 2.3 this will be escalated to a `DeprecationWarning`, and in 2.4 the old-style signature will be removed.
-
-For more details see the [2.2 release announcement][2.2-announcement].
+**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.
---
@@ -203,9 +205,9 @@ As well as global permissions, that are run against all incoming requests, you c
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
- if request.method in permissions.SAFE_METHODS:
+ if request.method in permissions.SAFE_METHODS:
return True
-
+
# Instance must have an attribute named `owner`.
return obj.owner == request.user
diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md
index cc4f5585..a79b6ea5 100644
--- a/docs/api-guide/relations.md
+++ b/docs/api-guide/relations.md
@@ -1,4 +1,10 @@
-<a class="github" href="relations.py"></a>
+source: relations.py
+
+---
+
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
# Serializer relations
@@ -16,6 +22,20 @@ Relational fields are used to represent model relationships. They can be applie
---
+#### Inspecting automatically generated 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.
+
+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()
+ >>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.
+ AccountSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ name = CharField(allow_blank=True, max_length=100, required=False)
+ owner = PrimaryKeyRelatedField(queryset=User.objects.all())
+
# 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.
@@ -33,19 +53,19 @@ In order to explain the various types of relational fields, we'll use a couple o
class Meta:
unique_together = ('album', 'order')
order_by = 'order'
-
+
def __unicode__(self):
return '%d: %s' % (self.order, self.title)
-## RelatedField
+## StringRelatedField
-`RelatedField` 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.
-
+
class AlbumSerializer(serializers.ModelSerializer):
- tracks = serializers.RelatedField(many=True)
-
+ tracks = serializers.StringRelatedField(many=True)
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -74,10 +94,10 @@ This field is read only.
`PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key.
For example, the following serializer:
-
+
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -99,20 +119,23 @@ 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`.
-* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=True`.
+* `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`.
## HyperlinkedRelatedField
`HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink.
For example, the following serializer:
-
+
class AlbumSerializer(serializers.ModelSerializer):
- tracks = serializers.HyperlinkedRelatedField(many=True, read_only=True,
- view_name='track-detail')
-
+ tracks = serializers.HyperlinkedRelatedField(
+ many=True,
+ read_only=True,
+ view_name='track-detail'
+ )
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -134,11 +157,12 @@ By default this field is read-write, although you can change this behavior using
**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 wil be a string with the format `<modelname>-detail`. **required**.
+* `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 `<modelname>-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`.
-* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=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
@@ -146,11 +170,14 @@ By default this field is read-write, although you can change this behavior using
`SlugRelatedField` may be used to represent the target of the relationship using a field on the target.
For example, the following serializer:
-
+
class AlbumSerializer(serializers.ModelSerializer):
- tracks = serializers.SlugRelatedField(many=True, read_only=True,
- slug_field='title')
-
+ tracks = serializers.SlugRelatedField(
+ many=True,
+ read_only=True,
+ slug_field='title'
+ )
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -175,9 +202,9 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e
**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`.
-* `required` - If set to `False`, the field will accept values of `None` or the empty-string for nullable relationships.
-* `queryset` - By default `ModelSerializer` classes will use the default queryset for the relationship. `Serializer` classes must either set a queryset explicitly, or set `read_only=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
@@ -202,7 +229,7 @@ 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 wil be a string with the format `<model_name>-detail`. **required**.
+* `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 `<model_name>-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'`.
* `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument.
@@ -222,10 +249,10 @@ For example, the following serializer:
class Meta:
model = Track
fields = ('order', 'title')
-
+
class AlbumSerializer(serializers.ModelSerializer):
- tracks = TrackSerializer(many=True)
-
+ tracks = TrackSerializer(many=True, read_only=True)
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -245,9 +272,9 @@ Would serialize to a nested representation like this:
# Custom relational fields
-To implement a custom relational field, you should override `RelatedField`, and implement the `.to_native(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.
+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 `.from_native(self, data)` method, and add `read_only = False` to the class definition.
+If you want to implement a read-write relational field, you must also implement the `.to_internal_value(self, data)` method.
## Example
@@ -256,13 +283,13 @@ For, example, we could define a relational field, to serialize a track to a cust
import time
class TrackListingField(serializers.RelatedField):
- def to_native(self, value):
+ def to_representation(self, value):
duration = time.strftime('%M:%S', time.gmtime(value.duration))
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackListingField(many=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -284,6 +311,16 @@ This custom field would then serialize to the following representation.
# Further notes
+## 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.
+
+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.
+
+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.
+
## 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:
@@ -302,7 +339,7 @@ If you have not set a related name for the reverse relationship, you'll need to
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
- fields = ('track_set', ...)
+ fields = ('track_set', ...)
See the Django documentation on [reverse relationships][reverse-relationships] for more details.
@@ -315,14 +352,14 @@ For example, given the following model for a tag, which has a generic relationsh
class TaggedItem(models.Model):
"""
Tags arbitrary model instances using a generic relation.
-
+
See: https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/
"""
tag_name = models.SlugField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
tagged_object = GenericForeignKey('content_type', 'object_id')
-
+
def __unicode__(self):
return self.tag
@@ -350,23 +387,23 @@ We could define a custom field that could be used to serialize tagged instances,
A custom field to use for the `tagged_object` generic relationship.
"""
- def to_native(self, value):
+ def to_representation(self, value):
"""
Serialize tagged objects to a simple textual representation.
- """
+ """
if isinstance(value, Bookmark):
return 'Bookmark: ' + value.url
elif isinstance(value, Note):
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_native()` method:
+If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_native()` method:
- def to_native(self, value):
+ def to_representation(self, value):
"""
Serialize bookmark instances using a bookmark serializer,
and note instances using a note serializer.
- """
+ """
if isinstance(value, Bookmark):
serializer = BookmarkSerializer(value)
elif isinstance(value, Note):
@@ -391,7 +428,7 @@ to ``True``.
## Advanced Hyperlinked fields
-If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`.
+If you have very specific requirements for the style of your hyperlinked relationships you can override `HyperlinkedRelatedField`.
There are two methods you'll need to override.
@@ -404,14 +441,13 @@ attributes are not configured to correctly match the URL conf.
#### get_object(self, queryset, view_name, view_args, view_kwargs)
-
This method should the object that corresponds to the matched URL conf arguments.
May raise an `ObjectDoesNotExist` exception.
### Example
-For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:
+For example, if all your object URLs used both a account and a slug in the the URL to reference the object, you might create a custom field like this:
class CustomHyperlinkedField(serializers.HyperlinkedRelatedField):
def get_url(self, obj, view_name, request, format):
@@ -425,25 +461,6 @@ For example, if all your object URLs used both a account and a slug in the the U
---
-## Deprecated APIs
-
-The following classes have been deprecated, in favor of the `many=<bool>` syntax.
-They continue to function, but their usage will raise a `PendingDeprecationWarning`, which is silent by default.
-
-* `ManyRelatedField`
-* `ManyPrimaryKeyRelatedField`
-* `ManyHyperlinkedRelatedField`
-* `ManySlugRelatedField`
-
-The `null=<bool>` flag has been deprecated in favor of the `required=<bool>` flag. It will continue to function, but will raise a `PendingDeprecationWarning`.
-
-In the 2.3 release, these warnings will be escalated to a `DeprecationWarning`, which is loud by default.
-In the 2.4 release, these parts of the API will be removed entirely.
-
-For more details see the [2.2 release announcement][2.2-announcement].
-
----
-
# Third Party Packages
The following third party packages are also available.
diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md
index 2e1c892f..035ec1d2 100644
--- a/docs/api-guide/renderers.md
+++ b/docs/api-guide/renderers.md
@@ -1,4 +1,4 @@
-<a class="github" href="renderers.py"></a>
+source: renderers.py
# Renderers
@@ -74,7 +74,7 @@ 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 uneccessary 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}
@@ -115,7 +115,7 @@ The `jsonp` approach is essentially a browser hack, and is [only appropriate for
## YAMLRenderer
-Renders the request data into `YAML`.
+Renders the request data into `YAML`.
Requires the `pyyaml` package to be installed.
@@ -131,7 +131,7 @@ Note that non-ascii characters will be rendered using `\uXXXX` character escape.
## UnicodeYAMLRenderer
-Renders the request data into `YAML`.
+Renders the request data into `YAML`.
Requires the `pyyaml` package to be installed.
@@ -184,7 +184,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
def get(self, request, *args, **kwargs):
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.
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.
@@ -205,7 +205,7 @@ An example of a view that uses `TemplateHTMLRenderer`:
@api_view(('GET',))
@renderer_classes((StaticHTMLRenderer,))
- def simple_html_view(request):
+ def simple_html_view(request):
data = '<html><body><h1>Hello, world</h1></body></html>'
return Response(data)
@@ -300,7 +300,7 @@ The following is an example plaintext renderer that will return a response with
class PlainTextRenderer(renderers.BaseRenderer):
media_type = 'text/plain'
format = 'txt'
-
+
def render(self, data, media_type=None, renderer_context=None):
return data.encode(self.charset)
@@ -340,7 +340,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e
* 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
diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md
index 0696fedf..77000ffa 100644
--- a/docs/api-guide/requests.md
+++ b/docs/api-guide/requests.md
@@ -1,4 +1,10 @@
-<a class="github" href="request.py"></a>
+source: request.py
+
+---
+
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
# Requests
@@ -14,26 +20,29 @@ REST framework's `Request` class extends the standard `HttpRequest`, adding supp
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
+## .data
-`request.DATA` returns the parsed content of the request body. This is similar to the standard `request.POST` attribute 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.
For more details see the [parsers documentation].
-## .FILES
+## .query_params
-`request.FILES` returns any uploaded files that may be present in the content of the request body. This is the same as the standard `HttpRequest` behavior, except that the same flexible request parsing is used for `request.DATA`.
+`request.query_params` is a more correctly named synonym for `request.GET`.
-For more details see the [parsers documentation].
+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.
-## .QUERY_PARAMS
+## .DATA and .FILES
-`request.QUERY_PARAMS` is a more correctly named synonym for `request.GET`.
+The old-style version 2.x `request.data` and `request.FILES` attributes are still available, but are now pending deprecation in favor of the unified `request.data` attribute.
+
+## .QUERY_PARAMS
-For clarity inside your code, we recommend using `request.QUERY_PARAMS` instead of the usual `request.GET`, as *any* HTTP method type may include query parameters.
+The old-style version 2.x `request.QUERY_PARAMS` attribute is still available, but is now pending deprecation in favor of the more pythonic `request.query_params`.
## .parsers
@@ -43,12 +52,26 @@ You won't typically need to access this property.
---
-**Note:** If a client sends malformed content, then accessing `request.DATA` or `request.FILES` 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.
---
+# 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.
+
+## .accepted_renderer
+
+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.
+
+---
+
# Authentication
REST framework provides flexible, per-request authentication, that gives you the ability to:
@@ -91,7 +114,7 @@ REST framework supports a few browser enhancements such as browser-based `PUT`,
Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported.
-For more information see the [browser enhancements documentation].
+For more information see the [browser enhancements documentation].
## .content_type
@@ -101,7 +124,7 @@ You won't typically need to directly access the request's content type, as you'l
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].
+For more information see the [browser enhancements documentation].
## .stream
@@ -111,7 +134,7 @@ You won't typically need to directly access the request's content, as you'll nor
If you do need to access the raw content directly, you should use the `.stream` property in preference to using `request.content`, as it provides transparent support for browser-based non-form content.
-For more information see the [browser enhancements documentation].
+For more information see the [browser enhancements documentation].
---
diff --git a/docs/api-guide/responses.md b/docs/api-guide/responses.md
index 5a42aa92..97f31271 100644
--- a/docs/api-guide/responses.md
+++ b/docs/api-guide/responses.md
@@ -1,4 +1,4 @@
-<a class="github" href="response.py"></a>
+source: response.py
# Responses
@@ -90,6 +90,6 @@ The `Response` class extends `SimpleTemplateResponse`, and all the usual attribu
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.
-
+
[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 383eca4c..71fb83f9 100644
--- a/docs/api-guide/reverse.md
+++ b/docs/api-guide/reverse.md
@@ -1,4 +1,4 @@
-<a class="github" href="reverse.py"></a>
+source: reverse.py
# Returning URLs
@@ -30,7 +30,7 @@ You should **include the request as a keyword argument** to the function, for ex
from rest_framework.reverse import reverse
from rest_framework.views import APIView
from django.utils.timezone import now
-
+
class APIRootView(APIView):
def get(self, request):
year = now().year
diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md
index 61a476b8..080230fa 100644
--- a/docs/api-guide/routers.md
+++ b/docs/api-guide/routers.md
@@ -1,4 +1,4 @@
-<a class="github" href="routers.py"></a>
+source: routers.py
# Routers
@@ -56,10 +56,10 @@ For example, given a method like this on the `UserViewSet` class:
from myapp.permissions import IsAdminOrIsSelf
from rest_framework.decorators import detail_route
-
+
class UserViewSet(ModelViewSet):
...
-
+
@detail_route(methods=['post'], permission_classes=[IsAdminOrIsSelf])
def set_password(self, request, pk=None):
...
@@ -228,7 +228,7 @@ 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.
diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md
index a3694510..0ee80d53 100644
--- a/docs/api-guide/serializers.md
+++ b/docs/api-guide/serializers.md
@@ -1,4 +1,10 @@
-<a class="github" href="serializers.py"></a>
+source: serializers.py
+
+---
+
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
# Serializers
@@ -10,7 +16,7 @@ will take some serious design work.
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.
-REST framework's serializers work very similarly to Django's `Form` and `ModelForm` classes. It provides 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
@@ -21,10 +27,10 @@ Let's start by creating a simple object we can use for example purposes:
self.email = email
self.content = content
self.created = created or datetime.datetime.now()
-
+
comment = Comment(email='leila@example.com', content='foo bar')
-We'll declare a serializer that we can use to serialize and deserialize `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:
@@ -35,25 +41,9 @@ Declaring a serializer looks very similar to declaring a form:
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
- def restore_object(self, attrs, instance=None):
- """
- Given a dictionary of deserialized field values, either update
- an existing model instance, or create a new model instance.
- """
- if instance is not None:
- instance.email = attrs.get('email', instance.email)
- instance.content = attrs.get('content', instance.content)
- instance.created = attrs.get('created', instance.created)
- return instance
- return Comment(**attrs)
-
-The first part of serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
-
-The `restore_object` method is optional, and is only required if we want our serializer to support deserialization into fully fledged object instances. If we don't define this method, then deserializing data will simply return a dictionary of items.
-
## 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
@@ -67,24 +57,9 @@ At this point we've translated the model instance into Python native datatypes.
json
# '{"email": "leila@example.com", "content": "foo bar", "created": "2012-08-22T16:20:09.822"}'
-### Customizing field representation
-
-Sometimes when serializing objects, you may not want to represent everything exactly the way it is in your model.
-
-If you need to customize the serialized value of a particular field, you can do this by creating a `transform_<fieldname>` method. For example if you needed to render some markdown from a text field:
-
- description = serializers.CharField()
- description_html = serializers.CharField(source='description', read_only=True)
-
- def transform_description_html(self, obj, value):
- from django.contrib.markup.templatetags.markup import markdown
- return markdown(value)
-
-These methods are essentially the reverse of `validate_<fieldname>` (see *Validation* below.)
-
## 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 StringIO import StringIO
from rest_framework.parsers import JSONParser
@@ -92,26 +67,90 @@ Deserialization is similar. First we parse a stream into Python native datatype
stream = StringIO(json)
data = JSONParser().parse(stream)
-...then we restore those native datatypes into a fully populated object instance.
+...then we restore those native datatypes into a dictionary of validated data.
serializer = CommentSerializer(data=data)
serializer.is_valid()
# True
- serializer.object
- # <Comment object at 0x10633b2d0>
+ serializer.validated_data
+ # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)}
+
+## 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:
+
+ class CommentSerializer(serializers.Serializer):
+ email = serializers.EmailField()
+ content = serializers.CharField(max_length=200)
+ created = serializers.DateTimeField()
+
+ def create(self, validated_data):
+ return Comment(**validated_data)
+
+ def update(self, instance, validated_data):
+ instance.email = validated_data.get('email', instance.email)
+ instance.content = validated_data.get('content', instance.content)
+ 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:
+
+ def create(self, validated_data):
+ return Comment.objcts.create(**validated_data)
+
+ def update(self, instance, validated_data):
+ instance.email = validated_data.get('email', instance.email)
+ instance.content = validated_data.get('content', instance.content)
+ instance.created = validated_data.get('created', instance.created)
+ instance.save()
+ return instance
+
+Now when deserializing data, we can call `.save()` to return an object instance, based on the validated data.
-When deserializing data, we can either create a new instance, or update an existing instance.
+ comment = serializer.save()
- serializer = CommentSerializer(data=data) # Create new instance
- serializer = CommentSerializer(comment, data=data) # Update `comment`
+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:
-By default, serializers must be passed values for all required fields or they will throw validation errors. You can use the `partial` argument in order to allow partial updates.
+ # .save() will create a new instance.
+ serializer = CommentSerializer(data=data)
+
+ # .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.
+
+#### 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.
+
+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.
+
+#### Overriding `.save()` directly.
- serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `comment` with partial data
+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.
+
+For example:
+
+ class ContactForm(serializers.Serializer):
+ email = serializers.EmailField()
+ message = serializers.CharField()
+
+ def save(self):
+ email = self.validated_data['email']
+ 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.
## Validation
-When deserializing data, you always need to call `is_valid()` before attempting to access the deserialized object. 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()
@@ -119,17 +158,26 @@ 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.
+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.
+#### 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.
+
+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_<fieldname>` methods to your `Serializer` subclass. These are analogous to `.clean_<fieldname>` methods on Django forms, but accept slightly different arguments.
+You can specify custom field-level validation by adding `.validate_<field_name>` methods to your `Serializer` subclass. These are similar to the `.clean_<field_name>` methods on Django forms.
-They take a dictionary of deserialized attributes as a first argument, and the field name in that dictionary as a second argument (which will be either the name of the field or the value of the `source` argument to the field, if one was provided).
+These methods take a single argument, which is the field value that requires validation.
-Your `validate_<fieldname>` methods should either just return the `attrs` dictionary or raise a `ValidationError`. For example:
+Your `validate_<field_name>` methods should return the validated value or raise a `serializers.ValidationError`. For example:
from rest_framework import serializers
@@ -137,18 +185,17 @@ Your `validate_<fieldname>` methods should either just return the `attrs` dictio
title = serializers.CharField(max_length=100)
content = serializers.CharField()
- def validate_title(self, attrs, source):
+ def validate_title(self, value):
"""
Check that the blog post is about Django.
"""
- value = attrs[source]
- if "django" not in value.lower():
+ if 'django' not in value.lower():
raise serializers.ValidationError("Blog post is not about Django")
- return attrs
+ return value
#### 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 the `attrs` dictionary. It should raise a `ValidationError` if necessary, or just return `attrs`. 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
@@ -157,24 +204,48 @@ To do any other validation that requires access to multiple fields, add a method
start = serializers.DateTimeField()
finish = serializers.DateTimeField()
- def validate(self, attrs):
+ def validate(self, data):
"""
Check that the start is before the stop.
"""
- if attrs['start'] > attrs['finish']:
+ if data['start'] > data['finish']:
raise serializers.ValidationError("finish must occur after start")
- return attrs
+ return data
+
+#### Validators
+
+Individual fields on a serializer can include validators, by declaring them on the field instance, for example:
+
+ def multiple_of_ten(value):
+ if value % 10 != 0:
+ raise serializers.ValidationError('Not a multiple of ten')
+
+ class GameRecord(serializers.Serializer):
+ 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:
-## Saving object state
+ class EventSerializer(serializers.Serializer):
+ name = serializers.CharField()
+ room_number = serializers.IntegerField(choices=[101, 102, 103, 201])
+ date = serializers.DateField()
+
+ class Meta:
+ # Each room only has one event per day.
+ validators = UniqueTogetherValidator(
+ queryset=Event.objects.all(),
+ fields=['room_number', 'date']
+ )
-To save the deserialized objects created by a serializer, call the `.save()` method:
+For more information see the [validators documentation](validators.md).
- if serializer.is_valid():
- serializer.save()
+## Partial updates
-The default behavior of the method is to simply call `.save()` on the deserialized object instance. You can override the default save behaviour by overriding the `.save_object(obj)` method on the serializer class.
+By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the `partial` argument in order to allow partial updates.
-The generic views provided by REST framework call the `.save()` method when updating or creating entities.
+ # Update `comment` with partial data
+ serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)
## Dealing with nested objects
@@ -206,7 +277,9 @@ Similarly if a nested representation should be a list of items, you should pass
content = serializers.CharField(max_length=200)
created = serializers.DateTimeField()
-Validation of nested objects will work the same as before. Errors with nested objects will be nested under the field name of the nested object.
+## Writable nested representations
+
+When dealing with nested representations that support deserializing the data, an 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()
@@ -214,95 +287,117 @@ Validation of nested objects will work the same as before. Errors with nested o
serializer.errors
# {'user': {'email': [u'Enter a valid e-mail address.']}, 'created': [u'This field is required.']}
-## Dealing with multiple objects
+Similarly, the `.validated_data` property will include nested data structures.
-The `Serializer` class can also handle serializing or deserializing lists of objects.
+#### Writing `.create()` methods for nested representations
-#### Serializing multiple objects
+If you're supporting writable nested representations you'll need to write `.create()` or `.update()` methods that handle saving 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.
+The following example demonstrates how you might handle creating a user with a nested profile object.
- queryset = Book.objects.all()
- serializer = BookSerializer(queryset, many=True)
- serializer.data
- # [
- # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
- # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
- # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
- # ]
+ class UserSerializer(serializers.ModelSerializer):
+ profile = ProfileSerializer()
-#### Deserializing multiple objects for creation
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'profile')
-To deserialize a list of object data, and create multiple object instances in a single pass, you should also set the `many=True` flag, and pass a list of data to be deserialized.
+ def create(self, validated_data):
+ profile_data = validated_data.pop('profile')
+ user = User.objects.create(**validated_data)
+ Profile.objects.create(user=user, **profile_data)
+ return user
-This allows you to write views that create multiple items when a `POST` request is made.
+#### Writing `.update()` methods for nested representations
-For example:
+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?
- data = [
- {'title': 'The bell jar', 'author': 'Sylvia Plath'},
- {'title': 'For whom the bell tolls', 'author': 'Ernest Hemingway'}
- ]
- serializer = BookSerializer(data=data, many=True)
- serializer.is_valid()
- # True
- serializer.save() # `.save()` will be called on each deserialized instance
+* 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.
-#### Deserializing multiple objects for update
+Here's an example for an `update()` method on our previous `UserSerializer` class.
-You can also deserialize a list of objects as part of a bulk update of multiple existing items.
-In this case you need to supply both an existing list or queryset of items, as well as a list of data to update those items with.
+ def update(self, instance, validated_data):
+ profile_data = validated_data.pop('profile')
+ # Unless the application properly enforces that this field is
+ # always set, the follow could raise a `DoesNotExist`, which
+ # would need to be handled.
+ profile = instance.profile
-This allows you to write views that update or create multiple items when a `PUT` request is made.
+ user.username = validated_data.get('username', instance.username)
+ user.email = validated_data.get('email', instance.email)
+ user.save()
- # Capitalizing the titles of the books
- queryset = Book.objects.all()
- data = [
- {'id': 3, 'title': 'The Bell Jar', 'author': 'Sylvia Plath'},
- {'id': 4, 'title': 'For Whom the Bell Tolls', 'author': 'Ernest Hemingway'}
- ]
- serializer = BookSerializer(queryset, data=data, many=True)
- serializer.is_valid()
- # True
- serializer.save() # `.save()` will be called on each updated or newly created instance.
+ profile.is_premium_member = profile_data.get(
+ 'is_premium_member',
+ profile.is_premium_member
+ )
+ profile.has_support_contract = profile_data.get(
+ 'has_support_contract',
+ profile.has_support_contract
+ )
+ profile.save()
-By default bulk updates will be limited to updating instances that already exist in the provided queryset.
+ return user
-When performing a bulk update you may want to allow new items to be created, and missing items to be deleted. To do so, pass `allow_add_remove=True` to the serializer.
+Because the behavior of nested creates and updates can be ambiguous, and may require complex dependancies 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.
- serializer = BookSerializer(queryset, data=data, many=True, allow_add_remove=True)
- serializer.is_valid()
- # True
- serializer.save() # `.save()` will be called on updated or newly created instances.
- # `.delete()` will be called on any other items in the `queryset`.
+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.
-Passing `allow_add_remove=True` ensures that any update operations will completely overwrite the existing queryset, rather than simply updating existing objects.
+#### Handling saving related instances in model manager classes
-#### How identity is determined when performing bulk updates
+An alternative to saving multiple related instances in the serializer is to write custom model manager classes handle creating the correct instances.
-Performing a bulk update is slightly more complicated than performing a bulk creation, because the serializer needs a way to determine how the items in the incoming data should be matched against the existing object 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:
-By default the serializer class will use the `id` key on the incoming data to determine the canonical identity of an object. If you need to change this behavior you should override the `get_identity` method on the `Serializer` class. For example:
+ class UserManager(models.Manager):
+ ...
- class AccountSerializer(serializers.Serializer):
- slug = serializers.CharField(max_length=100)
- created = serializers.DateTimeField()
- ... # Various other fields
-
- def get_identity(self, data):
- """
- This hook is required for bulk update.
- We need to override the default, to use the slug as the identity.
-
- Note that the data has not yet been validated at this point,
- so we need to deal gracefully with incorrect datatypes.
- """
- try:
- return data.get('slug', None)
- except AttributeError:
- return None
+ def create(self, username, email, is_premium_member=False, has_support_contract=False):
+ user = User(username=username, email=email)
+ user.save()
+ profile = Profile(
+ user=user,
+ is_premium_member=is_premium_member,
+ has_support_contract=has_support_contract
+ )
+ 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.
+
+ def create(self, validated_data):
+ return User.objects.create(
+ username=validated_data['username'],
+ email=validated_data['email']
+ is_premium_member=validated_data['profile']['is_premium_member']
+ 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 manger classes](encapsulation-blogpost).
+
+## Dealing with multiple objects
+
+The `Serializer` class can also handle serializing or deserializing lists of objects.
-To map the incoming data items to their corresponding object instances, the `.get_identity()` method will be called both against the incoming data, and against the serialized representation of the existing objects.
+#### 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.
+
+ queryset = Book.objects.all()
+ serializer = BookSerializer(queryset, many=True)
+ serializer.data
+ # [
+ # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
+ # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
+ # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
+ # ]
+
+#### 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.
## Including extra context
@@ -314,28 +409,46 @@ You can provide arbitrary additional context by passing a `context` argument whe
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_native()` 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 model definitions.
-The `ModelSerializer` class lets you automatically create a Serializer class with fields that correspond to the Model fields.
+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 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 includes simple default implementations of `.create()` and `.update()`.
+
+Declaring a `ModelSerializer` looks like this:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
-By default, all the model fields on the class will be mapped to 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`. Other models fields will be mapped to a corresponding serializer field.
+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`
-**Note**: When validation is applied to a `ModelSerializer`, both the serializer fields, and their corresponding model fields must correctly validate. If you have optional fields on your model, make sure to correctly set `blank=True` on the model field, as well as setting `required=False` on the serializer field.
+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…
+ >>> from myapp.serializers import AccountSerializer
+ >>> serializer = AccountSerializer()
+ >>> print repr(serializer) # Or `print(repr(serializer))` in Python 3.x.
+ AccountSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ name = CharField(allow_blank=True, max_length=100, required=False)
+ owner = PrimaryKeyRelatedField(queryset=User.objects.all())
+
## Specifying which fields should be included
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`.
@@ -347,6 +460,10 @@ For example:
model = Account
fields = ('id', 'account_name', 'users', 'created')
+The names in the `fields` option 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.
+
## Specifying nested serialization
The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option:
@@ -361,9 +478,24 @@ The `depth` option should be set to an integer value that indicates the depth of
If you want to customize the way the serialization is done (e.g. using `allow_add_remove`) you'll need to define the field yourself.
-## Specifying which fields should be read-only
+## Specifying fields explicitly
-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 `read_only_fields` Meta option, like so:
+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)
+ groups = serializers.PrimaryKeyRelatedField(many=True)
+
+ class Meta:
+ model = Account
+
+Extra fields can correspond to any property or callable on the model.
+
+## Specifying which fields should be read-only
+
+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:
class AccountSerializer(serializers.ModelSerializer):
class Meta:
@@ -371,39 +503,28 @@ You may wish to specify multiple fields as read-only. Instead of adding each fi
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.
+
+## Specifying additional keyword arguments for fields.
-## Specifying which fields should be write-only
+There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. Similarly to `read_only_fields` this means you do not need to explicitly declare the field on the serializer.
-You may wish to specify multiple fields as write-only. Instead of adding each field explicitly with the `write_only=True` attribute, you may use the `write_only_fields` Meta option, like so:
+This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example:
class CreateUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('email', 'username', 'password')
- write_only_fields = ('password',) # Note: Password field is write-only
-
- def restore_object(self, attrs, instance=None):
- """
- Instantiate a new User instance.
- """
- assert instance is None, 'Cannot update users with CreateUserSerializer'
- user = User(email=attrs['email'], username=attrs['username'])
- user.set_password(attrs['password'])
+ extra_kwargs = {'password': {'write_only': True}}
+
+ def create(self, validated_data):
+ user = User(
+ email=validated_data['email'],
+ username=validated_data['username']
+ )
+ user.set_password(validated_data['password'])
+ user.save()
return user
-
-## 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.
-
- class AccountSerializer(serializers.ModelSerializer):
- url = serializers.CharField(source='get_absolute_url', read_only=True)
- groups = serializers.PrimaryKeyRelatedField(many=True)
-
- class Meta:
- model = Account
-
-Extra fields can correspond to any property or callable on the model.
## Relational fields
@@ -413,6 +534,16 @@ Alternative representations include serializing using hyperlinks, serializing co
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:
+
+ 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.
+
---
# HyperlinkedModelSerializer
@@ -436,22 +567,23 @@ There needs to be a way of determining which views should be used for hyperlinki
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 change the field that is used for object lookups by setting the `lookup_field` option. The value of this option should correspond both with a kwarg in the URL conf, and with a field on the model. For example:
+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_field_kwargs` setting, like so:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Account
- fields = ('url', 'account_name', 'users', 'created')
- lookup_field = 'slug'
-
-Note that the `lookup_field` will be used as the default on *all* hyperlinked fields, including both the URL identity, and any hyperlinked relationships.
+ fields = ('account_url', 'account_name', 'users', 'created')
+ extra_field_kwargs = {
+ 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}
+ 'users': {'lookup_field': 'username'}
+ }
-For more specific requirements such as specifying a different lookup for each field, you'll want to set the fields on the serializer explicitly. For example:
+Alternatively you can set the fields on the serializer explicitly. For example:
class AccountSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
- view_name='account_detail',
- lookup_field='account_name'
+ view_name='accounts',
+ lookup_field='slug'
)
users = serializers.HyperlinkedRelatedField(
view_name='user-detail',
@@ -464,36 +596,267 @@ For more specific requirements such as specifying a different lookup for each fi
model = Account
fields = ('url', 'account_name', 'users', 'created')
-## Overriding the URL field behavior
+---
+
+**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.
-You can also override this on a per-serializer basis by using the `url_field_name` option on the serializer, like so:
+---
- class AccountSerializer(serializers.HyperlinkedModelSerializer):
+# 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.
+
+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`
+
+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 always ensuring that there is at least one 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 example:
+
+ class CustomListSerializer(serializers.ListSerializer):
+ ...
+
+ class CustomSerializer(serializers.Serializer):
+ ...
class Meta:
- model = Account
- fields = ('account_url', 'account_name', 'users', 'created')
- url_field_name = 'account_url'
+ list_serializer_class = CustomListSerializer
-**Note**: The generic view implementations normally generate a `Location` header in response to successful `POST` requests. Serializers using `url_field_name` option will not have this header automatically included by the view. If you need to do so you will ned to also override the view's `get_success_headers()` method.
+#### Customizing multiple create
-You can also override the URL field's view name and lookup field without overriding the field explicitly, by using the `view_name` and `lookup_field` options, like so:
+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.
- class AccountSerializer(serializers.HyperlinkedModelSerializer):
+For example:
+
+ class BookListSerializer(serializers.ListSerializer):
+ def create(self, validated_data):
+ books = [Book(**item) for item in validated_data]
+ return Book.objects.bulk_create(books)
+
+ class BookSerializer(serializers.Serializer):
+ ...
class Meta:
- model = Account
- fields = ('account_url', 'account_name', 'users', 'created')
- view_name = 'account_detail'
- lookup_field='account_name'
+ list_serializer_class = BookListSerializer
+
+#### 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.
+
+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?
+
+Here's an example of how you might choose to implement multiple updates:
+
+ class BookListSerializer(serializers.ListSerializer):
+ def update(self, instance, validated_data):
+ # Maps for id->instance and id->data item.
+ book_mapping = {book.id: book for book in instance}
+ data_mapping = {item['id']: item for item in validated_data}
+
+ # Perform creations and updates.
+ ret = []
+ for book_id, data in data_mapping.items():
+ book = book_mapping.get(book_id, None):
+ if book is None:
+ ret.append(self.child.create(data))
+ else:
+ ret.append(self.child.update(book, data))
+
+ # Perform deletions.
+ for book_id, book in book_mapping.items():
+ if book_id not in data_mapping:
+ book.delete()
+
+ return ret
+
+ class BookSerializer(serializers.Serializer):
+ ...
+ 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.
+
+---
+
+# BaseSerializer
+
+`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:
+
+* `.data` - Returns the outgoing primitive representation.
+* `.is_valid()` - Deserializes and validates incoming data.
+* `.validated_data` - Returns the validated incoming data.
+* `.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:
+
+* `.to_representation()` - Override this to support serialization, for read operations.
+* `.to_internal_value()` - Override this to support deserialization, for write operations.
+* `.create()` and `.update()` - Overide 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`.
+
+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:
+
+ 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.
+
+ class HighScoreSerializer(serializers.BaseSerializer):
+ def to_representation(self, obj):
+ return {
+ 'score': obj.score,
+ 'player_name': obj.player_name
+ }
+
+We can now use this class to serialize single `HighScore` instances:
+
+ @api_view(['GET'])
+ def high_score(request, pk):
+ instance = HighScore.objects.get(pk=pk)
+ serializer = HighScoreSerializer(instance)
+ return Response(serializer.data)
+
+Or use it to serialize multiple instances:
+
+ @api_view(['GET'])
+ def all_high_scores(request):
+ queryset = HighScore.objects.order_by('-score')
+ serializer = HighScoreSerializer(queryset, many=True)
+ return Response(serializer.data)
+
+##### 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.
+
+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.
+
+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):
+ score = data.get('score')
+ player_name = data.get('player_name')
+
+ # Perform the data validation.
+ if not score:
+ raise ValidationError({
+ 'score': 'This field is required.'
+ })
+ if not player_name:
+ raise ValidationError({
+ 'player_name': 'This field is required.'
+ })
+ if len(player_name) > 10:
+ raise ValidationError({
+ 'player_name': 'May not be more than 10 characters.'
+ })
+
+ # Return the validated values. This will be available as
+ # the `.validated_data` property.
+ return {
+ 'score': int(score),
+ 'player_name': player_name
+ }
+
+ def to_representation(self, obj):
+ return {
+ 'score': obj.score,
+ 'player_name': obj.player_name
+ }
+
+ def create(self, validated_data):
+ return HighScore.objects.create(**validated_data)
+
+#### 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 following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
+
+ class ObjectSerializer(serializers.BaseSerializer):
+ """
+ A read-only serializer that coerces arbitrary complex objects
+ into primitive representations.
+ """
+ def to_representation(self, obj):
+ for attribute_name in dir(obj):
+ attribute = getattr(obj, attribute_name)
+ if attribute_name('_'):
+ # Ignore private attributes.
+ pass
+ elif hasattr(attribute, '__call__'):
+ # Ignore methods and other callables.
+ pass
+ elif isinstance(attribute, (str, int, bool, float, type(None))):
+ # Primitive types can be passed through unmodified.
+ output[attribute_name] = attribute
+ elif isinstance(attribute, list):
+ # Recursively deal with items in lists.
+ output[attribute_name] = [
+ self.to_representation(item) for item in attribute
+ ]
+ elif isinstance(attribute, dict):
+ # Recursively deal with items in dictionaries.
+ output[attribute_name] = {
+ str(key): self.to_representation(value)
+ for key, value in attribute.items()
+ }
+ else:
+ # Force anything else to its string representation.
+ output[attribute_name] = str(attribute)
---
# Advanced serializer usage
-You can create customized subclasses of `ModelSerializer` or `HyperlinkedModelSerializer` that use a different set of default fields.
+## 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.
+
+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.
+
+The signatures for these methods are as follows:
+
+#### `.to_representation(self, obj)`
-Doing so should be considered advanced usage, and will only be needed if you have some particular serializer requirements that you often need to repeat.
+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.
+
+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.
## Dynamically modifying fields
@@ -514,11 +877,11 @@ For example, if you wanted to be able to set which fields should be used by a se
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
-
+
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
-
- if fields:
+
+ if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
@@ -538,47 +901,15 @@ This would then allow you to do the following:
>>> print UserSerializer(user, fields=('id', 'email'))
{'id': 2, 'email': 'jon@example.com'}
-## Customising the default fields
+## Customizing the default fields
-The `field_mapping` attribute is a dictionary that maps model classes to serializer classes. Overriding the attribute will let you set a different set of default serializer classes.
+REST framework 2 provided an API to allow developers to override how a `ModelSerializer` class would automatically generate the default set of fields.
-For more advanced customization than simply changing the default serializer class you can override various `get_<field_type>_field` methods. Doing so will allow you to customize the arguments that each serializer field is initialized with. Each of these methods may either return a field or serializer instance, or `None`.
-
-### get_pk_field
-
-**Signature**: `.get_pk_field(self, model_field)`
-
-Returns the field instance that should be used to represent the pk field.
-
-### get_nested_field
-
-**Signature**: `.get_nested_field(self, model_field, related_model, to_many)`
-
-Returns the field instance that should be used to represent a related field when `depth` is specified as being non-zero.
-
-Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship.
-
-### get_related_field
-
-**Signature**: `.get_related_field(self, model_field, related_model, to_many)`
-
-Returns the field instance that should be used to represent a related field when `depth` is not specified, or when nested representations are being used and the depth reaches zero.
-
-Note that the `model_field` argument will be `None` for reverse relationships. The `related_model` argument will be the model class for the target of the field. The `to_many` argument will be a boolean indicating if this is a to-one or to-many relationship.
-
-### get_field
-
-**Signature**: `.get_field(self, model_field)`
-
-Returns the field instance that should be used for non-relational, non-pk fields.
-
-### Example
+This API included the `.get_field()`, `.get_pk_field()` and other methods.
-The following custom model serializer could be used as a base class for model serializers that should always exclude the pk by default.
+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.
- class NoPKModelSerializer(serializers.ModelSerializer):
- def get_pk_field(self, model_field):
- return None
+A new interface for controlling this behavior is currently planned for REST framework 3.1.
---
@@ -600,6 +931,8 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
[relations]: relations.md
+[model-managers]: https://docs.djangoproject.com/en/dev/topics/db/managers/
+[encapsulation-blogpost]: http://www.dabapps.com/blog/django-models-and-encapsulation/
[mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
[django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis
[django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md
index 6a855c92..9005511b 100644
--- a/docs/api-guide/settings.md
+++ b/docs/api-guide/settings.md
@@ -1,4 +1,4 @@
-<a class="github" href="settings.py"></a>
+source: settings.py
# Settings
@@ -51,7 +51,7 @@ 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:
@@ -74,7 +74,7 @@ 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.
+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:
@@ -154,13 +154,13 @@ Default: `None`
### SEARCH_PARAM
-The name of a query paramater, 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 paramater, 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`
@@ -321,7 +321,7 @@ 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 prefered 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`
@@ -399,6 +399,12 @@ This should be a function with the following signature:
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.
+
+Default: `'non_field_errors'`
+
#### URL_FIELD_NAME
A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`.
diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md
index 64c46434..d81e092c 100644
--- a/docs/api-guide/status-codes.md
+++ b/docs/api-guide/status-codes.md
@@ -1,4 +1,4 @@
-<a class="github" href="status.py"></a>
+source: status.py
# Status Codes
@@ -27,7 +27,7 @@ The module also includes a set of helper functions for testing if a status code
url = reverse('index')
response = self.client.get(url)
self.assertTrue(status.is_success(response.status_code))
-
+
For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616]
and [RFC 6585][rfc6585].
@@ -51,7 +51,7 @@ This class of status code indicates that the client's request was successfully r
HTTP_205_RESET_CONTENT
HTTP_206_PARTIAL_CONTENT
-## Redirection - 3xx
+## 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.
diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md
index 72c33961..d059fdab 100644
--- a/docs/api-guide/testing.md
+++ b/docs/api-guide/testing.md
@@ -1,4 +1,4 @@
-<a class="github" href="test.py"></a>
+source: test.py
# Testing
@@ -170,7 +170,7 @@ This can be a useful shortcut if you're testing the API but don't want to have t
To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`.
- client.force_authenticate(user=None)
+ client.force_authenticate(user=None)
## CSRF validation
@@ -197,7 +197,7 @@ You can use any of REST framework's test case classes as you would for the regul
from django.core.urlresolvers import reverse
from rest_framework import status
- from rest_framework.test import APITestCase
+ from rest_framework.test import APITestCase
class AccountTests(APITestCase):
def test_create_account(self):
diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md
index 16a7457b..3f668867 100644
--- a/docs/api-guide/throttling.md
+++ b/docs/api-guide/throttling.md
@@ -1,4 +1,4 @@
-<a class="github" href="throttling.py"></a>
+source: throttling.py
# Throttling
@@ -74,7 +74,7 @@ If you need to strictly identify unique client IP addresses, you'll need to firs
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 identifing 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
@@ -83,9 +83,9 @@ The throttle classes provided by REST framework use Django's cache backend. You
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')
+ cache = get_cache('alternate')
-You'll need to rememeber 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.
---
@@ -147,15 +147,15 @@ For example, given the following views...
class ContactListView(APIView):
throttle_scope = 'contacts'
...
-
+
class ContactDetailView(ApiView):
throttle_scope = 'contacts'
...
- class UploadView(APIView):
+ class UploadView(APIView):
throttle_scope = 'uploads'
...
-
+
...and the following settings.
REST_FRAMEWORK = {
diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md
new file mode 100644
index 00000000..f087e191
--- /dev/null
+++ b/docs/api-guide/validators.md
@@ -0,0 +1,231 @@
+<a class="github" href="validators.py"></a>
+
+---
+
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
+
+# Validators
+
+> Validators can be useful for re-using validation logic between different types of fields.
+>
+> &mdash; [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.
+
+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.
+
+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.
+
+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.
+
+ 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`:
+
+ class CustomerReportSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = CustomerReportRecord
+
+If we open up the Django shell using `manage.py shell` we can now
+
+ >>> from project.example.serializers import CustomerReportSerializer
+ >>> serializer = CustomerReportSerializer()
+ >>> print(repr(serializer))
+ CustomerReportSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ time_raised = DateTimeField(read_only=True)
+ reference = CharField(max_length=20, validators=[<UniqueValidator(queryset=CustomerReportRecord.objects.all())>])
+ 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.
+
+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.
+
+---
+
+## UniqueValidator
+
+This validator can be used to enforce the `unique=True` constraint on model fields.
+It takes a single required argument, and an optional `messages` argument:
+
+* `queryset` *required* - This is the queryset against which uniqueness should be enforced.
+* `message` - The error message that should be used when validation fails.
+
+This validator should be applied to *serializer fields*, like so:
+
+ slug = SlugField(
+ max_length=100,
+ validators=[UniqueValidator(queryset=BlogPost.objects.all())]
+ )
+
+## UniqueTogetherValidator
+
+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.
+* `message` - The error message that should be used when validation fails.
+
+The validator should be applied to *serializer classes*, like so:
+
+ class ExampleSerializer(serializers.Serializer):
+ # ...
+ class Meta:
+ # ToDo items belong to a parent list, and have an ordering defined
+ # by the 'position' field. No two items in a given list may share
+ # the same position.
+ validators = [
+ UniqueTogetherValidator(
+ queryset=ToDoItem.objects.all(),
+ fields=('list', 'position')
+ )
+ ]
+
+---
+
+**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.
+
+---
+
+## UniqueForDateValidator
+
+## UniqueForMonthValidator
+
+## 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:
+
+* `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:
+
+ class ExampleSerializer(serializers.Serializer):
+ # ...
+ class Meta:
+ # Blog posts should have a slug that is unique for the current year.
+ validators = [
+ UniqueForYearValidator(
+ queryset=BlogPostItem.objects.all(),
+ field='slug',
+ date_field='published'
+ )
+ ]
+
+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.
+
+#### 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`.
+
+ 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.
+
+ 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`.
+
+#### 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.
+
+ published = serializers.HiddenField(default=timezone.now)
+
+---
+
+**Note**: The `UniqueFor<Range>Validation` 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 'default' argument usage
+
+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.
+
+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.
+
+ owner = serializers.HiddenField(
+ default=CurrentUserDefault()
+ )
+
+#### CreateOnlyDefault
+
+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.
+
+ created_at = serializers.DateTimeField(
+ read_only=True,
+ default=CreateOnlyDefault(timezone.now)
+ )
+
+---
+
+# Writing custom validators
+
+You can use any of Django's existing validators, or write your own custom validators.
+
+## Function based
+
+A validator may be any callable that raises a `serializers.ValidationError` on failure.
+
+ def even_number(value):
+ if value % 2 != 0:
+ raise serializers.ValidationError('This field must be an even number.')
+
+## 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.
+
+ class MultipleOf:
+ def __init__(self, base):
+ self.base = base
+
+ def __call__(self, value):
+ if value % self.base != 0
+ message = 'This field must be a multiple of %d.' % self.base
+ raise serializers.ValidationError(message)
+
+#### 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.
+
+ def set_context(self, serializer_field):
+ # Determine if this is an update or a create operation.
+ # In `__call__` we can then use that information to modify the validation behavior.
+ self.is_update = serializer_field.parent.instance is not None
+
+[cite]: https://docs.djangoproject.com/en/dev/ref/validators/
diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md
index 194a7a6b..31c62682 100644
--- a/docs/api-guide/views.md
+++ b/docs/api-guide/views.md
@@ -1,4 +1,5 @@
-<a class="github" href="decorators.py"></a> <a class="github" href="views.py"></a>
+source: decorators.py
+ views.py
# Class Based Views
@@ -26,7 +27,7 @@ For example:
class ListUsers(APIView):
"""
View to list all users in the system.
-
+
* Requires token authentication.
* Only admin users are able to access this view.
"""
@@ -54,7 +55,7 @@ The following attributes control the pluggable aspects of API views.
### .permission_classes
-### .content_negotiation_class
+### .content_negotiation_class
## API policy instantiation methods
diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md
index 9030e3ee..28186c64 100644
--- a/docs/api-guide/viewsets.md
+++ b/docs/api-guide/viewsets.md
@@ -1,4 +1,4 @@
-<a class="github" href="viewsets.py"></a>
+source: viewsets.py
# ViewSets
@@ -124,7 +124,7 @@ For example:
@detail_route(methods=['post'])
def set_password(self, request, pk=None):
user = self.get_object()
- serializer = PasswordSerializer(data=request.DATA)
+ serializer = PasswordSerializer(data=request.data)
if serializer.is_valid():
user.set_password(serializer.data['password'])
user.save()
diff --git a/docs/css/default.css b/docs/css/default.css
index 7f3acfed..8c9cd536 100644
--- a/docs/css/default.css
+++ b/docs/css/default.css
@@ -181,7 +181,7 @@ body{
}
.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand{
- color: white;
+ color: white;
}
.nav-list > .active > a, .navbar .navbar-inner .nav li a:hover {
@@ -190,8 +190,20 @@ body{
}
.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li{
- color: #A30000;
+ color: #A30000;
+}
+
+.dropdown-menu .active > a,
+.dropdown-menu .active > a:hover {
+ background-image: none;
}
+
+.navbar-inverse .nav .dropdown .active > a,
+.navbar-inverse .nav .dropdown .active > a:hover,
+.navbar-inverse .nav .dropdown .active > a:focus {
+ background-color: #eeeeee;
+}
+
.navbar .navbar-inner .dropdown-menu li a:hover{
background: #eeeeee;
color: #c20000;
diff --git a/docs/index.md b/docs/index.md
index 7e6f520c..dc7bb6d0 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -9,6 +9,10 @@
---
+**Note**: This is the documentation for the **version 3.0** of REST framework. Documentation for [version 2.4](http://tomchristie.github.io/rest-framework-2-docs/) is also available.
+
+---
+
<p>
<h1 style="position: absolute;
width: 1px;
@@ -22,9 +26,6 @@
<img alt="Django REST Framework" title="Logo by Jake 'Sid' Smith" src="img/logo.png" width="600px" style="display: block; margin: 0 auto 0 auto">
</p>
-<!--
-# Django REST framework
--->
Django REST framework is a powerful and flexible toolkit that makes it easy to build Web APIs.
@@ -43,14 +44,12 @@ Some reasons you might want to use REST framework:
**Above**: *Screenshot from the browsable API*
-----
-
## Requirements
REST framework requires the following:
-* Python (2.6.5+, 2.7, 3.2, 3.3)
-* Django (1.4.2+, 1.5, 1.6, 1.7)
+* Python (2.6.5+, 2.7, 3.2, 3.3, 3.4)
+* Django (1.4.11+, 1.5.5+, 1.6, 1.7)
The following packages are optional:
@@ -82,10 +81,10 @@ Add `'rest_framework'` to your `INSTALLED_APPS` setting.
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 = patterns('',
+ 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.
@@ -170,6 +169,7 @@ The API guide is your complete reference manual to all the functionality provide
* [Serializers][serializers]
* [Serializer fields][fields]
* [Serializer relations][relations]
+* [Validators][validators]
* [Authentication][authentication]
* [Permissions][permissions]
* [Throttling][throttling]
@@ -289,6 +289,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
[serializers]: api-guide/serializers.md
[fields]: api-guide/fields.md
[relations]: api-guide/relations.md
+[validators]: api-guide/validators.md
[authentication]: api-guide/authentication.md
[permissions]: api-guide/permissions.md
[throttling]: api-guide/throttling.md
diff --git a/docs/requirements.txt b/docs/requirements.txt
deleted file mode 100644
index a91fb978..00000000
--- a/docs/requirements.txt
+++ /dev/null
@@ -1 +0,0 @@
-markdown>=2.1.0
diff --git a/docs/template.html b/docs/template.html
deleted file mode 100644
index bb3ae221..00000000
--- a/docs/template.html
+++ /dev/null
@@ -1,238 +0,0 @@
-<!DOCTYPE html>
-<html lang="en">
-<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <meta charset="utf-8">
- <title>{{ title }}</title>
- <link href="{{ base_url }}/img/favicon.ico" rel="icon" type="image/x-icon">
- <link rel="canonical" href="{{ canonical_url }}"/>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="{{ description }}">
- <meta name="author" content="Tom Christie">
-
- <!-- Le styles -->
- <link href="{{ base_url }}/css/prettify.css" rel="stylesheet">
- <link href="{{ base_url }}/css/bootstrap.css" rel="stylesheet">
- <link href="{{ base_url }}/css/bootstrap-responsive.css" rel="stylesheet">
- <link href="{{ base_url }}/css/default.css" rel="stylesheet">
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <script type="text/javascript">
-
- var _gaq = _gaq || [];
- _gaq.push(['_setAccount', 'UA-18852272-2']);
- _gaq.push(['_trackPageview']);
-
- (function() {
- var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
- ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
- })();
-
- </script>
- <style>
-span.fusion-wrap a {
- display: block;
- margin-top: 10px;
- color: black;
-}
-
-a.fusion-poweredby {
- display: block;
- margin-top: 10px;
-}
-@media (max-width: 767px) {
- div.promo {display: none;}
-}
-</style>
- </head>
- <body onload="prettyPrint()" class="{{ page_id }}-page">
-
- <div class="wrapper">
-
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="navbar-inner">
- <div class="container-fluid">
- <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
- <a class="repo-link btn btn-inverse btn-small {{ next_url_disabled }}" href="{{ next_url }}">Next <i class="icon-arrow-right icon-white"></i></a>
- <a class="repo-link btn btn-inverse btn-small {{ prev_url_disabled }}" href="{{ prev_url }}"><i class="icon-arrow-left icon-white"></i> Previous</a>
- <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
- <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </a>
- <a class="brand" href="{{ base_url }}{{ index }}">Django REST framework</a>
- <div class="nav-collapse collapse">
- <ul class="nav">
- <li><a href="{{ base_url }}{{ index }}">Home</a></li>
- <li class="dropdown">
- <a href="#" class="dropdown-toggle" data-toggle="dropdown">Tutorial <b class="caret"></b></a>
- <ul class="dropdown-menu">
- <li><a href="{{ base_url }}/tutorial/quickstart{{ suffix }}">Quickstart</a></li>
- <li><a href="{{ base_url }}/tutorial/1-serialization{{ suffix }}">1 - Serialization</a></li>
- <li><a href="{{ base_url }}/tutorial/2-requests-and-responses{{ suffix }}">2 - Requests and responses</a></li>
- <li><a href="{{ base_url }}/tutorial/3-class-based-views{{ suffix }}">3 - Class based views</a></li>
- <li><a href="{{ base_url }}/tutorial/4-authentication-and-permissions{{ suffix }}">4 - Authentication and permissions</a></li>
- <li><a href="{{ base_url }}/tutorial/5-relationships-and-hyperlinked-apis{{ suffix }}">5 - Relationships and hyperlinked APIs</a></li>
- <li><a href="{{ base_url }}/tutorial/6-viewsets-and-routers{{ suffix }}">6 - Viewsets and routers</a></li>
- </ul>
- </li>
- <li class="dropdown">
- <a href="#" class="dropdown-toggle" data-toggle="dropdown">API Guide <b class="caret"></b></a>
- <ul class="dropdown-menu">
- <li><a href="{{ base_url }}/api-guide/requests{{ suffix }}">Requests</a></li>
- <li><a href="{{ base_url }}/api-guide/responses{{ suffix }}">Responses</a></li>
- <li><a href="{{ base_url }}/api-guide/views{{ suffix }}">Views</a></li>
- <li><a href="{{ base_url }}/api-guide/generic-views{{ suffix }}">Generic views</a></li>
- <li><a href="{{ base_url }}/api-guide/viewsets{{ suffix }}">Viewsets</a></li>
- <li><a href="{{ base_url }}/api-guide/routers{{ suffix }}">Routers</a></li>
- <li><a href="{{ base_url }}/api-guide/parsers{{ suffix }}">Parsers</a></li>
- <li><a href="{{ base_url }}/api-guide/renderers{{ suffix }}">Renderers</a></li>
- <li><a href="{{ base_url }}/api-guide/serializers{{ suffix }}">Serializers</a></li>
- <li><a href="{{ base_url }}/api-guide/fields{{ suffix }}">Serializer fields</a></li>
- <li><a href="{{ base_url }}/api-guide/relations{{ suffix }}">Serializer relations</a></li>
- <li><a href="{{ base_url }}/api-guide/authentication{{ suffix }}">Authentication</a></li>
- <li><a href="{{ base_url }}/api-guide/permissions{{ suffix }}">Permissions</a></li>
- <li><a href="{{ base_url }}/api-guide/throttling{{ suffix }}">Throttling</a></li>
- <li><a href="{{ base_url }}/api-guide/filtering{{ suffix }}">Filtering</a></li>
- <li><a href="{{ base_url }}/api-guide/pagination{{ suffix }}">Pagination</a></li>
- <li><a href="{{ base_url }}/api-guide/content-negotiation{{ suffix }}">Content negotiation</a></li>
- <li><a href="{{ base_url }}/api-guide/format-suffixes{{ suffix }}">Format suffixes</a></li>
- <li><a href="{{ base_url }}/api-guide/reverse{{ suffix }}">Returning URLs</a></li>
- <li><a href="{{ base_url }}/api-guide/exceptions{{ suffix }}">Exceptions</a></li>
- <li><a href="{{ base_url }}/api-guide/status-codes{{ suffix }}">Status codes</a></li>
- <li><a href="{{ base_url }}/api-guide/testing{{ suffix }}">Testing</a></li>
- <li><a href="{{ base_url }}/api-guide/settings{{ suffix }}">Settings</a></li>
- </ul>
- </li>
- <li class="dropdown">
- <a href="#" class="dropdown-toggle" data-toggle="dropdown">Topics <b class="caret"></b></a>
- <ul class="dropdown-menu">
- <li><a href="{{ base_url }}/topics/documenting-your-api{{ suffix }}">Documenting your API</a></li>
- <li><a href="{{ base_url }}/topics/ajax-csrf-cors{{ suffix }}">AJAX, CSRF & CORS</a></li>
- <li><a href="{{ base_url }}/topics/browser-enhancements{{ suffix }}">Browser enhancements</a></li>
- <li><a href="{{ base_url }}/topics/browsable-api{{ suffix }}">The Browsable API</a></li>
- <li><a href="{{ base_url }}/topics/rest-hypermedia-hateoas{{ suffix }}">REST, Hypermedia & HATEOAS</a></li>
- <li><a href="{{ base_url }}/topics/third-party-resources{{ suffix }}">Third Party Resources</a></li>
- <li><a href="{{ base_url }}/topics/contributing{{ suffix }}">Contributing to REST framework</a></li>
- <li><a href="{{ base_url }}/topics/rest-framework-2-announcement{{ suffix }}">2.0 Announcement</a></li>
- <li><a href="{{ base_url }}/topics/2.2-announcement{{ suffix }}">2.2 Announcement</a></li>
- <li><a href="{{ base_url }}/topics/2.3-announcement{{ suffix }}">2.3 Announcement</a></li>
- <li><a href="{{ base_url }}/topics/2.4-announcement{{ suffix }}">2.4 Announcement</a></li>
- <li><a href="{{ base_url }}/topics/kickstarter-announcement{{ suffix }}">Kickstarter Announcement</a></li>
- <li><a href="{{ base_url }}/topics/release-notes{{ suffix }}">Release Notes</a></li>
- <li><a href="{{ base_url }}/topics/credits{{ suffix }}">Credits</a></li>
- </ul>
- </li>
- </ul>
- <ul class="nav pull-right">
- <!-- TODO
- <li class="dropdown">
- <a href="#" class="dropdown-toggle" data-toggle="dropdown">Version: 2.0.0 <b class="caret"></b></a>
- <ul class="dropdown-menu">
- <li><a href="#">Trunk</a></li>
- <li><a href="#">2.0.0</a></li>
- </ul>
- </li>
- -->
- </ul>
- </div><!--/.nav-collapse -->
- </div>
- </div>
- </div>
-
- <div class="body-content">
- <div class="container-fluid">
-
-<!-- Search Modal -->
-<div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
- <h3 id="myModalLabel">Documentation search</h3>
- </div>
- <div class="modal-body">
- <!-- Custom google search -->
- <script>
- (function() {
- var cx = '015016005043623903336:rxraeohqk6w';
- var gcse = document.createElement('script');
- gcse.type = 'text/javascript';
- gcse.async = true;
- gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
- '//www.google.com/cse/cse.js?cx=' + cx;
- var s = document.getElementsByTagName('script')[0];
- s.parentNode.insertBefore(gcse, s);
- })();
- </script>
- <gcse:search></gcse:search>
- </div>
- <div class="modal-footer">
- <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
- </div>
-</div>
-
- <div class="row-fluid">
-
- <div class="span3">
- <!-- TODO
- <p style="margin-top: -12px">
- <a class="btn btn-mini btn-primary" style="width: 60px">&laquo; previous</a>
- <a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next &raquo;</a>
- </p>
- -->
- <div id="table-of-contents">
- <ul class="nav nav-list side-nav well sidebar-nav-fixed">
- {{ toc }}
- <div class="promo">
- {{ ad_block }}
- </div>
-</ul>
-
- </div>
- </div>
-
- <div id="main-content" class="span9">
- {{ content }}
- </div><!--/span-->
- </div><!--/row-->
- </div><!--/.fluid-container-->
- </div><!--/.body content-->
-
- <div id="push"></div>
- </div><!--/.wrapper -->
-
- <footer class="span12">
- <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
- </footer>
-
- <!-- Le javascript
- ================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script src="{{ base_url }}/js/jquery-1.8.1-min.js"></script>
- <script src="{{ base_url }}/js/prettify-1.0.js"></script>
- <script src="{{ base_url }}/js/bootstrap-2.1.1-min.js"></script>
-
- <script>
- //$('.side-nav').scrollspy()
- var shiftWindow = function() { scrollBy(0, -50) };
- if (location.hash) shiftWindow();
- window.addEventListener("hashchange", shiftWindow);
-
- $('.dropdown-menu').on('click touchstart', function(event) {
- event.stopPropagation();
- });
-
- // Dynamically force sidenav to no higher than browser window
- $('.side-nav').css('max-height', window.innerHeight - 130);
-
- $(function(){
- $(window).resize(function(){
- $('.side-nav').css('max-height', window.innerHeight - 130);
- });
- });
- </script>
-</body></html>
diff --git a/docs/topics/2.2-announcement.md b/docs/topics/2.2-announcement.md
index a997c782..1df52cff 100644
--- a/docs/topics/2.2-announcement.md
+++ b/docs/topics/2.2-announcement.md
@@ -42,7 +42,7 @@ The 2.2 release makes a few changes to the API, in order to make it more consist
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)
@@ -58,10 +58,10 @@ The change also applies to serializers. If you have a nested serializer, you sh
class Meta:
model = Track
fields = ('name', 'duration')
-
+
class AlbumSerializer(serializer.ModelSerializer):
tracks = TrackSerializer(many=True)
-
+
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
@@ -87,7 +87,7 @@ For example, is a user account has an optional foreign key to a company, that yo
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`.
diff --git a/docs/topics/2.3-announcement.md b/docs/topics/2.3-announcement.md
index ba435145..9c9f3e9f 100644
--- a/docs/topics/2.3-announcement.md
+++ b/docs/topics/2.3-announcement.md
@@ -15,7 +15,7 @@ As an example of just how simple REST framework APIs can now be, here's an API w
"""
A REST framework API for viewing and editing users and groups.
"""
- from django.conf.urls.defaults import url, patterns, include
+ from django.conf.urls.defaults import url, include
from django.contrib.auth.models import User, Group
from rest_framework import viewsets, routers
@@ -27,7 +27,7 @@ As an example of just how simple REST framework APIs can now be, here's an API w
class GroupViewSet(viewsets.ModelViewSet):
model = Group
-
+
# Routers provide an easy way of automatically determining the URL conf
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
@@ -36,10 +36,10 @@ As an example of just how simple REST framework APIs can now be, here's an API w
# Wire up our API using automatic URL routing.
# Additionally, we include login URLs for the browseable API.
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'^', include(router.urls)),
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.
@@ -197,13 +197,13 @@ Usage of the old-style attributes continues to be supported, but will raise a `P
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
+## 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.
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
@@ -211,7 +211,7 @@ The mechanics of how the names and descriptions used in the browseable API are g
If you've been customizing this behavior, for example perhaps to use `rst` markup for the browseable 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.
---
diff --git a/docs/topics/2.4-announcement.md b/docs/topics/2.4-announcement.md
index 09294b91..f38c743c 100644
--- a/docs/topics/2.4-announcement.md
+++ b/docs/topics/2.4-announcement.md
@@ -23,7 +23,7 @@ The documentation has previously stated that usage of the more explicit style is
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 unneccessary 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.
@@ -164,8 +164,8 @@ Once again, many thanks to all the generous [backers and sponsors][kickstarter-s
[lts-releases]: https://docs.djangoproject.com/en/dev/internals/release-process/#long-term-support-lts-releases
[2-4-release-notes]: release-notes#240
-[view-name-and-description-settings]: ../api-guide/settings/#view-names-and-descriptions
-[client-ip-identification]: ../api-guide/throttling/#how-clients-are-identified
+[view-name-and-description-settings]: ../api-guide/settings#view-names-and-descriptions
+[client-ip-identification]: ../api-guide/throttling#how-clients-are-identified
[2-3-announcement]: 2.3-announcement
[github-labels]: https://github.com/tomchristie/django-rest-framework/issues
[github-milestones]: https://github.com/tomchristie/django-rest-framework/milestones
diff --git a/docs/topics/3.0-announcement.md b/docs/topics/3.0-announcement.md
index 029d9896..b32fe510 100644
--- a/docs/topics/3.0-announcement.md
+++ b/docs/topics/3.0-announcement.md
@@ -1,70 +1,335 @@
-**THIS DOCUMENT IS CURRENTLY A WORK IN PROGRESS**
+# REST framework 3.0
-See the [Version 3.0 GitHub issue](https://github.com/tomchristie/django-rest-framework/pull/1800) for more details.
+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.
-# REST framework 3.0
+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.
+
+3.0 is the first of three releases that have been funded by our recent [Kickstarter campaign](kickstarter.com/projects/tomchristie/django-rest-framework-3).
-**Note incremental nature, discuss upgrading.**
+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.
-## Motivation
+## New features
-**TODO**
+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`.
+* [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 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.
+
+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.
+
+Below is an in-depth guide to the API changes and migration notes for 3.0.
---
## Request objects
-#### The `request.data` property.
+#### 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.
-**TODO**
+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.
-#### The parser API.
+You may now pass all the request data to a serializer class in a single argument:
-**TODO**
+ # Do this...
+ ExampleSerializer(data=request.data)
+
+Instead of passing the files argument separately:
+
+ # Don't do this...
+ 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`.
## Serializers
#### Single-step object creation.
-**TODO**: Drop `.restore_object()`, use `.create()` and `.update()` which should save the instance.
+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.
+
+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?
+
+We now use single-step object creation, like so:
+
+1. Validating the data makes the cleaned data available as `serializer.validated_data`.
+2. Calling `serializer.save()` then saves and returns the new object instance.
+
+The resulting API changes are further detailed below.
+
+#### The `.create()` and `.update()` methods.
+
+The `.restore_object()` method is now replaced with two separate methods, `.create()` and `.update()`.
+
+These methods also replace the optional `.save_object()` method, which no longer exists.
+
+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.
+
+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:
+ # Update existing instance
+ instance.title = attrs.get('title', instance.title)
+ instance.code = attrs.get('code', instance.code)
+ instance.linenos = attrs.get('linenos', instance.linenos)
+ instance.language = attrs.get('language', instance.language)
+ instance.style = attrs.get('style', instance.style)
+ return instance
+
+ # Create new instance
+ return Snippet(**attrs)
+
+This would now be split out into two separate methods.
+
+ def update(self, instance, validated_data):
+ instance.title = validated_data.get('title', instance.title)
+ instance.code = validated_data.get('code', instance.code)
+ instance.linenos = validated_data.get('linenos', instance.linenos)
+ instance.language = validated_data.get('language', instance.language)
+ instance.style = validated_data.get('style', instance.style)
+ instance.save()
+ return instance
+
+ def create(self, validated_data):
+ return Snippet.objects.create(**validated_data)
+
+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.
+
+For example the following code *is no longer valid*:
+
+ if serializer.is_valid():
+ name = serializer.object.name # Inspect validated field data.
+ logging.info('Creating ticket "%s"' % name)
+ 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.
+
+The corresponding code would now look like this:
+
+ if serializer.is_valid():
+ name = serializer.validated_data['name'] # Inspect validated field data.
+ logging.info('Creating ticket "%s"' % name)
+ serializer.save(user=request.user) # Include the user when saving.
+
+#### Using `.is_valid(raise_exception=True)`
+
+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.
+
+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.
+
+#### 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.
+
+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 are always 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.
+
+#### Change to `validate_<field_name>`.
+
+The `validate_<field_name>` 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.
+
+ 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.
+
+Because `.validate_<field_name>` 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`
+
+ 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:
+
+ 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.
+
+#### Removal of `transform_<field_name>`.
-**TODO**: Drop`.object`, use `.validated_data` or get the instance with `.save()`.
+The under-used `transform_<field_name>` 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.
-#### Always use `fields`, not `exclude`.
+For example:
-The `exclude` option is no longer available. You should use the more explicit `fields` option instead.
+ def to_representation(self, instance):
+ ret = super(UserSerializer, self).to_representation(instance)
+ 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.
+
+If you absolutely need to preserve `transform_<field_name>` 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):
+ """
+ A custom ModelSerializer class that preserves 2.x style `transform_<field_name>` behavior.
+ """
+ def to_representation(self, instance):
+ ret = super(BaseModelSerializer, self).to_representation(instance)
+ for key, value in ret.items():
+ method = getattr(self, 'transform_' + key, None)
+ if method is not None:
+ ret[key] = method(value)
+ return ret
+
+#### 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.
+
+It's important to note that this change also means that the model `.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.
+
+#### 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:
+
+* 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.
+
+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:
+ >>> model = Profile
+ >>> fields = ('address', 'phone')
+ >>>
+ >>> class UserSerializer(serializers.ModelSerializer):
+ >>> profile = ProfileSerializer()
+ >>> class Meta:
+ >>> model = User
+ >>> fields = ('username', 'email', 'profile')
+ >>>
+ >>> data = {
+ >>> 'username': 'lizzy',
+ >>> 'email': 'lizzy@example.com',
+ >>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'}
+ >>> }
+ >>>
+ >>> serializer = UserSerializer(data=data)
+ >>> 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.
+
+ class UserSerializer(serializers.ModelSerializer):
+ profile = ProfileSerializer()
+
+ class Meta:
+ model = User
+ fields = ('username', 'email', 'profile')
+
+ def create(self, validated_data):
+ profile_data = validated_data.pop('profile')
+ user = User.objects.create(**validated_data)
+ 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.
+
+#### Printable serializer representations.
+
+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:
+
+ class LocationRating(models.Model):
+ location = models.CharField(max_length=100)
+ rating = models.IntegerField()
+ created_by = models.ForeignKey(User)
+
+Let's create a simple `ModelSerializer` class corresponding to the `LocationRating` model.
+
+ class LocationRatingSerializer(serializer.ModelSerializer):
+ class Meta:
+ model = LocationRating
+
+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
+ LocationRatingSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ location = CharField(max_length=100)
+ rating = IntegerField()
+ created_by = PrimaryKeyRelatedField(queryset=User.objects.all())
#### The `extra_kwargs` option.
-The `read_only_fields` and `write_only_fields` options have been removed 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:
model = MyModel
fields = ('id', 'email', 'notes', 'is_admin')
extra_kwargs = {
- 'is_admin': {'read_only': True}
+ 'is_admin': {'write_only': True}
}
Alternatively, specify the field explicitly on the serializer class:
class MySerializer(serializer.ModelSerializer):
- is_admin = serializers.BooleanField(read_only=True)
+ is_admin = serializers.BooleanField(write_only=True)
class Meta:
model = MyModel
fields = ('id', 'email', 'notes', 'is_admin')
+The `read_only_fields` option remains as a convenient shortcut for the more common case.
+
#### Changes to `HyperlinkedModelSerializer`.
-The `view_name` and `lookup_field` options have been removed. 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:
model = MyModel
fields = ('url', 'email', 'notes', 'is_admin')
extra_kwargs = {
- 'url': {'lookup_field': 'uuid'}
+ 'url': {'lookup_field': 'uuid'}
}
Alternatively, specify the field explicitly on the serializer class:
@@ -81,15 +346,15 @@ Alternatively, specify the field explicitly on the serializer class:
#### Fields for model methods and properties.
-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()
to_email = models.EmailField()
message = models.CharField(max_length=1000)
- def expiry_date(self):
- return self.created + datetime.timedelta(days=30)
+ def expiry_date(self):
+ return self.created + datetime.timedelta(days=30)
You can include `expiry_date` as a field option on a `ModelSerializer` class.
@@ -107,55 +372,382 @@ These fields will be mapped to `serializers.ReadOnlyField()` instances.
message = CharField(max_length=1000)
expiry_date = ReadOnlyField()
+#### The `ListSerializer` class.
+
+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 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.
+
+#### The `BaseSerializer` class.
+
+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:
+
+* `.data` - Returns the outgoing primitive representation.
+* `.is_valid()` - Deserializes and validates incoming data.
+* `.validated_data` - Returns the validated incoming data.
+* `.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:
+
+* `.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`.
+
+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:
+
+ 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.
+
+ class HighScoreSerializer(serializers.BaseSerializer):
+ def to_representation(self, obj):
+ return {
+ 'score': obj.score,
+ 'player_name': obj.player_name
+ }
+
+We can now use this class to serialize single `HighScore` instances:
+
+ @api_view(['GET'])
+ def high_score(request, pk):
+ instance = HighScore.objects.get(pk=pk)
+ serializer = HighScoreSerializer(instance)
+ return Response(serializer.data)
+
+Or use it to serialize multiple instances:
+
+ @api_view(['GET'])
+ def all_high_scores(request):
+ queryset = HighScore.objects.order_by('-score')
+ serializer = HighScoreSerializer(queryset, many=True)
+ return Response(serializer.data)
+
+##### 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.
+
+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.
+
+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):
+ score = data.get('score')
+ player_name = data.get('player_name')
+
+ # Perform the data validation.
+ if not score:
+ raise ValidationError({
+ 'score': 'This field is required.'
+ })
+ if not player_name:
+ raise ValidationError({
+ 'player_name': 'This field is required.'
+ })
+ if len(player_name) > 10:
+ raise ValidationError({
+ 'player_name': 'May not be more than 10 characters.'
+ })
+
+ # Return the validated values. This will be available as
+ # the `.validated_data` property.
+ return {
+ 'score': int(score),
+ 'player_name': player_name
+ }
+
+ def to_representation(self, obj):
+ return {
+ 'score': obj.score,
+ 'player_name': obj.player_name
+ }
+
+ def create(self, validated_data):
+ return HighScore.objects.create(**validated_data)
+
+#### 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 following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations.
+
+ class ObjectSerializer(serializers.BaseSerializer):
+ """
+ A read-only serializer that coerces arbitrary complex objects
+ into primitive representations.
+ """
+ def to_representation(self, obj):
+ for attribute_name in dir(obj):
+ attribute = getattr(obj, attribute_name)
+ if attribute_name('_'):
+ # Ignore private attributes.
+ pass
+ elif hasattr(attribute, '__call__'):
+ # Ignore methods and other callables.
+ pass
+ elif isinstance(attribute, (str, int, bool, float, type(None))):
+ # Primitive types can be passed through unmodified.
+ output[attribute_name] = attribute
+ elif isinstance(attribute, list):
+ # Recursively deal with items in lists.
+ output[attribute_name] = [
+ self.to_representation(item) for item in attribute
+ ]
+ elif isinstance(attribute, dict):
+ # Recursively deal with items in dictionaries.
+ output[attribute_name] = {
+ str(key): self.to_representation(value)
+ for key, value in attribute.items()
+ }
+ else:
+ # Force anything else to its string representation.
+ output[attribute_name] = str(attribute)
## Serializer fields
#### The `Field` and `ReadOnly` field classes.
-**TODO**
+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.
+* `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.
+
+#### The `required`, `allow_none`, `allow_blank` and `default` arguments.
+
+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.
+
+We now have a better separation, with separate `required`, `allow_none` 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=<value>`: 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_none=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_none=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.
#### Coercing output types.
-**TODO**
+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 `ListSerializer` class.
+#### Removal of `.validate()`.
+
+The `.validate()` method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override `to_internal_value()`.
+
+ class UppercaseCharField(serializers.CharField):
+ def to_internal_value(self, data):
+ value = super(UppercaseCharField, self).to_internal_value(data)
+ if value != value.upper():
+ raise serializers.ValidationError('The input should be uppercase only.')
+ return value
+
+Previously validation errors could be raised in either `.to_native()` or `.validate()`, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API.
+
+#### 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:
+
+ 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:
+
+ class ScoresField(ListField):
+ child = IntegerField(min_value=0, max_value=100)
+
+We can now use the `ScoresField` class inside another serializer:
+
+ scores = ScoresField()
-**TODO**
+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:
+
+ color = ChoiceField(choices=['red', 'green', 'blue'])
#### The `MultipleChoiceField` class.
-**TODO**
+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.
-**TODO** `to_representation`, `to_internal_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...
+
+ 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:
+
+* 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:
-#### Explicit `querysets` required on relational fields.
+ def get_attribute(self, obj):
+ # Pass the entire object through to `to_representation()`,
+ # instead of the standard attribute lookup.
+ return obj
+
+ def to_representation(self, value):
+ return value.__class__.__name__
+
+#### 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`.
+
+This code *would be valid* in `2.4.3`:
+
+ class AccountSerializer(serializers.ModelSerializer):
+ organizations = serializers.SlugRelatedField(slug_field='name')
+
+ class Meta:
+ model = Account
-**TODO**
+However this code *would not be valid* in `2.4.3`:
+
+ # Missing `queryset`
+ class AccountSerializer(serializers.Serializer):
+ organizations = serializers.SlugRelatedField(slug_field='name')
+
+ 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.
+
+ class AccountSerializer(serializers.ModelSerializer):
+ organizations = serializers.SlugRelatedField(
+ slug_field='name',
+ queryset=Organization.objects.all()
+ )
+
+ 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`.
#### Optional argument to `SerializerMethodField`.
-**TODO**
+The argument to `SerializerMethodField` is now optional, and defaults to `get_<field_name>`. For example the following is valid:
+
+ class AccountSerializer(serializers.Serializer):
+ # `method_name='get_billing_details'` by default.
+ billing_details = serializers.SerializerMethodField()
+
+ def get_billing_details(self, account):
+ return calculate_billing(account)
+
+In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code *will raise an error*:
+
+ billing_details = serializers.SerializerMethodField('get_billing_details')
+
+#### Enforcing consistent `source` usage.
+
+I've see several codebases that unnecessarily include the `source` argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that `source` is usually not required.
+
+The following usage will *now raise an error*:
+
+ email = serializers.EmailField(source='email')
+
+#### The `UniqueValidator` and `UniqueTogetherValidator` classes.
+
+REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit `Serializer` class instead of using `ModelSerializer`.
+
+The `UniqueValidator` should be applied to a serializer field, and takes a single `queryset` argument.
+
+ from rest_framework import serializers
+ from rest_framework.validators import UniqueValidator
+
+ class OrganizationSerializer(serializers.Serializer):
+ url = serializers.HyperlinkedIdentityField(view_name='organization_detail')
+ created = serializers.DateTimeField(read_only=True)
+ name = serializers.CharField(
+ max_length=100,
+ validators=UniqueValidator(queryset=Organization.objects.all())
+ )
+
+The `UniqueTogetherValidator` should be applied to a serializer, and takes a `queryset` argument and a `fields` argument which should be a list or tuple of field names.
+
+ class RaceResultSerializer(serializers.Serializer):
+ category = serializers.ChoiceField(['5k', '10k'])
+ position = serializers.IntegerField()
+ name = serializers.CharField(max_length=100)
+
+ default_validators = [UniqueTogetherValidator(
+ queryset=RaceResult.objects.all(),
+ fields=('category', 'position')
+ )]
+
+#### The `UniqueForDateValidator` classes.
+
+REST framework also now includes explicit validator classes for validating the `unique_for_date`, `unique_for_month`, and `unique_for_year` model field constraints. These are used internally instead of calling into `Model.full_clean()`.
+
+These classes are documented in the [Validators](../api-guide/validators.md) section of the documentation.
## Generic views
#### Simplification of view logic.
-**TODO**
+The view logic for the default method handlers has been significantly simplified, due to the new serializers API.
+
+#### Changes to pre/post save hooks.
-#### Removal of pre/post save hooks.
+The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`.
-The following method hooks no longer exist on the new, simplified, generic views: `pre_save`, `post_save`, `pre_delete`, `post_delete`.
+These methods should save the object instance by calling `serializer.save()`, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior.
-If you do need custom behavior, you might choose to instead override the `.save()` method on your serializer class. For example:
+For example:
- def save(self, *args, **kwargs):
- instance = super(MySerializer).save(*args, **kwarg)
+ def perform_create(self, serializer):
+ # Include the owner attribute directly, rather than from request data.
+ instance = serializer.save(owner=self.request.user)
+ # Perform a custom post-save action.
send_email(instance.to_email, instance.message)
- return instance
-Alternatively write your view logic exlpicitly, or tie your pre/post save behavior into the model class or model manager.
+The `pre_delete` and `post_delete` hooks no longer exist, and are replaced with `.perform_destroy(self, instance)`, which should delete the instance and perform any custom actions.
+
+ def perform_destroy(self, instance):
+ # Perform a custom pre-delete action.
+ send_deletion_alert(user=instance.created_by, deleted=instance)
+ # Delete the object instance.
+ instance.delete()
#### Removal of view attributes.
@@ -165,7 +757,54 @@ I would personally recommend that developers treat view instances as immutable o
#### PUT as create.
-**TODO**
+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 we've now opted for the 404 behavior as the default, due to it being simpler and more obvious.
+
+If you need to restore the previous behavior you may want to include [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views.
+
+#### Customizing error responses.
+
+The generic views now raise `ValidationFailed` exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly.
+
+This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views.
+
+## The metadata API
+
+Behavior for dealing with `OPTIONS` requests was previously built directly into the class based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework.
+
+This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies.
+
+## Serializers as HTML forms
+
+REST framework 3.0 includes templated HTML form rendering for serializers.
+
+This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release.
+
+Significant changes that you do need to be aware of include:
+
+* Nested HTML forms are now supported, for example, a `UserSerializer` with a nested `ProfileSerializer` will now render a nested `fieldset` when used in the browsable API.
+* Nested lists of HTML forms are not yet supported, but are planned for 3.1.
+* Because we now use templated HTML form generation, **the `widget` option is no longer available for serializer fields**. You can instead control the template that is used for a given field, by using the `style` dictionary.
+
+#### The `style` keyword argument for serializer fields.
+
+The `style` keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the `HTMLFormRenderer` uses the `base_template` key to determine which template to render the field with.
+
+For example, to use a `textarea` control instead of the default `input` control, you would use the following…
+
+ additional_notes = serializers.CharField(
+ style={'base_template': 'text_area.html'}
+ )
+
+Similarly, to use a radio button control instead of the default `select` control, you would use the following…
+
+ color_channel = serializers.ChoiceField(
+ choices=['red', 'blue', 'green'],
+ style={'base_template': 'radio.html'}
+ )
+
+This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release.
## API style
@@ -195,6 +834,28 @@ The `COMPACT_JSON` setting has been added, and can be used to revert this behavi
'COMPACT_JSON': False
}
+#### File fields as URLs
+
+The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's [standard `MEDIA_URL` setting](https://docs.djangoproject.com/en/dev/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/dev/howto/static-files/#serving-uploaded-files-in-development).
+
+You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key:
+
+ REST_FRAMEWORK = {
+ 'UPLOADED_FILES_USE_URL': False
+ }
+
+You can also modify serializer fields individually, using the `use_url` argument:
+
+ uploaded_file = serializers.FileField(use_url=False)
+
+Also note that you should pass the `request` object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form `https://example.com/url_path/filename.txt`. For example:
+
+ context = {'request': request}
+ serializer = ExampleSerializer(instance, context=context)
+ return Response(serializer.data)
+
+If the request is omitted from the context, the returned URLs will be of the form `/url_path/filename.txt`.
+
#### Throttle headers using `Retry-After`.
The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application.
@@ -227,7 +888,7 @@ You can modify this behavior globally by using the `COERCE_DECIMAL_TO_STRING` se
'COERCE_DECIMAL_TO_STRING': False
}
-Or modify it on an individual serializer field, using the `corece_to_string` keyword argument.
+Or modify it on an individual serializer field, using the `coerce_to_string` keyword argument.
# Return `Decimal` instances in `serializer.data`, not strings.
amount = serializers.DecimalField(
@@ -236,4 +897,27 @@ Or modify it on an individual serializer field, using the `corece_to_string` key
coerce_to_string=False
)
-The default JSON renderer will return float objects for uncoerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
+The default JSON renderer will return float objects for un-coerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs.
+
+## Miscellaneous notes.
+
+* The serializer `ChoiceField` does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1.
+* Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand.
+
+## What's coming next.
+
+3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes.
+
+The 3.1 release is planned to address improvements in the following components:
+
+* Public API for using serializers as HTML forms.
+* Request parsing, mediatypes & the implementation of the browsable API.
+* Introduction of a new pagination API.
+* Better support for API versioning.
+
+The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API.
+
+You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/tomchristie/django-rest-framework/milestones).
+
+[sponsors]: http://www.django-rest-framework.org/topics/kickstarter-announcement/#sponsors
+[mixins.py]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py
diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md
index 97dd4710..ad88810d 100644
--- a/docs/topics/ajax-csrf-cors.md
+++ b/docs/topics/ajax-csrf-cors.md
@@ -10,7 +10,7 @@ If you’re building a JavaScript client to interface with your Web API, you'll
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
@@ -19,7 +19,7 @@ AJAX requests that are made on a different site from the API they are communicat
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.
+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.
@@ -35,7 +35,7 @@ The best way to deal with CORS in REST framework is to add the required response
[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)
-[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
+[csrf-ajax]: https://docs.djangoproject.com/en/dev/ref/csrf/#ajax
[cors]: http://www.w3.org/TR/cors/
[ottoyiu]: https://github.com/ottoyiu/
[django-cors-headers]: https://github.com/ottoyiu/django-cors-headers/
diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md
index ad812f4b..2879db74 100644
--- a/docs/topics/browsable-api.md
+++ b/docs/topics/browsable-api.md
@@ -130,34 +130,24 @@ You can override the `BrowsableAPIRenderer.get_context()` method to customise th
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.
-#### Autocompletion
+#### Handling `ChoiceField` with large numbers of items.
-When a `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. One solution is to replace the selector by an autocomplete widget, that only loads and renders a subset of the available options as needed.
+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.
-There are [a variety of packages for autocomplete widgets][autocomplete-packages], such as [django-autocomplete-light][django-autocomplete-light]. To setup `django-autocomplete-light`, follow the [installation documentation][django-autocomplete-light-install], add the the following to the `api.html` template:
+The simplest option in this case is to replace the select input with a standard text input. For example:
- {% block script %}
- {{ block.super }}
- {% include 'autocomplete_light/static.html' %}
- {% endblock %}
-
-You can now add the `autocomplete_light.ChoiceWidget` widget to the serializer field.
-
- import autocomplete_light
+ author = serializers.HyperlinkedRelatedField(
+ queryset=User.objects.all(),
+ style={'base_template': 'input.html'}
+ )
- class BookSerializer(serializers.ModelSerializer):
- author = serializers.ChoiceField(
- widget=autocomplete_light.ChoiceWidget('AuthorAutocomplete')
- )
+#### Autocomplete
- class Meta:
- model = Book
-
----
+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.
-![Autocomplete][autocomplete-image]
+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.
-*Screenshot of the autocomplete-light widget*
+Better support for autocomplete inputs is planned in future versions.
---
@@ -175,4 +165,3 @@ You can now add the `autocomplete_light.ChoiceWidget` widget to the serializer f
[autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/
[django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light
[django-autocomplete-light-install]: http://django-autocomplete-light.readthedocs.org/en/latest/#install
-[autocomplete-image]: ../img/autocomplete.png
diff --git a/docs/topics/contributing.md b/docs/topics/contributing.md
index 3400bc8f..99f4fc3c 100644
--- a/docs/topics/contributing.md
+++ b/docs/topics/contributing.md
@@ -10,9 +10,9 @@ There are many ways you can contribute to Django REST framework. We'd like it t
The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case.
-If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a 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 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.
@@ -33,7 +33,7 @@ Some tips on good issue reporting:
* When describing issues try to phrase your ticket in terms of the *behavior* you think needs changing rather than the *code* you think need changing.
* Search the issue list first for related items, and make sure you're running the latest version of REST framework before reporting an issue.
* If reporting a bug, then try to include a pull request with a failing test case. This will help us quickly identify if there is a valid issue, and make sure that it gets fixed more quickly if there is one.
-* Feature requests will often be closed with a recommendation that they be implemented outside of the core REST framework library. Keeping new feature requests implemented as third party libraries allows us to keep down the maintainence overhead of REST framework, so that the focus can be on continued stability, bugfixes, and great documentation.
+* 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.
## Triaging issues
@@ -52,7 +52,7 @@ To start developing on Django REST framework, clone the repo:
git clone git@github.com:tomchristie/django-rest-framework.git
-Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you setup your editor to automatically indicated non-conforming styles.
+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
@@ -71,31 +71,31 @@ To run the tests, clone the repository, and then:
Run using a more concise output style.
- ./runtests -q
+ ./runtests.py -q
Run the tests using a more concise output style, no coverage, no flake8.
- ./runtests --fast
+ ./runtests.py --fast
Don't run the flake8 code linting.
- ./runtests --nolint
+ ./runtests.py --nolint
Only run the flake8 code linting, don't run the tests.
- ./runtests --lintonly
+ ./runtests.py --lintonly
Run the tests for a given test case.
- ./runtests MyTestCase
+ ./runtests.py MyTestCase
Run the tests for a given test method.
- ./runtests MyTestCase.test_this_method
+ ./runtests.py MyTestCase.test_this_method
Shorter form to run the tests for a given test method.
- ./runtests 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.
@@ -109,7 +109,7 @@ You can also use the excellent [tox][tox] testing tool to run the tests against
It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission.
-It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another seperate issue without interfering with an ongoing pull requests.
+It's also 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.
@@ -117,7 +117,7 @@ GitHub's documentation for working on pull requests is [available here][pull-req
Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible with both Python 2 and Python 3, and that they run properly on all supported versions of Django.
-Once you've made a pull request take a look at the travis build status in the GitHub interface and make sure the tests are runnning as you'd expect.
+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]
@@ -131,19 +131,19 @@ Sometimes, in order to ensure your code works on various different versions of D
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, simply run the `mkdocs.py` script.
+To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command.
- ./mkdocs.py
+ mkdocs build
-This will build the html output into the `html` directory.
+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 `-p` flag.
+You can build the documentation and open a preview in a browser window by using the `serve` command.
- ./mkdocs.py -p
+ mkdocs serve
## Language style
@@ -152,8 +152,7 @@ Documentation should be in American English. The tone of the documentation is v
Some other tips:
* Keep paragraphs reasonably short.
-* Use double spacing after the end of sentences.
-* Don't use the abbreviations such as 'e.g.' but instead use long form, such as 'For example'.
+* Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'.
## Markdown style
@@ -186,7 +185,7 @@ If you are hyperlinking to another REST framework document, you should use a rel
[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
@@ -198,19 +197,6 @@ If you want to draw attention to a note or warning, use a pair of enclosing line
---
-# Third party packages
-
-New features to REST framework are generally recommended to be implemented as third party libraries that are developed outside of the core framework. Ideally third party libraries should be properly documented and packaged, and made available on PyPI.
-
-## Getting started
-
-If you have some functionality that you would like to implement as a third party package it's worth contacting the [discussion group][google-group] as others may be willing to get involved. We strongly encourage third party package development and will always try to prioritize time spent helping their development, documentation and packaging.
-
-We recommend the [`django-reusable-app`][django-reusable-app] template as a good resource for getting up and running with implementing a third party Django package.
-
-## Linking to your package
-
-Once your package is decently documented and available on PyPI open a pull request or issue, and we'll add a link to it from the main REST framework documentation.
[cite]: http://www.w3.org/People/Berners-Lee/FAQ.html
[code-of-conduct]: https://www.djangoproject.com/conduct/
@@ -224,4 +210,3 @@ Once your package is decently documented and available on PyPI open a pull reque
[markdown]: http://daringfireball.net/projects/markdown/basics
[docs]: https://github.com/tomchristie/django-rest-framework/tree/master/docs
[mou]: http://mouapp.com/
-[django-reusable-app]: https://github.com/dabapps/django-reusable-app
diff --git a/docs/topics/documenting-your-api.md b/docs/topics/documenting-your-api.md
index e20f9712..d65e251f 100644
--- a/docs/topics/documenting-your-api.md
+++ b/docs/topics/documenting-your-api.md
@@ -54,7 +54,7 @@ The title that is used in the browsable API is generated from the view class nam
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
@@ -65,9 +65,9 @@ If the python `markdown` library is installed, then [markdown syntax][markdown]
class AccountListView(views.APIView):
"""
Returns a list of all **active** accounts in the system.
-
+
For more details on how accounts are activated please [see here][ref].
-
+
[ref]: http://example.com/activating-accounts
"""
@@ -84,7 +84,7 @@ You can modify the response behavior to `OPTIONS` requests by overriding the `me
def metadata(self, request):
"""
Don't include the view description in OPTIONS responses.
- """
+ """
data = super(ExampleView, self).metadata(request)
data.pop('description')
return data
diff --git a/docs/topics/kickstarter-announcement.md b/docs/topics/kickstarter-announcement.md
index 7d1f6d0e..91ead751 100644
--- a/docs/topics/kickstarter-announcement.md
+++ b/docs/topics/kickstarter-announcement.md
@@ -43,20 +43,20 @@ We've now blazed way past all our goals, with a staggering £30,000 (~$50,000),
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.
<ul class="sponsor diamond">
-<li><a href="https://www.eventbrite.com/" rel="nofollow" style="background-image:url(../img/sponsors/0-eventbrite.png);">Eventbrite</a></li>
+<li><a href="https://www.eventbrite.com/" rel="nofollow" style="background-image:url(../../img/sponsors//0-eventbrite.png);">Eventbrite</a></li>
</ul>
<ul class="sponsor platinum">
-<li><a href="https://www.divio.ch/" rel="nofollow" style="background-image:url(../img/sponsors/1-divio.png);">Divio</a></li>
-<li><a href="http://company.onlulu.com/en/" rel="nofollow" style="background-image:url(../img/sponsors/1-lulu.png);">Lulu</a></li>
-<li><a href="https://p.ota.to/" rel="nofollow" style="background-image:url(../img/sponsors/1-potato.png);">Potato</a></li>
-<li><a href="http://www.wiredrive.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-wiredrive.png);">Wiredrive</a></li>
-<li><a href="http://www.cyaninc.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-cyan.png);">Cyan</a></li>
-<li><a href="https://www.runscope.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-runscope.png);">Runscope</a></li>
-<li><a href="http://simpleenergy.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-simple-energy.png);">Simple Energy</a></li>
-<li><a href="http://vokalinteractive.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-vokal_interactive.png);">VOKAL Interactive</a></li>
-<li><a href="http://www.purplebit.com/" rel="nofollow" style="background-image:url(../img/sponsors/1-purplebit.png);">Purple Bit</a></li>
-<li><a href="http://www.kuwaitnet.net/" rel="nofollow" style="background-image:url(../img/sponsors/1-kuwaitnet.png);">KuwaitNET</a></li>
+<li><a href="https://www.divio.ch/" rel="nofollow" style="background-image:url(../../img/sponsors//1-divio.png);">Divio</a></li>
+<li><a href="http://company.onlulu.com/en/" rel="nofollow" style="background-image:url(../../img/sponsors//1-lulu.png);">Lulu</a></li>
+<li><a href="https://p.ota.to/" rel="nofollow" style="background-image:url(../../img/sponsors//1-potato.png);">Potato</a></li>
+<li><a href="http://www.wiredrive.com/" rel="nofollow" style="background-image:url(../../img/sponsors//1-wiredrive.png);">Wiredrive</a></li>
+<li><a href="http://www.cyaninc.com/" rel="nofollow" style="background-image:url(../../img/sponsors//1-cyan.png);">Cyan</a></li>
+<li><a href="https://www.runscope.com/" rel="nofollow" style="background-image:url(../../img/sponsors//1-runscope.png);">Runscope</a></li>
+<li><a href="http://simpleenergy.com/" rel="nofollow" style="background-image:url(../../img/sponsors//1-simple-energy.png);">Simple Energy</a></li>
+<li><a href="http://vokalinteractive.com/" rel="nofollow" style="background-image:url(../../img/sponsors//1-vokal_interactive.png);">VOKAL Interactive</a></li>
+<li><a href="http://www.purplebit.com/" rel="nofollow" style="background-image:url(../../img/sponsors//1-purplebit.png);">Purple Bit</a></li>
+<li><a href="http://www.kuwaitnet.net/" rel="nofollow" style="background-image:url(../../img/sponsors//1-kuwaitnet.png);">KuwaitNET</a></li>
</ul>
<div style="clear: both"></div>
@@ -68,31 +68,31 @@ Our platinum sponsors have each made a hugely substantial contribution to the fu
Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.
<ul class="sponsor gold">
-<li><a href="https://laterpay.net/" rel="nofollow" style="background-image:url(../img/sponsors/2-laterpay.png);">LaterPay</a></li>
-<li><a href="https://www.schubergphilis.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-schuberg_philis.png);">Schuberg Philis</a></li>
-<li><a href="http://prorenata.se/" rel="nofollow" style="background-image:url(../img/sponsors/2-prorenata.png);">ProReNata AB</a></li>
-<li><a href="https://www.sgawebsites.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-sga.png);">SGA Websites</a></li>
-<li><a href="http://www.sirono.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-sirono.png);">Sirono</a></li>
-<li><a href="http://www.vinta.com.br/" rel="nofollow" style="background-image:url(../img/sponsors/2-vinta.png);">Vinta Software Studio</a></li>
-<li><a href="http://www.rapasso.nl/index.php/en" rel="nofollow" style="background-image:url(../img/sponsors/2-rapasso.png);">Rapasso</a></li>
-<li><a href="https://mirusresearch.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-mirus_research.png);">Mirus Research</a></li>
-<li><a href="http://hipolabs.com" rel="nofollow" style="background-image:url(../img/sponsors/2-hipo.png);">Hipo</a></li>
-<li><a href="http://www.byte.nl" rel="nofollow" style="background-image:url(../img/sponsors/2-byte.png);">Byte</a></li>
-<li><a href="http://lightningkite.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-lightning_kite.png);">Lightning Kite</a></li>
-<li><a href="https://opbeat.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-opbeat.png);">Opbeat</a></li>
-<li><a href="https://koordinates.com" rel="nofollow" style="background-image:url(../img/sponsors/2-koordinates.png);">Koordinates</a></li>
-<li><a href="http://pulsecode.ca" rel="nofollow" style="background-image:url(../img/sponsors/2-pulsecode.png);">Pulsecode Inc.</a></li>
-<li><a href="http://singinghorsestudio.com" rel="nofollow" style="background-image:url(../img/sponsors/2-singing-horse.png);">Singing Horse Studio Ltd.</a></li>
-<li><a href="https://www.heroku.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-heroku.png);">Heroku</a></li>
-<li><a href="https://www.galileo-press.de/" rel="nofollow" style="background-image:url(../img/sponsors/2-galileo_press.png);">Galileo Press</a></li>
-<li><a href="http://www.securitycompass.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-security_compass.png);">Security Compass</a></li>
-<li><a href="https://www.djangoproject.com/foundation/" rel="nofollow" style="background-image:url(../img/sponsors/2-django.png);">Django Software Foundation</a></li>
-<li><a href="http://www.hipflaskapp.com" rel="nofollow" style="background-image:url(../img/sponsors/2-hipflask.png);">Hipflask</a></li>
-<li><a href="http://www.crate.io/" rel="nofollow" style="background-image:url(../img/sponsors/2-crate.png);">Crate</a></li>
-<li><a href="http://crypticocorp.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-cryptico.png);">Cryptico Corp</a></li>
-<li><a href="http://www.nexthub.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-nexthub.png);">NextHub</a></li>
-<li><a href="https://www.compile.com/" rel="nofollow" style="background-image:url(../img/sponsors/2-compile.png);">Compile</a></li>
-<li><a href="http://wusawork.org" rel="nofollow" style="background-image:url(../img/sponsors/2-wusawork.png);">WusaWork</a></li>
+<li><a href="https://laterpay.net/" rel="nofollow" style="background-image:url(../../img/sponsors//2-laterpay.png);">LaterPay</a></li>
+<li><a href="https://www.schubergphilis.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-schuberg_philis.png);">Schuberg Philis</a></li>
+<li><a href="http://prorenata.se/" rel="nofollow" style="background-image:url(../../img/sponsors//2-prorenata.png);">ProReNata AB</a></li>
+<li><a href="https://www.sgawebsites.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-sga.png);">SGA Websites</a></li>
+<li><a href="http://www.sirono.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-sirono.png);">Sirono</a></li>
+<li><a href="http://www.vinta.com.br/" rel="nofollow" style="background-image:url(../../img/sponsors//2-vinta.png);">Vinta Software Studio</a></li>
+<li><a href="http://www.rapasso.nl/index.php/en" rel="nofollow" style="background-image:url(../../img/sponsors//2-rapasso.png);">Rapasso</a></li>
+<li><a href="https://mirusresearch.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-mirus_research.png);">Mirus Research</a></li>
+<li><a href="http://hipolabs.com" rel="nofollow" style="background-image:url(../../img/sponsors//2-hipo.png);">Hipo</a></li>
+<li><a href="http://www.byte.nl" rel="nofollow" style="background-image:url(../../img/sponsors//2-byte.png);">Byte</a></li>
+<li><a href="http://lightningkite.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-lightning_kite.png);">Lightning Kite</a></li>
+<li><a href="https://opbeat.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-opbeat.png);">Opbeat</a></li>
+<li><a href="https://koordinates.com" rel="nofollow" style="background-image:url(../../img/sponsors//2-koordinates.png);">Koordinates</a></li>
+<li><a href="http://pulsecode.ca" rel="nofollow" style="background-image:url(../../img/sponsors//2-pulsecode.png);">Pulsecode Inc.</a></li>
+<li><a href="http://singinghorsestudio.com" rel="nofollow" style="background-image:url(../../img/sponsors//2-singing-horse.png);">Singing Horse Studio Ltd.</a></li>
+<li><a href="https://www.heroku.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-heroku.png);">Heroku</a></li>
+<li><a href="https://www.galileo-press.de/" rel="nofollow" style="background-image:url(../../img/sponsors//2-galileo_press.png);">Galileo Press</a></li>
+<li><a href="http://www.securitycompass.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-security_compass.png);">Security Compass</a></li>
+<li><a href="https://www.djangoproject.com/foundation/" rel="nofollow" style="background-image:url(../../img/sponsors//2-django.png);">Django Software Foundation</a></li>
+<li><a href="http://www.hipflaskapp.com" rel="nofollow" style="background-image:url(../../img/sponsors//2-hipflask.png);">Hipflask</a></li>
+<li><a href="http://www.crate.io/" rel="nofollow" style="background-image:url(../../img/sponsors//2-crate.png);">Crate</a></li>
+<li><a href="http://crypticocorp.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-cryptico.png);">Cryptico Corp</a></li>
+<li><a href="http://www.nexthub.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-nexthub.png);">NextHub</a></li>
+<li><a href="https://www.compile.com/" rel="nofollow" style="background-image:url(../../img/sponsors//2-compile.png);">Compile</a></li>
+<li><a href="http://wusawork.org" rel="nofollow" style="background-image:url(../../img/sponsors//2-wusawork.png);">WusaWork</a></li>
<li><a href="http://envisionlinux.org/blog" rel="nofollow">Envision Linux</a></li>
</ul>
@@ -105,41 +105,41 @@ Our gold sponsors include companies large and small. Many thanks for their signi
The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank&nbsp;you to individuals who have choosen to privately support the project at this level.
<ul class="sponsor silver">
-<li><a href="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-imt_computer_services.png);">IMT Computer Services</a></li>
-<li><a href="http://wildfish.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-wildfish.png);">Wildfish</a></li>
-<li><a href="http://www.thermondo.de/" rel="nofollow" style="background-image:url(../img/sponsors/3-thermondo-gmbh.png);">Thermondo GmbH</a></li>
-<li><a href="http://providenz.fr/" rel="nofollow" style="background-image:url(../img/sponsors/3-providenz.png);">Providenz</a></li>
-<li><a href="https://www.alwaysdata.com" rel="nofollow" style="background-image:url(../img/sponsors/3-alwaysdata.png);">alwaysdata.com</a></li>
-<li><a href="http://www.triggeredmessaging.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-triggered_messaging.png);">Triggered Messaging</a></li>
-<li><a href="https://www.ipushpull.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-ipushpull.png);">PushPull Technology Ltd</a></li>
-<li><a href="http://www.transcode.de/" rel="nofollow" style="background-image:url(../img/sponsors/3-transcode.png);">Transcode</a></li>
-<li><a href="https://garfo.io/" rel="nofollow" style="background-image:url(../img/sponsors/3-garfo.png);">Garfo</a></li>
-<li><a href="https://goshippo.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-shippo.png);">Shippo</a></li>
-<li><a href="http://www.gizmag.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-gizmag.png);">Gizmag</a></li>
-<li><a href="http://www.tivix.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-tivix.png);">Tivix</a></li>
-<li><a href="http://www.safaribooksonline.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-safari.png);">Safari</a></li>
-<li><a href="http://brightloop.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-brightloop.png);">Bright Loop</a></li>
-<li><a href="http://www.aba-systems.com.au/" rel="nofollow" style="background-image:url(../img/sponsors/3-aba.png);">ABA Systems</a></li>
-<li><a href="http://beefarm.ru/" rel="nofollow" style="background-image:url(../img/sponsors/3-beefarm.png);">beefarm.ru</a></li>
-<li><a href="http://www.vzzual.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-vzzual.png);">Vzzual.com</a></li>
-<li><a href="http://infinite-code.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-infinite_code.png);">Infinite Code</a></li>
-<li><a href="http://crosswordtracker.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-crosswordtracker.png);">Crossword Tracker</a></li>
-<li><a href="https://www.pkgfarm.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-pkgfarm.png);">PkgFarm</a></li>
-<li><a href="http://life.tl/" rel="nofollow" style="background-image:url(../img/sponsors/3-life_the_game.png);">Life. The Game.</a></li>
-<li><a href="http://blimp.io/" rel="nofollow" style="background-image:url(../img/sponsors/3-blimp.png);">Blimp</a></li>
-<li><a href="http://pathwright.com" rel="nofollow" style="background-image:url(../img/sponsors/3-pathwright.png);">Pathwright</a></li>
-<li><a href="http://fluxility.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-fluxility.png);">Fluxility</a></li>
-<li><a href="http://teonite.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-teonite.png);">Teonite</a></li>
-<li><a href="http://trackmaven.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-trackmaven.png);">TrackMaven</a></li>
-<li><a href="http://www.phurba.net/" rel="nofollow" style="background-image:url(../img/sponsors/3-phurba.png);">Phurba</a></li>
-<li><a href="http://www.nephila.co.uk/" rel="nofollow" style="background-image:url(../img/sponsors/3-nephila.png);">Nephila</a></li>
-<li><a href="http://www.aditium.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-aditium.png);">Aditium</a></li>
-<li><a href="http://www.eyesopen.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-openeye.png);">OpenEye Scientific Software</a></li>
-<li><a href="https://holvi.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-holvi.png);">Holvi</a></li>
-<li><a href="http://cantemo.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-cantemo.gif);">Cantemo</a></li>
-<li><a href="https://www.makespace.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-makespace.png);">MakeSpace</a></li>
-<li><a href="https://www.ax-semantics.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-ax_semantics.png);">AX Semantics</a></li>
-<li><a href="http://istrategylabs.com/" rel="nofollow" style="background-image:url(../img/sponsors/3-isl.png);">ISL</a></li>
+<li><a href="http://www.imtapps.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-imt_computer_services.png);">IMT Computer Services</a></li>
+<li><a href="http://wildfish.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-wildfish.png);">Wildfish</a></li>
+<li><a href="http://www.thermondo.de/" rel="nofollow" style="background-image:url(../../img/sponsors//3-thermondo-gmbh.png);">Thermondo GmbH</a></li>
+<li><a href="http://providenz.fr/" rel="nofollow" style="background-image:url(../../img/sponsors//3-providenz.png);">Providenz</a></li>
+<li><a href="https://www.alwaysdata.com" rel="nofollow" style="background-image:url(../../img/sponsors//3-alwaysdata.png);">alwaysdata.com</a></li>
+<li><a href="http://www.triggeredmessaging.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-triggered_messaging.png);">Triggered Messaging</a></li>
+<li><a href="https://www.ipushpull.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-ipushpull.png);">PushPull Technology Ltd</a></li>
+<li><a href="http://www.transcode.de/" rel="nofollow" style="background-image:url(../../img/sponsors//3-transcode.png);">Transcode</a></li>
+<li><a href="https://garfo.io/" rel="nofollow" style="background-image:url(../../img/sponsors//3-garfo.png);">Garfo</a></li>
+<li><a href="https://goshippo.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-shippo.png);">Shippo</a></li>
+<li><a href="http://www.gizmag.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-gizmag.png);">Gizmag</a></li>
+<li><a href="http://www.tivix.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-tivix.png);">Tivix</a></li>
+<li><a href="http://www.safaribooksonline.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-safari.png);">Safari</a></li>
+<li><a href="http://brightloop.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-brightloop.png);">Bright Loop</a></li>
+<li><a href="http://www.aba-systems.com.au/" rel="nofollow" style="background-image:url(../../img/sponsors//3-aba.png);">ABA Systems</a></li>
+<li><a href="http://beefarm.ru/" rel="nofollow" style="background-image:url(../../img/sponsors//3-beefarm.png);">beefarm.ru</a></li>
+<li><a href="http://www.vzzual.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-vzzual.png);">Vzzual.com</a></li>
+<li><a href="http://infinite-code.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-infinite_code.png);">Infinite Code</a></li>
+<li><a href="http://crosswordtracker.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-crosswordtracker.png);">Crossword Tracker</a></li>
+<li><a href="https://www.pkgfarm.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-pkgfarm.png);">PkgFarm</a></li>
+<li><a href="http://life.tl/" rel="nofollow" style="background-image:url(../../img/sponsors//3-life_the_game.png);">Life. The Game.</a></li>
+<li><a href="http://blimp.io/" rel="nofollow" style="background-image:url(../../img/sponsors//3-blimp.png);">Blimp</a></li>
+<li><a href="http://pathwright.com" rel="nofollow" style="background-image:url(../../img/sponsors//3-pathwright.png);">Pathwright</a></li>
+<li><a href="http://fluxility.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-fluxility.png);">Fluxility</a></li>
+<li><a href="http://teonite.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-teonite.png);">Teonite</a></li>
+<li><a href="http://trackmaven.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-trackmaven.png);">TrackMaven</a></li>
+<li><a href="http://www.phurba.net/" rel="nofollow" style="background-image:url(../../img/sponsors//3-phurba.png);">Phurba</a></li>
+<li><a href="http://www.nephila.co.uk/" rel="nofollow" style="background-image:url(../../img/sponsors//3-nephila.png);">Nephila</a></li>
+<li><a href="http://www.aditium.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-aditium.png);">Aditium</a></li>
+<li><a href="http://www.eyesopen.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-openeye.png);">OpenEye Scientific Software</a></li>
+<li><a href="https://holvi.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-holvi.png);">Holvi</a></li>
+<li><a href="http://cantemo.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-cantemo.gif);">Cantemo</a></li>
+<li><a href="https://www.makespace.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-makespace.png);">MakeSpace</a></li>
+<li><a href="https://www.ax-semantics.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-ax_semantics.png);">AX Semantics</a></li>
+<li><a href="http://istrategylabs.com/" rel="nofollow" style="background-image:url(../../img/sponsors//3-isl.png);">ISL</a></li>
</ul>
<div style="clear: both; padding-bottom: 40px;"></div>
@@ -160,4 +160,4 @@ The following individuals made a significant financial contribution to the devel
### Supporters
-There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you! \ No newline at end of file
+There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you!
diff --git a/docs/topics/release-notes.md b/docs/topics/release-notes.md
index d758ae6a..53187589 100644
--- a/docs/topics/release-notes.md
+++ b/docs/topics/release-notes.md
@@ -10,7 +10,7 @@ Minor version numbers (0.0.x) are used for changes that are API compatible. You
Medium version numbers (0.x.0) may include API changes, in line with the [deprecation policy][deprecation-policy]. You should read the release notes carefully before upgrading between medium point releases.
-Major version numbers (x.0.0) are reserved for substantial project milestones. No major point releases are currently planned.
+Major version numbers (x.0.0) are reserved for substantial project milestones.
## Deprecation policy
@@ -40,21 +40,47 @@ You can determine your currently installed version using `pip freeze`:
## 2.4.x series
+### 2.4.4
+
+**Date**: [3rd November 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.4+Release%22+).
+
+* **Security fix**: Escape URLs when replacing `format=` query parameter, as used in dropdown on `GET` button in browsable API to allow explicit selection of JSON vs HTML output.
+* Maintain ordering of URLs in API root view for `DefaultRouter`.
+* Fix `follow=True` in `APIRequestFactory`
+* Resolve issue with invalid `read_only=True`, `required=True` fields being automatically generated by `ModelSerializer` in some cases.
+* Resolve issue with `OPTIONS` requests returning incorrect information for views using `get_serializer_class` to dynamically determine serializer based on request method.
+
+### 2.4.3
+
+**Date**: [19th September 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.3+Release%22+).
+
+* Support translatable view docstrings being displayed in the browsable API.
+* Support [encoded `filename*`][rfc-6266] in raw file uploads with `FileUploadParser`.
+* Allow routers to support viewsets that don't include any list routes or that don't include any detail routes.
+* Don't render an empty login control in browsable API if `login` view is not included.
+* CSRF exemption performed in `.as_view()` to prevent accidental omission if overriding `.dispatch()`.
+* Login on browsable API now displays validation errors.
+* Bugfix: Fix migration in `authtoken` application.
+* Bugfix: Allow selection of integer keys in nested choices.
+* Bugfix: Return `None` instead of `'None'` in `CharField` with `allow_none=True`.
+* Bugfix: Ensure custom model fields map to equivelent serializer fields more reliably.
+* Bugfix: `DjangoFilterBackend` no longer quietly changes queryset ordering.
+
### 2.4.2
-**Date**: 3rd September 2014
+**Date**: [3rd September 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.2+Release%22+).
* Bugfix: Fix broken pagination for 2.4.x series.
### 2.4.1
-**Date**: 1st September 2014
+**Date**: [1st September 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.1+Release%22+).
* Bugfix: Fix broken login template for browsable API.
### 2.4.0
-**Date**: 29th August 2014
+**Date**: [29th August 2014](https://github.com/tomchristie/django-rest-framework/issues?q=milestone%3A%222.4.0+Release%22+).
**Django version requirements**: The lowest supported version of Django is now 1.4.2.
@@ -133,7 +159,7 @@ You can determine your currently installed version using `pip freeze`:
* Added `write_only_fields` option to `ModelSerializer` classes.
* JSON renderer now deals with objects that implement a dict-like interface.
* Fix compatiblity with newer versions of `django-oauth-plus`.
-* Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unneccessary queryset re-evaluations.
+* Bugfix: Refine behavior that calls model manager `all()` across nested serializer relationships, preventing erronous behavior with some non-ORM objects, and preventing unnecessary queryset re-evaluations.
* Bugfix: Allow defaults on BooleanFields to be properly honored when values are not supplied.
* Bugfix: Prevent double-escaping of non-latin1 URL query params when appending `format=json` params.
@@ -416,7 +442,7 @@ The security vulnerabilities only affect APIs which use the `XMLParser` class, b
* Bugfix: Validation errors instead of exceptions when related fields receive incorrect types.
* Bugfix: Handle ObjectDoesNotExist exception when serializing null reverse one-to-one
-**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [#582] for more details.
+**Note**: Prior to 2.1.16, The Decimals would render in JSON using floating point if `simplejson` was installed, but otherwise render using string notation. Now that use of `simplejson` has been deprecated, Decimals will consistently render using string notation. See [ticket 582](ticket-582) for more details.
### 2.1.15
@@ -588,122 +614,7 @@ This change will not affect user code, so long as it's following the recommended
* **Fix all of the things.** (Well, almost.)
* For more information please see the [2.0 announcement][announcement].
----
-
-## 0.4.x series
-
-### 0.4.0
-
-* Supports Django 1.5.
-* Fixes issues with 'HEAD' method.
-* Allow views to specify template used by TemplateRenderer
-* More consistent error responses
-* Some serializer fixes
-* Fix internet explorer ajax behavior
-* Minor xml and yaml fixes
-* Improve setup (e.g. use staticfiles, not the defunct ADMIN_MEDIA_PREFIX)
-* Sensible absolute URL generation, not using hacky set_script_prefix
-
----
-
-## 0.3.x series
-
-### 0.3.3
-
-* Added DjangoModelPermissions class to support `django.contrib.auth` style permissions.
-* Use `staticfiles` for css files.
- - Easier to override. Won't conflict with customized admin styles (e.g. grappelli)
-* Templates are now nicely namespaced.
- - Allows easier overriding.
-* Drop implied 'pk' filter if last arg in urlconf is unnamed.
- - Too magical. Explicit is better than implicit.
-* Saner template variable auto-escaping.
-* Tidier setup.py
-* Updated for URLObject 2.0
-* Bugfixes:
- - Bug with PerUserThrottling when user contains unicode chars.
-
-### 0.3.2
-
-* Bugfixes:
- * Fix 403 for POST and PUT from the UI with UserLoggedInAuthentication (#115)
- * serialize_model method in serializer.py may cause wrong value (#73)
- * Fix Error when clicking OPTIONS button (#146)
- * And many other fixes
-* Remove short status codes
- - Zen of Python: "There should be one-- and preferably only one --obvious way to do it."
-* get_name, get_description become methods on the view - makes them overridable.
-* Improved model mixin API - Hooks for build_query, get_instance_data, get_model, get_queryset, get_ordering
-
-### 0.3.1
-
-* [not documented]
-
-### 0.3.0
-
-* JSONP Support
-* Bugfixes, including support for latest markdown release
-
----
-
-## 0.2.x series
-
-### 0.2.4
-
-* Fix broken IsAdminUser permission.
-* OPTIONS support.
-* XMLParser.
-* Drop mentions of Blog, BitBucket.
-
-### 0.2.3
-
-* Fix some throttling bugs.
-* ``X-Throttle`` header on throttling.
-* Support for nesting resources on related models.
-
-### 0.2.2
-
-* Throttling support complete.
-
-### 0.2.1
-
-* Couple of simple bugfixes over 0.2.0
-
-### 0.2.0
-
-* Big refactoring changes since 0.1.0, ask on the discussion group if anything isn't clear.
- The public API has been massively cleaned up. Expect it to be fairly stable from here on in.
-
-* ``Resource`` becomes decoupled into ``View`` and ``Resource``, your views should now inherit from ``View``, not ``Resource``.
-
-* The handler functions on views ``.get() .put() .post()`` etc, no longer have the ``content`` and ``auth`` args.
- Use ``self.CONTENT`` inside a view to access the deserialized, validated content.
- Use ``self.user`` inside a view to access the authenticated user.
-
-* ``allowed_methods`` and ``anon_allowed_methods`` are now defunct. if a method is defined, it's available.
- The ``permissions`` attribute on a ``View`` is now used to provide generic permissions checking.
- Use permission classes such as ``FullAnonAccess``, ``IsAuthenticated`` or ``IsUserOrIsAnonReadOnly`` to set the permissions.
-
-* The ``authenticators`` class becomes ``authentication``. Class names change to ``Authentication``.
-
-* The ``emitters`` class becomes ``renderers``. Class names change to ``Renderers``.
-
-* ``ResponseException`` becomes ``ErrorResponse``.
-
-* The mixin classes have been nicely refactored, the basic mixins are now ``RequestMixin``, ``ResponseMixin``, ``AuthMixin``, and ``ResourceMixin``
- You can reuse these mixin classes individually without using the ``View`` class.
-
----
-
-## 0.1.x series
-
-### 0.1.1
-
-* Final build before pulling in all the refactoring changes for 0.2, in case anyone needs to hang on to 0.1.
-
-### 0.1.0
-
-* Initial release.
+For older release notes, [please see the GitHub repo](old-release-notes).
[cite]: http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html
[deprecation-policy]: #deprecation-policy
@@ -716,4 +627,6 @@ This change will not affect user code, so long as it's following the recommended
[staticfiles13]: https://docs.djangoproject.com/en/1.3/howto/static-files/#with-a-template-tag
[2.1.0-notes]: https://groups.google.com/d/topic/django-rest-framework/Vv2M0CMY9bg/discussion
[announcement]: rest-framework-2-announcement.md
-[#582]: https://github.com/tomchristie/django-rest-framework/issues/582
+[ticket-582]: https://github.com/tomchristie/django-rest-framework/issues/582
+[rfc-6266]: http://tools.ietf.org/html/rfc6266#section-4.3
+[old-release-notes]: https://github.com/tomchristie/django-rest-framework/blob/2.4.4/docs/topics/release-notes.md#04x-series
diff --git a/docs/topics/rest-framework-2-announcement.md b/docs/topics/rest-framework-2-announcement.md
index f1060d90..a7746932 100644
--- a/docs/topics/rest-framework-2-announcement.md
+++ b/docs/topics/rest-framework-2-announcement.md
@@ -8,7 +8,7 @@ What it is, and why you should care.
---
-**Announcement:** REST framework 2 released - Tue 30th Oct 2012
+**Announcement:** REST framework 2 released - Tue 30th Oct 2012
---
@@ -37,7 +37,7 @@ REST framework 2 includes a totally re-worked serialization engine, that was ini
* A declarative serialization API, that mirrors Django's `Forms`/`ModelForms` API.
* Structural concerns are decoupled from encoding concerns.
* Able to support rendering and parsing to many formats, including both machine-readable representations and HTML forms.
-* Validation that can be mapped to obvious and comprehensive error responses.
+* Validation that can be mapped to obvious and comprehensive error responses.
* Serializers that support both nested, flat, and partially-nested representations.
* Relationships that can be expressed as primary keys, hyperlinks, slug fields, and other custom representations.
diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md
index 3d700488..7e6d2408 100644
--- a/docs/topics/rest-hypermedia-hateoas.md
+++ b/docs/topics/rest-hypermedia-hateoas.md
@@ -1,19 +1,19 @@
# REST, Hypermedia & HATEOAS
-> You keep using that word "REST". I do not think it means what you think it means.
+> You keep using that word "REST". I do not think it means what you think it means.
>
> &mdash; Mike Amundsen, [REST fest 2012 keynote][cite].
-First off, the disclaimer. The name "Django REST framework" was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
+First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to sure the project would be easily found by developers. Throughout the documentation we try to use the more simple and technically correct terminology of "Web APIs".
-If you are serious about designing a Hypermedia APIs, you should look to resources outside of this documentation to help inform your design choices.
+If you are serious about designing a Hypermedia API, you should look to resources outside of this documentation to help inform your design choices.
The following fall into the "required reading" category.
* Roy Fielding's dissertation - [Architectural Styles and
the Design of Network-based Software Architectures][dissertation].
* Roy Fielding's "[REST APIs must be hypertext-driven][hypertext-driven]" blog post.
-* Leonard Richardson & Sam Ruby's [RESTful Web Services][restful-web-services].
+* Leonard Richardson & Mike Amundsen's [RESTful Web APIs][restful-web-apis].
* Mike Amundsen's [Building Hypermedia APIs with HTML5 and Node][building-hypermedia-apis].
* Steve Klabnik's [Designing Hypermedia APIs][designing-hypermedia-apis].
* The [Richardson Maturity Model][maturitymodel].
@@ -32,12 +32,12 @@ REST framework also includes [serialization] and [parser]/[renderer] components
## What REST framework doesn't provide.
-What REST framework doesn't do is give you is machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
+What REST framework doesn't do is give you is machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope.
[cite]: http://vimeo.com/channels/restfest/page:2
[dissertation]: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
[hypertext-driven]: http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven
-[restful-web-services]: http://www.amazon.com/Restful-Web-Services-Leonard-Richardson/dp/0596529260
+[restful-web-apis]: http://restfulwebapis.org/
[building-hypermedia-apis]: http://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578
[designing-hypermedia-apis]: http://designinghypermediaapis.com/
[restisover]: http://blog.steveklabnik.com/posts/2012-02-23-rest-is-over
diff --git a/docs/topics/third-party-resources.md b/docs/topics/third-party-resources.md
index 1ca91742..ffb490af 100644
--- a/docs/topics/third-party-resources.md
+++ b/docs/topics/third-party-resources.md
@@ -1,91 +1,322 @@
# Third Party Resources
-Django REST Framework has a growing community of developers, packages, and resources.
+## About Third Party Packages
+
+Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases.
+
+We **support**, **encourage** and **strongly favour** the creation of Third Party Packages to encapsulate new behaviour rather than adding additional functionality directly to Django REST Framework.
+
+We aim to make creating Third Party Packages as easy as possible, whilst keeping the **simplicity** of the core API and ensuring that **maintenance** of the main project remains under control. If a Third Party Package proves popular it is relatively easy to move it into the main project; removing features is much more problematic.
+
+If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to dicuss ideas on the [Mailing List][discussion-group].
+
+## How to create a Third Party Package
+
+### Creating your package
+
+You can use [this cookiecutter template][cookiecutter] for creating reusable Django REST Framework packages quickly. Cookiecutter creates projects from project templates. While optional, this cookiecutter template includes best practices from Django REST framework and other packages, as well as a Travis CI configuration, Tox configuration, and a sane setup.py for easy PyPI registration/distribution.
+
+Note: Let us know if you have an alternate cookiecuter package so we can also link to it.
+
+#### Running the initial cookiecutter command
+
+To run the initial cookiecutter command, you'll first need to install the Python `cookiecutter` package.
+
+ $ pip install cookiecutter
+
+Once `cookiecutter` is installed just run the following to create a new project.
+
+ $ cookiecutter gh:jpadilla/cookiecutter-django-rest-framework
+
+You'll be prompted for some questions, answer them, then it'll create your Python package in the current working directory based on those values.
+
+ full_name (default is "Your full name here")? Johnny Appleseed
+ email (default is "you@example.com")? jappleseed@example.com
+ github_username (default is "yourname")? jappleseed
+ pypi_project_name (default is "dj-package")? djangorestframework-custom-auth
+ repo_name (default is "dj-package")? django-rest-framework-custom-auth
+ app_name (default is "djpackage")? custom_auth
+ project_short_description (default is "Your project description goes here")?
+ year (default is "2014")?
+ version (default is "0.1.0")?
+
+#### Getting it onto GitHub
+
+To put your project up on GitHub, you'll need a repository for it to live in. You can create a new repository [here][new-repo]. If you need help, check out the [Create A Repo][create-a-repo] article on GitHub.
+
+
+#### Adding to Travis CI
+
+We recommend using [Travis CI][travis-ci], a hosted continuous integration service which integrates well with GitHub and is free for public repositories.
+
+To get started with Travis CI, [sign in][travis-ci] with your GitHub account. Once you're signed in, go to your [profile page][travis-profile] and enable the service hook for the repository you want.
+
+If you use the cookiecutter template, your project will already contain a `.travis.yml` file which Travis CI will use to build your project and run tests. By default, builds are triggered everytime you push to your repository or create Pull Request.
+
+#### Uploading to PyPI
+
+Once you've got at least a prototype working and tests running, you should publish it on PyPI to allow others to install it via `pip`.
+
+You must [register][pypi-register] an account before publishing to PyPI.
+
+To register your package on PyPI run the following command.
+
+ $ python setup.py register
+
+If this is the first time publishing to PyPI, you'll be prompted to login.
+
+Note: Before publishing you'll need to make sure you have the latest pip that supports `wheel` as well as install the `wheel` package.
+
+ $ pip install --upgrade pip
+ $ pip install wheel
+
+After this, every time you want to release a new version on PyPI just run the following command.
+
+ $ python setup.py publish
+ You probably want to also tag the version now:
+ git tag -a {0} -m 'version 0.1.0'
+ git push --tags
+
+After releasing a new version to PyPI, it's always a good idea to tag the version and make available as a GitHub Release.
+
+We recommend to follow [Semantic Versioning][semver] for your package's versions.
+
+### Development
+
+#### Version requirements
+
+The cookiecutter template assumes a set of supported versions will be provided for Python and Django. Make sure you correctly update your requirements, docs, `tox.ini`, `.travis.yml`, and `setup.py` to match the set of versions you wish to support.
+
+#### Tests
+
+The cookiecutter template includes a `runtests.py` which uses the `pytest` package as a test runner.
+
+Before running, you'll need to install a couple test requirements.
+
+ $ pip install -r requirements-test.txt
-Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages](https://www.djangopackages.com/grids/g/django-rest-framework/).
+Once requirements installed, you can run `runtests.py`.
-To submit new content, [open an issue](https://github.com/tomchristie/django-rest-framework/issues/new) or [create a pull request](https://github.com/tomchristie/django-rest-framework/).
+ $ ./runtests.py
-## Libraries and Extensions
+Run using a more concise output style.
+
+ $ ./runtests.py -q
+
+Run the tests using a more concise output style, no coverage, no flake8.
+
+ $ ./runtests.py --fast
+
+Don't run the flake8 code linting.
+
+ $ ./runtests.py --nolint
+
+Only run the flake8 code linting, don't run the tests.
+
+ $ ./runtests.py --lintonly
+
+Run the tests for a given test case.
+
+ $ ./runtests.py MyTestCase
+
+Run the tests for a given test method.
+
+ $ ./runtests.py MyTestCase.test_this_method
+
+Shorter form to run the tests for a given test method.
+
+ $ ./runtests.py test_this_method
+
+To run your tests against multiple versions of Python as different versions of requirements such as Django we recommend using `tox`. [Tox][tox-docs] is a generic virtualenv management and test command line tool.
+
+First, install `tox` globally.
+
+ $ pip install tox
+
+To run `tox`, just simply run:
+
+ $ tox
+
+To run a particular `tox` environment:
+
+ $ tox -e envlist
+
+`envlist` is a comma-separated value to that specifies the environments to run tests against. To view a list of all possible test environments, run:
+
+ $ tox -l
+
+#### Version compatibility
+
+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 a `compat.py` module, and should provide a single common interface that the rest of the codebase can use.
+
+Check out Django REST framework's [compat.py][drf-compat] for an example.
+
+### Once your package is available
+
+Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful.
+
+#### Adding to the Django REST framework grid
+
+We suggest adding your package to the [REST Framework][rest-framework-grid] grid on Django Packages.
+
+#### Adding to the Django REST framework docs
+
+Create a [Pull Request][drf-create-pr] or [Issue][drf-create-issue] on GitHub, and we'll add a link to it from the main REST framework documentation. You can add your package under **Third party packages** of the API Guide section that best applies, like [Authentication][authentication] or [Permissions][permissions]. You can also link your package under the [Third Party Resources][third-party-resources] section.
+
+#### Announce on the discussion group.
+
+You can also let others know about your package through the [discussion group][discussion-group].
+
+## Existing Third Party Packages
+
+Django REST Framework has a growing community of developers, packages, and resources.
+
+Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid].
+
+To submit new content, [open an issue][drf-create-issue] or [create a pull request][drf-create-pr].
### Authentication
-* [djangorestframework-digestauth](https://github.com/juanriaza/django-rest-framework-digestauth) - Provides Digest Access Authentication support.
-* [django-oauth-toolkit](https://github.com/evonove/django-oauth-toolkit) - Provides OAuth 2.0 support.
-* [doac](https://github.com/Rediker-Software/doac) - Provides OAuth 2.0 support.
-* [djangorestframework-jwt](https://github.com/GetBlimp/django-rest-framework-jwt) - Provides JSON Web Token Authentication support.
-* [hawkrest](https://github.com/kumar303/hawkrest) - Provides Hawk HTTP Authorization.
-* [djangorestframework-httpsignature](https://github.com/etoccalino/django-rest-framework-httpsignature) - Provides an easy to use HTTP Signature Authentication mechanism.
+* [djangorestframework-digestauth][djangorestframework-digestauth] - Provides Digest Access Authentication support.
+* [django-oauth-toolkit][django-oauth-toolkit] - Provides OAuth 2.0 support.
+* [doac][doac] - Provides OAuth 2.0 support.
+* [djangorestframework-jwt][djangorestframework-jwt] - Provides JSON Web Token Authentication support.
+* [hawkrest][hawkrest] - Provides Hawk HTTP Authorization.
+* [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism.
+* [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation.
### Permissions
-* [drf-any-permissions](https://github.com/kevin-brown/drf-any-permissions) - Provides alternative permission handling.
-* [djangorestframework-composed-permissions](https://github.com/niwibe/djangorestframework-composed-permissions) - Provides a simple way to define complex permissions.
-* [rest_condition](https://github.com/caxap/rest_condition) - Another extension for building complex permissions in a simple and convenient way.
+* [drf-any-permissions][drf-any-permissions] - Provides alternative permission handling.
+* [djangorestframework-composed-permissions][djangorestframework-composed-permissions] - Provides a simple way to define complex permissions.
+* [rest_condition][rest-condition] - Another extension for building complex permissions in a simple and convenient way.
### Serializers
-* [django-rest-framework-mongoengine](https://github.com/umutbozkurt/django-rest-framework-mongoengine) - Serializer class that supports using MongoDB as the storage layer for Django REST framework.
-* [djangorestframework-gis](https://github.com/djangonauts/django-rest-framework-gis) - Geographic add-ons
-* [djangorestframework-hstore](https://github.com/djangonauts/django-rest-framework-hstore) - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.
+* [django-rest-framework-mongoengine][django-rest-framework-mongoengine] - Serializer class that supports using MongoDB as the storage layer for Django REST framework.
+* [djangorestframework-gis][djangorestframework-gis] - Geographic add-ons
+* [djangorestframework-hstore][djangorestframework-hstore] - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature.
### Serializer fields
-* [drf-compound-fields](https://github.com/estebistec/drf-compound-fields) - Provides "compound" serializer fields, such as lists of simple values.
-* [django-extra-fields](https://github.com/Hipo/drf-extra-fields) - Provides extra serializer fields.
+* [drf-compound-fields][drf-compound-fields] - Provides "compound" serializer fields, such as lists of simple values.
+* [django-extra-fields][django-extra-fields] - Provides extra serializer fields.
### Views
-* [djangorestframework-bulk](https://github.com/miki725/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.
+* [djangorestframework-bulk][djangorestframework-bulk] - Implements generic view mixins as well as some common concrete generic views to allow to apply bulk operations via API requests.
### Routers
-* [drf-nested-routers](https://github.com/alanjds/drf-nested-routers) - Provides routers and relationship fields for working with nested resources.
-* [wq.db.rest](http://wq.io/docs/about-rest) - Provides an admin-style model registration API with reasonable default URLs and viewsets.
+* [drf-nested-routers][drf-nested-routers] - Provides routers and relationship fields for working with nested resources.
+* [wq.db.rest][wq.db.rest] - Provides an admin-style model registration API with reasonable default URLs and viewsets.
### Parsers
-* [djangorestframework-msgpack](https://github.com/juanriaza/django-rest-framework-msgpack) - Provides MessagePack renderer and parser support.
-* [djangorestframework-camel-case](https://github.com/vbabiy/djangorestframework-camel-case) - Provides camel case JSON renderers and parsers.
+* [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support.
+* [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers.
### Renderers
-* [djangorestframework-csv](https://github.com/mjumbewu/django-rest-framework-csv) - Provides CSV renderer support.
-* [drf_ujson](https://github.com/gizmag/drf-ujson-renderer) - Implements JSON rendering using the UJSON package.
-* [Django REST Pandas](https://github.com/wq/django-rest-pandas) - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
+* [djangorestframework-csv][djangorestframework-csv] - Provides CSV renderer support.
+* [drf_ujson][drf_ujson] - Implements JSON rendering using the UJSON package.
+* [rest-pandas][rest-pandas] - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats.
### Filtering
-* [djangorestframework-chain](https://github.com/philipn/django-rest-framework-chain) - Allows arbitrary chaining of both relations and lookup filters.
+* [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters.
### Misc
-* [djangorestrelationalhyperlink](https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project) - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
-* [django-rest-swagger](https://github.com/marcgibbons/django-rest-swagger) - An API documentation generator for Swagger UI.
-* [django-rest-framework-proxy ](https://github.com/eofs/django-rest-framework-proxy) - Proxy to redirect incoming request to another API server.
-* [gaiarestframework](https://github.com/AppsFuel/gaiarestframework) - Utils for django-rest-framewok
-* [drf-extensions](https://github.com/chibisov/drf-extensions) - A collection of custom extensions
-* [ember-data-django-rest-adapter](https://github.com/toranb/ember-data-django-rest-adapter) - An ember-data adapter
+* [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serialiser that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer.
+* [django-rest-swagger][django-rest-swagger] - An API documentation generator for Swagger UI.
+* [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server.
+* [gaiarestframework][gaiarestframework] - Utils for django-rest-framewok
+* [drf-extensions][drf-extensions] - A collection of custom extensions
+* [ember-data-django-rest-adapter][ember-data-django-rest-adapter] - An ember-data adapter
+
+## Other Resources
+
+### Tutorials
+
+* [Beginner's Guide to the Django Rest Framework][beginners-guide-to-the-django-rest-framework]
+* [Getting Started with Django Rest Framework and AngularJS][getting-started-with-django-rest-framework-and-angularjs]
+* [End to end web app with Django-Rest-Framework & AngularJS][end-to-end-web-app-with-django-rest-framework-angularjs]
+* [Start Your API - django-rest-framework part 1][start-your-api-django-rest-framework-part-1]
+* [Permissions & Authentication - django-rest-framework part 2][permissions-authentication-django-rest-framework-part-2]
+* [ViewSets and Routers - django-rest-framework part 3][viewsets-and-routers-django-rest-framework-part-3]
+* [Django Rest Framework User Endpoint][django-rest-framework-user-endpoint]
+* [Check credentials using Django Rest Framework][check-credentials-using-django-rest-framework]
-## Tutorials
+### Videos
-* [Beginner's Guide to the Django Rest Framework](http://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786)
-* [Getting Started with Django Rest Framework and AngularJS](http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html)
-* [End to end web app with Django-Rest-Framework & AngularJS](http://blog.mourafiq.com/post/55034504632/end-to-end-web-app-with-django-rest-framework)
-* [Start Your API - django-rest-framework part 1](https://godjango.com/41-start-your-api-django-rest-framework-part-1/)
-* [Permissions & Authentication - django-rest-framework part 2](https://godjango.com/43-permissions-authentication-django-rest-framework-part-2/)
-* [ViewSets and Routers - django-rest-framework part 3](https://godjango.com/45-viewsets-and-routers-django-rest-framework-part-3/)
-* [Django Rest Framework User Endpoint](http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/)
-* [Check credentials using Django Rest Framework](http://richardtier.com/2014/03/06/110/)
+* [Ember and Django Part 1 (Video)][ember-and-django-part 1-video]
+* [Django Rest Framework Part 1 (Video)][django-rest-framework-part-1-video]
+* [Pyowa July 2013 - Django Rest Framework (Video)][pyowa-july-2013-django-rest-framework-video]
+* [django-rest-framework and angularjs (Video)][django-rest-framework-and-angularjs-video]
-## Videos
+### Articles
-* [Ember and Django Part 1 (Video)](http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1)
-* [Django Rest Framework Part 1 (Video)](http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1)
-* [Pyowa July 2013 - Django Rest Framework (Video)](http://www.youtube.com/watch?v=E1ZrehVxpBo)
-* [django-rest-framework and angularjs (Video)](http://www.youtube.com/watch?v=Q8FRBGTJ020)
+* [Web API performance: profiling Django REST framework][web-api-performance-profiling-django-rest-framework]
+* [API Development with Django and Django REST Framework][api-development-with-django-and-django-rest-framework]
-## Articles
-* [Web API performance: profiling Django REST framework](http://dabapps.com/blog/api-performance-profiling-django-rest-framework/)
-* [API Development with Django and Django REST Framework](https://bnotions.com/api-development-with-django-and-django-rest-framework/)
+[cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework
+[new-repo]: https://github.com/new
+[create-a-repo]: https://help.github.com/articles/create-a-repo/
+[travis-ci]: https://travis-ci.org
+[travis-profile]: https://travis-ci.org/profile
+[pypi-register]: https://pypi.python.org/pypi?%3Aaction=register_form
+[semver]: http://semver.org/
+[tox-docs]: https://tox.readthedocs.org/en/latest/
+[drf-compat]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/compat.py
+[rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/
+[drf-create-pr]: https://github.com/tomchristie/django-rest-framework/compare
+[drf-create-issue]: https://github.com/tomchristie/django-rest-framework/issues/new
+[authentication]: ../api-guide/authentication.md
+[permissions]: ../api-guide/permissions.md
+[discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework
+[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
+[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
+[doac]: https://github.com/Rediker-Software/doac
+[djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt
+[hawkrest]: https://github.com/kumar303/hawkrest
+[djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature
+[djoser]: https://github.com/sunscrapers/djoser
+[drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions
+[djangorestframework-composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions
+[rest-condition]: https://github.com/caxap/rest_condition
+[django-rest-framework-mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine
+[djangorestframework-gis]: https://github.com/djangonauts/django-rest-framework-gis
+[djangorestframework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore
+[drf-compound-fields]: https://github.com/estebistec/drf-compound-fields
+[django-extra-fields]: https://github.com/Hipo/drf-extra-fields
+[djangorestframework-bulk]: https://github.com/miki725/django-rest-framework-bulk
+[drf-nested-routers]: https://github.com/alanjds/drf-nested-routers
+[wq.db.rest]: http://wq.io/docs/about-rest
+[djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack
+[djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case
+[djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv
+[drf_ujson]: https://github.com/gizmag/drf-ujson-renderer
+[rest-pandas]: https://github.com/wq/django-rest-pandas
+[djangorestframework-chain]: https://github.com/philipn/django-rest-framework-chain
+[djangorestrelationalhyperlink]: https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project
+[django-rest-swagger]: https://github.com/marcgibbons/django-rest-swagger
+[django-rest-framework-proxy]: https://github.com/eofs/django-rest-framework-proxy
+[gaiarestframework]: https://github.com/AppsFuel/gaiarestframework
+[drf-extensions]: https://github.com/chibisov/drf-extensions
+[ember-data-django-rest-adapter]: https://github.com/toranb/ember-data-django-rest-adapter
+[beginners-guide-to-the-django-rest-framework]: http://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786
+[getting-started-with-django-rest-framework-and-angularjs]: http://blog.kevinastone.com/getting-started-with-django-rest-framework-and-angularjs.html
+[end-to-end-web-app-with-django-rest-framework-angularjs]: http://blog.mourafiq.com/post/55034504632/end-to-end-web-app-with-django-rest-framework
+[start-your-api-django-rest-framework-part-1]: https://godjango.com/41-start-your-api-django-rest-framework-part-1/
+[permissions-authentication-django-rest-framework-part-2]: https://godjango.com/43-permissions-authentication-django-rest-framework-part-2/
+[viewsets-and-routers-django-rest-framework-part-3]: https://godjango.com/45-viewsets-and-routers-django-rest-framework-part-3/
+[django-rest-framework-user-endpoint]: http://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/
+[check-credentials-using-django-rest-framework]: http://richardtier.com/2014/03/06/110/
+[ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1
+[django-rest-framework-part-1-video]: http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1
+[pyowa-july-2013-django-rest-framework-video]: http://www.youtube.com/watch?v=e1zrehvxpbo
+[django-rest-framework-and-angularjs-video]: http://www.youtube.com/watch?v=q8frbgtj020
+[web-api-performance-profiling-django-rest-framework]: http://dabapps.com/blog/api-performance-profiling-django-rest-framework/
+[api-development-with-django-and-django-rest-framework]: https://bnotions.com/api-development-with-django-and-django-rest-framework/
diff --git a/docs/topics/writable-nested-serializers.md b/docs/topics/writable-nested-serializers.md
index 66ea7815..ed614bd2 100644
--- a/docs/topics/writable-nested-serializers.md
+++ b/docs/topics/writable-nested-serializers.md
@@ -6,9 +6,9 @@
Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures.
-Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependancies between the various model instances, and the need to save or delete multiple instances in a single action.
+Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependencies between the various model instances, and the need to save or delete multiple instances in a single action.
-## One-to-many data structures
+## One-to-many data structures
*Example of a **read-only** nested serializer. Nothing complex to worry about here.*
@@ -16,10 +16,10 @@ Nested data structures are easy enough to work with if they're read-only - simpl
class Meta:
model = ToDoItem
fields = ('text', 'is_completed')
-
+
class ToDoListSerializer(serializers.ModelSerializer):
items = ToDoItemSerializer(many=True, read_only=True)
-
+
class Meta:
model = ToDoList
fields = ('title', 'items')
@@ -31,7 +31,7 @@ Some example output from our serializer.
'items': {
{'text': 'Compile playlist', 'is_completed': True},
{'text': 'Send invites', 'is_completed': False},
- {'text': 'Clean house', 'is_completed': False}
+ {'text': 'Clean house', 'is_completed': False}
}
}
@@ -44,4 +44,4 @@ Let's take a look at updating our nested one-to-many data structure.
### Making PATCH requests
-[cite]: http://jsonapi.org/format/#url-based-json-api \ No newline at end of file
+[cite]: http://jsonapi.org/format/#url-based-json-api
diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md
index 96214f5b..a3c19858 100644
--- a/docs/tutorial/1-serialization.md
+++ b/docs/tutorial/1-serialization.md
@@ -41,20 +41,7 @@ Once that's done we can create an app that we'll use to create a simple Web API.
python manage.py startapp snippets
-The simplest way to get up and running will probably be to use an `sqlite3` database for the tutorial. Edit the `tutorial/settings.py` file, and set the default database `"ENGINE"` to `"sqlite3"`, and `"NAME"` to `"tmp.db"`.
-
- DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3',
- 'NAME': 'tmp.db',
- 'USER': '',
- 'PASSWORD': '',
- 'HOST': '',
- 'PORT': '',
- }
- }
-
-We'll also need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`.
+We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file:
INSTALLED_APPS = (
...
@@ -64,15 +51,15 @@ We'll also need to add our new `snippets` app and the `rest_framework` app to `I
We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'^', include('snippets.urls')),
- )
+ ]
Okay, we're ready to roll.
## Creating a model to work with
-For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets` app's `models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
+For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself.
from django.db import models
from pygments.lexers import get_all_lexers
@@ -98,9 +85,10 @@ For the purposes of this tutorial we're going to start by creating a simple `Sni
class Meta:
ordering = ('created',)
-Don't forget to sync the database for the first time.
+We'll also need to create an initial migration for our snippet model, and sync the database for the first time.
- python manage.py syncdb
+ python manage.py makemigrations snippets
+ python manage.py migrate
## Creating a Serializer class
@@ -112,42 +100,41 @@ The first thing we need to get started on our Web API is to provide a way of ser
class SnippetSerializer(serializers.Serializer):
- pk = serializers.Field() # Note: `Field` is an untyped read-only field.
+ pk = serializers.IntegerField(read_only=True)
title = serializers.CharField(required=False,
max_length=100)
- code = serializers.CharField(widget=widgets.Textarea,
- max_length=100000)
+ code = serializers.CharField(style={'type': 'textarea'})
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES,
default='friendly')
- def restore_object(self, attrs, instance=None):
+ def create(self, validated_attrs):
"""
- Create or update a new snippet instance, given a dictionary
- of deserialized field values.
+ Create and return a new `Snippet` instance, given the validated data.
+ """
+ return Snippet.objects.create(**validated_attrs)
- Note that if we don't define this method, then deserializing
- data will simply return a dictionary of items.
+ def update(self, instance, validated_attrs):
+ """
+ Update and return an existing `Snippet` instance, given the validated data.
"""
- if instance:
- # Update existing instance
- instance.title = attrs.get('title', instance.title)
- instance.code = attrs.get('code', instance.code)
- instance.linenos = attrs.get('linenos', instance.linenos)
- instance.language = attrs.get('language', instance.language)
- instance.style = attrs.get('style', instance.style)
- return instance
+ instance.title = validated_attrs.get('title', instance.title)
+ instance.code = validated_attrs.get('code', instance.code)
+ instance.linenos = validated_attrs.get('linenos', instance.linenos)
+ instance.language = validated_attrs.get('language', instance.language)
+ instance.style = validated_attrs.get('style', instance.style)
+ instance.save()
+ return instance
- # Create new instance
- return Snippet(**attrs)
+The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()`
-The first part of the serializer class defines the fields that get serialized/deserialized. The `restore_object` method defines how fully fledged instances get created when deserializing data.
+A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`.
-Notice that we can also use various attributes that would typically be used on form fields, such as `widget=widgets.Textarea`. These can be used to control how the serializer should render when displayed as an HTML form. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
+The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `style={'type': 'textarea'}` flag above is equivelent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial.
-We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit.
+We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit.
## Working with Serializers
@@ -219,6 +206,24 @@ Open the file `snippets/serializers.py` again, and edit the `SnippetSerializer`
model = Snippet
fields = ('id', 'title', 'code', 'linenos', 'language', 'style')
+One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing it's representation. Open the Django shell with `python manange.py shell`, then try the following:
+
+ >>> from snippets.serializers import SnippetSerializer
+ >>> serializer = SnippetSerializer()
+ >>> print repr(serializer) # In python 3 use `print(repr(serializer))`
+ SnippetSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ title = CharField(allow_blank=True, max_length=100, required=False)
+ code = CharField(style={'type': 'textarea'})
+ linenos = BooleanField(required=False)
+ language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')...
+ style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')...
+
+It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes:
+
+* An automatically determined set of fields.
+* Simple default implementations for the `create()` and `update()` methods.
+
## Writing regular Django views using our Serializer
Let's see how we can write some API views using our new Serializer class.
@@ -297,11 +302,12 @@ We'll also need a view which corresponds to an individual snippet, and can be us
Finally we need to wire these views up. Create the `snippets/urls.py` file:
from django.conf.urls import patterns, url
+ from snippets import views
- urlpatterns = patterns('snippets.views',
- url(r'^snippets/$', 'snippet_list'),
- url(r'^snippets/(?P<pk>[0-9]+)/$', 'snippet_detail'),
- )
+ urlpatterns = [
+ url(r'^snippets/$', views.snippet_list),
+ url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
+ ]
It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now.
diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md
index e70bbbfc..f377c712 100644
--- a/docs/tutorial/2-requests-and-responses.md
+++ b/docs/tutorial/2-requests-and-responses.md
@@ -5,10 +5,10 @@ Let's introduce a couple of essential building blocks.
## Request objects
-REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.DATA` attribute, which is similar to `request.POST`, but more useful for working with Web APIs.
+REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs.
request.POST # Only handles form data. Only works for 'POST' method.
- request.DATA # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
+ request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods.
## Response objects
@@ -29,7 +29,7 @@ REST framework provides two wrappers you can use to write API views.
These wrappers provide a few bits of functionality such as making sure you receive `Request` instances in your view, and adding context to `Response` objects so that content negotiation can be performed.
-The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.DATA` with malformed input.
+The wrappers also provide behaviour such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exception that occurs when accessing `request.data` with malformed input.
## Pulling it all together
@@ -55,7 +55,7 @@ We don't need our `JSONResponse` class in `views.py` anymore, so go ahead and de
return Response(serializer.data)
elif request.method == 'POST':
- serializer = SnippetSerializer(data=request.DATA)
+ serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
@@ -80,7 +80,7 @@ Here is the view for an individual snippet, in the `views.py` module.
return Response(serializer.data)
elif request.method == 'PUT':
- serializer = SnippetSerializer(snippet, data=request.DATA)
+ serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@@ -92,7 +92,7 @@ Here is the view for an individual snippet, in the `views.py` module.
This should all feel very familiar - it is not a lot different from working with regular Django views.
-Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.DATA` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
+Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.data` can handle incoming `json` requests, but it can also handle `yaml` and other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.
## Adding optional format suffixes to our URLs
@@ -110,11 +110,12 @@ Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
from django.conf.urls import patterns, url
from rest_framework.urlpatterns import format_suffix_patterns
+ from snippets import views
- urlpatterns = patterns('snippets.views',
- url(r'^snippets/$', 'snippet_list'),
- url(r'^snippets/(?P<pk>[0-9]+)$', 'snippet_detail'),
- )
+ urlpatterns = [
+ url(r'^snippets/$', views.snippet_list),
+ url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
+ ]
urlpatterns = format_suffix_patterns(urlpatterns)
diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md
index e04072ca..0a9ea3f1 100644
--- a/docs/tutorial/3-class-based-views.md
+++ b/docs/tutorial/3-class-based-views.md
@@ -24,7 +24,7 @@ We'll start by rewriting the root view as a class based view. All this involves
return Response(serializer.data)
def post(self, request, format=None):
- serializer = SnippetSerializer(data=request.DATA)
+ serializer = SnippetSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
@@ -49,7 +49,7 @@ So far, so good. It looks pretty similar to the previous case, but we've got be
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
- serializer = SnippetSerializer(snippet, data=request.DATA)
+ serializer = SnippetSerializer(snippet, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
@@ -68,10 +68,10 @@ We'll also need to refactor our `urls.py` slightly now we're using class based v
from rest_framework.urlpatterns import format_suffix_patterns
from snippets import views
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'^snippets/$', views.SnippetList.as_view()),
url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
- )
+ ]
urlpatterns = format_suffix_patterns(urlpatterns)
diff --git a/docs/tutorial/4-authentication-and-permissions.md b/docs/tutorial/4-authentication-and-permissions.md
index 74ad9a55..4e4edeea 100644
--- a/docs/tutorial/4-authentication-and-permissions.md
+++ b/docs/tutorial/4-authentication-and-permissions.md
@@ -44,7 +44,9 @@ When that's all done we'll need to update our database tables.
Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again.
rm tmp.db
- python manage.py syncdb
+ rm -r snippets/migrations
+ python manage.py makemigrations snippets
+ python manage.py migrate
You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command.
@@ -92,24 +94,26 @@ Finally we need to add those views into the API, by referencing them from the UR
Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request.
-The way we deal with that is by overriding a `.pre_save()` method on our snippet views, that allows us to handle any information that is implicit in the incoming request or requested URL.
+The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL.
-On **both** the `SnippetList` and `SnippetDetail` view classes, add the following method:
+On the `SnippetList` view class, add the following method:
- def pre_save(self, obj):
- obj.owner = self.request.user
+ def perform_create(self, serializer):
+ serializer.save(owner=self.request.user)
+
+The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request.
## Updating our serializer
Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`:
- owner = serializers.Field(source='owner.username')
+ owner = serializers.ReadOnlyField(source='owner.username')
**Note**: Make sure you also add `'owner',` to the list of fields in the inner `Meta` class.
This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language.
-The field we've added is the untyped `Field` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `Field` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized.
+The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here.
## Adding required permissions to views
@@ -137,10 +141,10 @@ Add the following import at the top of the file:
And, at the end of the file, add a pattern to include the login and logout views for the browsable API.
- urlpatterns += patterns('',
+ urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
- )
+ ]
The `r'^api-auth/'` part of pattern can actually be whatever URL you want to use. The only restriction is that the included urls must use the `'rest_framework'` namespace.
diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
index 9c61fe3d..50552616 100644
--- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md
+++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md
@@ -6,7 +6,6 @@ At the moment relationships within our API are represented by using primary keys
Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add:
- from rest_framework import renderers
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
@@ -108,8 +107,8 @@ If we're going to have a hyperlinked API, we need to make sure we name our URL p
After adding all those names into our URLconf, our final `snippets/urls.py` file should look something like this:
# API endpoints
- urlpatterns = format_suffix_patterns(patterns('snippets.views',
- url(r'^$', 'api_root'),
+ urlpatterns = format_suffix_patterns([
+ url(r'^$', views.api_root),
url(r'^snippets/$',
views.SnippetList.as_view(),
name='snippet-list'),
@@ -125,13 +124,13 @@ After adding all those names into our URLconf, our final `snippets/urls.py` file
url(r'^users/(?P<pk>[0-9]+)/$',
views.UserDetail.as_view(),
name='user-detail')
- ))
+ ])
# Login and logout views for the browsable API
- urlpatterns += patterns('',
+ urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls',
namespace='rest_framework')),
- )
+ ]
## Adding pagination
diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md
index b2019520..3fad509a 100644
--- a/docs/tutorial/6-viewsets-and-routers.md
+++ b/docs/tutorial/6-viewsets-and-routers.md
@@ -60,7 +60,7 @@ To see what's going on under the hood let's first explicitly create a set of vie
In the `urls.py` file we bind our `ViewSet` classes into a set of concrete views.
- from snippets.views import SnippetViewSet, UserViewSet
+ from snippets.views import SnippetViewSet, UserViewSet, api_root
from rest_framework import renderers
snippet_list = SnippetViewSet.as_view({
@@ -87,14 +87,14 @@ Notice how we're creating multiple views from each `ViewSet` class, by binding t
Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual.
- urlpatterns = format_suffix_patterns(patterns('snippets.views',
- url(r'^$', 'api_root'),
+ urlpatterns = format_suffix_patterns([
+ url(r'^$', api_root),
url(r'^snippets/$', snippet_list, name='snippet-list'),
url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
url(r'^users/$', user_list, name='user-list'),
url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
- ))
+ ])
## Using Routers
@@ -102,7 +102,7 @@ Because we're using `ViewSet` classes rather than `View` classes, we actually do
Here's our re-wired `urls.py` file.
- from django.conf.urls import patterns, url, include
+ from django.conf.urls import url, include
from snippets import views
from rest_framework.routers import DefaultRouter
@@ -113,10 +113,10 @@ Here's our re-wired `urls.py` file.
# The API URLs are now determined automatically by the router.
# Additionally, we include the login URLs for the browseable API.
- urlpatterns = patterns('',
+ urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
- )
+ ]
Registering the viewsets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the viewset itself.
diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md
index 813e9872..1c398c1f 100644
--- a/docs/tutorial/quickstart.md
+++ b/docs/tutorial/quickstart.md
@@ -19,18 +19,20 @@ Create a new Django project named `tutorial`, then start a new app called `quick
pip install djangorestframework
# Set up a new project with a single application
- django-admin.py startproject tutorial .
+ django-admin.py startproject tutorial
cd tutorial
django-admin.py startapp quickstart
cd ..
Now sync your database for the first time:
- python manage.py syncdb
+ python manage.py migrate
-Make sure to create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example.
+We'll also create an initial user named `admin` with a password of `password`. We'll authenticate as that user later in our example.
-Once you've set up a database and got everything synced and ready to go, open up the app's directory and we'll get coding...
+ python manage.py createsuperuser
+
+Once you've set up a database and initial user created and ready to go, open up the app's directory and we'll get coding...
## Serializers
diff --git a/docs/404.html b/docs_theme/404.html
index 864247e7..44993e37 100644
--- a/docs/404.html
+++ b/docs_theme/404.html
@@ -1,50 +1,54 @@
<!DOCTYPE html>
<html lang="en">
-<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <meta charset="utf-8">
- <title>Django REST framework - 404 - Page not found</title>
- <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
- <link rel="canonical" href="http://www.django-rest-framework.org/404"/>
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="Django, API, REST, 404 - Page not found">
- <meta name="author" content="Tom Christie">
-
- <!-- Le styles -->
- <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet">
- <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
- <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
- <link href="http://www.django-rest-framework.org/css/default.css" rel="stylesheet">
-
- <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
- <!--[if lt IE 9]>
- <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
- <![endif]-->
-
- <script type="text/javascript">
-
- var _gaq = _gaq || [];
- _gaq.push(['_setAccount', 'UA-18852272-2']);
- _gaq.push(['_trackPageview']);
-
- (function() {
- var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
- ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
- var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
- })();
-
- </script>
- </head>
- <body onload="prettyPrint()" class="404-page">
+
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <meta charset="utf-8">
+ <title>Django REST framework - 404 - Page not found</title>
+ <link href="http://www.django-rest-framework.org/img/favicon.ico" rel="icon" type="image/x-icon">
+ <link rel="canonical" href="http://www.django-rest-framework.org/404" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="description" content="Django, API, REST, 404 - Page not found">
+ <meta name="author" content="Tom Christie">
+
+ <!-- Le styles -->
+ <link href="http://www.django-rest-framework.org/css/prettify.css" rel="stylesheet">
+ <link href="http://www.django-rest-framework.org/css/bootstrap.css" rel="stylesheet">
+ <link href="http://www.django-rest-framework.org/css/bootstrap-responsive.css" rel="stylesheet">
+ <link href="http://www.django-rest-framework.org/css/default.css" rel="stylesheet">
+
+ <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
+ <!--[if lt IE 9]>
+ <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
+ <![endif]-->
+
+ <script type="text/javascript">
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-18852272-2']);
+ _gaq.push(['_trackPageview']);
+
+ (function() {
+ var ga = document.createElement('script');
+ ga.type = 'text/javascript';
+ ga.async = true;
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+ var s = document.getElementsByTagName('script')[0];
+ s.parentNode.insertBefore(ga, s);
+ })();
+ </script>
+</head>
+
+<body onload="prettyPrint()" class="404-page">
<div class="wrapper">
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid">
- <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
- <a class="repo-link btn btn-inverse btn-small disabled" href="#">Next <i class="icon-arrow-right icon-white"></i></a>
- <a class="repo-link btn btn-inverse btn-small disabled" href="#"><i class="icon-arrow-left icon-white"></i> Previous</a>
- <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
+ <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
+ <a class="repo-link btn btn-inverse btn-small disabled" href="#">Next <i class="icon-arrow-right icon-white"></i></a>
+ <a class="repo-link btn btn-inverse btn-small disabled" href="#"><i class="icon-arrow-left icon-white"></i> Previous</a>
+ <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
@@ -121,81 +125,92 @@
</li>
-->
</ul>
- </div><!--/.nav-collapse -->
+ </div>
+ <!--/.nav-collapse -->
</div>
</div>
</div>
<div class="body-content">
<div class="container-fluid">
-
-<!-- Search Modal -->
-<div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
- <div class="modal-header">
- <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
- <h3 id="myModalLabel">Documentation search</h3>
- </div>
- <div class="modal-body">
- <!-- Custom google search -->
- <script>
- (function() {
- var cx = '015016005043623903336:rxraeohqk6w';
- var gcse = document.createElement('script');
- gcse.type = 'text/javascript';
- gcse.async = true;
- gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
- '//www.google.com/cse/cse.js?cx=' + cx;
- var s = document.getElementsByTagName('script')[0];
- s.parentNode.insertBefore(gcse, s);
- })();
- </script>
- <gcse:search></gcse:search>
- </div>
- <div class="modal-footer">
- <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
- </div>
-</div>
+ <!-- Search Modal -->
+ <div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
+ <div class="modal-header">
+ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
+ <h3 id="myModalLabel">Documentation search</h3>
+ </div>
+ <div class="modal-body">
+ <!-- Custom google search -->
+ <script>
+ (function() {
+ var cx = '015016005043623903336:rxraeohqk6w';
+ var gcse = document.createElement('script');
+ gcse.type = 'text/javascript';
+ gcse.async = true;
+ gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
+ '//www.google.com/cse/cse.js?cx=' + cx;
+ var s = document.getElementsByTagName('script')[0];
+ s.parentNode.insertBefore(gcse, s);
+ })();
+ </script>
+ <gcse:search></gcse:search>
+ </div>
+ <div class="modal-footer">
+ <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
+ </div>
+ </div>
<div class="row-fluid">
<div id="main-content" class="span12">
<h1 id="404-page-not-found" style="text-align: center">404</h1>
- <p style="text-align: center"><strong>Page not found</strong></p>
+ <p style="text-align: center"><strong>Page not found</strong>
+ </p>
<p style="text-align: center">Try the <a href="http://www.django-rest-framework.org/">homepage</a>, or <a href="#searchModal" data-toggle="modal">search the documentation</a>.</p>
- </div><!--/span-->
- </div><!--/row-->
- </div><!--/.fluid-container-->
- </div><!--/.body content-->
+ </div>
+ <!--/span-->
+ </div>
+ <!--/row-->
+ </div>
+ <!--/.fluid-container-->
+ </div>
+ <!--/.body content-->
- <div id="push"></div>
- </div><!--/.wrapper -->
+ <div id="push"></div>
+ </div>
+ <!--/.wrapper -->
<footer class="span12">
- <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a></p>
+ <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</a>
+ </p>
</footer>
- <!-- Le javascript
+ <!-- Le javascript
================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script src="http://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
- <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script>
- <script src="http://www.django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
- <script>
- //$('.side-nav').scrollspy()
- var shiftWindow = function() { scrollBy(0, -50) };
- if (location.hash) shiftWindow();
- window.addEventListener("hashchange", shiftWindow);
-
- $('.dropdown-menu').on('click touchstart', function(event) {
- event.stopPropagation();
+ <!-- Placed at the end of the document so the pages load faster -->
+ <script src="http://www.django-rest-framework.org/js/jquery-1.8.1-min.js"></script>
+ <script src="http://www.django-rest-framework.org/js/prettify-1.0.js"></script>
+ <script src="http://www.django-rest-framework.org/js/bootstrap-2.1.1-min.js"></script>
+ <script>
+ //$('.side-nav').scrollspy()
+ var shiftWindow = function() {
+ scrollBy(0, -50)
+ };
+ if (location.hash) shiftWindow();
+ window.addEventListener("hashchange", shiftWindow);
+
+ $('.dropdown-menu').on('click touchstart', function(event) {
+ event.stopPropagation();
+ });
+
+ // Dynamically force sidenav to no higher than browser window
+ $('.side-nav').css('max-height', window.innerHeight - 130);
+
+ $(function() {
+ $(window).resize(function() {
+ $('.side-nav').css('max-height', window.innerHeight - 130);
});
+ });
+ </script>
+</body>
- // Dynamically force sidenav to no higher than browser window
- $('.side-nav').css('max-height', window.innerHeight - 130);
-
- $(function(){
- $(window).resize(function(){
- $('.side-nav').css('max-height', window.innerHeight - 130);
- });
- });
- </script>
-</body></html>
+</html>
diff --git a/docs_theme/base.html b/docs_theme/base.html
new file mode 100644
index 00000000..25bd33ef
--- /dev/null
+++ b/docs_theme/base.html
@@ -0,0 +1,196 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
+ <meta charset="utf-8">
+ <title>{{ page_title }}</title>
+ <link href="{{ base_url }}/img/favicon.ico" rel="icon" type="image/x-icon">
+ <link rel="canonical" href="{{ canonical_url }}" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <meta name="description" content="Django, API, REST, {{ current_page.title }}">
+ <meta name="author" content="Tom Christie">
+
+ <!-- Le styles -->
+ <link href="{{ base_url }}/css/prettify.css" rel="stylesheet">
+ <link href="{{ base_url }}/css/bootstrap.css" rel="stylesheet">
+ <link href="{{ base_url }}/css/bootstrap-responsive.css" rel="stylesheet">
+ <link href="{{ base_url }}/css/default.css" rel="stylesheet">
+
+ <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
+ <!--[if lt IE 9]>
+ <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
+ <![endif]-->
+
+ <script type="text/javascript">
+ var _gaq = _gaq || [];
+ _gaq.push(['_setAccount', 'UA-18852272-2']);
+ _gaq.push(['_trackPageview']);
+
+ (function() {
+ var ga = document.createElement('script');
+ ga.type = 'text/javascript';
+ ga.async = true;
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+ var s = document.getElementsByTagName('script')[0];
+ s.parentNode.insertBefore(ga, s);
+ })();
+ </script>
+
+ <style>
+ span.fusion-wrap a {
+ display: block;
+ margin-top: 10px;
+ color: black;
+ }
+ a.fusion-poweredby {
+ display: block;
+ margin-top: 10px;
+ }
+ @media (max-width: 767px) {
+ div.promo {
+ display: none;
+ }
+ }
+ </style>
+</head>
+<body onload="prettyPrint()" class="{% if current_page.is_homepage %}index{% endif %}-page">
+
+ <div class="wrapper">
+
+ {% include "nav.html" %}
+
+ <div class="body-content">
+ <div class="container-fluid">
+
+ <!-- Search Modal -->
+ <div id="searchModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
+ <div class="modal-header">
+ <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
+ <h3 id="myModalLabel">Documentation search</h3>
+ </div>
+
+ <div class="modal-body">
+ <!-- Custom google search -->
+ <script>
+ (function() {
+ var cx = '015016005043623903336:rxraeohqk6w';
+ var gcse = document.createElement('script');
+ gcse.type = 'text/javascript';
+ gcse.async = true;
+ gcse.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') +
+ '//www.google.com/cse/cse.js?cx=' + cx;
+ var s = document.getElementsByTagName('script')[0];
+ s.parentNode.insertBefore(gcse, s);
+ })();
+ </script>
+ <gcse:search></gcse:search>
+ </div>
+
+ <div class="modal-footer">
+ <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
+ </div>
+ </div>
+
+ <div class="row-fluid">
+
+ <div class="span3">
+ <!-- TODO
+ <p style="margin-top: -12px">
+ <a class="btn btn-mini btn-primary" style="width: 60px">&laquo; previous</a>
+ <a class="btn btn-mini btn-primary" style="float: right; margin-right: 8px; width: 60px;">next &raquo;</a>
+ </p>
+ -->
+ <div id="table-of-contents">
+ <ul class="nav nav-list side-nav well sidebar-nav-fixed">
+
+ {% if current_page.is_homepage %}
+ <li class="main">
+ <a href="#">Django REST framework</a>
+ </li>
+ {% endif %}
+
+ {% for toc_item in toc %}
+
+ <li class="{% if not current_page.is_homepage %}main{% endif %}">
+ <a href="{{ toc_item.url }}">{{ toc_item.title }}</a>
+ </li>
+
+ {% for toc_item in toc_item.children %}
+ <li>
+ <a href="{{ toc_item.url }}">{{ toc_item.title }}</a>
+ </li>
+ {% endfor %}
+
+ {% endfor %}
+
+ {% if current_page.is_homepage %}
+ <div class="promo">
+ <hr/>
+ <script type="text/javascript" src="//cdn.fusionads.net/fusion.js?zoneid=1332&serve=C6SDP2Y&placement=djangorestframework" id="_fusionads_js"></script>
+ </div>
+ {% endif %}
+
+ </ul>
+
+ </div>
+ </div>
+
+ <div id="main-content" class="span9">
+ {% if meta.source %}
+ {% for filename in meta.source %}
+ <a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/{{ filename }}">
+ <span class="label label-info">{{ filename }}</span>
+ </a>
+ {% endfor %}
+ {% endif %}
+
+ {{ content }}
+ </div>
+ <!--/span-->
+ </div>
+ <!--/row-->
+ </div>
+ <!--/.fluid-container-->
+ </div>
+ <!--/.body content-->
+ <div id="push"></div>
+ </div>
+ <!--/.wrapper -->
+
+ <footer class="span12">
+ <p>Documentation built with <a href="http://www.mkdocs.org/">MkDocs</a>.</a>
+ </p>
+ </footer>
+
+ <!-- Le javascript
+ ================================================== -->
+ <!-- Placed at the end of the document so the pages load faster -->
+ <script src="{{ base_url }}/js/jquery-1.8.1-min.js"></script>
+ <script src="{{ base_url }}/js/prettify-1.0.js"></script>
+ <script src="{{ base_url }}/js/bootstrap-2.1.1-min.js"></script>
+
+ <script>
+ //$('.side-nav').scrollspy()
+ var shiftWindow = function() {
+ scrollBy(0, -50)
+ };
+ if (location.hash) shiftWindow();
+ window.addEventListener("hashchange", shiftWindow);
+
+ $('.dropdown-menu').on('click touchstart', function(event) {
+ event.stopPropagation();
+ });
+
+ // Dynamically force sidenav to no higher than browser window
+ $('.side-nav').css('max-height', window.innerHeight - 130);
+
+ $(function() {
+ $(window).resize(function() {
+ $('.side-nav').css('max-height', window.innerHeight - 130);
+ });
+ });
+ </script>
+</body>
+
+</html>
diff --git a/docs_theme/nav.html b/docs_theme/nav.html
new file mode 100644
index 00000000..ca1afc0e
--- /dev/null
+++ b/docs_theme/nav.html
@@ -0,0 +1,47 @@
+ <div class="navbar navbar-inverse navbar-fixed-top">
+ <div class="navbar-inner">
+ <div class="container-fluid">
+ <a class="repo-link btn btn-primary btn-small" href="https://github.com/tomchristie/django-rest-framework/tree/master">GitHub</a>
+ <a class="repo-link btn btn-inverse btn-small {% if not next_page %}disabled{% endif %}" rel="prev" {% if next_page %}href="{{ next_page.url }}"{% endif %}>
+ Next <i class="icon-arrow-right icon-white"></i>
+ </a>
+ <a class="repo-link btn btn-inverse btn-small {% if not previous_page %}disabled{% endif %}" rel="next" {% if previous_page %}href="{{ previous_page.url }}"{% endif %}>
+ <i class="icon-arrow-left icon-white"></i> Previous
+ </a>
+ <a class="repo-link btn btn-inverse btn-small" href="#searchModal" data-toggle="modal"><i class="icon-search icon-white"></i> Search</a>
+ <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ <span class="icon-bar"></span>
+ </a>
+ <a class="brand" href="http://www.django-rest-framework.org">Django REST framework</a>
+ <div class="nav-collapse collapse">
+ {% if include_nav %}
+ <!-- Main navigation -->
+ <ul class="nav navbar-nav">
+ <li {% if current_page.is_homepage %}class="active"{% endif %}><a href="/">Home</a></li>
+ {% for nav_item in nav %} {% if nav_item.children %}
+ <li class="dropdown{% if nav_item.active %} active{% endif %}">
+ <a href="#" class="dropdown-toggle" data-toggle="dropdown">{{ nav_item.title }} <b class="caret"></b></a>
+ <ul class="dropdown-menu">
+ {% for nav_item in nav_item.children %}
+ <li {% if nav_item.active %}class="active" {% endif %}>
+ <a href="{{ nav_item.url }}">{{ nav_item.title }}</a>
+ </li>
+ {% endfor %}
+ </ul>
+ </li>
+ {% else %}
+ <li {% if nav_item.active %}class="active" {% endif %}>
+ <a href="{{ nav_item.url }}">{{ nav_item.title }}</a>
+ </li>
+ {% endif %} {% endfor %}
+
+ </ul>
+ {% endif %}
+ </div>
+ <!--/.nav-collapse -->
+
+ </div>
+ </div>
+ </div>
diff --git a/mkdocs.py b/mkdocs.py
deleted file mode 100755
index 25cb55e2..00000000
--- a/mkdocs.py
+++ /dev/null
@@ -1,202 +0,0 @@
-#!/usr/bin/env python
-
-import markdown
-import os
-import re
-import shutil
-import sys
-
-root_dir = os.path.abspath(os.path.dirname(__file__))
-docs_dir = os.path.join(root_dir, 'docs')
-html_dir = os.path.join(root_dir, 'html')
-
-local = not '--deploy' in sys.argv
-preview = '-p' in sys.argv
-
-if local:
- base_url = 'file://%s/' % os.path.normpath(os.path.join(os.getcwd(), html_dir))
- suffix = '.html'
- index = 'index.html'
-else:
- base_url = 'http://www.django-rest-framework.org'
- suffix = ''
- index = ''
-
-
-main_header = '<li class="main"><a href="#{{ anchor }}">{{ title }}</a></li>'
-sub_header = '<li><a href="#{{ anchor }}">{{ title }}</a></li>'
-code_label = r'<a class="github" href="https://github.com/tomchristie/django-rest-framework/tree/master/rest_framework/\1"><span class="label label-info">\1</span></a>'
-
-page = open(os.path.join(docs_dir, 'template.html'), 'r').read()
-
-# Copy static files
-# for static in ['css', 'js', 'img']:
-# source = os.path.join(docs_dir, 'static', static)
-# target = os.path.join(html_dir, static)
-# if os.path.exists(target):
-# shutil.rmtree(target)
-# shutil.copytree(source, target)
-
-
-# Hacky, but what the hell, it'll do the job
-path_list = [
- 'index.md',
- 'tutorial/quickstart.md',
- 'tutorial/1-serialization.md',
- 'tutorial/2-requests-and-responses.md',
- 'tutorial/3-class-based-views.md',
- 'tutorial/4-authentication-and-permissions.md',
- 'tutorial/5-relationships-and-hyperlinked-apis.md',
- 'tutorial/6-viewsets-and-routers.md',
- 'api-guide/requests.md',
- 'api-guide/responses.md',
- 'api-guide/views.md',
- 'api-guide/generic-views.md',
- 'api-guide/viewsets.md',
- 'api-guide/routers.md',
- 'api-guide/parsers.md',
- 'api-guide/renderers.md',
- 'api-guide/serializers.md',
- 'api-guide/fields.md',
- 'api-guide/relations.md',
- 'api-guide/authentication.md',
- 'api-guide/permissions.md',
- 'api-guide/throttling.md',
- 'api-guide/filtering.md',
- 'api-guide/pagination.md',
- 'api-guide/content-negotiation.md',
- 'api-guide/format-suffixes.md',
- 'api-guide/reverse.md',
- 'api-guide/exceptions.md',
- 'api-guide/status-codes.md',
- 'api-guide/testing.md',
- 'api-guide/settings.md',
- 'topics/documenting-your-api.md',
- 'topics/ajax-csrf-cors.md',
- 'topics/browser-enhancements.md',
- 'topics/browsable-api.md',
- 'topics/rest-hypermedia-hateoas.md',
- 'topics/third-party-resources.md',
- 'topics/contributing.md',
- 'topics/rest-framework-2-announcement.md',
- 'topics/2.2-announcement.md',
- 'topics/2.3-announcement.md',
- 'topics/2.4-announcement.md',
- 'topics/release-notes.md',
- 'topics/credits.md',
-]
-
-prev_url_map = {}
-next_url_map = {}
-for idx in range(len(path_list)):
- path = path_list[idx]
- rel = '../' * path.count('/')
-
- if idx == 1 and not local:
- # Link back to '/', not '/index'
- prev_url_map[path] = '/'
- elif idx > 0:
- prev_url_map[path] = rel + path_list[idx - 1][:-3] + suffix
-
- if idx < len(path_list) - 1:
- next_url_map[path] = rel + path_list[idx + 1][:-3] + suffix
-
-
-for (dirpath, dirnames, filenames) in os.walk(docs_dir):
- relative_dir = dirpath.replace(docs_dir, '').lstrip(os.path.sep)
- build_dir = os.path.join(html_dir, relative_dir)
-
- if not os.path.exists(build_dir):
- os.makedirs(build_dir)
-
- for filename in filenames:
- path = os.path.join(dirpath, filename)
- relative_path = os.path.join(relative_dir, filename)
-
- if not filename.endswith('.md'):
- if relative_dir:
- output_path = os.path.join(build_dir, filename)
- shutil.copy(path, output_path)
- continue
-
- output_path = os.path.join(build_dir, filename[:-3] + '.html')
-
- toc = ''
- text = open(path, 'r').read().decode('utf-8')
- main_title = None
- description = 'Django, API, REST'
- for line in text.splitlines():
- if line.startswith('# '):
- title = line[2:].strip()
- template = main_header
- description = description + ', ' + title
- elif line.startswith('## '):
- title = line[3:].strip()
- template = sub_header
- else:
- continue
-
- if not main_title:
- main_title = title
- anchor = title.lower().replace(' ', '-').replace(':-', '-').replace("'", '').replace('?', '').replace('.', '')
- template = template.replace('{{ title }}', title)
- template = template.replace('{{ anchor }}', anchor)
- toc += template + '\n'
-
- if filename == 'index.md':
- main_title = 'Django REST framework - Web APIs for Django'
- else:
- main_title = main_title + ' - Django REST framework'
-
- if relative_path == 'index.md':
- canonical_url = base_url
- else:
- canonical_url = base_url + '/' + relative_path[:-3] + suffix
- prev_url = prev_url_map.get(relative_path)
- next_url = next_url_map.get(relative_path)
-
- content = markdown.markdown(text, ['headerid'])
-
- output = page.replace('{{ content }}', content).replace('{{ toc }}', toc).replace('{{ base_url }}', base_url).replace('{{ suffix }}', suffix).replace('{{ index }}', index)
- output = output.replace('{{ title }}', main_title)
- output = output.replace('{{ description }}', description)
- output = output.replace('{{ page_id }}', filename[:-3])
- output = output.replace('{{ canonical_url }}', canonical_url)
-
- if filename =='index.md':
- output = output.replace('{{ ad_block }}', """<hr/>
- <script type="text/javascript" src="//cdn.fusionads.net/fusion.js?zoneid=1332&serve=C6SDP2Y&placement=djangorestframework" id="_fusionads_js"></script>""")
- else:
- output = output.replace('{{ ad_block }}', '')
-
- if prev_url:
- output = output.replace('{{ prev_url }}', prev_url)
- output = output.replace('{{ prev_url_disabled }}', '')
- else:
- output = output.replace('{{ prev_url }}', '#')
- output = output.replace('{{ prev_url_disabled }}', 'disabled')
-
- if next_url:
- output = output.replace('{{ next_url }}', next_url)
- output = output.replace('{{ next_url_disabled }}', '')
- else:
- output = output.replace('{{ next_url }}', '#')
- output = output.replace('{{ next_url_disabled }}', 'disabled')
-
- output = re.sub(r'a href="([^"]*)\.md"', r'a href="\1%s"' % suffix, output)
- output = re.sub(r'<pre><code>:::bash', r'<pre class="prettyprint lang-bsh">', output)
- output = re.sub(r'<pre>', r'<pre class="prettyprint lang-py">', output)
- output = re.sub(r'<a class="github" href="([^"]*)"></a>', code_label, output)
- open(output_path, 'w').write(output.encode('utf-8'))
-
-if preview:
- import subprocess
-
- url = 'html/index.html'
-
- try:
- subprocess.Popen(["open", url]) # Mac
- except OSError:
- subprocess.Popen(["xdg-open", url]) # Linux
- except:
- os.startfile(url) # Windows
diff --git a/mkdocs.yml b/mkdocs.yml
new file mode 100644
index 00000000..cc31b1be
--- /dev/null
+++ b/mkdocs.yml
@@ -0,0 +1,55 @@
+site_name: Django REST framework
+site_url: http://www.django-rest-framework.org/
+site_description: Django REST framework - Web APIs for Django
+
+repo_url: https://github.com/tomchristie/django-rest-framework
+
+theme_dir: docs_theme
+
+pages:
+ - ['index.md', 'Home']
+ - ['tutorial/quickstart.md', 'Tutorial', 'Quickstart']
+ - ['tutorial/1-serialization.md', 'Tutorial', '1 - Serialization']
+ - ['tutorial/2-requests-and-responses.md', 'Tutorial', '2 - Requests and responses']
+ - ['tutorial/3-class-based-views.md', 'Tutorial', '3 - Class based views']
+ - ['tutorial/4-authentication-and-permissions.md', 'Tutorial', '4 - Authentication and permissions']
+ - ['tutorial/5-relationships-and-hyperlinked-apis.md', 'Tutorial', '5 - Relationships and hyperlinked APIs']
+ - ['tutorial/6-viewsets-and-routers.md', 'Tutorial', '6 - Viewsets and routers']
+ - ['api-guide/requests.md', 'API Guide', 'Requests']
+ - ['api-guide/responses.md', 'API Guide', 'Responses']
+ - ['api-guide/views.md', 'API Guide', 'Views']
+ - ['api-guide/generic-views.md', 'API Guide', 'Generic views']
+ - ['api-guide/viewsets.md', 'API Guide', 'Viewsets']
+ - ['api-guide/routers.md', 'API Guide', 'Routers']
+ - ['api-guide/parsers.md', 'API Guide', 'Parsers']
+ - ['api-guide/renderers.md', 'API Guide', 'Renderers']
+ - ['api-guide/serializers.md', 'API Guide', 'Serializers']
+ - ['api-guide/fields.md', 'API Guide', 'Serializer fields']
+ - ['api-guide/relations.md', 'API Guide', 'Serializer relations']
+ - ['api-guide/validators.md', 'API Guide', 'Validators']
+ - ['api-guide/authentication.md', 'API Guide', 'Authentication']
+ - ['api-guide/permissions.md', 'API Guide', 'Permissions']
+ - ['api-guide/throttling.md', 'API Guide', 'Throttling']
+ - ['api-guide/filtering.md', 'API Guide', 'Filtering']
+ - ['api-guide/pagination.md', 'API Guide', 'Pagination']
+ - ['api-guide/content-negotiation.md', 'API Guide', 'Content negotiation']
+ - ['api-guide/format-suffixes.md', 'API Guide', 'Format suffixes']
+ - ['api-guide/reverse.md', 'API Guide', 'Returning URLs']
+ - ['api-guide/exceptions.md', 'API Guide', 'Exceptions']
+ - ['api-guide/status-codes.md', 'API Guide', 'Status codes']
+ - ['api-guide/testing.md', 'API Guide', 'Testing']
+ - ['api-guide/settings.md', 'API Guide', 'Settings']
+ - ['topics/documenting-your-api.md', 'Topics', 'Documenting your API']
+ - ['topics/ajax-csrf-cors.md', 'Topics', 'AJAX, CSRF & CORS']
+ - ['topics/browser-enhancements.md', 'Topics',]
+ - ['topics/browsable-api.md', 'Topics', 'The Browsable API']
+ - ['topics/rest-hypermedia-hateoas.md', 'Topics', 'REST, Hypermedia & HATEOAS']
+ - ['topics/third-party-resources.md', 'Topics', 'Third Party Resources']
+ - ['topics/contributing.md', 'Topics', 'Contributing to REST framework']
+ - ['topics/rest-framework-2-announcement.md', 'Topics', '2.0 Announcement']
+ - ['topics/2.2-announcement.md', 'Topics', '2.2 Announcement']
+ - ['topics/2.3-announcement.md', 'Topics', '2.3 Announcement']
+ - ['topics/2.4-announcement.md', 'Topics', '2.4 Announcement']
+ - ['topics/kickstarter-announcement.md', 'Topics', 'Kickstarter Announcement']
+ - ['topics/release-notes.md', 'Topics', 'Release Notes']
+ - ['topics/credits.md', 'Topics', 'Credits']
diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py
index 8d82a4b9..261c9c98 100644
--- a/rest_framework/__init__.py
+++ b/rest_framework/__init__.py
@@ -8,7 +8,7 @@ ______ _____ _____ _____ __
"""
__title__ = 'Django REST framework'
-__version__ = '2.4.2'
+__version__ = '3.0.0'
__author__ = 'Tom Christie'
__license__ = 'BSD 2-Clause'
__copyright__ = 'Copyright 2011-2014 Tom Christie'
diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py
index ff1c44e0..124ef68a 100644
--- a/rest_framework/authentication.py
+++ b/rest_framework/authentication.py
@@ -124,7 +124,7 @@ class SessionAuthentication(BaseAuthentication):
reason = CSRFCheck().process_view(request, None, (), {})
if reason:
# CSRF failed, bail with explicit error message
- raise exceptions.AuthenticationFailed('CSRF Failed: %s' % reason)
+ raise exceptions.PermissionDenied('CSRF Failed: %s' % reason)
class TokenAuthentication(BaseAuthentication):
diff --git a/rest_framework/authtoken/serializers.py b/rest_framework/authtoken/serializers.py
index c2c456de..f31dded1 100644
--- a/rest_framework/authtoken/serializers.py
+++ b/rest_framework/authtoken/serializers.py
@@ -1,7 +1,7 @@
from django.contrib.auth import authenticate
from django.utils.translation import ugettext_lazy as _
-from rest_framework import serializers
+from rest_framework import exceptions, serializers
class AuthTokenSerializer(serializers.Serializer):
@@ -18,13 +18,13 @@ class AuthTokenSerializer(serializers.Serializer):
if user:
if not user.is_active:
msg = _('User account is disabled.')
- raise serializers.ValidationError(msg)
+ raise exceptions.ValidationError(msg)
else:
msg = _('Unable to log in with provided credentials.')
- raise serializers.ValidationError(msg)
+ raise exceptions.ValidationError(msg)
else:
msg = _('Must include "username" and "password"')
- raise serializers.ValidationError(msg)
+ raise exceptions.ValidationError(msg)
attrs['user'] = user
return attrs
diff --git a/rest_framework/authtoken/views.py b/rest_framework/authtoken/views.py
index 94e6f061..b75c2e25 100644
--- a/rest_framework/authtoken/views.py
+++ b/rest_framework/authtoken/views.py
@@ -1,5 +1,4 @@
from rest_framework.views import APIView
-from rest_framework import status
from rest_framework import parsers
from rest_framework import renderers
from rest_framework.response import Response
@@ -12,16 +11,13 @@ class ObtainAuthToken(APIView):
permission_classes = ()
parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,)
renderer_classes = (renderers.JSONRenderer,)
- serializer_class = AuthTokenSerializer
- model = Token
def post(self, request):
- serializer = self.serializer_class(data=request.DATA)
- if serializer.is_valid():
- user = serializer.validated_data['user']
- token, created = Token.objects.get_or_create(user=user)
- return Response({'token': token.key})
- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
+ serializer = AuthTokenSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ user = serializer.validated_data['user']
+ token, created = Token.objects.get_or_create(user=user)
+ return Response({'token': token.key})
obtain_auth_token = ObtainAuthToken.as_view()
diff --git a/rest_framework/compat.py b/rest_framework/compat.py
index 6c243462..da2496d8 100644
--- a/rest_framework/compat.py
+++ b/rest_framework/compat.py
@@ -5,11 +5,12 @@ versions of django/python, and compatibility wrappers around optional packages.
# flake8: noqa
from __future__ import unicode_literals
-import django
-import inspect
+
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
from django.utils import six
+import django
+import inspect
# Handle django.utils.encoding rename in 1.5 onwards.
@@ -25,6 +26,16 @@ except ImportError:
from django.utils.encoding import force_unicode as force_text
+# OrderedDict only available in Python 2.7.
+# This will always be the case in Django 1.7 and above, as these versions
+# no longer support Python 2.6.
+# For Django <= 1.6 and Python 2.6 fall back to OrderedDict.
+try:
+ from collections import OrderedDict
+except:
+ from django.utils.datastructures import SortedDict as OrderedDict
+
+
# HttpResponseBase only exists from 1.5 onwards
try:
from django.http.response import HttpResponseBase
@@ -84,15 +95,6 @@ except ImportError:
from collections import UserDict
from collections import MutableMapping as DictMixin
-# Try to import PIL in either of the two ways it can end up installed.
-try:
- from PIL import Image
-except ImportError:
- try:
- import Image
- except ImportError:
- Image = None
-
def get_model_name(model_cls):
try:
@@ -121,6 +123,62 @@ else:
return [m.upper() for m in self.http_method_names if hasattr(self, m)]
+
+# MinValueValidator, MaxValueValidator et al. only accept `message` in 1.8+
+if django.VERSION >= (1, 8):
+ from django.core.validators import MinValueValidator, MaxValueValidator
+ from django.core.validators import MinLengthValidator, MaxLengthValidator
+else:
+ from django.core.validators import MinValueValidator as DjangoMinValueValidator
+ from django.core.validators import MaxValueValidator as DjangoMaxValueValidator
+ from django.core.validators import MinLengthValidator as DjangoMinLengthValidator
+ from django.core.validators import MaxLengthValidator as DjangoMaxLengthValidator
+
+ class MinValueValidator(DjangoMinValueValidator):
+ def __init__(self, *args, **kwargs):
+ self.message = kwargs.pop('message', self.message)
+ super(MinValueValidator, self).__init__(*args, **kwargs)
+
+ class MaxValueValidator(DjangoMaxValueValidator):
+ def __init__(self, *args, **kwargs):
+ self.message = kwargs.pop('message', self.message)
+ super(MaxValueValidator, self).__init__(*args, **kwargs)
+
+ class MinLengthValidator(DjangoMinLengthValidator):
+ def __init__(self, *args, **kwargs):
+ self.message = kwargs.pop('message', self.message)
+ super(MinLengthValidator, self).__init__(*args, **kwargs)
+
+ class MaxLengthValidator(DjangoMaxLengthValidator):
+ def __init__(self, *args, **kwargs):
+ self.message = kwargs.pop('message', self.message)
+ super(MaxLengthValidator, self).__init__(*args, **kwargs)
+
+
+# URLValidator only accepts `message` in 1.6+
+if django.VERSION >= (1, 6):
+ from django.core.validators import URLValidator
+else:
+ from django.core.validators import URLValidator as DjangoURLValidator
+
+ class URLValidator(DjangoURLValidator):
+ def __init__(self, *args, **kwargs):
+ self.message = kwargs.pop('message', self.message)
+ super(URLValidator, self).__init__(*args, **kwargs)
+
+
+# EmailValidator requires explicit regex prior to 1.6+
+if django.VERSION >= (1, 6):
+ from django.core.validators import EmailValidator
+else:
+ from django.core.validators import EmailValidator as DjangoEmailValidator
+ from django.core.validators import email_re
+
+ class EmailValidator(DjangoEmailValidator):
+ def __init__(self, *args, **kwargs):
+ super(EmailValidator, self).__init__(email_re, *args, **kwargs)
+
+
# PATCH method is not implemented by Django
if 'patch' not in View.http_method_names:
View.http_method_names = View.http_method_names + ['patch']
@@ -144,12 +202,12 @@ class RequestFactory(DjangoRequestFactory):
r = {
'PATH_INFO': self._get_path(parsed),
'QUERY_STRING': force_text(parsed[4]),
- 'REQUEST_METHOD': str(method),
+ 'REQUEST_METHOD': six.text_type(method),
}
if data:
r.update({
'CONTENT_LENGTH': len(data),
- 'CONTENT_TYPE': str(content_type),
+ 'CONTENT_TYPE': six.text_type(content_type),
'wsgi.input': FakePayload(data),
})
elif django.VERSION <= (1, 4):
@@ -193,6 +251,16 @@ except ImportError:
etree = None
+# `seperators` argument to `json.dumps()` differs between 2.x and 3.x
+# See: http://bugs.python.org/issue22767
+if six.PY3:
+ SHORT_SEPARATORS = (',', ':')
+ LONG_SEPARATORS = (', ', ': ')
+else:
+ SHORT_SEPARATORS = (b',', b':')
+ LONG_SEPARATORS = (b', ', b': ')
+
+
# Handle lazy strings across Py2/Py3
from django.utils.functional import Promise
diff --git a/rest_framework/exceptions.py b/rest_framework/exceptions.py
index 06b5e8a2..906de3b0 100644
--- a/rest_framework/exceptions.py
+++ b/rest_framework/exceptions.py
@@ -5,80 +5,143 @@ In addition Django's built in 403 and 404 exceptions are handled.
(`django.http.Http404` and `django.core.exceptions.PermissionDenied`)
"""
from __future__ import unicode_literals
+
+from django.utils.translation import ugettext_lazy as _
+from django.utils.translation import ungettext_lazy
from rest_framework import status
+from rest_framework.compat import force_text
import math
+def _force_text_recursive(data):
+ """
+ Descend into a nested data structure, forcing any
+ lazy translation strings into plain text.
+ """
+ if isinstance(data, list):
+ return [
+ _force_text_recursive(item) for item in data
+ ]
+ elif isinstance(data, dict):
+ return dict([
+ (key, _force_text_recursive(value))
+ for key, value in data.items()
+ ])
+ return force_text(data)
+
+
class APIException(Exception):
"""
Base class for REST framework exceptions.
Subclasses should provide `.status_code` and `.default_detail` properties.
"""
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
- default_detail = 'A server error occured'
+ default_detail = _('A server error occured')
def __init__(self, detail=None):
- self.detail = detail or self.default_detail
+ if detail is not None:
+ self.detail = force_text(detail)
+ else:
+ self.detail = force_text(self.default_detail)
def __str__(self):
return self.detail
+# The recommended style for using `ValidationError` is to keep it namespaced
+# under `serializers`, in order to minimize potential confusion with Django's
+# built in `ValidationError`. For example:
+#
+# from rest_framework import serializers
+# raise serializers.ValidationError('Value was invalid')
+
+class ValidationError(APIException):
+ status_code = status.HTTP_400_BAD_REQUEST
+
+ def __init__(self, detail):
+ # For validation errors the 'detail' key is always required.
+ # The details should always be coerced to a list if not already.
+ if not isinstance(detail, dict) and not isinstance(detail, list):
+ detail = [detail]
+ self.detail = _force_text_recursive(detail)
+
+ def __str__(self):
+ return str(self.detail)
+
+
class ParseError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
- default_detail = 'Malformed request.'
+ default_detail = _('Malformed request.')
class AuthenticationFailed(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
- default_detail = 'Incorrect authentication credentials.'
+ default_detail = _('Incorrect authentication credentials.')
class NotAuthenticated(APIException):
status_code = status.HTTP_401_UNAUTHORIZED
- default_detail = 'Authentication credentials were not provided.'
+ default_detail = _('Authentication credentials were not provided.')
class PermissionDenied(APIException):
status_code = status.HTTP_403_FORBIDDEN
- default_detail = 'You do not have permission to perform this action.'
+ default_detail = _('You do not have permission to perform this action.')
class MethodNotAllowed(APIException):
status_code = status.HTTP_405_METHOD_NOT_ALLOWED
- default_detail = "Method '%s' not allowed."
+ default_detail = _("Method '%s' not allowed.")
def __init__(self, method, detail=None):
- self.detail = (detail or self.default_detail) % method
+ if detail is not None:
+ self.detail = force_text(detail)
+ else:
+ self.detail = force_text(self.default_detail) % method
class NotAcceptable(APIException):
status_code = status.HTTP_406_NOT_ACCEPTABLE
- default_detail = "Could not satisfy the request Accept header"
+ default_detail = _('Could not satisfy the request Accept header')
def __init__(self, detail=None, available_renderers=None):
- self.detail = detail or self.default_detail
+ if detail is not None:
+ self.detail = force_text(detail)
+ else:
+ self.detail = force_text(self.default_detail)
self.available_renderers = available_renderers
class UnsupportedMediaType(APIException):
status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE
- default_detail = "Unsupported media type '%s' in request."
+ default_detail = _("Unsupported media type '%s' in request.")
def __init__(self, media_type, detail=None):
- self.detail = (detail or self.default_detail) % media_type
+ if detail is not None:
+ self.detail = force_text(detail)
+ else:
+ self.detail = force_text(self.default_detail) % media_type
class Throttled(APIException):
status_code = status.HTTP_429_TOO_MANY_REQUESTS
- default_detail = 'Request was throttled.'
- extra_detail = " Expected available in %d second%s."
+ default_detail = _('Request was throttled.')
+ extra_detail = ungettext_lazy(
+ 'Expected available in %(wait)d second.',
+ 'Expected available in %(wait)d seconds.',
+ 'wait'
+ )
def __init__(self, wait=None, detail=None):
+ if detail is not None:
+ self.detail = force_text(detail)
+ else:
+ self.detail = force_text(self.default_detail)
+
if wait is None:
- self.detail = detail or self.default_detail
self.wait = None
else:
- format = (detail or self.default_detail) + self.extra_detail
- self.detail = format % (wait, wait != 1 and 's' or '')
self.wait = math.ceil(wait)
+ self.detail += ' ' + force_text(
+ self.extra_detail % {'wait': self.wait}
+ )
diff --git a/rest_framework/fields.py b/rest_framework/fields.py
index 0c78b3fb..ca9c479f 100644
--- a/rest_framework/fields.py
+++ b/rest_framework/fields.py
@@ -1,18 +1,25 @@
from django.conf import settings
-from django.core import validators
-from django.core.exceptions import ValidationError
-from django.utils import timezone
+from django.core.exceptions import ObjectDoesNotExist
+from django.core.exceptions import ValidationError as DjangoValidationError
+from django.core.validators import RegexValidator
+from django.forms import ImageField as DjangoImageField
+from django.utils import six, timezone
from django.utils.dateparse import parse_date, parse_datetime, parse_time
from django.utils.encoding import is_protected_type
from django.utils.translation import ugettext_lazy as _
from rest_framework import ISO_8601
-from rest_framework.compat import smart_text
+from rest_framework.compat import (
+ smart_text, EmailValidator, MinValueValidator, MaxValueValidator,
+ MinLengthValidator, MaxLengthValidator, URLValidator, OrderedDict
+)
+from rest_framework.exceptions import ValidationError
from rest_framework.settings import api_settings
from rest_framework.utils import html, representation, humanize_datetime
+import copy
import datetime
import decimal
import inspect
-import warnings
+import re
class empty:
@@ -49,13 +56,20 @@ def get_attribute(instance, attrs):
Also accepts either attribute lookup on objects or dictionary lookups.
"""
for attr in attrs:
+ if instance is None:
+ # Break out early if we get `None` at any point in a nested lookup.
+ return None
try:
instance = getattr(instance, attr)
+ except ObjectDoesNotExist:
+ return None
except AttributeError as exc:
try:
return instance[attr]
- except (KeyError, TypeError):
+ except (KeyError, TypeError, AttributeError):
raise exc
+ if is_simple_callable(instance):
+ instance = instance()
return instance
@@ -80,14 +94,48 @@ def set_value(dictionary, keys, value):
dictionary[keys[-1]] = value
+class CreateOnlyDefault:
+ """
+ This class may be used to provide default values that are only used
+ for create operations, but that do not return any value for update
+ operations.
+ """
+ def __init__(self, default):
+ self.default = default
+
+ def set_context(self, serializer_field):
+ self.is_update = serializer_field.parent.instance is not None
+
+ def __call__(self):
+ if self.is_update:
+ raise SkipField()
+ if callable(self.default):
+ return self.default()
+ return self.default
+
+ def __repr__(self):
+ return '%s(%s)' % (self.__class__.__name__, repr(self.default))
+
+
+class CurrentUserDefault:
+ def set_context(self, serializer_field):
+ self.user = serializer_field.context['request'].user
+
+ def __call__(self):
+ return self.user
+
+ def __repr__(self):
+ return '%s()' % self.__class__.__name__
+
+
class SkipField(Exception):
pass
NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`'
NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`'
-NOT_READ_ONLY_DEFAULT = 'May not set both `read_only` and `default`'
NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`'
+USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField'
MISSING_ERROR_MESSAGE = (
'ValidationError raised by `{class_name}`, but error key `{key}` does '
'not exist in the `error_messages` dictionary.'
@@ -98,14 +146,17 @@ class Field(object):
_creation_counter = 0
default_error_messages = {
- 'required': _('This field is required.')
+ 'required': _('This field is required.'),
+ 'null': _('This field may not be null.')
}
default_validators = []
+ default_empty_html = empty
+ initial = None
def __init__(self, read_only=False, write_only=False,
- required=None, default=empty, initial=None, source=None,
+ required=None, default=empty, initial=empty, source=None,
label=None, help_text=None, style=None,
- error_messages=None, validators=[]):
+ error_messages=None, validators=None, allow_null=False):
self._creation_counter = Field._creation_counter
Field._creation_counter += 1
@@ -116,19 +167,29 @@ class Field(object):
# Some combinations of keyword arguments do not make sense.
assert not (read_only and write_only), NOT_READ_ONLY_WRITE_ONLY
assert not (read_only and required), NOT_READ_ONLY_REQUIRED
- assert not (read_only and default is not empty), NOT_READ_ONLY_DEFAULT
assert not (required and default is not empty), NOT_REQUIRED_DEFAULT
+ assert not (read_only and self.__class__ == Field), USE_READONLYFIELD
self.read_only = read_only
self.write_only = write_only
self.required = required
self.default = default
self.source = source
- self.initial = initial
+ self.initial = self.initial if (initial is empty) else initial
self.label = label
self.help_text = help_text
self.style = {} if style is None else style
- self.validators = validators or self.default_validators[:]
+ self.allow_null = allow_null
+
+ if allow_null and self.default_empty_html is empty:
+ self.default_empty_html = None
+
+ if validators is not None:
+ self.validators = validators[:]
+
+ # These are set up by `.bind()` when the field is added to a serializer.
+ self.field_name = None
+ self.parent = None
# Collect default error message from self and parent classes
messages = {}
@@ -137,26 +198,26 @@ class Field(object):
messages.update(error_messages or {})
self.error_messages = messages
- def __new__(cls, *args, **kwargs):
+ def bind(self, field_name, parent):
"""
- When a field is instantiated, we store the arguments that were used,
- so that we can present a helpful representation of the object.
+ Initializes the field name and parent for the field instance.
+ Called when a field is added to the parent serializer instance.
"""
- instance = super(Field, cls).__new__(cls)
- instance._args = args
- instance._kwargs = kwargs
- return instance
- def bind(self, field_name, parent, root):
- """
- Setup the context for the field instance.
- """
+ # In order to enforce a consistent style, we error if a redundant
+ # 'source' argument has been used. For example:
+ # my_field = serializer.CharField(source='my_field')
+ assert self.source != field_name, (
+ "It is redundant to specify `source='%s'` on field '%s' in "
+ "serializer '%s', because it is the same as the field name. "
+ "Remove the `source` keyword argument." %
+ (field_name, self.__class__.__name__, parent.__class__.__name__)
+ )
+
self.field_name = field_name
self.parent = parent
- self.root = root
- self.context = parent.context
- # `self.label` should deafult to being based on the field name.
+ # `self.label` should default to being based on the field name.
if self.label is None:
self.label = field_name.replace('_', ' ').capitalize()
@@ -171,24 +232,48 @@ class Field(object):
else:
self.source_attrs = self.source.split('.')
+ # .validators is a lazily loaded property, that gets its default
+ # value from `get_validators`.
+ @property
+ def validators(self):
+ if not hasattr(self, '_validators'):
+ self._validators = self.get_validators()
+ return self._validators
+
+ @validators.setter
+ def validators(self, validators):
+ self._validators = validators
+
+ def get_validators(self):
+ return self.default_validators[:]
+
def get_initial(self):
"""
- Return a value to use when the field is being returned as a primative
+ Return a value to use when the field is being returned as a primitive
value, without any object instance.
"""
return self.initial
def get_value(self, dictionary):
"""
- Given the *incoming* primative data, return the value for this field
+ Given the *incoming* primitive data, return the value for this field
that should be validated and transformed to a native value.
"""
+ if html.is_html_input(dictionary):
+ # HTML forms will represent empty fields as '', and cannot
+ # represent None or False values directly.
+ if self.field_name not in dictionary:
+ if getattr(self.root, 'partial', False):
+ return empty
+ return self.default_empty_html
+ ret = dictionary[self.field_name]
+ return self.default_empty_html if (ret == '') else ret
return dictionary.get(self.field_name, empty)
def get_attribute(self, instance):
"""
- Given the *outgoing* object instance, return the value for this field
- that should be returned as a primative value.
+ Given the *outgoing* object instance, return the primitive value
+ that should be used for this field.
"""
return get_attribute(instance, self.source_attrs)
@@ -203,47 +288,74 @@ class Field(object):
"""
if self.default is empty:
raise SkipField()
+ if callable(self.default):
+ if hasattr(self.default, 'set_context'):
+ self.default.set_context(self)
+ return self.default()
return self.default
def run_validation(self, data=empty):
"""
Validate a simple representation and return the internal value.
- The provided data may be `empty` if no representation was included.
- May return `empty` if the field should not be included in the
+ The provided data may be `empty` if no representation was included
+ in the input.
+
+ May raise `SkipField` if the field should not be included in the
validated data.
"""
+ if self.read_only:
+ return self.get_default()
+
if data is empty:
+ if getattr(self.root, 'partial', False):
+ raise SkipField()
if self.required:
self.fail('required')
return self.get_default()
+ if data is None:
+ if not self.allow_null:
+ self.fail('null')
+ return None
+
value = self.to_internal_value(data)
self.run_validators(value)
return value
def run_validators(self, value):
- if value in (None, '', [], (), {}):
- return
-
+ """
+ Test the given value against all the validators on the field,
+ and either raise a `ValidationError` or simply return.
+ """
errors = []
for validator in self.validators:
+ if hasattr(validator, 'set_context'):
+ validator.set_context(self)
+
try:
validator(value)
except ValidationError as exc:
+ # If the validation error contains a mapping of fields to
+ # errors then simply raise it immediately rather than
+ # attempting to accumulate a list of errors.
+ if isinstance(exc.detail, dict):
+ raise
+ errors.extend(exc.detail)
+ except DjangoValidationError as exc:
errors.extend(exc.messages)
if errors:
raise ValidationError(errors)
def to_internal_value(self, data):
"""
- Transform the *incoming* primative data into a native value.
+ Transform the *incoming* primitive data into a native value.
"""
raise NotImplementedError('to_internal_value() must be implemented.')
def to_representation(self, value):
"""
- Transform the *outgoing* native value into primative data.
+ Transform the *outgoing* native value into primitive data.
"""
raise NotImplementedError('to_representation() must be implemented.')
@@ -257,9 +369,59 @@ class Field(object):
class_name = self.__class__.__name__
msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key)
raise AssertionError(msg)
- raise ValidationError(msg.format(**kwargs))
+ message_string = msg.format(**kwargs)
+ raise ValidationError(message_string)
+
+ @property
+ def root(self):
+ """
+ Returns the top-level serializer for this field.
+ """
+ root = self
+ while root.parent is not None:
+ root = root.parent
+ return root
+
+ @property
+ def context(self):
+ """
+ Returns the context as passed to the root serializer on initialization.
+ """
+ return getattr(self.root, '_context', {})
+
+ def __new__(cls, *args, **kwargs):
+ """
+ When a field is instantiated, we store the arguments that were used,
+ so that we can present a helpful representation of the object.
+ """
+ instance = super(Field, cls).__new__(cls)
+ instance._args = args
+ instance._kwargs = kwargs
+ return instance
+
+ def __deepcopy__(self, memo):
+ """
+ When cloning fields we instantiate using the arguments it was
+ originally created with, rather than copying the complete state.
+ """
+ args = copy.deepcopy(self._args)
+ kwargs = dict(self._kwargs)
+ # Bit ugly, but we need to special case 'validators' as Django's
+ # RegexValidator does not support deepcopy.
+ # We treat validator callables as immutable objects.
+ # See https://github.com/tomchristie/django-rest-framework/issues/1954
+ validators = kwargs.pop('validators', None)
+ kwargs = copy.deepcopy(kwargs)
+ if validators is not None:
+ kwargs['validators'] = validators
+ return self.__class__(*args, **kwargs)
def __repr__(self):
+ """
+ Fields are represented using their initial calling arguments.
+ This allows us to create descriptive representations for serializer
+ instances that show all the declared fields on the serializer.
+ """
return representation.field_repr(self)
@@ -269,25 +431,55 @@ class BooleanField(Field):
default_error_messages = {
'invalid': _('`{input}` is not a valid boolean.')
}
+ default_empty_html = False
+ initial = False
TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True))
FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False))
- def get_value(self, dictionary):
- if html.is_html_input(dictionary):
- # HTML forms do not send a `False` value on an empty checkbox,
- # so we override the default empty value to be False.
- return dictionary.get(self.field_name, False)
- return dictionary.get(self.field_name, empty)
+ def __init__(self, **kwargs):
+ assert 'allow_null' not in kwargs, '`allow_null` is not a valid option. Use `NullBooleanField` instead.'
+ super(BooleanField, self).__init__(**kwargs)
+
+ def to_internal_value(self, data):
+ if data in self.TRUE_VALUES:
+ return True
+ elif data in self.FALSE_VALUES:
+ return False
+ self.fail('invalid', input=data)
+
+ def to_representation(self, value):
+ if value in self.TRUE_VALUES:
+ return True
+ elif value in self.FALSE_VALUES:
+ return False
+ return bool(value)
+
+
+class NullBooleanField(Field):
+ default_error_messages = {
+ 'invalid': _('`{input}` is not a valid boolean.')
+ }
+ initial = None
+ TRUE_VALUES = set(('t', 'T', 'true', 'True', 'TRUE', '1', 1, True))
+ FALSE_VALUES = set(('f', 'F', 'false', 'False', 'FALSE', '0', 0, 0.0, False))
+ NULL_VALUES = set(('n', 'N', 'null', 'Null', 'NULL', '', None))
+
+ def __init__(self, **kwargs):
+ assert 'allow_null' not in kwargs, '`allow_null` is not a valid option.'
+ kwargs['allow_null'] = True
+ super(NullBooleanField, self).__init__(**kwargs)
def to_internal_value(self, data):
if data in self.TRUE_VALUES:
return True
elif data in self.FALSE_VALUES:
return False
+ elif data in self.NULL_VALUES:
+ return None
self.fail('invalid', input=data)
def to_representation(self, value):
- if value is None:
+ if value in self.NULL_VALUES:
return None
if value in self.TRUE_VALUES:
return True
@@ -300,136 +492,174 @@ class BooleanField(Field):
class CharField(Field):
default_error_messages = {
- 'blank': _('This field may not be blank.')
+ 'blank': _('This field may not be blank.'),
+ 'max_length': _('Ensure this field has no more than {max_length} characters.'),
+ 'min_length': _('Ensure this field has no more than {min_length} characters.')
}
+ initial = ''
+ coerce_blank_to_null = False
+ default_empty_html = ''
def __init__(self, **kwargs):
self.allow_blank = kwargs.pop('allow_blank', False)
- self.max_length = kwargs.pop('max_length', None)
- self.min_length = kwargs.pop('min_length', None)
+ max_length = kwargs.pop('max_length', None)
+ min_length = kwargs.pop('min_length', None)
super(CharField, self).__init__(**kwargs)
+ if max_length is not None:
+ message = self.error_messages['max_length'].format(max_length=max_length)
+ self.validators.append(MaxLengthValidator(max_length, message=message))
+ if min_length is not None:
+ message = self.error_messages['min_length'].format(min_length=min_length)
+ self.validators.append(MinLengthValidator(min_length, message=message))
+
+ def run_validation(self, data=empty):
+ # Test for the empty string here so that it does not get validated,
+ # and so that subclasses do not need to handle it explicitly
+ # inside the `to_internal_value()` method.
+ if data == '':
+ if not self.allow_blank:
+ self.fail('blank')
+ return ''
+ return super(CharField, self).run_validation(data)
def to_internal_value(self, data):
- if data == '' and not self.allow_blank:
- self.fail('blank')
- if data is None:
- return None
- return str(data)
+ return six.text_type(data)
def to_representation(self, value):
- if value is None:
- return None
- return str(value)
+ return six.text_type(value)
class EmailField(CharField):
default_error_messages = {
'invalid': _('Enter a valid email address.')
}
- default_validators = [validators.validate_email]
+
+ def __init__(self, **kwargs):
+ super(EmailField, self).__init__(**kwargs)
+ validator = EmailValidator(message=self.error_messages['invalid'])
+ self.validators.append(validator)
def to_internal_value(self, data):
- if data == '' and not self.allow_blank:
- self.fail('blank')
- if data is None:
- return None
- return str(data).strip()
+ return six.text_type(data).strip()
def to_representation(self, value):
- if value is None:
- return None
- return str(value).strip()
+ return six.text_type(value).strip()
class RegexField(CharField):
+ default_error_messages = {
+ 'invalid': _('This value does not match the required pattern.')
+ }
+
def __init__(self, regex, **kwargs):
- kwargs['validators'] = (
- [validators.RegexValidator(regex)] +
- kwargs.get('validators', [])
- )
super(RegexField, self).__init__(**kwargs)
+ validator = RegexValidator(regex, message=self.error_messages['invalid'])
+ self.validators.append(validator)
class SlugField(CharField):
default_error_messages = {
'invalid': _("Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens.")
}
- default_validators = [validators.validate_slug]
+
+ def __init__(self, **kwargs):
+ super(SlugField, self).__init__(**kwargs)
+ slug_regex = re.compile(r'^[-a-zA-Z0-9_]+$')
+ validator = RegexValidator(slug_regex, message=self.error_messages['invalid'])
+ self.validators.append(validator)
class URLField(CharField):
default_error_messages = {
'invalid': _("Enter a valid URL.")
}
- default_validators = [validators.URLValidator()]
+
+ def __init__(self, **kwargs):
+ super(URLField, self).__init__(**kwargs)
+ validator = URLValidator(message=self.error_messages['invalid'])
+ self.validators.append(validator)
# Number types...
class IntegerField(Field):
default_error_messages = {
- 'invalid': _('A valid integer is required.')
+ 'invalid': _('A valid integer is required.'),
+ 'max_value': _('Ensure this value is less than or equal to {max_value}.'),
+ 'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
+ 'max_string_length': _('String value too large')
}
+ MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
def __init__(self, **kwargs):
max_value = kwargs.pop('max_value', None)
min_value = kwargs.pop('min_value', None)
super(IntegerField, self).__init__(**kwargs)
if max_value is not None:
- self.validators.append(validators.MaxValueValidator(max_value))
+ message = self.error_messages['max_value'].format(max_value=max_value)
+ self.validators.append(MaxValueValidator(max_value, message=message))
if min_value is not None:
- self.validators.append(validators.MinValueValidator(min_value))
+ message = self.error_messages['min_value'].format(min_value=min_value)
+ self.validators.append(MinValueValidator(min_value, message=message))
def to_internal_value(self, data):
+ if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
+ self.fail('max_string_length')
+
try:
- data = int(str(data))
+ data = int(data)
except (ValueError, TypeError):
self.fail('invalid')
return data
def to_representation(self, value):
- if value is None:
- return None
return int(value)
class FloatField(Field):
default_error_messages = {
- 'invalid': _("'%s' value must be a float."),
+ 'invalid': _("A valid number is required."),
+ 'max_value': _('Ensure this value is less than or equal to {max_value}.'),
+ 'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
+ 'max_string_length': _('String value too large')
}
+ MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
def __init__(self, **kwargs):
max_value = kwargs.pop('max_value', None)
min_value = kwargs.pop('min_value', None)
super(FloatField, self).__init__(**kwargs)
if max_value is not None:
- self.validators.append(validators.MaxValueValidator(max_value))
+ message = self.error_messages['max_value'].format(max_value=max_value)
+ self.validators.append(MaxValueValidator(max_value, message=message))
if min_value is not None:
- self.validators.append(validators.MinValueValidator(min_value))
+ message = self.error_messages['min_value'].format(min_value=min_value)
+ self.validators.append(MinValueValidator(min_value, message=message))
- def to_internal_value(self, value):
- if value is None:
- return None
- return float(value)
+ def to_internal_value(self, data):
+ if isinstance(data, six.text_type) and len(data) > self.MAX_STRING_LENGTH:
+ self.fail('max_string_length')
- def to_representation(self, value):
- if value is None:
- return None
try:
- return float(value)
+ return float(data)
except (TypeError, ValueError):
- self.fail('invalid', value=value)
+ self.fail('invalid')
+
+ def to_representation(self, value):
+ return float(value)
class DecimalField(Field):
default_error_messages = {
- 'invalid': _('Enter a number.'),
+ 'invalid': _('A valid number is required.'),
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'),
'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'),
- 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.')
+ 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.'),
+ 'max_string_length': _('String value too large')
}
+ MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
coerce_to_string = api_settings.COERCE_DECIMAL_TO_STRING
@@ -439,23 +669,25 @@ class DecimalField(Field):
self.coerce_to_string = coerce_to_string if (coerce_to_string is not None) else self.coerce_to_string
super(DecimalField, self).__init__(**kwargs)
if max_value is not None:
- self.validators.append(validators.MaxValueValidator(max_value))
+ message = self.error_messages['max_value'].format(max_value=max_value)
+ self.validators.append(MaxValueValidator(max_value, message=message))
if min_value is not None:
- self.validators.append(validators.MinValueValidator(min_value))
+ message = self.error_messages['min_value'].format(min_value=min_value)
+ self.validators.append(MinValueValidator(min_value, message=message))
- def to_internal_value(self, value):
+ def to_internal_value(self, data):
"""
Validates that the input is a decimal number. Returns a Decimal
instance. Returns None for empty values. Ensures that there are no more
than max_digits in the number, and no more than decimal_places digits
after the decimal point.
"""
- if value in (None, ''):
- return None
+ data = smart_text(data).strip()
+ if len(data) > self.MAX_STRING_LENGTH:
+ self.fail('max_string_length')
- value = smart_text(value).strip()
try:
- value = decimal.Decimal(value)
+ value = decimal.Decimal(data)
except decimal.DecimalException:
self.fail('invalid')
@@ -485,125 +717,116 @@ class DecimalField(Field):
if self.decimal_places is not None and decimals > self.decimal_places:
self.fail('max_decimal_places', max_decimal_places=self.decimal_places)
if self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places):
- self.fail('max_whole_digits', max_while_digits=self.max_digits - self.decimal_places)
+ self.fail('max_whole_digits', max_whole_digits=self.max_digits - self.decimal_places)
return value
def to_representation(self, value):
- if isinstance(value, decimal.Decimal):
- context = decimal.getcontext().copy()
- context.prec = self.max_digits
- quantized = value.quantize(
- decimal.Decimal('.1') ** self.decimal_places,
- context=context
- )
- if not self.coerce_to_string:
- return quantized
- return '{0:f}'.format(quantized)
-
+ if not isinstance(value, decimal.Decimal):
+ value = decimal.Decimal(six.text_type(value).strip())
+
+ context = decimal.getcontext().copy()
+ context.prec = self.max_digits
+ quantized = value.quantize(
+ decimal.Decimal('.1') ** self.decimal_places,
+ context=context
+ )
if not self.coerce_to_string:
- return value
- return '%.*f' % (self.max_decimal_places, value)
+ return quantized
+ return '{0:f}'.format(quantized)
# Date & time fields...
-class DateField(Field):
+class DateTimeField(Field):
default_error_messages = {
- 'invalid': _('Date has wrong format. Use one of these formats instead: {format}'),
+ 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'),
+ 'date': _('Expected a datetime but got a date.'),
}
- format = api_settings.DATE_FORMAT
- input_formats = api_settings.DATE_INPUT_FORMATS
+ format = api_settings.DATETIME_FORMAT
+ input_formats = api_settings.DATETIME_INPUT_FORMATS
+ default_timezone = timezone.get_default_timezone() if settings.USE_TZ else None
- def __init__(self, format=None, input_formats=None, *args, **kwargs):
- self.format = format if format is not None else self.format
+ def __init__(self, format=empty, input_formats=None, default_timezone=None, *args, **kwargs):
+ self.format = format if format is not empty else self.format
self.input_formats = input_formats if input_formats is not None else self.input_formats
- super(DateField, self).__init__(*args, **kwargs)
+ self.default_timezone = default_timezone if default_timezone is not None else self.default_timezone
+ super(DateTimeField, self).__init__(*args, **kwargs)
+
+ def enforce_timezone(self, value):
+ """
+ When `self.default_timezone` is `None`, always return naive datetimes.
+ When `self.default_timezone` is not `None`, always return aware datetimes.
+ """
+ if (self.default_timezone is not None) and not timezone.is_aware(value):
+ return timezone.make_aware(value, self.default_timezone)
+ elif (self.default_timezone is None) and timezone.is_aware(value):
+ return timezone.make_naive(value, timezone.UTC())
+ return value
def to_internal_value(self, value):
- if value in (None, ''):
- return None
+ if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime):
+ self.fail('date')
if isinstance(value, datetime.datetime):
- if timezone and settings.USE_TZ and timezone.is_aware(value):
- # Convert aware datetimes to the default time zone
- # before casting them to dates (#17742).
- default_timezone = timezone.get_default_timezone()
- value = timezone.make_naive(value, default_timezone)
- return value.date()
-
- if isinstance(value, datetime.date):
- return value
+ return self.enforce_timezone(value)
for format in self.input_formats:
if format.lower() == ISO_8601:
try:
- parsed = parse_date(value)
+ parsed = parse_datetime(value)
except (ValueError, TypeError):
pass
else:
if parsed is not None:
- return parsed
+ return self.enforce_timezone(parsed)
else:
try:
parsed = datetime.datetime.strptime(value, format)
except (ValueError, TypeError):
pass
else:
- return parsed.date()
+ return self.enforce_timezone(parsed)
- humanized_format = humanize_datetime.date_formats(self.input_formats)
+ humanized_format = humanize_datetime.datetime_formats(self.input_formats)
self.fail('invalid', format=humanized_format)
def to_representation(self, value):
- if value is None or self.format is None:
+ if self.format is None:
return value
- if isinstance(value, datetime.datetime):
- value = value.date()
-
if self.format.lower() == ISO_8601:
- return value.isoformat()
+ value = value.isoformat()
+ if value.endswith('+00:00'):
+ value = value[:-6] + 'Z'
+ return value
return value.strftime(self.format)
-class DateTimeField(Field):
+class DateField(Field):
default_error_messages = {
- 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}'),
+ 'invalid': _('Date has wrong format. Use one of these formats instead: {format}'),
+ 'datetime': _('Expected a date but got a datetime.'),
}
- format = api_settings.DATETIME_FORMAT
- input_formats = api_settings.DATETIME_INPUT_FORMATS
+ format = api_settings.DATE_FORMAT
+ input_formats = api_settings.DATE_INPUT_FORMATS
- def __init__(self, format=None, input_formats=None, *args, **kwargs):
- self.format = format if format is not None else self.format
+ def __init__(self, format=empty, input_formats=None, *args, **kwargs):
+ self.format = format if format is not empty else self.format
self.input_formats = input_formats if input_formats is not None else self.input_formats
- super(DateTimeField, self).__init__(*args, **kwargs)
+ super(DateField, self).__init__(*args, **kwargs)
def to_internal_value(self, value):
- if value in (None, ''):
- return None
-
if isinstance(value, datetime.datetime):
- return value
+ self.fail('datetime')
if isinstance(value, datetime.date):
- value = datetime.datetime(value.year, value.month, value.day)
- if settings.USE_TZ:
- # For backwards compatibility, interpret naive datetimes in
- # local time. This won't work during DST change, but we can't
- # do much about it, so we let the exceptions percolate up the
- # call stack.
- warnings.warn("DateTimeField received a naive datetime (%s)"
- " while time zone support is active." % value,
- RuntimeWarning)
- default_timezone = timezone.get_default_timezone()
- value = timezone.make_aware(value, default_timezone)
return value
for format in self.input_formats:
if format.lower() == ISO_8601:
try:
- parsed = parse_datetime(value)
+ parsed = parse_date(value)
except (ValueError, TypeError):
pass
else:
@@ -615,20 +838,26 @@ class DateTimeField(Field):
except (ValueError, TypeError):
pass
else:
- return parsed
+ return parsed.date()
- humanized_format = humanize_datetime.datetime_formats(self.input_formats)
+ humanized_format = humanize_datetime.date_formats(self.input_formats)
self.fail('invalid', format=humanized_format)
def to_representation(self, value):
- if value is None or self.format is None:
+ if self.format is None:
return value
+ # Applying a `DateField` to a datetime value is almost always
+ # not a sensible thing to do, as it means naively dropping
+ # any explicit or implicit timezone info.
+ assert not isinstance(value, datetime.datetime), (
+ 'Expected a `date`, but got a `datetime`. Refusing to coerce, '
+ 'as this may mean losing timezone information. Use a custom '
+ 'read-only field and deal with timezone issues explicitly.'
+ )
+
if self.format.lower() == ISO_8601:
- ret = value.isoformat()
- if ret.endswith('+00:00'):
- ret = ret[:-6] + 'Z'
- return ret
+ return value.isoformat()
return value.strftime(self.format)
@@ -639,15 +868,12 @@ class TimeField(Field):
format = api_settings.TIME_FORMAT
input_formats = api_settings.TIME_INPUT_FORMATS
- def __init__(self, format=None, input_formats=None, *args, **kwargs):
- self.format = format if format is not None else self.format
+ def __init__(self, format=empty, input_formats=None, *args, **kwargs):
+ self.format = format if format is not empty else self.format
self.input_formats = input_formats if input_formats is not None else self.input_formats
super(TimeField, self).__init__(*args, **kwargs)
- def from_native(self, value):
- if value in (None, ''):
- return None
-
+ def to_internal_value(self, value):
if isinstance(value, datetime.time):
return value
@@ -672,11 +898,17 @@ class TimeField(Field):
self.fail('invalid', format=humanized_format)
def to_representation(self, value):
- if value is None or self.format is None:
+ if self.format is None:
return value
- if isinstance(value, datetime.datetime):
- value = value.time()
+ # Applying a `TimeField` to a datetime value is almost always
+ # not a sensible thing to do, as it means naively dropping
+ # any explicit or implicit timezone info.
+ assert not isinstance(value, datetime.datetime), (
+ 'Expected a `time`, but got a `datetime`. Refusing to coerce, '
+ 'as this may mean losing timezone information. Use a custom '
+ 'read-only field and deal with timezone issues explicitly.'
+ )
if self.format.lower() == ISO_8601:
return value.isoformat()
@@ -699,58 +931,171 @@ class ChoiceField(Field):
for item in choices
]
if all(pairs):
- self.choices = dict([(key, display_value) for key, display_value in choices])
+ self.choices = OrderedDict([(key, display_value) for key, display_value in choices])
else:
- self.choices = dict([(item, item) for item in choices])
+ self.choices = OrderedDict([(item, item) for item in choices])
# Map the string representation of choices to the underlying value.
# Allows us to deal with eg. integer choices while supporting either
# integer or string input, but still get the correct datatype out.
self.choice_strings_to_values = dict([
- (str(key), key) for key in self.choices.keys()
+ (six.text_type(key), key) for key in self.choices.keys()
])
super(ChoiceField, self).__init__(**kwargs)
def to_internal_value(self, data):
try:
- return self.choice_strings_to_values[str(data)]
+ return self.choice_strings_to_values[six.text_type(data)]
except KeyError:
self.fail('invalid_choice', input=data)
def to_representation(self, value):
- return value
+ if value in ('', None):
+ return value
+ return self.choice_strings_to_values[six.text_type(value)]
class MultipleChoiceField(ChoiceField):
default_error_messages = {
'invalid_choice': _('`{input}` is not a valid choice.'),
- 'not_a_list': _('Expected a list of items but got type `{input_type}`')
+ 'not_a_list': _('Expected a list of items but got type `{input_type}`.')
}
+ default_empty_html = []
+
+ def get_value(self, dictionary):
+ # We override the default field access in order to support
+ # lists in HTML forms.
+ if html.is_html_input(dictionary):
+ return dictionary.getlist(self.field_name)
+ return dictionary.get(self.field_name, empty)
def to_internal_value(self, data):
- if not hasattr(data, '__iter__'):
+ if isinstance(data, type('')) or not hasattr(data, '__iter__'):
self.fail('not_a_list', input_type=type(data).__name__)
+
return set([
super(MultipleChoiceField, self).to_internal_value(item)
for item in data
])
def to_representation(self, value):
- return value
+ return set([
+ self.choice_strings_to_values[six.text_type(item)] for item in value
+ ])
# File types...
class FileField(Field):
- pass # TODO
+ default_error_messages = {
+ 'required': _("No file was submitted."),
+ 'invalid': _("The submitted data was not a file. Check the encoding type on the form."),
+ 'no_name': _("No filename could be determined."),
+ 'empty': _("The submitted file is empty."),
+ 'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'),
+ }
+ use_url = api_settings.UPLOADED_FILES_USE_URL
+
+ def __init__(self, *args, **kwargs):
+ self.max_length = kwargs.pop('max_length', None)
+ self.allow_empty_file = kwargs.pop('allow_empty_file', False)
+ self.use_url = kwargs.pop('use_url', self.use_url)
+ super(FileField, self).__init__(*args, **kwargs)
+
+ def to_internal_value(self, data):
+ try:
+ # `UploadedFile` objects should have name and size attributes.
+ file_name = data.name
+ file_size = data.size
+ except AttributeError:
+ self.fail('invalid')
+
+ if not file_name:
+ self.fail('no_name')
+ if not self.allow_empty_file and not file_size:
+ self.fail('empty')
+ if self.max_length and len(file_name) > self.max_length:
+ self.fail('max_length', max_length=self.max_length, length=len(file_name))
+
+ return data
+
+ def to_representation(self, value):
+ if self.use_url:
+ if not value:
+ return None
+ url = value.url
+ request = self.context.get('request', None)
+ if request is not None:
+ return request.build_absolute_uri(url)
+ return url
+ return value.name
+
+
+class ImageField(FileField):
+ default_error_messages = {
+ 'invalid_image': _(
+ 'Upload a valid image. The file you uploaded was either not an '
+ 'image or a corrupted image.'
+ ),
+ }
+
+ def __init__(self, *args, **kwargs):
+ self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField)
+ super(ImageField, self).__init__(*args, **kwargs)
+
+ def to_internal_value(self, data):
+ # Image validation is a bit grungy, so we'll just outright
+ # defer to Django's implementation so we don't need to
+ # consider it, or treat PIL as a test dependency.
+ file_object = super(ImageField, self).to_internal_value(data)
+ django_field = self._DjangoImageField()
+ django_field.error_messages = self.error_messages
+ django_field.to_python(file_object)
+ return file_object
+
+
+# Composite field types...
+
+class ListField(Field):
+ child = None
+ initial = []
+ default_error_messages = {
+ 'not_a_list': _('Expected a list of items but got type `{input_type}`')
+ }
+
+ def __init__(self, *args, **kwargs):
+ self.child = kwargs.pop('child', copy.deepcopy(self.child))
+ assert self.child is not None, '`child` is a required argument.'
+ assert not inspect.isclass(self.child), '`child` has not been instantiated.'
+ super(ListField, self).__init__(*args, **kwargs)
+ self.child.bind(field_name='', parent=self)
+
+ def get_value(self, dictionary):
+ # We override the default field access in order to support
+ # lists in HTML forms.
+ if html.is_html_input(dictionary):
+ return html.parse_html_list(dictionary, prefix=self.field_name)
+ return dictionary.get(self.field_name, empty)
+ def to_internal_value(self, data):
+ """
+ List of dicts of native values <- List of dicts of primitive datatypes.
+ """
+ if html.is_html_input(data):
+ data = html.parse_html_list(data)
+ if isinstance(data, type('')) or not hasattr(data, '__iter__'):
+ self.fail('not_a_list', input_type=type(data).__name__)
+ return [self.child.run_validation(item) for item in data]
-class ImageField(Field):
- pass # TODO
+ def to_representation(self, data):
+ """
+ List of object instances -> List of dicts of primitive datatypes.
+ """
+ return [self.child.to_representation(item) for item in data]
-# Advanced field types...
+# Miscellaneous field types...
class ReadOnlyField(Field):
"""
@@ -770,11 +1115,31 @@ class ReadOnlyField(Field):
super(ReadOnlyField, self).__init__(**kwargs)
def to_representation(self, value):
- if is_simple_callable(value):
- return value()
return value
+class HiddenField(Field):
+ """
+ A hidden field does not take input from the user, or present any output,
+ but it does populate a field in `validated_data`, based on its default
+ value. This is particularly useful when we have a `unique_for_date`
+ constraint on a pair of fields, as we need some way to include the date in
+ the validated data.
+ """
+ def __init__(self, **kwargs):
+ assert 'default' in kwargs, 'default is a required argument.'
+ kwargs['write_only'] = True
+ super(HiddenField, self).__init__(**kwargs)
+
+ def get_value(self, dictionary):
+ # We always use the default value for `HiddenField`.
+ # User input is never provided or accepted.
+ return empty
+
+ def to_internal_value(self, data):
+ return data
+
+
class SerializerMethodField(Field):
"""
A read-only field that get its representation from calling a method on the
@@ -790,17 +1155,32 @@ class SerializerMethodField(Field):
def get_extra_info(self, obj):
return ... # Calculate some data to return.
"""
- def __init__(self, method_attr=None, **kwargs):
- self.method_attr = method_attr
+ def __init__(self, method_name=None, **kwargs):
+ self.method_name = method_name
kwargs['source'] = '*'
kwargs['read_only'] = True
super(SerializerMethodField, self).__init__(**kwargs)
+ def bind(self, field_name, parent):
+ # In order to enforce a consistent style, we error if a redundant
+ # 'method_name' argument has been used. For example:
+ # my_field = serializer.CharField(source='my_field')
+ default_method_name = 'get_{field_name}'.format(field_name=field_name)
+ assert self.method_name != default_method_name, (
+ "It is redundant to specify `%s` on SerializerMethodField '%s' in "
+ "serializer '%s', because it is the same as the default method name. "
+ "Remove the `method_name` argument." %
+ (self.method_name, field_name, parent.__class__.__name__)
+ )
+
+ # The method name should default to `get_{field_name}`.
+ if self.method_name is None:
+ self.method_name = default_method_name
+
+ super(SerializerMethodField, self).bind(field_name, parent)
+
def to_representation(self, value):
- method_attr = self.method_attr
- if method_attr is None:
- method_attr = 'get_{field_name}'.format(field_name=self.field_name)
- method = getattr(self.parent, method_attr)
+ method = getattr(self.parent, self.method_name)
return method(value)
@@ -811,10 +1191,19 @@ class ModelField(Field):
This is used by `ModelSerializer` when dealing with custom model fields,
that do not have a serializer field to be mapped to.
"""
+ default_error_messages = {
+ 'max_length': _('Ensure this field has no more than {max_length} characters.'),
+ }
+
def __init__(self, model_field, **kwargs):
self.model_field = model_field
- kwargs['source'] = '*'
+ # The `max_length` option is supported by Django's base `Field` class,
+ # so we'd better support it here.
+ max_length = kwargs.pop('max_length', None)
super(ModelField, self).__init__(**kwargs)
+ if max_length is not None:
+ message = self.error_messages['max_length'].format(max_length=max_length)
+ self.validators.append(MaxLengthValidator(max_length, message=message))
def to_internal_value(self, data):
rel = getattr(self.model_field, 'rel', None)
@@ -822,6 +1211,11 @@ class ModelField(Field):
return rel.to._meta.get_field(rel.field_name).to_python(data)
return self.model_field.to_python(data)
+ def get_attribute(self, obj):
+ # We pass the object instance onto `to_representation`,
+ # not just the field attribute.
+ return obj
+
def to_representation(self, obj):
value = self.model_field._get_val_from_obj(obj)
if is_protected_type(value):
diff --git a/rest_framework/filters.py b/rest_framework/filters.py
index c580f935..d188a2d1 100644
--- a/rest_framework/filters.py
+++ b/rest_framework/filters.py
@@ -3,6 +3,7 @@ Provides generic filtering backends that can be used to filter the results
returned by list views.
"""
from __future__ import unicode_literals
+
from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils import six
@@ -64,7 +65,7 @@ class DjangoFilterBackend(BaseFilterBackend):
filter_class = self.get_filter_class(view, queryset)
if filter_class:
- return filter_class(request.QUERY_PARAMS, queryset=queryset).qs
+ return filter_class(request.query_params, queryset=queryset).qs
return queryset
@@ -78,7 +79,7 @@ class SearchFilter(BaseFilterBackend):
Search terms are set by a ?search=... query parameter,
and may be comma and/or whitespace delimited.
"""
- params = request.QUERY_PARAMS.get(self.search_param, '')
+ params = request.query_params.get(self.search_param, '')
return params.replace(',', ' ').split()
def construct_search(self, field_name):
@@ -97,7 +98,7 @@ class SearchFilter(BaseFilterBackend):
if not search_fields:
return queryset
- orm_lookups = [self.construct_search(str(search_field))
+ orm_lookups = [self.construct_search(six.text_type(search_field))
for search_field in search_fields]
for search_term in self.get_search_terms(request):
@@ -121,7 +122,7 @@ class OrderingFilter(BaseFilterBackend):
the `ordering_param` value on the OrderingFilter or by
specifying an `ORDERING_PARAM` value in the API settings.
"""
- params = request.QUERY_PARAMS.get(self.ordering_param)
+ params = request.query_params.get(self.ordering_param)
if params:
return [param.strip() for param in params.split(',')]
@@ -147,7 +148,7 @@ class OrderingFilter(BaseFilterBackend):
if not getattr(field, 'write_only', False)
]
elif valid_fields == '__all__':
- # View explictly allows filtering on any model field
+ # View explicitly allows filtering on any model field
valid_fields = [field.name for field in queryset.model._meta.fields]
valid_fields += queryset.query.aggregates.keys()
diff --git a/rest_framework/generics.py b/rest_framework/generics.py
index eb6b64ef..3d6cf168 100644
--- a/rest_framework/generics.py
+++ b/rest_framework/generics.py
@@ -3,14 +3,13 @@ Generic views that provide commonly needed behaviour.
"""
from __future__ import unicode_literals
-from django.db.models.query import QuerySet
-from django.core.exceptions import PermissionDenied
from django.core.paginator import Paginator, InvalidPage
+from django.db.models.query import QuerySet
from django.http import Http404
from django.shortcuts import get_object_or_404 as _get_object_or_404
+from django.utils import six
from django.utils.translation import ugettext as _
-from rest_framework import views, mixins, exceptions
-from rest_framework.request import clone_request
+from rest_framework import views, mixins
from rest_framework.settings import api_settings
@@ -114,7 +113,7 @@ class GenericAPIView(views.APIView):
paginator = self.paginator_class(queryset, page_size)
page_kwarg = self.kwargs.get(self.page_kwarg)
- page_query_param = self.request.QUERY_PARAMS.get(self.page_kwarg)
+ page_query_param = self.request.query_params.get(self.page_kwarg)
page = page_kwarg or page_query_param or 1
try:
page_number = paginator.validate_number(page)
@@ -129,7 +128,7 @@ class GenericAPIView(views.APIView):
error_format = _('Invalid page (%(page_number)s): %(message)s')
raise Http404(error_format % {
'page_number': page_number,
- 'message': str(exc)
+ 'message': six.text_type(exc)
})
return page
@@ -168,7 +167,7 @@ class GenericAPIView(views.APIView):
if self.paginate_by_param:
try:
return strict_positive_int(
- self.request.QUERY_PARAMS[self.paginate_by_param],
+ self.request.query_params[self.paginate_by_param],
cutoff=self.max_paginate_by
)
except (KeyError, ValueError):
@@ -249,53 +248,6 @@ class GenericAPIView(views.APIView):
return obj
- # The following are placeholder methods,
- # and are intended to be overridden.
- #
- # The are not called by GenericAPIView directly,
- # but are used by the mixin methods.
- def metadata(self, request):
- """
- Return a dictionary of metadata about the view.
- Used to return responses for OPTIONS requests.
-
- We override the default behavior, and add some extra information
- about the required request body for POST and PUT operations.
- """
- ret = super(GenericAPIView, self).metadata(request)
-
- actions = {}
- for method in ('PUT', 'POST'):
- if method not in self.allowed_methods:
- continue
-
- cloned_request = clone_request(request, method)
- try:
- # Test global permissions
- self.check_permissions(cloned_request)
- # Test object permissions
- if method == 'PUT':
- try:
- self.get_object()
- except Http404:
- # Http404 should be acceptable and the serializer
- # metadata should be populated. Except this so the
- # outer "else" clause of the try-except-else block
- # will be executed.
- pass
- except (exceptions.APIException, PermissionDenied):
- pass
- else:
- # If user has appropriate permissions for the view, include
- # appropriate metadata about the fields that should be supplied.
- serializer = self.get_serializer()
- actions[method] = serializer.metadata()
-
- if actions:
- ret['actions'] = actions
-
- return ret
-
# Concrete view classes that provide method handlers
# by composing the mixin classes with the base view.
diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py
new file mode 100644
index 00000000..de829d00
--- /dev/null
+++ b/rest_framework/metadata.py
@@ -0,0 +1,131 @@
+"""
+The metadata API is used to allow cusomization of how `OPTIONS` requests
+are handled. We currently provide a single default implementation that returns
+some fairly ad-hoc information about the view.
+
+Future implementations might use JSON schema or other definations in order
+to return this information in a more standardized way.
+"""
+from __future__ import unicode_literals
+
+from django.core.exceptions import PermissionDenied
+from django.http import Http404
+from rest_framework import exceptions, serializers
+from rest_framework.compat import force_text, OrderedDict
+from rest_framework.request import clone_request
+from rest_framework.utils.field_mapping import ClassLookupDict
+
+
+class BaseMetadata(object):
+ def determine_metadata(self, request, view):
+ """
+ Return a dictionary of metadata about the view.
+ Used to return responses for OPTIONS requests.
+ """
+ raise NotImplementedError(".determine_metadata() must be overridden.")
+
+
+class SimpleMetadata(BaseMetadata):
+ """
+ This is the default metadata implementation.
+ It returns an ad-hoc set of information about the view.
+ There are not any formalized standards for `OPTIONS` responses
+ for us to base this on.
+ """
+ label_lookup = ClassLookupDict({
+ serializers.Field: 'field',
+ serializers.BooleanField: 'boolean',
+ serializers.CharField: 'string',
+ serializers.URLField: 'url',
+ serializers.EmailField: 'email',
+ serializers.RegexField: 'regex',
+ serializers.SlugField: 'slug',
+ serializers.IntegerField: 'integer',
+ serializers.FloatField: 'float',
+ serializers.DecimalField: 'decimal',
+ serializers.DateField: 'date',
+ serializers.DateTimeField: 'datetime',
+ serializers.TimeField: 'time',
+ serializers.ChoiceField: 'choice',
+ serializers.MultipleChoiceField: 'multiple choice',
+ serializers.FileField: 'file upload',
+ serializers.ImageField: 'image upload',
+ })
+
+ def determine_metadata(self, request, view):
+ metadata = OrderedDict()
+ metadata['name'] = view.get_view_name()
+ metadata['description'] = view.get_view_description()
+ metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes]
+ metadata['parses'] = [parser.media_type for parser in view.parser_classes]
+ if hasattr(view, 'get_serializer'):
+ actions = self.determine_actions(request, view)
+ if actions:
+ metadata['actions'] = actions
+ return metadata
+
+ def determine_actions(self, request, view):
+ """
+ For generic class based views we return information about
+ the fields that are accepted for 'PUT' and 'POST' methods.
+ """
+ actions = {}
+ for method in set(['PUT', 'POST']) & set(view.allowed_methods):
+ view.request = clone_request(request, method)
+ try:
+ # Test global permissions
+ if hasattr(view, 'check_permissions'):
+ view.check_permissions(view.request)
+ # Test object permissions
+ if method == 'PUT' and hasattr(view, 'get_object'):
+ view.get_object()
+ except (exceptions.APIException, PermissionDenied, Http404):
+ pass
+ else:
+ # If user has appropriate permissions for the view, include
+ # appropriate metadata about the fields that should be supplied.
+ serializer = view.get_serializer()
+ actions[method] = self.get_serializer_info(serializer)
+ finally:
+ view.request = request
+
+ return actions
+
+ def get_serializer_info(self, serializer):
+ """
+ Given an instance of a serializer, return a dictionary of metadata
+ about its fields.
+ """
+ if hasattr(serializer, 'child'):
+ # If this is a `ListSerializer` then we want to examine the
+ # underlying child serializer instance instead.
+ serializer = serializer.child
+ return OrderedDict([
+ (field_name, self.get_field_info(field))
+ for field_name, field in serializer.fields.items()
+ ])
+
+ def get_field_info(self, field):
+ """
+ Given an instance of a serializer field, return a dictionary
+ of metadata about it.
+ """
+ field_info = OrderedDict()
+ field_info['type'] = self.label_lookup[field]
+ field_info['required'] = getattr(field, 'required', False)
+
+ for attr in ['read_only', 'label', 'help_text', 'min_length', 'max_length']:
+ value = getattr(field, attr, None)
+ if value is not None and value != '':
+ field_info[attr] = force_text(value, strings_only=True)
+
+ if hasattr(field, 'choices'):
+ field_info['choices'] = [
+ {
+ 'value': choice_value,
+ 'display_name': force_text(choice_name, strings_only=True)
+ }
+ for choice_value, choice_name in field.choices.items()
+ ]
+
+ return field_info
diff --git a/rest_framework/mixins.py b/rest_framework/mixins.py
index 14a6b44b..2074a107 100644
--- a/rest_framework/mixins.py
+++ b/rest_framework/mixins.py
@@ -6,10 +6,8 @@ which allows mixin classes to be composed in interesting ways.
"""
from __future__ import unicode_literals
-from django.http import Http404
from rest_framework import status
from rest_framework.response import Response
-from rest_framework.request import clone_request
from rest_framework.settings import api_settings
@@ -18,12 +16,15 @@ class CreateModelMixin(object):
Create a model instance.
"""
def create(self, request, *args, **kwargs):
- serializer = self.get_serializer(data=request.DATA)
+ serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
- serializer.save()
+ self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
+ def perform_create(self, serializer):
+ serializer.save()
+
def get_success_headers(self, data):
try:
return {'Location': data[api_settings.URL_FIELD_NAME]}
@@ -62,11 +63,14 @@ class UpdateModelMixin(object):
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
- serializer = self.get_serializer(instance, data=request.DATA, partial=partial)
+ serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
- serializer.save()
+ self.perform_update(serializer)
return Response(serializer.data)
+ def perform_update(self, serializer):
+ serializer.save()
+
def partial_update(self, request, *args, **kwargs):
kwargs['partial'] = True
return self.update(request, *args, **kwargs)
@@ -78,51 +82,8 @@ class DestroyModelMixin(object):
"""
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
- instance.delete()
+ self.perform_destroy(instance)
return Response(status=status.HTTP_204_NO_CONTENT)
-
-# The AllowPUTAsCreateMixin was previously the default behaviour
-# for PUT requests. This has now been removed and must be *explictly*
-# included if it is the behavior that you want.
-# For more info see: ...
-
-class AllowPUTAsCreateMixin(object):
- """
- The following mixin class may be used in order to support PUT-as-create
- behavior for incoming requests.
- """
- def update(self, request, *args, **kwargs):
- partial = kwargs.pop('partial', False)
- instance = self.get_object_or_none()
- serializer = self.get_serializer(instance, data=request.DATA, partial=partial)
- serializer.is_valid(raise_exception=True)
-
- if instance is None:
- lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field
- lookup_value = self.kwargs[lookup_url_kwarg]
- extras = {self.lookup_field: lookup_value}
- serializer.save(extras=extras)
- return Response(serializer.data, status=status.HTTP_201_CREATED)
-
- serializer.save()
- return Response(serializer.data)
-
- def partial_update(self, request, *args, **kwargs):
- kwargs['partial'] = True
- return self.update(request, *args, **kwargs)
-
- def get_object_or_none(self):
- try:
- return self.get_object()
- except Http404:
- if self.request.method == 'PUT':
- # For PUT-as-create operation, we need to ensure that we have
- # relevant permissions, as if this was a POST request. This
- # will either raise a PermissionDenied exception, or simply
- # return None.
- self.check_permissions(clone_request(self.request, 'POST'))
- else:
- # PATCH requests where the object does not exist should still
- # return a 404 response.
- raise
+ def perform_destroy(self, instance):
+ instance.delete()
diff --git a/rest_framework/negotiation.py b/rest_framework/negotiation.py
index ca7b5397..1838130a 100644
--- a/rest_framework/negotiation.py
+++ b/rest_framework/negotiation.py
@@ -38,7 +38,7 @@ class DefaultContentNegotiation(BaseContentNegotiation):
"""
# Allow URL style format override. eg. "?format=json
format_query_param = self.settings.URL_FORMAT_OVERRIDE
- format = format_suffix or request.QUERY_PARAMS.get(format_query_param)
+ format = format_suffix or request.query_params.get(format_query_param)
if format:
renderers = self.filter_renderers(renderers, format)
@@ -87,5 +87,5 @@ class DefaultContentNegotiation(BaseContentNegotiation):
Allows URL style accept override. eg. "?accept=application/json"
"""
header = request.META.get('HTTP_ACCEPT', '*/*')
- header = request.QUERY_PARAMS.get(self.settings.URL_ACCEPT_OVERRIDE, header)
+ header = request.query_params.get(self.settings.URL_ACCEPT_OVERRIDE, header)
return [token.strip() for token in header.split(',')]
diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py
index c5a9270a..fb451285 100644
--- a/rest_framework/pagination.py
+++ b/rest_framework/pagination.py
@@ -72,7 +72,6 @@ class BasePaginationSerializer(serializers.Serializer):
child=object_serializer(),
source='object_list'
)
- self.fields[results_field].bind(results_field, self, self)
class PaginationSerializer(BasePaginationSerializer):
diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py
index fa02ecf1..ccb82f03 100644
--- a/rest_framework/parsers.py
+++ b/rest_framework/parsers.py
@@ -5,6 +5,7 @@ They give us a generic way of being able to handle various media types
on the request, such as form content or json encoded data.
"""
from __future__ import unicode_literals
+
from django.conf import settings
from django.core.files.uploadhandler import StopFutureHandlers
from django.http import QueryDict
@@ -132,7 +133,7 @@ class MultiPartParser(BaseParser):
data, files = parser.parse()
return DataAndFiles(data, files)
except MultiPartParserError as exc:
- raise ParseError('Multipart form parse error - %s' % str(exc))
+ raise ParseError('Multipart form parse error - %s' % six.text_type(exc))
class XMLParser(BaseParser):
diff --git a/rest_framework/relations.py b/rest_framework/relations.py
index 5aa1f8bd..d1ea497a 100644
--- a/rest_framework/relations.py
+++ b/rest_framework/relations.py
@@ -1,12 +1,32 @@
from rest_framework.compat import smart_text, urlparse
-from rest_framework.fields import Field
+from rest_framework.fields import get_attribute, empty, Field
from rest_framework.reverse import reverse
+from rest_framework.utils import html
from django.core.exceptions import ObjectDoesNotExist, ImproperlyConfigured
from django.core.urlresolvers import resolve, get_script_prefix, NoReverseMatch, Resolver404
from django.db.models.query import QuerySet
+from django.utils import six
from django.utils.translation import ugettext_lazy as _
+class PKOnlyObject(object):
+ """
+ This is a mock object, used for when we only need the pk of the object
+ instance, but still want to return an object with a .pk attribute,
+ in order to keep the same interface as a regular model instance.
+ """
+ def __init__(self, pk):
+ self.pk = pk
+
+
+# We assume that 'validators' are intended for the child serializer,
+# rather than the parent serializer.
+MANY_RELATION_KWARGS = (
+ 'read_only', 'write_only', 'required', 'default', 'initial', 'source',
+ 'label', 'help_text', 'style', 'error_messages'
+)
+
+
class RelatedField(Field):
def __init__(self, **kwargs):
self.queryset = kwargs.pop('queryset', None)
@@ -22,14 +42,40 @@ class RelatedField(Field):
def __new__(cls, *args, **kwargs):
# We override this method in order to automagically create
- # `ManyRelation` classes instead when `many=True` is set.
+ # `ManyRelatedField` classes instead when `many=True` is set.
if kwargs.pop('many', False):
- return ManyRelation(
- child_relation=cls(*args, **kwargs),
- read_only=kwargs.get('read_only', False)
- )
+ return cls.many_init(*args, **kwargs)
return super(RelatedField, cls).__new__(cls, *args, **kwargs)
+ @classmethod
+ def many_init(cls, *args, **kwargs):
+ """
+ This method handles creating a parent `ManyRelatedField` instance
+ when the `many=True` keyword argument is passed.
+
+ Typically you won't need to override this method.
+
+ Note that we're over-cautious in passing most arguments to both parent
+ and child classes in order to try to cover the general case. If you're
+ overriding this method you'll probably want something much simpler, eg:
+
+ @classmethod
+ def many_init(cls, *args, **kwargs):
+ kwargs['child'] = cls()
+ return CustomManyRelatedField(*args, **kwargs)
+ """
+ list_kwargs = {'child_relation': cls(*args, **kwargs)}
+ for key in kwargs.keys():
+ if key in MANY_RELATION_KWARGS:
+ list_kwargs[key] = kwargs[key]
+ return ManyRelatedField(**list_kwargs)
+
+ def run_validation(self, data=empty):
+ # We force empty strings to None values for relational fields.
+ if data == '':
+ data = None
+ return super(RelatedField, self).run_validation(data)
+
def get_queryset(self):
queryset = self.queryset
if isinstance(queryset, QuerySet):
@@ -37,8 +83,22 @@ class RelatedField(Field):
queryset = queryset.all()
return queryset
+ def get_iterable(self, instance, source_attrs):
+ relationship = get_attribute(instance, source_attrs)
+ return relationship.all() if (hasattr(relationship, 'all')) else relationship
+
+ @property
+ def choices(self):
+ return dict([
+ (
+ str(self.to_representation(item)),
+ str(item)
+ )
+ for item in self.queryset.all()
+ ])
+
-class StringRelatedField(Field):
+class StringRelatedField(RelatedField):
"""
A read only field that represents its targets using their
plain string representation.
@@ -49,7 +109,7 @@ class StringRelatedField(Field):
super(StringRelatedField, self).__init__(**kwargs)
def to_representation(self, value):
- return str(value)
+ return six.text_type(value)
class PrimaryKeyRelatedField(RelatedField):
@@ -67,6 +127,32 @@ class PrimaryKeyRelatedField(RelatedField):
except (TypeError, ValueError):
self.fail('incorrect_type', data_type=type(data).__name__)
+ def get_attribute(self, instance):
+ # We customize `get_attribute` here for performance reasons.
+ # For relationships the instance will already have the pk of
+ # the related object. We return this directly instead of returning the
+ # object itself, which would require a database lookup.
+ try:
+ instance = get_attribute(instance, self.source_attrs[:-1])
+ return PKOnlyObject(pk=instance.serializable_value(self.source_attrs[-1]))
+ except AttributeError:
+ return get_attribute(instance, self.source_attrs)
+
+ def get_iterable(self, instance, source_attrs):
+ # For consistency with `get_attribute` we're using `serializable_value()`
+ # here. Typically there won't be any difference, but some custom field
+ # types might return a non-primative value for the pk otherwise.
+ #
+ # We could try to get smart with `values_list('pk', flat=True)`, which
+ # would be better in some case, but would actually end up with *more*
+ # queries if the developer is using `prefetch_related` across the
+ # relationship.
+ relationship = super(PrimaryKeyRelatedField, self).get_iterable(instance, source_attrs)
+ return [
+ PKOnlyObject(pk=item.serializable_value('pk'))
+ for item in relationship
+ ]
+
def to_representation(self, value):
return value.pk
@@ -89,9 +175,9 @@ class HyperlinkedRelatedField(RelatedField):
self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field)
self.format = kwargs.pop('format', None)
- # We include these simply for dependancy injection in tests.
+ # We include these simply for dependency injection in tests.
# We can't add them as class attributes or they would expect an
- # implict `self` argument to be passed.
+ # implicit `self` argument to be passed.
self.reverse = reverse
self.resolve = resolve
@@ -227,26 +313,33 @@ class SlugRelatedField(RelatedField):
return getattr(obj, self.slug_field)
-class ManyRelation(Field):
+class ManyRelatedField(Field):
"""
Relationships with `many=True` transparently get coerced into instead being
- a ManyRelation with a child relationship.
+ a ManyRelatedField with a child relationship.
- The `ManyRelation` class is responsible for handling iterating through
+ The `ManyRelatedField` class is responsible for handling iterating through
the values and passing each one to the child relationship.
- You shouldn't need to be using this class directly yourself.
+ This class is treated as private API.
+ You shouldn't generally need to be using this class directly yourself,
+ and should instead simply set 'many=True' on the relationship.
"""
+ initial = []
+ default_empty_html = []
def __init__(self, child_relation=None, *args, **kwargs):
self.child_relation = child_relation
assert child_relation is not None, '`child_relation` is a required argument.'
- super(ManyRelation, self).__init__(*args, **kwargs)
+ super(ManyRelatedField, self).__init__(*args, **kwargs)
+ self.child_relation.bind(field_name='', parent=self)
- def bind(self, field_name, parent, root):
- # ManyRelation needs to provide the current context to the child relation.
- super(ManyRelation, self).bind(field_name, parent, root)
- self.child_relation.bind(field_name, parent, root)
+ def get_value(self, dictionary):
+ # We override the default field access in order to support
+ # lists in HTML forms.
+ if html.is_html_input(dictionary):
+ return dictionary.getlist(self.field_name)
+ return dictionary.get(self.field_name, empty)
def to_internal_value(self, data):
return [
@@ -254,8 +347,27 @@ class ManyRelation(Field):
for item in data
]
- def to_representation(self, obj):
+ def get_attribute(self, instance):
+ return self.child_relation.get_iterable(instance, self.source_attrs)
+
+ def to_representation(self, iterable):
return [
self.child_relation.to_representation(value)
- for value in obj.all()
+ for value in iterable
]
+
+ @property
+ def choices(self):
+ queryset = self.child_relation.queryset
+ iterable = queryset.all() if (hasattr(queryset, 'all')) else queryset
+ items_and_representations = [
+ (item, self.child_relation.to_representation(item))
+ for item in iterable
+ ]
+ return dict([
+ (
+ str(item_representation),
+ str(item) + ' - ' + str(item_representation)
+ )
+ for item, item_representation in items_and_representations
+ ])
diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py
index 3bf03e62..e87d16d0 100644
--- a/rest_framework/renderers.py
+++ b/rest_framework/renderers.py
@@ -13,17 +13,20 @@ import django
from django import forms
from django.core.exceptions import ImproperlyConfigured
from django.http.multipartparser import parse_header
-from django.template import RequestContext, loader, Template
+from django.template import Context, RequestContext, loader, Template
from django.test.client import encode_multipart
from django.utils import six
from django.utils.xmlutils import SimplerXMLGenerator
-from rest_framework.compat import StringIO, smart_text, yaml
+from rest_framework import exceptions, serializers, status, VERSION
+from rest_framework.compat import (
+ SHORT_SEPARATORS, LONG_SEPARATORS, StringIO, smart_text, yaml
+)
from rest_framework.exceptions import ParseError
from rest_framework.settings import api_settings
from rest_framework.request import is_form_media_type, override_method
from rest_framework.utils import encoders
from rest_framework.utils.breadcrumbs import get_breadcrumbs
-from rest_framework import exceptions, status, VERSION
+from rest_framework.utils.field_mapping import ClassLookupDict
def zero_as_none(value):
@@ -86,7 +89,7 @@ class JSONRenderer(BaseRenderer):
renderer_context = renderer_context or {}
indent = self.get_indent(accepted_media_type, renderer_context)
- separators = (',', ':') if (indent is None and self.compact) else (', ', ': ')
+ separators = SHORT_SEPARATORS if (indent is None and self.compact) else LONG_SEPARATORS
ret = json.dumps(
data, cls=self.encoder_class,
@@ -120,7 +123,7 @@ class JSONPRenderer(JSONRenderer):
Determine the name of the callback to wrap around the json output.
"""
request = renderer_context.get('request', None)
- params = request and request.QUERY_PARAMS or {}
+ params = request and request.query_params or {}
return params.get(self.callback_parameter, self.default_callback)
def render(self, data, accepted_media_type=None, renderer_context=None):
@@ -338,18 +341,109 @@ class HTMLFormRenderer(BaseRenderer):
"""
media_type = 'text/html'
format = 'form'
- template = 'rest_framework/form.html'
charset = 'utf-8'
+ template_pack = 'rest_framework/horizontal/'
+ base_template = 'form.html'
+
+ default_style = ClassLookupDict({
+ serializers.Field: {
+ 'base_template': 'input.html',
+ 'input_type': 'text'
+ },
+ serializers.EmailField: {
+ 'base_template': 'input.html',
+ 'input_type': 'email'
+ },
+ serializers.URLField: {
+ 'base_template': 'input.html',
+ 'input_type': 'url'
+ },
+ serializers.IntegerField: {
+ 'base_template': 'input.html',
+ 'input_type': 'number'
+ },
+ serializers.DateTimeField: {
+ 'base_template': 'input.html',
+ 'input_type': 'datetime-local'
+ },
+ serializers.DateField: {
+ 'base_template': 'input.html',
+ 'input_type': 'date'
+ },
+ serializers.TimeField: {
+ 'base_template': 'input.html',
+ 'input_type': 'time'
+ },
+ serializers.BooleanField: {
+ 'base_template': 'checkbox.html'
+ },
+ serializers.ChoiceField: {
+ 'base_template': 'select.html', # Also valid: 'radio.html'
+ },
+ serializers.MultipleChoiceField: {
+ 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html'
+ },
+ serializers.RelatedField: {
+ 'base_template': 'select.html', # Also valid: 'radio.html'
+ },
+ serializers.ManyRelatedField: {
+ 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html'
+ },
+ serializers.Serializer: {
+ 'base_template': 'fieldset.html'
+ },
+ serializers.ListSerializer: {
+ 'base_template': 'list_fieldset.html'
+ }
+ })
+
+ def render_field(self, field, parent_style):
+ style = dict(self.default_style[field])
+ style.update(field.style)
+ if 'template_pack' not in style:
+ style['template_pack'] = parent_style.get('template_pack', self.template_pack)
+ style['renderer'] = self
+
+ if style.get('input_type') == 'datetime-local' and isinstance(field.value, six.text_type):
+ field.value = field.value.rstrip('Z')
+
+ if 'template' in style:
+ template_name = style['template']
+ else:
+ template_name = style['template_pack'].strip('/') + '/' + style['base_template']
+
+ template = loader.get_template(template_name)
+ context = Context({'field': field, 'style': style})
+ return template.render(context)
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Render serializer data and return an HTML form, as a string.
"""
+ form = data.serializer
+ meta = getattr(form, 'Meta', None)
+ style = getattr(meta, 'style', {})
+ if 'template_pack' not in style:
+ style['template_pack'] = self.template_pack
+ if 'base_template' not in style:
+ style['base_template'] = self.base_template
+ style['renderer'] = self
+
+ # This API needs to be finessed and finalized for 3.1
+ if 'template' in renderer_context:
+ template_name = renderer_context['template']
+ elif 'template' in style:
+ template_name = style['template']
+ else:
+ template_name = style['template_pack'].strip('/') + '/' + style['base_template']
+
renderer_context = renderer_context or {}
request = renderer_context['request']
-
- template = loader.get_template(self.template)
- context = RequestContext(request, {'form': data})
+ template = loader.get_template(template_name)
+ context = RequestContext(request, {
+ 'form': form,
+ 'style': style
+ })
return template.render(context)
@@ -417,27 +511,35 @@ class BrowsableAPIRenderer(BaseRenderer):
return False # Doesn't have permissions
return True
- def get_rendered_html_form(self, view, method, request):
+ def get_rendered_html_form(self, data, view, method, request):
"""
Return a string representing a rendered HTML form, possibly bound to
either the input or output data.
In the absence of the View having an associated form then return None.
"""
- if request.method == method:
+ # See issue #2089 for refactoring this.
+ serializer = getattr(data, 'serializer', None)
+ if serializer and not getattr(serializer, 'many', False):
+ instance = getattr(serializer, 'instance', None)
+ else:
+ instance = None
+
+ # If this is valid serializer data, and the form is for the same
+ # HTTP method as was used in the request then use the existing
+ # serializer instance, rather than dynamically creating a new one.
+ if request.method == method and serializer is not None:
try:
- data = request.DATA
- # files = request.FILES
+ data = request.data
except ParseError:
data = None
- # files = None
+ existing_serializer = serializer
else:
data = None
- # files = None
+ existing_serializer = None
with override_method(view, request, method) as request:
- obj = getattr(view, 'object', None)
- if not self.show_form_for_method(view, method, request, obj):
+ if not self.show_form_for_method(view, method, request, instance):
return
if method in ('DELETE', 'OPTIONS'):
@@ -449,19 +551,38 @@ class BrowsableAPIRenderer(BaseRenderer):
):
return
- serializer = view.get_serializer(instance=obj, data=data)
- serializer.is_valid()
- data = serializer.data
-
+ if existing_serializer is not None:
+ serializer = existing_serializer
+ else:
+ if method in ('PUT', 'PATCH'):
+ serializer = view.get_serializer(instance=instance, data=data)
+ else:
+ serializer = view.get_serializer(data=data)
+ if data is not None:
+ serializer.is_valid()
form_renderer = self.form_renderer_class()
- return form_renderer.render(data, self.accepted_media_type, self.renderer_context)
-
- def get_raw_data_form(self, view, method, request):
+ return form_renderer.render(
+ serializer.data,
+ self.accepted_media_type,
+ dict(
+ list(self.renderer_context.items()) +
+ [('template', 'rest_framework/api_form.html')]
+ )
+ )
+
+ def get_raw_data_form(self, data, view, method, request):
"""
Returns a form that allows for arbitrary content types to be tunneled
via standard HTML forms.
(Which are typically application/x-www-form-urlencoded)
"""
+ # See issue #2089 for refactoring this.
+ serializer = getattr(data, 'serializer', None)
+ if serializer and not getattr(serializer, 'many', False):
+ instance = getattr(serializer, 'instance', None)
+ else:
+ instance = None
+
with override_method(view, request, method) as request:
# If we're not using content overloading there's no point in
# supplying a generic form, as the view won't treat the form's
@@ -471,8 +592,7 @@ class BrowsableAPIRenderer(BaseRenderer):
return None
# Check permissions
- obj = getattr(view, 'object', None)
- if not self.show_form_for_method(view, method, request, obj):
+ if not self.show_form_for_method(view, method, request, instance):
return
# If possible, serialize the initial content for the generic form
@@ -482,12 +602,10 @@ class BrowsableAPIRenderer(BaseRenderer):
# View has a serializer defined and parser class has a
# corresponding renderer that can be used to render the data.
- # Get a read-only version of the serializer
- serializer = view.get_serializer(instance=obj)
- if obj is None:
- for name, field in serializer.fields.items():
- if getattr(field, 'read_only', None):
- del serializer.fields[name]
+ if method in ('PUT', 'PATCH'):
+ serializer = view.get_serializer(instance=instance)
+ else:
+ serializer = view.get_serializer()
# Render the raw data content
renderer = renderer_class()
@@ -544,9 +662,9 @@ class BrowsableAPIRenderer(BaseRenderer):
renderer = self.get_default_renderer(view)
- raw_data_post_form = self.get_raw_data_form(view, 'POST', request)
- raw_data_put_form = self.get_raw_data_form(view, 'PUT', request)
- raw_data_patch_form = self.get_raw_data_form(view, 'PATCH', request)
+ raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request)
+ raw_data_put_form = self.get_raw_data_form(data, view, 'PUT', request)
+ raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request)
raw_data_put_or_patch_form = raw_data_put_form or raw_data_patch_form
response_headers = dict(response.items())
@@ -570,10 +688,10 @@ class BrowsableAPIRenderer(BaseRenderer):
'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes],
'response_headers': response_headers,
- # 'put_form': self.get_rendered_html_form(view, 'PUT', request),
- # 'post_form': self.get_rendered_html_form(view, 'POST', request),
- # 'delete_form': self.get_rendered_html_form(view, 'DELETE', request),
- # 'options_form': self.get_rendered_html_form(view, 'OPTIONS', request),
+ 'put_form': self.get_rendered_html_form(data, view, 'PUT', request),
+ 'post_form': self.get_rendered_html_form(data, view, 'POST', request),
+ 'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request),
+ 'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request),
'raw_data_put_form': raw_data_put_form,
'raw_data_post_form': raw_data_post_form,
diff --git a/rest_framework/request.py b/rest_framework/request.py
index 27532661..d7e74674 100644
--- a/rest_framework/request.py
+++ b/rest_framework/request.py
@@ -4,7 +4,7 @@ The Request class is used as a wrapper around the standard request object.
The wrapped request then offers a richer API, in particular :
- content automatically parsed according to `Content-Type` header,
- and available as `request.DATA`
+ and available as `request.data`
- full support of PUT method, including support for file uploads
- form overloading of HTTP method, content type and content
"""
@@ -13,10 +13,12 @@ from django.conf import settings
from django.http import QueryDict
from django.http.multipartparser import parse_header
from django.utils.datastructures import MultiValueDict
+from django.utils.datastructures import MergeDict as DjangoMergeDict
from rest_framework import HTTP_HEADER_ENCODING
from rest_framework import exceptions
from rest_framework.compat import BytesIO
from rest_framework.settings import api_settings
+import warnings
def is_form_media_type(media_type):
@@ -58,6 +60,15 @@ class override_method(object):
self.view.action = self.action
+class MergeDict(DjangoMergeDict, dict):
+ """
+ Using this as a workaround until the parsers API is properly
+ addressed in 3.1.
+ """
+ def __init__(self, *dicts):
+ self.dicts = dicts
+
+
class Empty(object):
"""
Placeholder for unset attributes.
@@ -82,6 +93,7 @@ def clone_request(request, method):
parser_context=request.parser_context)
ret._data = request._data
ret._files = request._files
+ ret._full_data = request._full_data
ret._content_type = request._content_type
ret._stream = request._stream
ret._method = method
@@ -91,6 +103,10 @@ def clone_request(request, method):
ret._auth = request._auth
if hasattr(request, '_authenticator'):
ret._authenticator = request._authenticator
+ if hasattr(request, 'accepted_renderer'):
+ ret.accepted_renderer = request.accepted_renderer
+ if hasattr(request, 'accepted_media_type'):
+ ret.accepted_media_type = request.accepted_media_type
return ret
@@ -133,6 +149,7 @@ class Request(object):
self.parser_context = parser_context
self._data = Empty
self._files = Empty
+ self._full_data = Empty
self._method = Empty
self._content_type = Empty
self._stream = Empty
@@ -186,13 +203,31 @@ class Request(object):
return self._stream
@property
- def QUERY_PARAMS(self):
+ def query_params(self):
"""
More semantically correct name for request.GET.
"""
return self._request.GET
@property
+ def QUERY_PARAMS(self):
+ """
+ Synonym for `.query_params`, for backwards compatibility.
+ """
+ warnings.warn(
+ "`request.QUERY_PARAMS` is pending deprecation. Use `request.query_params` instead.",
+ PendingDeprecationWarning,
+ stacklevel=1
+ )
+ return self._request.GET
+
+ @property
+ def data(self):
+ if not _hasattr(self, '_full_data'):
+ self._load_data_and_files()
+ return self._full_data
+
+ @property
def DATA(self):
"""
Parses the request body and returns the data.
@@ -200,6 +235,11 @@ class Request(object):
Similar to usual behaviour of `request.POST`, except that it handles
arbitrary parsers, and also works on methods other than POST (eg PUT).
"""
+ warnings.warn(
+ "`request.DATA` is pending deprecation. Use `request.data` instead.",
+ PendingDeprecationWarning,
+ stacklevel=1
+ )
if not _hasattr(self, '_data'):
self._load_data_and_files()
return self._data
@@ -212,6 +252,11 @@ class Request(object):
Similar to usual behaviour of `request.FILES`, except that it handles
arbitrary parsers, and also works on methods other than POST (eg PUT).
"""
+ warnings.warn(
+ "`request.FILES` is pending deprecation. Use `request.data` instead.",
+ PendingDeprecationWarning,
+ stacklevel=1
+ )
if not _hasattr(self, '_files'):
self._load_data_and_files()
return self._files
@@ -265,13 +310,17 @@ class Request(object):
def _load_data_and_files(self):
"""
- Parses the request content into self.DATA and self.FILES.
+ Parses the request content into `self.data`.
"""
if not _hasattr(self, '_content_type'):
self._load_method_and_content_type()
if not _hasattr(self, '_data'):
self._data, self._files = self._parse()
+ if self._files:
+ self._full_data = MergeDict(self._data, self._files)
+ else:
+ self._full_data = self._data
def _load_method_and_content_type(self):
"""
@@ -333,6 +382,7 @@ class Request(object):
# At this point we're committed to parsing the request as form data.
self._data = self._request.POST
self._files = self._request.FILES
+ self._full_data = MergeDict(self._data, self._files)
# Method overloading - change the method and remove the param from the content.
if (
@@ -350,7 +400,7 @@ class Request(object):
):
self._content_type = self._data[self._CONTENTTYPE_PARAM]
self._stream = BytesIO(self._data[self._CONTENT_PARAM].encode(self.parser_context['encoding']))
- self._data, self._files = (Empty, Empty)
+ self._data, self._files, self._full_data = (Empty, Empty, Empty)
def _parse(self):
"""
@@ -380,6 +430,7 @@ class Request(object):
# logging the request or similar.
self._data = QueryDict('', encoding=self._request._encoding)
self._files = MultiValueDict()
+ self._full_data = self._data
raise
# Parser classes may return the raw data, or a
diff --git a/rest_framework/response.py b/rest_framework/response.py
index 0a7d313f..d6ca1aad 100644
--- a/rest_framework/response.py
+++ b/rest_framework/response.py
@@ -5,7 +5,6 @@ it is initialized with unrendered data, instead of a pre-rendered string.
The appropriate renderer is called during Django's template response rendering.
"""
from __future__ import unicode_literals
-import django
from django.core.handlers.wsgi import STATUS_CODE_TEXT
from django.template.response import SimpleTemplateResponse
from django.utils import six
@@ -16,9 +15,6 @@ class Response(SimpleTemplateResponse):
An HttpResponse that allows its data to be rendered into
arbitrary media types.
"""
- # TODO: remove that once Django 1.3 isn't supported
- if django.VERSION >= (1, 4):
- rendering_attrs = SimpleTemplateResponse.rendering_attrs + ['_closable_objects']
def __init__(self, data=None, status=None,
template_name=None, headers=None,
diff --git a/rest_framework/reverse.py b/rest_framework/reverse.py
index a51b07f5..a74e8aa2 100644
--- a/rest_framework/reverse.py
+++ b/rest_framework/reverse.py
@@ -3,6 +3,7 @@ Provide reverse functions that return fully qualified URLs
"""
from __future__ import unicode_literals
from django.core.urlresolvers import reverse as django_reverse
+from django.utils import six
from django.utils.functional import lazy
@@ -20,4 +21,4 @@ def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra
return url
-reverse_lazy = lazy(reverse, str)
+reverse_lazy = lazy(reverse, six.text_type)
diff --git a/rest_framework/routers.py b/rest_framework/routers.py
index f2d06211..6e99f14d 100644
--- a/rest_framework/routers.py
+++ b/rest_framework/routers.py
@@ -21,6 +21,7 @@ from django.conf.urls import patterns, url
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import NoReverseMatch
from rest_framework import views
+from rest_framework.compat import OrderedDict
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework.urlpatterns import format_suffix_patterns
@@ -277,7 +278,7 @@ class DefaultRouter(SimpleRouter):
"""
Return a view to use as the API root.
"""
- api_root_dict = {}
+ api_root_dict = OrderedDict()
list_name = self.routes[0].name
for prefix, viewset, basename in self.registry:
api_root_dict[prefix] = list_name.format(basename=basename)
@@ -286,7 +287,7 @@ class DefaultRouter(SimpleRouter):
_ignore_model_permissions = True
def get(self, request, *args, **kwargs):
- ret = {}
+ ret = OrderedDict()
for key, url_name in api_root_dict.items():
try:
ret[key] = reverse(
diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py
index d2740fc2..f7aa3a7d 100644
--- a/rest_framework/serializers.py
+++ b/rest_framework/serializers.py
@@ -10,20 +10,31 @@ python primitives.
2. The process of marshalling between python primitives and request and
response content is handled by parsers and renderers.
"""
-from django.core.exceptions import ImproperlyConfigured, ValidationError
+from django.core.exceptions import ImproperlyConfigured
from django.db import models
+from django.db.models.fields import FieldDoesNotExist
from django.utils import six
-from django.utils.datastructures import SortedDict
-from collections import namedtuple
+from django.utils.translation import ugettext_lazy as _
+from rest_framework.compat import OrderedDict
+from rest_framework.exceptions import ValidationError
from rest_framework.fields import empty, set_value, Field, SkipField
from rest_framework.settings import api_settings
from rest_framework.utils import html, model_meta, representation
from rest_framework.utils.field_mapping import (
get_url_kwargs, get_field_kwargs,
get_relation_kwargs, get_nested_relation_kwargs,
- lookup_class
+ ClassLookupDict
+)
+from rest_framework.utils.serializer_helpers import (
+ ReturnDict, ReturnList, BoundField, NestedBoundField, BindingDict
+)
+from rest_framework.validators import (
+ UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator,
+ UniqueTogetherValidator
)
import copy
+import inspect
+import warnings
# Note: We do the following so that users of the framework can use this style:
#
@@ -36,19 +47,64 @@ from rest_framework.relations import * # NOQA
from rest_framework.fields import * # NOQA
-FieldResult = namedtuple('FieldResult', ['field', 'value', 'error'])
+# We assume that 'validators' are intended for the child serializer,
+# rather than the parent serializer.
+LIST_SERIALIZER_KWARGS = (
+ 'read_only', 'write_only', 'required', 'default', 'initial', 'source',
+ 'label', 'help_text', 'style', 'error_messages',
+ 'instance', 'data', 'partial', 'context'
+)
+# BaseSerializer
+# --------------
+
class BaseSerializer(Field):
"""
The BaseSerializer class provides a minimal class which may be used
for writing custom serializer implementations.
"""
-
def __init__(self, instance=None, data=None, **kwargs):
- super(BaseSerializer, self).__init__(**kwargs)
self.instance = instance
self._initial_data = data
+ self.partial = kwargs.pop('partial', False)
+ self._context = kwargs.pop('context', {})
+ kwargs.pop('many', None)
+ super(BaseSerializer, self).__init__(**kwargs)
+
+ def __new__(cls, *args, **kwargs):
+ # We override this method in order to automagically create
+ # `ListSerializer` classes instead when `many=True` is set.
+ if kwargs.pop('many', False):
+ return cls.many_init(*args, **kwargs)
+ return super(BaseSerializer, cls).__new__(cls, *args, **kwargs)
+
+ @classmethod
+ def many_init(cls, *args, **kwargs):
+ """
+ This method implements the creation of a `ListSerializer` parent
+ class when `many=True` is used. You can customize it if you need to
+ control which keyword arguments are passed to the parent, and
+ which are passed to the child.
+
+ Note that we're over-cautious in passing most arguments to both parent
+ and child classes in order to try to cover the general case. If you're
+ overriding this method you'll probably want something much simpler, eg:
+
+ @classmethod
+ def many_init(cls, *args, **kwargs):
+ kwargs['child'] = cls()
+ return CustomListSerializer(*args, **kwargs)
+ """
+ child_serializer = cls(*args, **kwargs)
+ list_kwargs = {'child': child_serializer}
+ list_kwargs.update(dict([
+ (key, value) for key, value in kwargs.items()
+ if key in LIST_SERIALIZER_KWARGS
+ ]))
+ meta = getattr(cls, 'Meta', None)
+ list_serializer_class = getattr(meta, 'list_serializer_class', ListSerializer)
+ return list_serializer_class(*args, **list_kwargs)
def to_internal_value(self, data):
raise NotImplementedError('`to_internal_value()` must be implemented.')
@@ -56,31 +112,52 @@ class BaseSerializer(Field):
def to_representation(self, instance):
raise NotImplementedError('`to_representation()` must be implemented.')
- def update(self, instance, attrs):
+ def update(self, instance, validated_data):
raise NotImplementedError('`update()` must be implemented.')
- def create(self, attrs):
+ def create(self, validated_data):
raise NotImplementedError('`create()` must be implemented.')
- def save(self, extras=None):
- attrs = self.validated_data
- if extras is not None:
- attrs = dict(list(attrs.items()) + list(extras.items()))
+ def save(self, **kwargs):
+ assert not hasattr(self, 'save_object'), (
+ 'Serializer `%s.%s` has old-style version 2 `.save_object()` '
+ 'that is no longer compatible with REST framework 3. '
+ 'Use the new-style `.create()` and `.update()` methods instead.' %
+ (self.__class__.__module__, self.__class__.__name__)
+ )
+
+ validated_data = dict(
+ list(self.validated_data.items()) +
+ list(kwargs.items())
+ )
if self.instance is not None:
- self.update(self.instance, attrs)
+ self.instance = self.update(self.instance, validated_data)
+ assert self.instance is not None, (
+ '`update()` did not return an object instance.'
+ )
else:
- self.instance = self.create(attrs)
+ self.instance = self.create(validated_data)
+ assert self.instance is not None, (
+ '`create()` did not return an object instance.'
+ )
return self.instance
def is_valid(self, raise_exception=False):
+ assert not hasattr(self, 'restore_object'), (
+ 'Serializer `%s.%s` has old-style version 2 `.restore_object()` '
+ 'that is no longer compatible with REST framework 3. '
+ 'Use the new-style `.create()` and `.update()` methods instead.' %
+ (self.__class__.__module__, self.__class__.__name__)
+ )
+
if not hasattr(self, '_validated_data'):
try:
- self._validated_data = self.to_internal_value(self._initial_data)
+ self._validated_data = self.run_validation(self._initial_data)
except ValidationError as exc:
self._validated_data = {}
- self._errors = exc.message_dict
+ self._errors = exc.detail
else:
self._errors = {}
@@ -92,13 +169,10 @@ class BaseSerializer(Field):
@property
def data(self):
if not hasattr(self, '_data'):
- if self.instance is not None:
+ if self.instance is not None and not getattr(self, '_errors', None):
self._data = self.to_representation(self.instance)
- elif self._initial_data is not None:
- self._data = dict([
- (field_name, field.get_value(self._initial_data))
- for field_name, field in self.fields.items()
- ])
+ elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None):
+ self._data = self.to_representation(self.validated_data)
else:
self._data = self.get_initial()
return self._data
@@ -118,6 +192,9 @@ class BaseSerializer(Field):
return self._validated_data
+# Serializer & ListSerializer classes
+# -----------------------------------
+
class SerializerMetaclass(type):
"""
This metaclass sets a dictionary named `base_fields` on the class.
@@ -141,7 +218,7 @@ class SerializerMetaclass(type):
if hasattr(base, '_declared_fields'):
fields = list(base._declared_fields.items()) + fields
- return SortedDict(fields)
+ return OrderedDict(fields)
def __new__(cls, name, bases, attrs):
attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs)
@@ -150,44 +227,53 @@ class SerializerMetaclass(type):
@six.add_metaclass(SerializerMetaclass)
class Serializer(BaseSerializer):
- def __init__(self, *args, **kwargs):
- self.context = kwargs.pop('context', {})
- kwargs.pop('partial', None)
- kwargs.pop('many', None)
-
- super(Serializer, self).__init__(*args, **kwargs)
+ default_error_messages = {
+ 'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.')
+ }
+ @property
+ def fields(self):
+ """
+ A dictionary of {field_name: field_instance}.
+ """
+ # `fields` is evalutated lazily. We do this to ensure that we don't
+ # have issues importing modules that use ModelSerializers as fields,
+ # even if Django's app-loading stage has not yet run.
+ if not hasattr(self, '_fields'):
+ self._fields = BindingDict(self)
+ for key, value in self.get_fields().items():
+ self._fields[key] = value
+ return self._fields
+
+ def get_fields(self):
+ """
+ Returns a dictionary of {field_name: field_instance}.
+ """
# Every new serializer is created with a clone of the field instances.
# This allows users to dynamically modify the fields on a serializer
# instance without affecting every other serializer class.
- self.fields = self._get_base_fields()
-
- # Setup all the child fields, to provide them with the current context.
- for field_name, field in self.fields.items():
- field.bind(field_name, self, self)
-
- def __new__(cls, *args, **kwargs):
- # We override this method in order to automagically create
- # `ListSerializer` classes instead when `many=True` is set.
- if kwargs.pop('many', False):
- kwargs['child'] = cls()
- return ListSerializer(*args, **kwargs)
- return super(Serializer, cls).__new__(cls, *args, **kwargs)
-
- def _get_base_fields(self):
return copy.deepcopy(self._declared_fields)
- def bind(self, field_name, parent, root):
- # If the serializer is used as a field then when it becomes bound
- # it also needs to bind all its child fields.
- super(Serializer, self).bind(field_name, parent, root)
- for field_name, field in self.fields.items():
- field.bind(field_name, self, root)
+ def get_validators(self):
+ """
+ Returns a list of validator callables.
+ """
+ # Used by the lazily-evaluated `validators` property.
+ return getattr(getattr(self, 'Meta', None), 'validators', [])
def get_initial(self):
- return dict([
+ if self._initial_data is not None:
+ return OrderedDict([
+ (field_name, field.get_value(self._initial_data))
+ for field_name, field in self.fields.items()
+ if field.get_value(self._initial_data) is not empty
+ and not field.read_only
+ ])
+
+ return OrderedDict([
(field.field_name, field.get_initial())
for field in self.fields.values()
+ if not field.read_only
])
def get_value(self, dictionary):
@@ -197,18 +283,66 @@ class Serializer(BaseSerializer):
return html.parse_html_dict(dictionary, prefix=self.field_name)
return dictionary.get(self.field_name, empty)
- def to_internal_value(self, data):
+ def run_validation(self, data=empty):
"""
- Dict of native values <- Dict of primitive datatypes.
+ We override the default `run_validation`, because the validation
+ performed by validators and the `.validate()` method should
+ be coerced into an error dictionary with a 'non_fields_error' key.
"""
+ if data is empty:
+ if getattr(self.root, 'partial', False):
+ raise SkipField()
+ if self.required:
+ self.fail('required')
+ return self.get_default()
+
+ if data is None:
+ if not self.allow_null:
+ self.fail('null')
+ return None
+
if not isinstance(data, dict):
+ message = self.error_messages['invalid'].format(
+ datatype=type(data).__name__
+ )
raise ValidationError({
- api_settings.NON_FIELD_ERRORS_KEY: ['Invalid data']
+ api_settings.NON_FIELD_ERRORS_KEY: [message]
})
- ret = {}
- errors = {}
- fields = [field for field in self.fields.values() if not field.read_only]
+ value = self.to_internal_value(data)
+ try:
+ self.run_validators(value)
+ value = self.validate(value)
+ assert value is not None, '.validate() should return the validated data'
+ except ValidationError as exc:
+ if isinstance(exc.detail, dict):
+ # .validate() errors may be a dict, in which case, use
+ # standard {key: list of values} style.
+ raise ValidationError(dict([
+ (key, value if isinstance(value, list) else [value])
+ for key, value in exc.detail.items()
+ ]))
+ elif isinstance(exc.detail, list):
+ raise ValidationError({
+ api_settings.NON_FIELD_ERRORS_KEY: exc.detail
+ })
+ else:
+ raise ValidationError({
+ api_settings.NON_FIELD_ERRORS_KEY: [exc.detail]
+ })
+
+ return value
+
+ def to_internal_value(self, data):
+ """
+ Dict of native values <- Dict of primitive datatypes.
+ """
+ ret = OrderedDict()
+ errors = OrderedDict()
+ fields = [
+ field for field in self.fields.values()
+ if (not field.read_only) or (field.default is not empty)
+ ]
for field in fields:
validate_method = getattr(self, 'validate_' + field.field_name, None)
@@ -218,7 +352,7 @@ class Serializer(BaseSerializer):
if validate_method is not None:
validated_value = validate_method(validated_value)
except ValidationError as exc:
- errors[field.field_name] = exc.messages
+ errors[field.field_name] = exc.detail
except SkipField:
pass
else:
@@ -227,63 +361,90 @@ class Serializer(BaseSerializer):
if errors:
raise ValidationError(errors)
- try:
- return self.validate(ret)
- except ValidationError as exc:
- raise ValidationError({
- api_settings.NON_FIELD_ERRORS_KEY: exc.messages
- })
+ return ret
def to_representation(self, instance):
"""
Object instance -> Dict of primitive datatypes.
"""
- ret = SortedDict()
+ ret = OrderedDict()
fields = [field for field in self.fields.values() if not field.write_only]
for field in fields:
- native_value = field.get_attribute(instance)
- ret[field.field_name] = field.to_representation(native_value)
+ attribute = field.get_attribute(instance)
+ if attribute is None:
+ ret[field.field_name] = None
+ else:
+ ret[field.field_name] = field.to_representation(attribute)
return ret
def validate(self, attrs):
return attrs
+ def __repr__(self):
+ return representation.serializer_repr(self, indent=1)
+
+ # The following are used for accessing `BoundField` instances on the
+ # serializer, for the purposes of presenting a form-like API onto the
+ # field values and field errors.
+
def __iter__(self):
- errors = self.errors if hasattr(self, '_errors') else {}
for field in self.fields.values():
- value = self.data.get(field.field_name) if self.data else None
- error = errors.get(field.field_name)
- yield FieldResult(field, value, error)
+ yield self[field.field_name]
- def __repr__(self):
- return representation.serializer_repr(self, indent=1)
+ def __getitem__(self, key):
+ field = self.fields[key]
+ value = self.data.get(key)
+ error = self.errors.get(key) if hasattr(self, '_errors') else None
+ if isinstance(field, Serializer):
+ return NestedBoundField(field, value, error)
+ return BoundField(field, value, error)
+ # Include a backlink to the serializer class on return objects.
+ # Allows renderers such as HTMLFormRenderer to get the full field info.
+
+ @property
+ def data(self):
+ ret = super(Serializer, self).data
+ return ReturnDict(ret, serializer=self)
+
+ @property
+ def errors(self):
+ ret = super(Serializer, self).errors
+ return ReturnDict(ret, serializer=self)
+
+
+# There's some replication of `ListField` here,
+# but that's probably better than obfuscating the call hierarchy.
class ListSerializer(BaseSerializer):
child = None
- initial = []
+ many = True
+
+ default_error_messages = {
+ 'not_a_list': _('Expected a list of items but got type `{input_type}`.')
+ }
def __init__(self, *args, **kwargs):
self.child = kwargs.pop('child', copy.deepcopy(self.child))
assert self.child is not None, '`child` is a required argument.'
- self.context = kwargs.pop('context', {})
- kwargs.pop('partial', None)
-
+ assert not inspect.isclass(self.child), '`child` has not been instantiated.'
super(ListSerializer, self).__init__(*args, **kwargs)
- self.child.bind('', self, self)
+ self.child.bind(field_name='', parent=self)
- def bind(self, field_name, parent, root):
- # If the list is used as a field then it needs to provide
- # the current context to the child serializer.
- super(ListSerializer, self).bind(field_name, parent, root)
- self.child.bind(field_name, self, root)
+ def get_initial(self):
+ if self._initial_data is not None:
+ return self.to_representation(self._initial_data)
+ return []
def get_value(self, dictionary):
+ """
+ Given the input dictionary, return the field value.
+ """
# We override the default field access in order to support
# lists in HTML forms.
- if is_html_input(dictionary):
+ if html.is_html_input(dictionary):
return html.parse_html_list(dictionary, prefix=self.field_name)
return dictionary.get(self.field_name, empty)
@@ -294,29 +455,107 @@ class ListSerializer(BaseSerializer):
if html.is_html_input(data):
data = html.parse_html_list(data)
- return [self.child.run_validation(item) for item in data]
+ if not isinstance(data, list):
+ message = self.error_messages['not_a_list'].format(
+ input_type=type(data).__name__
+ )
+ raise ValidationError({
+ api_settings.NON_FIELD_ERRORS_KEY: [message]
+ })
+
+ ret = []
+ errors = []
+
+ for item in data:
+ try:
+ validated = self.child.run_validation(item)
+ except ValidationError as exc:
+ errors.append(exc.detail)
+ else:
+ ret.append(validated)
+ errors.append({})
+
+ if any(errors):
+ raise ValidationError(errors)
+
+ return ret
def to_representation(self, data):
"""
List of object instances -> List of dicts of primitive datatypes.
"""
- return [self.child.to_representation(item) for item in data]
+ iterable = data.all() if (hasattr(data, 'all')) else data
+ return [
+ self.child.to_representation(item) for item in iterable
+ ]
+
+ def update(self, instance, validated_data):
+ raise NotImplementedError(
+ "Serializers with many=True do not support multiple update by "
+ "default, only multiple create. For updates it is unclear how to "
+ "deal with insertions and deletions. If you need to support "
+ "multiple update, use a `ListSerializer` class and override "
+ "`.update()` so you can specify the behavior exactly."
+ )
- def create(self, attrs_list):
- return [self.child.create(attrs) for attrs in attrs_list]
+ def create(self, validated_data):
+ return [
+ self.child.create(attrs) for attrs in validated_data
+ ]
+
+ def save(self, **kwargs):
+ """
+ Save and return a list of object instances.
+ """
+ validated_data = [
+ dict(list(attrs.items()) + list(kwargs.items()))
+ for attrs in self.validated_data
+ ]
- def save(self):
if self.instance is not None:
- self.update(self.instance, self.validated_data)
- self.instance = self.create(self.validated_data)
+ self.instance = self.update(self.instance, validated_data)
+ assert self.instance is not None, (
+ '`update()` did not return an object instance.'
+ )
+ else:
+ self.instance = self.create(validated_data)
+ assert self.instance is not None, (
+ '`create()` did not return an object instance.'
+ )
+
return self.instance
def __repr__(self):
return representation.list_repr(self, indent=1)
+ # Include a backlink to the serializer class on return objects.
+ # Allows renderers such as HTMLFormRenderer to get the full field info.
+
+ @property
+ def data(self):
+ ret = super(ListSerializer, self).data
+ return ReturnList(ret, serializer=self)
+
+ @property
+ def errors(self):
+ ret = super(ListSerializer, self).errors
+ if isinstance(ret, dict):
+ return ReturnDict(ret, serializer=self)
+ return ReturnList(ret, serializer=self)
+
+
+# ModelSerializer & HyperlinkedModelSerializer
+# --------------------------------------------
class ModelSerializer(Serializer):
- _field_mapping = {
+ """
+ A `ModelSerializer` is just a regular `Serializer`, except that:
+
+ * A set of default fields are automatically populated.
+ * A set of default validators are automatically populated.
+ * Default `.create()` and `.update()` implementations are provided.
+ """
+ _field_mapping = ClassLookupDict({
models.AutoField: IntegerField,
models.BigIntegerField: IntegerField,
models.BooleanField: BooleanField,
@@ -331,7 +570,7 @@ class ModelSerializer(Serializer):
models.FloatField: FloatField,
models.ImageField: ImageField,
models.IntegerField: IntegerField,
- models.NullBooleanField: BooleanField,
+ models.NullBooleanField: NullBooleanField,
models.PositiveIntegerField: IntegerField,
models.PositiveSmallIntegerField: IntegerField,
models.SlugField: SlugField,
@@ -339,22 +578,35 @@ class ModelSerializer(Serializer):
models.TextField: CharField,
models.TimeField: TimeField,
models.URLField: URLField,
- }
+ })
_related_class = PrimaryKeyRelatedField
- def create(self, attrs):
+ def create(self, validated_attrs):
+ # Check that the user isn't trying to handle a writable nested field.
+ # If we don't do this explicitly they'd likely get a confusing
+ # error at the point of calling `Model.objects.create()`.
+ assert not any(
+ isinstance(field, BaseSerializer) and not field.read_only
+ for field in self.fields.values()
+ ), (
+ 'The `.create()` method does not suport nested writable fields '
+ 'by default. Write an explicit `.create()` method for serializer '
+ '`%s.%s`, or set `read_only=True` on nested serializer fields.' %
+ (self.__class__.__module__, self.__class__.__name__)
+ )
+
ModelClass = self.Meta.model
- # Remove many-to-many relationships from attrs.
+ # Remove many-to-many relationships from validated_attrs.
# They are not valid arguments to the default `.create()` method,
# as they require that the instance has already been saved.
info = model_meta.get_field_info(ModelClass)
many_to_many = {}
for field_name, relation_info in info.relations.items():
- if relation_info.to_many and (field_name in attrs):
- many_to_many[field_name] = attrs.pop(field_name)
+ if relation_info.to_many and (field_name in validated_attrs):
+ many_to_many[field_name] = validated_attrs.pop(field_name)
- instance = ModelClass.objects.create(**attrs)
+ instance = ModelClass.objects.create(**validated_attrs)
# Save many-to-many relationships after the instance is created.
if many_to_many:
@@ -363,42 +615,185 @@ class ModelSerializer(Serializer):
return instance
- def update(self, obj, attrs):
- for attr, value in attrs.items():
- setattr(obj, attr, value)
- obj.save()
+ def update(self, instance, validated_attrs):
+ assert not any(
+ isinstance(field, BaseSerializer) and not field.read_only
+ for field in self.fields.values()
+ ), (
+ 'The `.update()` method does not suport nested writable fields '
+ 'by default. Write an explicit `.update()` method for serializer '
+ '`%s.%s`, or set `read_only=True` on nested serializer fields.' %
+ (self.__class__.__module__, self.__class__.__name__)
+ )
+
+ for attr, value in validated_attrs.items():
+ setattr(instance, attr, value)
+ instance.save()
+ return instance
+
+ def get_validators(self):
+ field_names = set([
+ field.source for field in self.fields.values()
+ if (field.source != '*') and ('.' not in field.source)
+ ])
- def _get_base_fields(self):
+ validators = getattr(getattr(self, 'Meta', None), 'validators', [])
+ model_class = self.Meta.model
+
+ # Note that we make sure to check `unique_together` both on the
+ # base model class, but also on any parent classes.
+ for parent_class in [model_class] + list(model_class._meta.parents.keys()):
+ for unique_together in parent_class._meta.unique_together:
+ if field_names.issuperset(set(unique_together)):
+ validator = UniqueTogetherValidator(
+ queryset=parent_class._default_manager,
+ fields=unique_together
+ )
+ validators.append(validator)
+
+ # Add any unique_for_date/unique_for_month/unique_for_year constraints.
+ info = model_meta.get_field_info(model_class)
+ for field_name, field in info.fields_and_pk.items():
+ if field.unique_for_date and field_name in field_names:
+ validator = UniqueForDateValidator(
+ queryset=model_class._default_manager,
+ field=field_name,
+ date_field=field.unique_for_date
+ )
+ validators.append(validator)
+
+ if field.unique_for_month and field_name in field_names:
+ validator = UniqueForMonthValidator(
+ queryset=model_class._default_manager,
+ field=field_name,
+ date_field=field.unique_for_month
+ )
+ validators.append(validator)
+
+ if field.unique_for_year and field_name in field_names:
+ validator = UniqueForYearValidator(
+ queryset=model_class._default_manager,
+ field=field_name,
+ date_field=field.unique_for_year
+ )
+ validators.append(validator)
+
+ return validators
+
+ def get_fields(self):
declared_fields = copy.deepcopy(self._declared_fields)
- ret = SortedDict()
+ ret = OrderedDict()
model = getattr(self.Meta, 'model')
fields = getattr(self.Meta, 'fields', None)
+ exclude = getattr(self.Meta, 'exclude', None)
depth = getattr(self.Meta, 'depth', 0)
extra_kwargs = getattr(self.Meta, 'extra_kwargs', {})
+ assert not (fields and exclude), "Cannot set both 'fields' and 'exclude'."
+
+ extra_kwargs = self._include_additional_options(extra_kwargs)
+
# Retrieve metadata about fields & relationships on the model class.
info = model_meta.get_field_info(model)
- # Use the default set of fields if none is supplied explicitly.
+ # Use the default set of field names if none is supplied explicitly.
if fields is None:
fields = self._get_default_field_names(declared_fields, info)
+ exclude = getattr(self.Meta, 'exclude', None)
+ if exclude is not None:
+ for field_name in exclude:
+ fields.remove(field_name)
+
+ # Determine the set of model fields, and the fields that they map to.
+ # We actually only need this to deal with the slightly awkward case
+ # of supporting `unique_for_date`/`unique_for_month`/`unique_for_year`.
+ model_field_mapping = {}
+ for field_name in fields:
+ if field_name in declared_fields:
+ field = declared_fields[field_name]
+ source = field.source or field_name
+ else:
+ try:
+ source = extra_kwargs[field_name]['source']
+ except KeyError:
+ source = field_name
+ # Model fields will always have a simple source mapping,
+ # they can't be nested attribute lookups.
+ if '.' not in source and source != '*':
+ model_field_mapping[source] = field_name
+
+ # Determine if we need any additional `HiddenField` or extra keyword
+ # arguments to deal with `unique_for` dates that are required to
+ # be in the input data in order to validate it.
+ hidden_fields = {}
+ unique_constraint_names = set()
+
+ for model_field_name, field_name in model_field_mapping.items():
+ try:
+ model_field = model._meta.get_field(model_field_name)
+ except FieldDoesNotExist:
+ continue
+ # Include each of the `unique_for_*` field names.
+ unique_constraint_names |= set([
+ model_field.unique_for_date,
+ model_field.unique_for_month,
+ model_field.unique_for_year
+ ])
+
+ unique_constraint_names -= set([None])
+
+ # Include each of the `unique_together` field names,
+ # so long as all the field names are included on the serializer.
+ for parent_class in [model] + list(model._meta.parents.keys()):
+ for unique_together_list in parent_class._meta.unique_together:
+ if set(fields).issuperset(set(unique_together_list)):
+ unique_constraint_names |= set(unique_together_list)
+
+ # Now we have all the field names that have uniqueness constraints
+ # applied, we can add the extra 'required=...' or 'default=...'
+ # arguments that are appropriate to these fields, or add a `HiddenField` for it.
+ for unique_constraint_name in unique_constraint_names:
+ # Get the model field that is refered too.
+ unique_constraint_field = model._meta.get_field(unique_constraint_name)
+
+ if getattr(unique_constraint_field, 'auto_now_add', None):
+ default = CreateOnlyDefault(timezone.now)
+ elif getattr(unique_constraint_field, 'auto_now', None):
+ default = timezone.now
+ elif unique_constraint_field.has_default():
+ default = unique_constraint_field.default
+ else:
+ default = empty
+
+ if unique_constraint_name in model_field_mapping:
+ # The corresponding field is present in the serializer
+ if unique_constraint_name not in extra_kwargs:
+ extra_kwargs[unique_constraint_name] = {}
+ if default is empty:
+ if 'required' not in extra_kwargs[unique_constraint_name]:
+ extra_kwargs[unique_constraint_name]['required'] = True
+ else:
+ if 'default' not in extra_kwargs[unique_constraint_name]:
+ extra_kwargs[unique_constraint_name]['default'] = default
+ elif default is not empty:
+ # The corresponding field is not present in the,
+ # serializer. We have a default to use for it, so
+ # add in a hidden field that populates it.
+ hidden_fields[unique_constraint_name] = HiddenField(default=default)
+
+ # Now determine the fields that should be included on the serializer.
for field_name in fields:
if field_name in declared_fields:
# Field is explicitly declared on the class, use that.
ret[field_name] = declared_fields[field_name]
continue
- elif field_name == api_settings.URL_FIELD_NAME:
- # Create the URL field.
- field_cls = HyperlinkedIdentityField
- kwargs = get_url_kwargs(model)
-
elif field_name in info.fields_and_pk:
# Create regular model fields.
model_field = info.fields_and_pk[field_name]
- field_cls = lookup_class(self._field_mapping, model_field)
+ field_cls = self._field_mapping[model_field]
kwargs = get_field_kwargs(field_name, model_field)
if 'choices' in kwargs:
# Fields with choices get coerced into `ChoiceField`
@@ -409,6 +804,9 @@ class ModelSerializer(Serializer):
# `ModelField`, which is used when no other typed field
# matched to the model field.
kwargs.pop('model_field', None)
+ if not issubclass(field_cls, CharField):
+ # `allow_blank` is only valid for textual fields.
+ kwargs.pop('allow_blank', None)
elif field_name in info.relations:
# Create forward and reverse relationships.
@@ -428,6 +826,11 @@ class ModelSerializer(Serializer):
field_cls = ReadOnlyField
kwargs = {}
+ elif field_name == api_settings.URL_FIELD_NAME:
+ # Create the URL field.
+ field_cls = HyperlinkedIdentityField
+ kwargs = get_url_kwargs(model)
+
else:
raise ImproperlyConfigured(
'Field name `%s` is not valid for model `%s`.' %
@@ -446,13 +849,76 @@ class ModelSerializer(Serializer):
)
# Populate any kwargs defined in `Meta.extra_kwargs`
- kwargs.update(extra_kwargs.get(field_name, {}))
+ extras = extra_kwargs.get(field_name, {})
+ if extras.get('read_only', False):
+ for attr in [
+ 'required', 'default', 'allow_blank', 'allow_null',
+ 'min_length', 'max_length', 'min_value', 'max_value',
+ 'validators', 'queryset'
+ ]:
+ kwargs.pop(attr, None)
+
+ if extras.get('default') and kwargs.get('required') is False:
+ kwargs.pop('required')
+
+ kwargs.update(extras)
# Create the serializer field.
ret[field_name] = field_cls(**kwargs)
+ for field_name, field in hidden_fields.items():
+ ret[field_name] = field
+
return ret
+ def _include_additional_options(self, extra_kwargs):
+ read_only_fields = getattr(self.Meta, 'read_only_fields', None)
+ if read_only_fields is not None:
+ for field_name in read_only_fields:
+ kwargs = extra_kwargs.get(field_name, {})
+ kwargs['read_only'] = True
+ extra_kwargs[field_name] = kwargs
+
+ # These are all pending deprecation.
+ write_only_fields = getattr(self.Meta, 'write_only_fields', None)
+ if write_only_fields is not None:
+ warnings.warn(
+ "The `Meta.write_only_fields` option is pending deprecation. "
+ "Use `Meta.extra_kwargs={<field_name>: {'write_only': True}}` instead.",
+ PendingDeprecationWarning,
+ stacklevel=3
+ )
+ for field_name in write_only_fields:
+ kwargs = extra_kwargs.get(field_name, {})
+ kwargs['write_only'] = True
+ extra_kwargs[field_name] = kwargs
+
+ view_name = getattr(self.Meta, 'view_name', None)
+ if view_name is not None:
+ warnings.warn(
+ "The `Meta.view_name` option is pending deprecation. "
+ "Use `Meta.extra_kwargs={'url': {'view_name': ...}}` instead.",
+ PendingDeprecationWarning,
+ stacklevel=3
+ )
+ kwargs = extra_kwargs.get(api_settings.URL_FIELD_NAME, {})
+ kwargs['view_name'] = view_name
+ extra_kwargs[api_settings.URL_FIELD_NAME] = kwargs
+
+ lookup_field = getattr(self.Meta, 'lookup_field', None)
+ if lookup_field is not None:
+ warnings.warn(
+ "The `Meta.lookup_field` option is pending deprecation. "
+ "Use `Meta.extra_kwargs={'url': {'lookup_field': ...}}` instead.",
+ PendingDeprecationWarning,
+ stacklevel=3
+ )
+ kwargs = extra_kwargs.get(api_settings.URL_FIELD_NAME, {})
+ kwargs['lookup_field'] = lookup_field
+ extra_kwargs[api_settings.URL_FIELD_NAME] = kwargs
+
+ return extra_kwargs
+
def _get_default_field_names(self, declared_fields, model_info):
return (
[model_info.pk.name] +
@@ -470,6 +936,13 @@ class ModelSerializer(Serializer):
class HyperlinkedModelSerializer(ModelSerializer):
+ """
+ A type of `ModelSerializer` that uses hyperlinked relationships instead
+ of primary key relationships. Specifically:
+
+ * A 'url' field is included instead of the 'id' field.
+ * Relationships to other instances are hyperlinks, instead of primary keys.
+ """
_related_class = HyperlinkedRelatedField
def _get_default_field_names(self, declared_fields, model_info):
diff --git a/rest_framework/settings.py b/rest_framework/settings.py
index 421e146c..1e8c27fc 100644
--- a/rest_framework/settings.py
+++ b/rest_framework/settings.py
@@ -45,6 +45,7 @@ DEFAULTS = {
),
'DEFAULT_THROTTLE_CLASSES': (),
'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'rest_framework.negotiation.DefaultContentNegotiation',
+ 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata',
# Genric view behavior
'DEFAULT_MODEL_SERIALIZER_CLASS': 'rest_framework.serializers.ModelSerializer',
@@ -109,7 +110,8 @@ DEFAULTS = {
# Encoding
'UNICODE_JSON': True,
'COMPACT_JSON': True,
- 'COERCE_DECIMAL_TO_STRING': True
+ 'COERCE_DECIMAL_TO_STRING': True,
+ 'UPLOADED_FILES_USE_URL': True
}
@@ -121,6 +123,7 @@ IMPORT_STRINGS = (
'DEFAULT_PERMISSION_CLASSES',
'DEFAULT_THROTTLE_CLASSES',
'DEFAULT_CONTENT_NEGOTIATION_CLASS',
+ 'DEFAULT_METADATA_CLASS',
'DEFAULT_MODEL_SERIALIZER_CLASS',
'DEFAULT_PAGINATION_SERIALIZER_CLASS',
'DEFAULT_FILTER_BACKENDS',
diff --git a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css
index 6fa1e6cb..36c7be48 100644
--- a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css
+++ b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css
@@ -10,6 +10,12 @@ a single block in the template.
background: transparent;
border-top-color: transparent;
padding-top: 0;
+ text-align: right;
+}
+
+#generic-content-form textarea {
+ font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;
+ font-size: 80%;
}
.navbar-inverse .brand a {
@@ -29,7 +35,7 @@ a single block in the template.
z-index: 3;
}
-.navbar .navbar-inner {
+.navbar {
background: #2C2C2C;
color: white;
border: none;
@@ -37,7 +43,7 @@ a single block in the template.
border-radius: 0px;
}
-.navbar .navbar-inner .nav li, .navbar .navbar-inner .nav li a, .navbar .navbar-inner .brand:hover {
+.navbar .nav li, .navbar .nav li a, .navbar .brand:hover {
color: white;
}
@@ -45,11 +51,11 @@ a single block in the template.
background: #2C2C2C;
}
-.navbar .navbar-inner .dropdown-menu li a, .navbar .navbar-inner .dropdown-menu li {
+.navbar .dropdown-menu li a, .navbar .dropdown-menu li {
color: #A30000;
}
-.navbar .navbar-inner .dropdown-menu li a:hover {
+.navbar .dropdown-menu li a:hover {
background: #EEEEEE;
color: #C20000;
}
@@ -61,10 +67,10 @@ html {
background: none;
}
-body, .navbar .navbar-inner .container-fluid {
+/*body, .navbar .container-fluid {
max-width: 1150px;
margin: 0 auto;
-}
+}*/
body {
background: url("../img/grid.png") repeat-x;
@@ -109,10 +115,6 @@ html, body {
margin-bottom: 0;
}
-.well form .help-block {
- color: #999999;
-}
-
.nav-tabs {
border: 0;
}
@@ -167,7 +169,7 @@ footer a:hover {
.page-header {
border-bottom: none;
padding-bottom: 0px;
- margin-bottom: 20px;
+ margin: 0;
}
/* custom general page styles */
diff --git a/rest_framework/static/rest_framework/css/bootstrap.min.css b/rest_framework/static/rest_framework/css/bootstrap.min.css
index 373f4b43..a9f35cee 100644
--- a/rest_framework/static/rest_framework/css/bootstrap.min.css
+++ b/rest_framework/static/rest_framework/css/bootstrap.min.css
@@ -1,841 +1,5 @@
/*!
- * Bootstrap v2.1.1
- *
- * Copyright 2012 Twitter, Inc
- * Licensed under the Apache License v2.0
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Designed and built with all the love in the world @twitter by @mdo and @fat.
- */
-.clearfix{*zoom:1;}.clearfix:before,.clearfix:after{display:table;content:"";line-height:0;}
-.clearfix:after{clear:both;}
-.hide-text{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0;}
-.input-block-level{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}
-article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block;}
-audio,canvas,video{display:inline-block;*display:inline;*zoom:1;}
-audio:not([controls]){display:none;}
-html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;}
-a:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;}
-a:hover,a:active{outline:0;}
-sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline;}
-sup{top:-0.5em;}
-sub{bottom:-0.25em;}
-img{max-width:100%;width:auto\9;height:auto;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic;}
-#map_canvas img{max-width:none;}
-button,input,select,textarea{margin:0;font-size:100%;vertical-align:middle;}
-button,input{*overflow:visible;line-height:normal;}
-button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0;}
-button,input[type="button"],input[type="reset"],input[type="submit"]{cursor:pointer;-webkit-appearance:button;}
-input[type="search"]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield;}
-input[type="search"]::-webkit-search-decoration,input[type="search"]::-webkit-search-cancel-button{-webkit-appearance:none;}
-textarea{overflow:auto;vertical-align:top;}
-body{margin:0;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:20px;color:#333333;background-color:#ffffff;}
-a{color:#0088cc;text-decoration:none;}
-a:hover{color:#005580;text-decoration:underline;}
-.img-rounded{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}
-.img-polaroid{padding:4px;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);box-shadow:0 1px 3px rgba(0, 0, 0, 0.1);}
-.img-circle{-webkit-border-radius:500px;-moz-border-radius:500px;border-radius:500px;}
-.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;}
-.row:after{clear:both;}
-[class*="span"]{float:left;min-height:1px;margin-left:20px;}
-.container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;}
-.span12{width:940px;}
-.span11{width:860px;}
-.span10{width:780px;}
-.span9{width:700px;}
-.span8{width:620px;}
-.span7{width:540px;}
-.span6{width:460px;}
-.span5{width:380px;}
-.span4{width:300px;}
-.span3{width:220px;}
-.span2{width:140px;}
-.span1{width:60px;}
-.offset12{margin-left:980px;}
-.offset11{margin-left:900px;}
-.offset10{margin-left:820px;}
-.offset9{margin-left:740px;}
-.offset8{margin-left:660px;}
-.offset7{margin-left:580px;}
-.offset6{margin-left:500px;}
-.offset5{margin-left:420px;}
-.offset4{margin-left:340px;}
-.offset3{margin-left:260px;}
-.offset2{margin-left:180px;}
-.offset1{margin-left:100px;}
-.row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;}
-.row-fluid:after{clear:both;}
-.row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.127659574468085%;*margin-left:2.074468085106383%;}
-.row-fluid [class*="span"]:first-child{margin-left:0;}
-.row-fluid .span12{width:100%;*width:99.94680851063829%;}
-.row-fluid .span11{width:91.48936170212765%;*width:91.43617021276594%;}
-.row-fluid .span10{width:82.97872340425532%;*width:82.92553191489361%;}
-.row-fluid .span9{width:74.46808510638297%;*width:74.41489361702126%;}
-.row-fluid .span8{width:65.95744680851064%;*width:65.90425531914893%;}
-.row-fluid .span7{width:57.44680851063829%;*width:57.39361702127659%;}
-.row-fluid .span6{width:48.93617021276595%;*width:48.88297872340425%;}
-.row-fluid .span5{width:40.42553191489362%;*width:40.37234042553192%;}
-.row-fluid .span4{width:31.914893617021278%;*width:31.861702127659576%;}
-.row-fluid .span3{width:23.404255319148934%;*width:23.351063829787233%;}
-.row-fluid .span2{width:14.893617021276595%;*width:14.840425531914894%;}
-.row-fluid .span1{width:6.382978723404255%;*width:6.329787234042553%;}
-.row-fluid .offset12{margin-left:104.25531914893617%;*margin-left:104.14893617021275%;}
-.row-fluid .offset12:first-child{margin-left:102.12765957446808%;*margin-left:102.02127659574467%;}
-.row-fluid .offset11{margin-left:95.74468085106382%;*margin-left:95.6382978723404%;}
-.row-fluid .offset11:first-child{margin-left:93.61702127659574%;*margin-left:93.51063829787232%;}
-.row-fluid .offset10{margin-left:87.23404255319149%;*margin-left:87.12765957446807%;}
-.row-fluid .offset10:first-child{margin-left:85.1063829787234%;*margin-left:84.99999999999999%;}
-.row-fluid .offset9{margin-left:78.72340425531914%;*margin-left:78.61702127659572%;}
-.row-fluid .offset9:first-child{margin-left:76.59574468085106%;*margin-left:76.48936170212764%;}
-.row-fluid .offset8{margin-left:70.2127659574468%;*margin-left:70.10638297872339%;}
-.row-fluid .offset8:first-child{margin-left:68.08510638297872%;*margin-left:67.9787234042553%;}
-.row-fluid .offset7{margin-left:61.70212765957446%;*margin-left:61.59574468085106%;}
-.row-fluid .offset7:first-child{margin-left:59.574468085106375%;*margin-left:59.46808510638297%;}
-.row-fluid .offset6{margin-left:53.191489361702125%;*margin-left:53.085106382978715%;}
-.row-fluid .offset6:first-child{margin-left:51.063829787234035%;*margin-left:50.95744680851063%;}
-.row-fluid .offset5{margin-left:44.68085106382979%;*margin-left:44.57446808510638%;}
-.row-fluid .offset5:first-child{margin-left:42.5531914893617%;*margin-left:42.4468085106383%;}
-.row-fluid .offset4{margin-left:36.170212765957444%;*margin-left:36.06382978723405%;}
-.row-fluid .offset4:first-child{margin-left:34.04255319148936%;*margin-left:33.93617021276596%;}
-.row-fluid .offset3{margin-left:27.659574468085104%;*margin-left:27.5531914893617%;}
-.row-fluid .offset3:first-child{margin-left:25.53191489361702%;*margin-left:25.425531914893618%;}
-.row-fluid .offset2{margin-left:19.148936170212764%;*margin-left:19.04255319148936%;}
-.row-fluid .offset2:first-child{margin-left:17.02127659574468%;*margin-left:16.914893617021278%;}
-.row-fluid .offset1{margin-left:10.638297872340425%;*margin-left:10.53191489361702%;}
-.row-fluid .offset1:first-child{margin-left:8.51063829787234%;*margin-left:8.404255319148938%;}
-[class*="span"].hide,.row-fluid [class*="span"].hide{display:none;}
-[class*="span"].pull-right,.row-fluid [class*="span"].pull-right{float:right;}
-.container{margin-right:auto;margin-left:auto;*zoom:1;}.container:before,.container:after{display:table;content:"";line-height:0;}
-.container:after{clear:both;}
-.container-fluid{padding-right:20px;padding-left:20px;*zoom:1;}.container-fluid:before,.container-fluid:after{display:table;content:"";line-height:0;}
-.container-fluid:after{clear:both;}
-p{margin:0 0 10px;}
-.lead{margin-bottom:20px;font-size:21px;font-weight:200;line-height:30px;}
-small{font-size:85%;}
-strong{font-weight:bold;}
-em{font-style:italic;}
-cite{font-style:normal;}
-.muted{color:#999999;}
-.text-warning{color:#c09853;}
-.text-error{color:#b94a48;}
-.text-info{color:#3a87ad;}
-.text-success{color:#468847;}
-h1,h2,h3,h4,h5,h6{margin:10px 0;font-family:inherit;font-weight:bold;line-height:1;color:inherit;text-rendering:optimizelegibility;}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small{font-weight:normal;line-height:1;color:#999999;}
-h1{font-size:36px;line-height:40px;}
-h2{font-size:30px;line-height:40px;}
-h3{font-size:24px;line-height:40px;}
-h4{font-size:18px;line-height:20px;}
-h5{font-size:14px;line-height:20px;}
-h6{font-size:12px;line-height:20px;}
-h1 small{font-size:24px;}
-h2 small{font-size:18px;}
-h3 small{font-size:14px;}
-h4 small{font-size:14px;}
-.page-header{padding-bottom:9px;margin:20px 0 30px;border-bottom:1px solid #eeeeee;}
-ul,ol{padding:0;margin:0 0 10px 25px;}
-ul ul,ul ol,ol ol,ol ul{margin-bottom:0;}
-li{line-height:20px;}
-ul.unstyled,ol.unstyled{margin-left:0;list-style:none;}
-dl{margin-bottom:20px;}
-dt,dd{line-height:20px;}
-dt{font-weight:bold;}
-dd{margin-left:10px;}
-.dl-horizontal{*zoom:1;}.dl-horizontal:before,.dl-horizontal:after{display:table;content:"";line-height:0;}
-.dl-horizontal:after{clear:both;}
-.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
-.dl-horizontal dd{margin-left:180px;}
-hr{margin:20px 0;border:0;border-top:1px solid #eeeeee;border-bottom:1px solid #ffffff;}
-abbr[title]{cursor:help;border-bottom:1px dotted #999999;}
-abbr.initialism{font-size:90%;text-transform:uppercase;}
-blockquote{padding:0 0 0 15px;margin:0 0 20px;border-left:5px solid #eeeeee;}blockquote p{margin-bottom:0;font-size:16px;font-weight:300;line-height:25px;}
-blockquote small{display:block;line-height:20px;color:#999999;}blockquote small:before{content:'\2014 \00A0';}
-blockquote.pull-right{float:right;padding-right:15px;padding-left:0;border-right:5px solid #eeeeee;border-left:0;}blockquote.pull-right p,blockquote.pull-right small{text-align:right;}
-blockquote.pull-right small:before{content:'';}
-blockquote.pull-right small:after{content:'\00A0 \2014';}
-q:before,q:after,blockquote:before,blockquote:after{content:"";}
-address{display:block;margin-bottom:20px;font-style:normal;line-height:20px;}
-code,pre{padding:0 3px 2px;font-family:Monaco,Menlo,Consolas,"Courier New",monospace;font-size:12px;color:#333333;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
-code{padding:2px 4px;color:#d14;background-color:#f7f7f9;border:1px solid #e1e1e8;}
-pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:20px;word-break:break-all;word-wrap:break-word;white-space:pre;white-space:pre-wrap;background-color:#f5f5f5;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.15);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}pre.prettyprint{margin-bottom:20px;}
-pre code{padding:0;color:inherit;background-color:transparent;border:0;}
-.pre-scrollable{max-height:340px;overflow-y:scroll;}
-.label,.badge{font-size:11.844px;font-weight:bold;line-height:14px;color:#ffffff;vertical-align:baseline;white-space:nowrap;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#999999;}
-.label{padding:1px 4px 2px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
-.badge{padding:1px 9px 2px;-webkit-border-radius:9px;-moz-border-radius:9px;border-radius:9px;}
-a.label:hover,a.badge:hover{color:#ffffff;text-decoration:none;cursor:pointer;}
-.label-important,.badge-important{background-color:#b94a48;}
-.label-important[href],.badge-important[href]{background-color:#953b39;}
-.label-warning,.badge-warning{background-color:#f89406;}
-.label-warning[href],.badge-warning[href]{background-color:#c67605;}
-.label-success,.badge-success{background-color:#468847;}
-.label-success[href],.badge-success[href]{background-color:#356635;}
-.label-info,.badge-info{background-color:#3a87ad;}
-.label-info[href],.badge-info[href]{background-color:#2d6987;}
-.label-inverse,.badge-inverse{background-color:#333333;}
-.label-inverse[href],.badge-inverse[href]{background-color:#1a1a1a;}
-.btn .label,.btn .badge{position:relative;top:-1px;}
-.btn-mini .label,.btn-mini .badge{top:0;}
-table{max-width:100%;background-color:transparent;border-collapse:collapse;border-spacing:0;}
-.table{width:100%;margin-bottom:20px;}.table th,.table td{padding:8px;line-height:20px;text-align:left;vertical-align:top;border-top:1px solid #dddddd;}
-.table th{font-weight:bold;}
-.table thead th{vertical-align:bottom;}
-.table caption+thead tr:first-child th,.table caption+thead tr:first-child td,.table colgroup+thead tr:first-child th,.table colgroup+thead tr:first-child td,.table thead:first-child tr:first-child th,.table thead:first-child tr:first-child td{border-top:0;}
-.table tbody+tbody{border-top:2px solid #dddddd;}
-.table-condensed th,.table-condensed td{padding:4px 5px;}
-.table-bordered{border:1px solid #dddddd;border-collapse:separate;*border-collapse:collapse;border-left:0;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.table-bordered th,.table-bordered td{border-left:1px solid #dddddd;}
-.table-bordered caption+thead tr:first-child th,.table-bordered caption+tbody tr:first-child th,.table-bordered caption+tbody tr:first-child td,.table-bordered colgroup+thead tr:first-child th,.table-bordered colgroup+tbody tr:first-child th,.table-bordered colgroup+tbody tr:first-child td,.table-bordered thead:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child th,.table-bordered tbody:first-child tr:first-child td{border-top:0;}
-.table-bordered thead:first-child tr:first-child th:first-child,.table-bordered tbody:first-child tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px;}
-.table-bordered thead:first-child tr:first-child th:last-child,.table-bordered tbody:first-child tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topright:4px;}
-.table-bordered thead:last-child tr:last-child th:first-child,.table-bordered tbody:last-child tr:last-child td:first-child,.table-bordered tfoot:last-child tr:last-child td:first-child{-webkit-border-radius:0 0 0 4px;-moz-border-radius:0 0 0 4px;border-radius:0 0 0 4px;-webkit-border-bottom-left-radius:4px;border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;}
-.table-bordered thead:last-child tr:last-child th:last-child,.table-bordered tbody:last-child tr:last-child td:last-child,.table-bordered tfoot:last-child tr:last-child td:last-child{-webkit-border-bottom-right-radius:4px;border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;}
-.table-bordered caption+thead tr:first-child th:first-child,.table-bordered caption+tbody tr:first-child td:first-child,.table-bordered colgroup+thead tr:first-child th:first-child,.table-bordered colgroup+tbody tr:first-child td:first-child{-webkit-border-top-left-radius:4px;border-top-left-radius:4px;-moz-border-radius-topleft:4px;}
-.table-bordered caption+thead tr:first-child th:last-child,.table-bordered caption+tbody tr:first-child td:last-child,.table-bordered colgroup+thead tr:first-child th:last-child,.table-bordered colgroup+tbody tr:first-child td:last-child{-webkit-border-top-right-radius:4px;border-top-right-radius:4px;-moz-border-radius-topleft:4px;}
-.table-striped tbody tr:nth-child(odd) td,.table-striped tbody tr:nth-child(odd) th{background-color:#f9f9f9;}
-.table-hover tbody tr:hover td,.table-hover tbody tr:hover th{background-color:#f5f5f5;}
-table [class*=span],.row-fluid table [class*=span]{display:table-cell;float:none;margin-left:0;}
-.table .span1{float:none;width:44px;margin-left:0;}
-.table .span2{float:none;width:124px;margin-left:0;}
-.table .span3{float:none;width:204px;margin-left:0;}
-.table .span4{float:none;width:284px;margin-left:0;}
-.table .span5{float:none;width:364px;margin-left:0;}
-.table .span6{float:none;width:444px;margin-left:0;}
-.table .span7{float:none;width:524px;margin-left:0;}
-.table .span8{float:none;width:604px;margin-left:0;}
-.table .span9{float:none;width:684px;margin-left:0;}
-.table .span10{float:none;width:764px;margin-left:0;}
-.table .span11{float:none;width:844px;margin-left:0;}
-.table .span12{float:none;width:924px;margin-left:0;}
-.table .span13{float:none;width:1004px;margin-left:0;}
-.table .span14{float:none;width:1084px;margin-left:0;}
-.table .span15{float:none;width:1164px;margin-left:0;}
-.table .span16{float:none;width:1244px;margin-left:0;}
-.table .span17{float:none;width:1324px;margin-left:0;}
-.table .span18{float:none;width:1404px;margin-left:0;}
-.table .span19{float:none;width:1484px;margin-left:0;}
-.table .span20{float:none;width:1564px;margin-left:0;}
-.table .span21{float:none;width:1644px;margin-left:0;}
-.table .span22{float:none;width:1724px;margin-left:0;}
-.table .span23{float:none;width:1804px;margin-left:0;}
-.table .span24{float:none;width:1884px;margin-left:0;}
-.table tbody tr.success td{background-color:#dff0d8;}
-.table tbody tr.error td{background-color:#f2dede;}
-.table tbody tr.warning td{background-color:#fcf8e3;}
-.table tbody tr.info td{background-color:#d9edf7;}
-.table-hover tbody tr.success:hover td{background-color:#d0e9c6;}
-.table-hover tbody tr.error:hover td{background-color:#ebcccc;}
-.table-hover tbody tr.warning:hover td{background-color:#faf2cc;}
-.table-hover tbody tr.info:hover td{background-color:#c4e3f3;}
-form{margin:0 0 20px;}
-fieldset{padding:0;margin:0;border:0;}
-legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:40px;color:#333333;border:0;border-bottom:1px solid #e5e5e5;}legend small{font-size:15px;color:#999999;}
-label,input,button,select,textarea{font-size:14px;font-weight:normal;line-height:20px;}
-input,button,select,textarea{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;}
-label{display:block;margin-bottom:5px;}
-select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px 6px;margin-bottom:9px;font-size:14px;line-height:20px;color:#555555;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
-input,textarea,.uneditable-input{width:206px;}
-textarea{height:auto;}
-textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear .2s, box-shadow linear .2s;-moz-transition:border linear .2s, box-shadow linear .2s;-o-transition:border linear .2s, box-shadow linear .2s;transition:border linear .2s, box-shadow linear .2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);}
-input[type="radio"],input[type="checkbox"]{margin:4px 0 0;*margin-top:0;margin-top:1px \9;line-height:normal;cursor:pointer;}
-input[type="file"],input[type="image"],input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
-select,input[type="file"]{height:30px;*margin-top:4px;line-height:30px;}
-select{width:220px;border:1px solid #cccccc;background-color:#ffffff;}
-select[multiple],select[size]{height:auto;}
-select:focus,input[type="file"]:focus,input[type="radio"]:focus,input[type="checkbox"]:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;}
-.uneditable-input,.uneditable-textarea{color:#999999;background-color:#fcfcfc;border-color:#cccccc;-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.025);cursor:not-allowed;}
-.uneditable-input{overflow:hidden;white-space:nowrap;}
-.uneditable-textarea{width:auto;height:auto;}
-input:-moz-placeholder,textarea:-moz-placeholder{color:#999999;}
-input:-ms-input-placeholder,textarea:-ms-input-placeholder{color:#999999;}
-input::-webkit-input-placeholder,textarea::-webkit-input-placeholder{color:#999999;}
-.radio,.checkbox{min-height:18px;padding-left:18px;}
-.radio input[type="radio"],.checkbox input[type="checkbox"]{float:left;margin-left:-18px;}
-.controls>.radio:first-child,.controls>.checkbox:first-child{padding-top:5px;}
-.radio.inline,.checkbox.inline{display:inline-block;padding-top:5px;margin-bottom:0;vertical-align:middle;}
-.radio.inline+.radio.inline,.checkbox.inline+.checkbox.inline{margin-left:10px;}
-.input-mini{width:60px;}
-.input-small{width:90px;}
-.input-medium{width:150px;}
-.input-large{width:210px;}
-.input-xlarge{width:270px;}
-.input-xxlarge{width:530px;}
-input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"]{float:none;margin-left:0;}
-.input-append input[class*="span"],.input-append .uneditable-input[class*="span"],.input-prepend input[class*="span"],.input-prepend .uneditable-input[class*="span"],.row-fluid input[class*="span"],.row-fluid select[class*="span"],.row-fluid textarea[class*="span"],.row-fluid .uneditable-input[class*="span"],.row-fluid .input-prepend [class*="span"],.row-fluid .input-append [class*="span"]{display:inline-block;}
-input,textarea,.uneditable-input{margin-left:0;}
-.controls-row [class*="span"]+[class*="span"]{margin-left:20px;}
-input.span12, textarea.span12, .uneditable-input.span12{width:926px;}
-input.span11, textarea.span11, .uneditable-input.span11{width:846px;}
-input.span10, textarea.span10, .uneditable-input.span10{width:766px;}
-input.span9, textarea.span9, .uneditable-input.span9{width:686px;}
-input.span8, textarea.span8, .uneditable-input.span8{width:606px;}
-input.span7, textarea.span7, .uneditable-input.span7{width:526px;}
-input.span6, textarea.span6, .uneditable-input.span6{width:446px;}
-input.span5, textarea.span5, .uneditable-input.span5{width:366px;}
-input.span4, textarea.span4, .uneditable-input.span4{width:286px;}
-input.span3, textarea.span3, .uneditable-input.span3{width:206px;}
-input.span2, textarea.span2, .uneditable-input.span2{width:126px;}
-input.span1, textarea.span1, .uneditable-input.span1{width:46px;}
-.controls-row{*zoom:1;}.controls-row:before,.controls-row:after{display:table;content:"";line-height:0;}
-.controls-row:after{clear:both;}
-.controls-row [class*="span"]{float:left;}
-input[disabled],select[disabled],textarea[disabled],input[readonly],select[readonly],textarea[readonly]{cursor:not-allowed;background-color:#eeeeee;}
-input[type="radio"][disabled],input[type="checkbox"][disabled],input[type="radio"][readonly],input[type="checkbox"][readonly]{background-color:transparent;}
-.control-group.warning>label,.control-group.warning .help-block,.control-group.warning .help-inline{color:#c09853;}
-.control-group.warning .checkbox,.control-group.warning .radio,.control-group.warning input,.control-group.warning select,.control-group.warning textarea{color:#c09853;}
-.control-group.warning input,.control-group.warning select,.control-group.warning textarea{border-color:#c09853;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.warning input:focus,.control-group.warning select:focus,.control-group.warning textarea:focus{border-color:#a47e3c;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;}
-.control-group.warning .input-prepend .add-on,.control-group.warning .input-append .add-on{color:#c09853;background-color:#fcf8e3;border-color:#c09853;}
-.control-group.error>label,.control-group.error .help-block,.control-group.error .help-inline{color:#b94a48;}
-.control-group.error .checkbox,.control-group.error .radio,.control-group.error input,.control-group.error select,.control-group.error textarea{color:#b94a48;}
-.control-group.error input,.control-group.error select,.control-group.error textarea{border-color:#b94a48;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.error input:focus,.control-group.error select:focus,.control-group.error textarea:focus{border-color:#953b39;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;}
-.control-group.error .input-prepend .add-on,.control-group.error .input-append .add-on{color:#b94a48;background-color:#f2dede;border-color:#b94a48;}
-.control-group.success>label,.control-group.success .help-block,.control-group.success .help-inline{color:#468847;}
-.control-group.success .checkbox,.control-group.success .radio,.control-group.success input,.control-group.success select,.control-group.success textarea{color:#468847;}
-.control-group.success input,.control-group.success select,.control-group.success textarea{border-color:#468847;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.success input:focus,.control-group.success select:focus,.control-group.success textarea:focus{border-color:#356635;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;}
-.control-group.success .input-prepend .add-on,.control-group.success .input-append .add-on{color:#468847;background-color:#dff0d8;border-color:#468847;}
-.control-group.info>label,.control-group.info .help-block,.control-group.info .help-inline{color:#3a87ad;}
-.control-group.info .checkbox,.control-group.info .radio,.control-group.info input,.control-group.info select,.control-group.info textarea{color:#3a87ad;}
-.control-group.info input,.control-group.info select,.control-group.info textarea{border-color:#3a87ad;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);}.control-group.info input:focus,.control-group.info select:focus,.control-group.info textarea:focus{border-color:#2d6987;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3;-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3;box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7ab5d3;}
-.control-group.info .input-prepend .add-on,.control-group.info .input-append .add-on{color:#3a87ad;background-color:#d9edf7;border-color:#3a87ad;}
-input:focus:required:invalid,textarea:focus:required:invalid,select:focus:required:invalid{color:#b94a48;border-color:#ee5f5b;}input:focus:required:invalid:focus,textarea:focus:required:invalid:focus,select:focus:required:invalid:focus{border-color:#e9322d;-webkit-box-shadow:0 0 6px #f8b9b7;-moz-box-shadow:0 0 6px #f8b9b7;box-shadow:0 0 6px #f8b9b7;}
-.form-actions{padding:19px 20px 20px;margin-top:20px;margin-bottom:20px;background-color:#f5f5f5;border-top:1px solid #e5e5e5;*zoom:1;}.form-actions:before,.form-actions:after{display:table;content:"";line-height:0;}
-.form-actions:after{clear:both;}
-.help-block,.help-inline{color:#595959;}
-.help-block{display:block;margin-bottom:10px;}
-.help-inline{display:inline-block;*display:inline;*zoom:1;vertical-align:middle;padding-left:5px;}
-.input-append,.input-prepend{margin-bottom:5px;font-size:0;white-space:nowrap;}.input-append input,.input-prepend input,.input-append select,.input-prepend select,.input-append .uneditable-input,.input-prepend .uneditable-input{position:relative;margin-bottom:0;*margin-left:0;font-size:14px;vertical-align:top;-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;}.input-append input:focus,.input-prepend input:focus,.input-append select:focus,.input-prepend select:focus,.input-append .uneditable-input:focus,.input-prepend .uneditable-input:focus{z-index:2;}
-.input-append .add-on,.input-prepend .add-on{display:inline-block;width:auto;height:20px;min-width:16px;padding:4px 5px;font-size:14px;font-weight:normal;line-height:20px;text-align:center;text-shadow:0 1px 0 #ffffff;background-color:#eeeeee;border:1px solid #ccc;}
-.input-append .add-on,.input-prepend .add-on,.input-append .btn,.input-prepend .btn{vertical-align:top;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.input-append .active,.input-prepend .active{background-color:#a9dba9;border-color:#46a546;}
-.input-prepend .add-on,.input-prepend .btn{margin-right:-1px;}
-.input-prepend .add-on:first-child,.input-prepend .btn:first-child{-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;}
-.input-append input,.input-append select,.input-append .uneditable-input{-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;}
-.input-append .add-on,.input-append .btn{margin-left:-1px;}
-.input-append .add-on:last-child,.input-append .btn:last-child{-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;}
-.input-prepend.input-append input,.input-prepend.input-append select,.input-prepend.input-append .uneditable-input{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.input-prepend.input-append .add-on:first-child,.input-prepend.input-append .btn:first-child{margin-right:-1px;-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;}
-.input-prepend.input-append .add-on:last-child,.input-prepend.input-append .btn:last-child{margin-left:-1px;-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;}
-input.search-query{padding-right:14px;padding-right:4px \9;padding-left:14px;padding-left:4px \9;margin-bottom:0;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;}
-.form-search .input-append .search-query,.form-search .input-prepend .search-query{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.form-search .input-append .search-query{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;}
-.form-search .input-append .btn{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;}
-.form-search .input-prepend .search-query{-webkit-border-radius:0 14px 14px 0;-moz-border-radius:0 14px 14px 0;border-radius:0 14px 14px 0;}
-.form-search .input-prepend .btn{-webkit-border-radius:14px 0 0 14px;-moz-border-radius:14px 0 0 14px;border-radius:14px 0 0 14px;}
-.form-search input,.form-inline input,.form-horizontal input,.form-search textarea,.form-inline textarea,.form-horizontal textarea,.form-search select,.form-inline select,.form-horizontal select,.form-search .help-inline,.form-inline .help-inline,.form-horizontal .help-inline,.form-search .uneditable-input,.form-inline .uneditable-input,.form-horizontal .uneditable-input,.form-search .input-prepend,.form-inline .input-prepend,.form-horizontal .input-prepend,.form-search .input-append,.form-inline .input-append,.form-horizontal .input-append{display:inline-block;*display:inline;*zoom:1;margin-bottom:0;vertical-align:middle;}
-.form-search .hide,.form-inline .hide,.form-horizontal .hide{display:none;}
-.form-search label,.form-inline label,.form-search .btn-group,.form-inline .btn-group{display:inline-block;}
-.form-search .input-append,.form-inline .input-append,.form-search .input-prepend,.form-inline .input-prepend{margin-bottom:0;}
-.form-search .radio,.form-search .checkbox,.form-inline .radio,.form-inline .checkbox{padding-left:0;margin-bottom:0;vertical-align:middle;}
-.form-search .radio input[type="radio"],.form-search .checkbox input[type="checkbox"],.form-inline .radio input[type="radio"],.form-inline .checkbox input[type="checkbox"]{float:left;margin-right:3px;margin-left:0;}
-.control-group{margin-bottom:10px;}
-legend+.control-group{margin-top:20px;-webkit-margin-top-collapse:separate;}
-.form-horizontal .control-group{margin-bottom:20px;*zoom:1;}.form-horizontal .control-group:before,.form-horizontal .control-group:after{display:table;content:"";line-height:0;}
-.form-horizontal .control-group:after{clear:both;}
-.form-horizontal .control-label{float:left;width:160px;padding-top:5px;text-align:right;}
-.form-horizontal .controls{*display:inline-block;*padding-left:20px;margin-left:180px;*margin-left:0;}.form-horizontal .controls:first-child{*padding-left:180px;}
-.form-horizontal .help-block{margin-bottom:0;}
-.form-horizontal input+.help-block,.form-horizontal select+.help-block,.form-horizontal textarea+.help-block{margin-top:10px;}
-.form-horizontal .form-actions{padding-left:180px;}
-.btn{display:inline-block;*display:inline;*zoom:1;padding:4px 14px;margin-bottom:0;font-size:14px;line-height:20px;*line-height:20px;text-align:center;vertical-align:middle;cursor:pointer;color:#333333;text-shadow:0 1px 1px rgba(255, 255, 255, 0.75);background-color:#f5f5f5;background-image:-moz-linear-gradient(top, #ffffff, #e6e6e6);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6));background-image:-webkit-linear-gradient(top, #ffffff, #e6e6e6);background-image:-o-linear-gradient(top, #ffffff, #e6e6e6);background-image:linear-gradient(to bottom, #ffffff, #e6e6e6);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0);border-color:#e6e6e6 #e6e6e6 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e6e6e6;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);border:1px solid #bbbbbb;*border:0;border-bottom-color:#a2a2a2;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;*margin-left:.3em;-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);}.btn:hover,.btn:active,.btn.active,.btn.disabled,.btn[disabled]{color:#333333;background-color:#e6e6e6;*background-color:#d9d9d9;}
-.btn:active,.btn.active{background-color:#cccccc \9;}
-.btn:first-child{*margin-left:0;}
-.btn:hover{color:#333333;text-decoration:none;background-color:#e6e6e6;*background-color:#d9d9d9;background-position:0 -15px;-webkit-transition:background-position 0.1s linear;-moz-transition:background-position 0.1s linear;-o-transition:background-position 0.1s linear;transition:background-position 0.1s linear;}
-.btn:focus{outline:thin dotted #333;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px;}
-.btn.active,.btn:active{background-color:#e6e6e6;background-color:#d9d9d9 \9;background-image:none;outline:0;-webkit-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);}
-.btn.disabled,.btn[disabled]{cursor:default;background-color:#e6e6e6;background-image:none;opacity:0.65;filter:alpha(opacity=65);-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;}
-.btn-large{padding:9px 14px;font-size:16px;line-height:normal;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;}
-.btn-large [class^="icon-"]{margin-top:2px;}
-.btn-small{padding:3px 9px;font-size:12px;line-height:18px;}
-.btn-small [class^="icon-"]{margin-top:0;}
-.btn-mini{padding:2px 6px;font-size:11px;line-height:17px;}
-.btn-block{display:block;width:100%;padding-left:0;padding-right:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}
-.btn-block+.btn-block{margin-top:5px;}
-input[type="submit"].btn-block,input[type="reset"].btn-block,input[type="button"].btn-block{width:100%;}
-.btn-primary.active,.btn-warning.active,.btn-danger.active,.btn-success.active,.btn-info.active,.btn-inverse.active{color:rgba(255, 255, 255, 0.75);}
-.btn{border-color:#c5c5c5;border-color:rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.15) rgba(0, 0, 0, 0.25);}
-.btn-primary{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#006dcc;background-image:-moz-linear-gradient(top, #0088cc, #0044cc);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0044cc));background-image:-webkit-linear-gradient(top, #0088cc, #0044cc);background-image:-o-linear-gradient(top, #0088cc, #0044cc);background-image:linear-gradient(to bottom, #0088cc, #0044cc);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0044cc', GradientType=0);border-color:#0044cc #0044cc #002a80;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#0044cc;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-primary:hover,.btn-primary:active,.btn-primary.active,.btn-primary.disabled,.btn-primary[disabled]{color:#ffffff;background-color:#0044cc;*background-color:#003bb3;}
-.btn-primary:active,.btn-primary.active{background-color:#003399 \9;}
-.btn-warning{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);border-color:#f89406 #f89406 #ad6704;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#f89406;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-warning:hover,.btn-warning:active,.btn-warning.active,.btn-warning.disabled,.btn-warning[disabled]{color:#ffffff;background-color:#f89406;*background-color:#df8505;}
-.btn-warning:active,.btn-warning.active{background-color:#c67605 \9;}
-.btn-danger{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#da4f49;background-image:-moz-linear-gradient(top, #ee5f5b, #bd362f);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#bd362f));background-image:-webkit-linear-gradient(top, #ee5f5b, #bd362f);background-image:-o-linear-gradient(top, #ee5f5b, #bd362f);background-image:linear-gradient(to bottom, #ee5f5b, #bd362f);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffbd362f', GradientType=0);border-color:#bd362f #bd362f #802420;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#bd362f;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-danger:hover,.btn-danger:active,.btn-danger.active,.btn-danger.disabled,.btn-danger[disabled]{color:#ffffff;background-color:#bd362f;*background-color:#a9302a;}
-.btn-danger:active,.btn-danger.active{background-color:#942a25 \9;}
-.btn-success{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#5bb75b;background-image:-moz-linear-gradient(top, #62c462, #51a351);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#51a351));background-image:-webkit-linear-gradient(top, #62c462, #51a351);background-image:-o-linear-gradient(top, #62c462, #51a351);background-image:linear-gradient(to bottom, #62c462, #51a351);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff51a351', GradientType=0);border-color:#51a351 #51a351 #387038;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#51a351;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-success:hover,.btn-success:active,.btn-success.active,.btn-success.disabled,.btn-success[disabled]{color:#ffffff;background-color:#51a351;*background-color:#499249;}
-.btn-success:active,.btn-success.active{background-color:#408140 \9;}
-.btn-info{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#49afcd;background-image:-moz-linear-gradient(top, #5bc0de, #2f96b4);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#2f96b4));background-image:-webkit-linear-gradient(top, #5bc0de, #2f96b4);background-image:-o-linear-gradient(top, #5bc0de, #2f96b4);background-image:linear-gradient(to bottom, #5bc0de, #2f96b4);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2f96b4', GradientType=0);border-color:#2f96b4 #2f96b4 #1f6377;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#2f96b4;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-info:hover,.btn-info:active,.btn-info.active,.btn-info.disabled,.btn-info[disabled]{color:#ffffff;background-color:#2f96b4;*background-color:#2a85a0;}
-.btn-info:active,.btn-info.active{background-color:#24748c \9;}
-.btn-inverse{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#363636;background-image:-moz-linear-gradient(top, #444444, #222222);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#444444), to(#222222));background-image:-webkit-linear-gradient(top, #444444, #222222);background-image:-o-linear-gradient(top, #444444, #222222);background-image:linear-gradient(to bottom, #444444, #222222);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff444444', endColorstr='#ff222222', GradientType=0);border-color:#222222 #222222 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#222222;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.btn-inverse:hover,.btn-inverse:active,.btn-inverse.active,.btn-inverse.disabled,.btn-inverse[disabled]{color:#ffffff;background-color:#222222;*background-color:#151515;}
-.btn-inverse:active,.btn-inverse.active{background-color:#080808 \9;}
-button.btn,input[type="submit"].btn{*padding-top:3px;*padding-bottom:3px;}button.btn::-moz-focus-inner,input[type="submit"].btn::-moz-focus-inner{padding:0;border:0;}
-button.btn.btn-large,input[type="submit"].btn.btn-large{*padding-top:7px;*padding-bottom:7px;}
-button.btn.btn-small,input[type="submit"].btn.btn-small{*padding-top:3px;*padding-bottom:3px;}
-button.btn.btn-mini,input[type="submit"].btn.btn-mini{*padding-top:1px;*padding-bottom:1px;}
-.btn-link,.btn-link:active,.btn-link[disabled]{background-color:transparent;background-image:none;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;}
-.btn-link{border-color:transparent;cursor:pointer;color:#0088cc;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.btn-link:hover{color:#005580;text-decoration:underline;background-color:transparent;}
-.btn-link[disabled]:hover{color:#333333;text-decoration:none;}
-[class^="icon-"],[class*=" icon-"]{display:inline-block;width:14px;height:14px;*margin-right:.3em;line-height:14px;vertical-align:text-top;background-image:url("../img/glyphicons-halflings.png");background-position:14px 14px;background-repeat:no-repeat;margin-top:1px;}
-.icon-white,.nav-tabs>.active>a>[class^="icon-"],.nav-tabs>.active>a>[class*=" icon-"],.nav-pills>.active>a>[class^="icon-"],.nav-pills>.active>a>[class*=" icon-"],.nav-list>.active>a>[class^="icon-"],.nav-list>.active>a>[class*=" icon-"],.navbar-inverse .nav>.active>a>[class^="icon-"],.navbar-inverse .nav>.active>a>[class*=" icon-"],.dropdown-menu>li>a:hover>[class^="icon-"],.dropdown-menu>li>a:hover>[class*=" icon-"],.dropdown-menu>.active>a>[class^="icon-"],.dropdown-menu>.active>a>[class*=" icon-"]{background-image:url("../img/glyphicons-halflings-white.png");}
-.icon-glass{background-position:0 0;}
-.icon-music{background-position:-24px 0;}
-.icon-search{background-position:-48px 0;}
-.icon-envelope{background-position:-72px 0;}
-.icon-heart{background-position:-96px 0;}
-.icon-star{background-position:-120px 0;}
-.icon-star-empty{background-position:-144px 0;}
-.icon-user{background-position:-168px 0;}
-.icon-film{background-position:-192px 0;}
-.icon-th-large{background-position:-216px 0;}
-.icon-th{background-position:-240px 0;}
-.icon-th-list{background-position:-264px 0;}
-.icon-ok{background-position:-288px 0;}
-.icon-remove{background-position:-312px 0;}
-.icon-zoom-in{background-position:-336px 0;}
-.icon-zoom-out{background-position:-360px 0;}
-.icon-off{background-position:-384px 0;}
-.icon-signal{background-position:-408px 0;}
-.icon-cog{background-position:-432px 0;}
-.icon-trash{background-position:-456px 0;}
-.icon-home{background-position:0 -24px;}
-.icon-file{background-position:-24px -24px;}
-.icon-time{background-position:-48px -24px;}
-.icon-road{background-position:-72px -24px;}
-.icon-download-alt{background-position:-96px -24px;}
-.icon-download{background-position:-120px -24px;}
-.icon-upload{background-position:-144px -24px;}
-.icon-inbox{background-position:-168px -24px;}
-.icon-play-circle{background-position:-192px -24px;}
-.icon-repeat{background-position:-216px -24px;}
-.icon-refresh{background-position:-240px -24px;}
-.icon-list-alt{background-position:-264px -24px;}
-.icon-lock{background-position:-287px -24px;}
-.icon-flag{background-position:-312px -24px;}
-.icon-headphones{background-position:-336px -24px;}
-.icon-volume-off{background-position:-360px -24px;}
-.icon-volume-down{background-position:-384px -24px;}
-.icon-volume-up{background-position:-408px -24px;}
-.icon-qrcode{background-position:-432px -24px;}
-.icon-barcode{background-position:-456px -24px;}
-.icon-tag{background-position:0 -48px;}
-.icon-tags{background-position:-25px -48px;}
-.icon-book{background-position:-48px -48px;}
-.icon-bookmark{background-position:-72px -48px;}
-.icon-print{background-position:-96px -48px;}
-.icon-camera{background-position:-120px -48px;}
-.icon-font{background-position:-144px -48px;}
-.icon-bold{background-position:-167px -48px;}
-.icon-italic{background-position:-192px -48px;}
-.icon-text-height{background-position:-216px -48px;}
-.icon-text-width{background-position:-240px -48px;}
-.icon-align-left{background-position:-264px -48px;}
-.icon-align-center{background-position:-288px -48px;}
-.icon-align-right{background-position:-312px -48px;}
-.icon-align-justify{background-position:-336px -48px;}
-.icon-list{background-position:-360px -48px;}
-.icon-indent-left{background-position:-384px -48px;}
-.icon-indent-right{background-position:-408px -48px;}
-.icon-facetime-video{background-position:-432px -48px;}
-.icon-picture{background-position:-456px -48px;}
-.icon-pencil{background-position:0 -72px;}
-.icon-map-marker{background-position:-24px -72px;}
-.icon-adjust{background-position:-48px -72px;}
-.icon-tint{background-position:-72px -72px;}
-.icon-edit{background-position:-96px -72px;}
-.icon-share{background-position:-120px -72px;}
-.icon-check{background-position:-144px -72px;}
-.icon-move{background-position:-168px -72px;}
-.icon-step-backward{background-position:-192px -72px;}
-.icon-fast-backward{background-position:-216px -72px;}
-.icon-backward{background-position:-240px -72px;}
-.icon-play{background-position:-264px -72px;}
-.icon-pause{background-position:-288px -72px;}
-.icon-stop{background-position:-312px -72px;}
-.icon-forward{background-position:-336px -72px;}
-.icon-fast-forward{background-position:-360px -72px;}
-.icon-step-forward{background-position:-384px -72px;}
-.icon-eject{background-position:-408px -72px;}
-.icon-chevron-left{background-position:-432px -72px;}
-.icon-chevron-right{background-position:-456px -72px;}
-.icon-plus-sign{background-position:0 -96px;}
-.icon-minus-sign{background-position:-24px -96px;}
-.icon-remove-sign{background-position:-48px -96px;}
-.icon-ok-sign{background-position:-72px -96px;}
-.icon-question-sign{background-position:-96px -96px;}
-.icon-info-sign{background-position:-120px -96px;}
-.icon-screenshot{background-position:-144px -96px;}
-.icon-remove-circle{background-position:-168px -96px;}
-.icon-ok-circle{background-position:-192px -96px;}
-.icon-ban-circle{background-position:-216px -96px;}
-.icon-arrow-left{background-position:-240px -96px;}
-.icon-arrow-right{background-position:-264px -96px;}
-.icon-arrow-up{background-position:-289px -96px;}
-.icon-arrow-down{background-position:-312px -96px;}
-.icon-share-alt{background-position:-336px -96px;}
-.icon-resize-full{background-position:-360px -96px;}
-.icon-resize-small{background-position:-384px -96px;}
-.icon-plus{background-position:-408px -96px;}
-.icon-minus{background-position:-433px -96px;}
-.icon-asterisk{background-position:-456px -96px;}
-.icon-exclamation-sign{background-position:0 -120px;}
-.icon-gift{background-position:-24px -120px;}
-.icon-leaf{background-position:-48px -120px;}
-.icon-fire{background-position:-72px -120px;}
-.icon-eye-open{background-position:-96px -120px;}
-.icon-eye-close{background-position:-120px -120px;}
-.icon-warning-sign{background-position:-144px -120px;}
-.icon-plane{background-position:-168px -120px;}
-.icon-calendar{background-position:-192px -120px;}
-.icon-random{background-position:-216px -120px;width:16px;}
-.icon-comment{background-position:-240px -120px;}
-.icon-magnet{background-position:-264px -120px;}
-.icon-chevron-up{background-position:-288px -120px;}
-.icon-chevron-down{background-position:-313px -119px;}
-.icon-retweet{background-position:-336px -120px;}
-.icon-shopping-cart{background-position:-360px -120px;}
-.icon-folder-close{background-position:-384px -120px;}
-.icon-folder-open{background-position:-408px -120px;width:16px;}
-.icon-resize-vertical{background-position:-432px -119px;}
-.icon-resize-horizontal{background-position:-456px -118px;}
-.icon-hdd{background-position:0 -144px;}
-.icon-bullhorn{background-position:-24px -144px;}
-.icon-bell{background-position:-48px -144px;}
-.icon-certificate{background-position:-72px -144px;}
-.icon-thumbs-up{background-position:-96px -144px;}
-.icon-thumbs-down{background-position:-120px -144px;}
-.icon-hand-right{background-position:-144px -144px;}
-.icon-hand-left{background-position:-168px -144px;}
-.icon-hand-up{background-position:-192px -144px;}
-.icon-hand-down{background-position:-216px -144px;}
-.icon-circle-arrow-right{background-position:-240px -144px;}
-.icon-circle-arrow-left{background-position:-264px -144px;}
-.icon-circle-arrow-up{background-position:-288px -144px;}
-.icon-circle-arrow-down{background-position:-312px -144px;}
-.icon-globe{background-position:-336px -144px;}
-.icon-wrench{background-position:-360px -144px;}
-.icon-tasks{background-position:-384px -144px;}
-.icon-filter{background-position:-408px -144px;}
-.icon-briefcase{background-position:-432px -144px;}
-.icon-fullscreen{background-position:-456px -144px;}
-.btn-group{position:relative;font-size:0;vertical-align:middle;white-space:nowrap;*margin-left:.3em;}.btn-group:first-child{*margin-left:0;}
-.btn-group+.btn-group{margin-left:5px;}
-.btn-toolbar{font-size:0;margin-top:10px;margin-bottom:10px;}.btn-toolbar .btn-group{display:inline-block;*display:inline;*zoom:1;}
-.btn-toolbar .btn+.btn,.btn-toolbar .btn-group+.btn,.btn-toolbar .btn+.btn-group{margin-left:5px;}
-.btn-group>.btn{position:relative;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.btn-group>.btn+.btn{margin-left:-1px;}
-.btn-group>.btn,.btn-group>.dropdown-menu{font-size:14px;}
-.btn-group>.btn-mini{font-size:11px;}
-.btn-group>.btn-small{font-size:12px;}
-.btn-group>.btn-large{font-size:16px;}
-.btn-group>.btn:first-child{margin-left:0;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;}
-.btn-group>.btn:last-child,.btn-group>.dropdown-toggle{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;}
-.btn-group>.btn.large:first-child{margin-left:0;-webkit-border-top-left-radius:6px;-moz-border-radius-topleft:6px;border-top-left-radius:6px;-webkit-border-bottom-left-radius:6px;-moz-border-radius-bottomleft:6px;border-bottom-left-radius:6px;}
-.btn-group>.btn.large:last-child,.btn-group>.large.dropdown-toggle{-webkit-border-top-right-radius:6px;-moz-border-radius-topright:6px;border-top-right-radius:6px;-webkit-border-bottom-right-radius:6px;-moz-border-radius-bottomright:6px;border-bottom-right-radius:6px;}
-.btn-group>.btn:hover,.btn-group>.btn:focus,.btn-group>.btn:active,.btn-group>.btn.active{z-index:2;}
-.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0;}
-.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px;-webkit-box-shadow:inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 1px 0 0 rgba(255, 255, 255, 0.125), inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);*padding-top:5px;*padding-bottom:5px;}
-.btn-group>.btn-mini+.dropdown-toggle{padding-left:5px;padding-right:5px;*padding-top:2px;*padding-bottom:2px;}
-.btn-group>.btn-small+.dropdown-toggle{*padding-top:5px;*padding-bottom:4px;}
-.btn-group>.btn-large+.dropdown-toggle{padding-left:12px;padding-right:12px;*padding-top:7px;*padding-bottom:7px;}
-.btn-group.open .dropdown-toggle{background-image:none;-webkit-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:inset 0 2px 4px rgba(0, 0, 0, 0.15), 0 1px 2px rgba(0, 0, 0, 0.05);}
-.btn-group.open .btn.dropdown-toggle{background-color:#e6e6e6;}
-.btn-group.open .btn-primary.dropdown-toggle{background-color:#0044cc;}
-.btn-group.open .btn-warning.dropdown-toggle{background-color:#f89406;}
-.btn-group.open .btn-danger.dropdown-toggle{background-color:#bd362f;}
-.btn-group.open .btn-success.dropdown-toggle{background-color:#51a351;}
-.btn-group.open .btn-info.dropdown-toggle{background-color:#2f96b4;}
-.btn-group.open .btn-inverse.dropdown-toggle{background-color:#222222;}
-.btn .caret{margin-top:8px;margin-left:0;}
-.btn-mini .caret,.btn-small .caret,.btn-large .caret{margin-top:6px;}
-.btn-large .caret{border-left-width:5px;border-right-width:5px;border-top-width:5px;}
-.dropup .btn-large .caret{border-bottom:5px solid #000000;border-top:0;}
-.btn-primary .caret,.btn-warning .caret,.btn-danger .caret,.btn-info .caret,.btn-success .caret,.btn-inverse .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;}
-.btn-group-vertical{display:inline-block;*display:inline;*zoom:1;}
-.btn-group-vertical .btn{display:block;float:none;width:100%;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.btn-group-vertical .btn+.btn{margin-left:0;margin-top:-1px;}
-.btn-group-vertical .btn:first-child{-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;}
-.btn-group-vertical .btn:last-child{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;}
-.btn-group-vertical .btn-large:first-child{-webkit-border-radius:6px 6px 0 0;-moz-border-radius:6px 6px 0 0;border-radius:6px 6px 0 0;}
-.btn-group-vertical .btn-large:last-child{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;}
-.nav{margin-left:0;margin-bottom:20px;list-style:none;}
-.nav>li>a{display:block;}
-.nav>li>a:hover{text-decoration:none;background-color:#eeeeee;}
-.nav>.pull-right{float:right;}
-.nav-header{display:block;padding:3px 15px;font-size:11px;font-weight:bold;line-height:20px;color:#999999;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);text-transform:uppercase;}
-.nav li+.nav-header{margin-top:9px;}
-.nav-list{padding-left:15px;padding-right:15px;margin-bottom:0;}
-.nav-list>li>a,.nav-list .nav-header{margin-left:-15px;margin-right:-15px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);}
-.nav-list>li>a{padding:3px 15px;}
-.nav-list>.active>a,.nav-list>.active>a:hover{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.2);background-color:#0088cc;}
-.nav-list [class^="icon-"]{margin-right:2px;}
-.nav-list .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;}
-.nav-tabs,.nav-pills{*zoom:1;}.nav-tabs:before,.nav-pills:before,.nav-tabs:after,.nav-pills:after{display:table;content:"";line-height:0;}
-.nav-tabs:after,.nav-pills:after{clear:both;}
-.nav-tabs>li,.nav-pills>li{float:left;}
-.nav-tabs>li>a,.nav-pills>li>a{padding-right:12px;padding-left:12px;margin-right:2px;line-height:14px;}
-.nav-tabs{border-bottom:1px solid #ddd;}
-.nav-tabs>li{margin-bottom:-1px;}
-.nav-tabs>li>a{padding-top:8px;padding-bottom:8px;line-height:20px;border:1px solid transparent;-webkit-border-radius:4px 4px 0 0;-moz-border-radius:4px 4px 0 0;border-radius:4px 4px 0 0;}.nav-tabs>li>a:hover{border-color:#eeeeee #eeeeee #dddddd;}
-.nav-tabs>.active>a,.nav-tabs>.active>a:hover{color:#555555;background-color:#ffffff;border:1px solid #ddd;border-bottom-color:transparent;cursor:default;}
-.nav-pills>li>a{padding-top:8px;padding-bottom:8px;margin-top:2px;margin-bottom:2px;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;}
-.nav-pills>.active>a,.nav-pills>.active>a:hover{color:#ffffff;background-color:#0088cc;}
-.nav-stacked>li{float:none;}
-.nav-stacked>li>a{margin-right:0;}
-.nav-tabs.nav-stacked{border-bottom:0;}
-.nav-tabs.nav-stacked>li>a{border:1px solid #ddd;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.nav-tabs.nav-stacked>li:first-child>a{-webkit-border-top-right-radius:4px;-moz-border-radius-topright:4px;border-top-right-radius:4px;-webkit-border-top-left-radius:4px;-moz-border-radius-topleft:4px;border-top-left-radius:4px;}
-.nav-tabs.nav-stacked>li:last-child>a{-webkit-border-bottom-right-radius:4px;-moz-border-radius-bottomright:4px;border-bottom-right-radius:4px;-webkit-border-bottom-left-radius:4px;-moz-border-radius-bottomleft:4px;border-bottom-left-radius:4px;}
-.nav-tabs.nav-stacked>li>a:hover{border-color:#ddd;z-index:2;}
-.nav-pills.nav-stacked>li>a{margin-bottom:3px;}
-.nav-pills.nav-stacked>li:last-child>a{margin-bottom:1px;}
-.nav-tabs .dropdown-menu{-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;}
-.nav-pills .dropdown-menu{-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}
-.nav .dropdown-toggle .caret{border-top-color:#0088cc;border-bottom-color:#0088cc;margin-top:6px;}
-.nav .dropdown-toggle:hover .caret{border-top-color:#005580;border-bottom-color:#005580;}
-.nav-tabs .dropdown-toggle .caret{margin-top:8px;}
-.nav .active .dropdown-toggle .caret{border-top-color:#fff;border-bottom-color:#fff;}
-.nav-tabs .active .dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;}
-.nav>.dropdown.active>a:hover{cursor:pointer;}
-.nav-tabs .open .dropdown-toggle,.nav-pills .open .dropdown-toggle,.nav>li.dropdown.open.active>a:hover{color:#ffffff;background-color:#999999;border-color:#999999;}
-.nav li.dropdown.open .caret,.nav li.dropdown.open.active .caret,.nav li.dropdown.open a:hover .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;opacity:1;filter:alpha(opacity=100);}
-.tabs-stacked .open>a:hover{border-color:#999999;}
-.tabbable{*zoom:1;}.tabbable:before,.tabbable:after{display:table;content:"";line-height:0;}
-.tabbable:after{clear:both;}
-.tab-content{overflow:auto;}
-.tabs-below>.nav-tabs,.tabs-right>.nav-tabs,.tabs-left>.nav-tabs{border-bottom:0;}
-.tab-content>.tab-pane,.pill-content>.pill-pane{display:none;}
-.tab-content>.active,.pill-content>.active{display:block;}
-.tabs-below>.nav-tabs{border-top:1px solid #ddd;}
-.tabs-below>.nav-tabs>li{margin-top:-1px;margin-bottom:0;}
-.tabs-below>.nav-tabs>li>a{-webkit-border-radius:0 0 4px 4px;-moz-border-radius:0 0 4px 4px;border-radius:0 0 4px 4px;}.tabs-below>.nav-tabs>li>a:hover{border-bottom-color:transparent;border-top-color:#ddd;}
-.tabs-below>.nav-tabs>.active>a,.tabs-below>.nav-tabs>.active>a:hover{border-color:transparent #ddd #ddd #ddd;}
-.tabs-left>.nav-tabs>li,.tabs-right>.nav-tabs>li{float:none;}
-.tabs-left>.nav-tabs>li>a,.tabs-right>.nav-tabs>li>a{min-width:74px;margin-right:0;margin-bottom:3px;}
-.tabs-left>.nav-tabs{float:left;margin-right:19px;border-right:1px solid #ddd;}
-.tabs-left>.nav-tabs>li>a{margin-right:-1px;-webkit-border-radius:4px 0 0 4px;-moz-border-radius:4px 0 0 4px;border-radius:4px 0 0 4px;}
-.tabs-left>.nav-tabs>li>a:hover{border-color:#eeeeee #dddddd #eeeeee #eeeeee;}
-.tabs-left>.nav-tabs .active>a,.tabs-left>.nav-tabs .active>a:hover{border-color:#ddd transparent #ddd #ddd;*border-right-color:#ffffff;}
-.tabs-right>.nav-tabs{float:right;margin-left:19px;border-left:1px solid #ddd;}
-.tabs-right>.nav-tabs>li>a{margin-left:-1px;-webkit-border-radius:0 4px 4px 0;-moz-border-radius:0 4px 4px 0;border-radius:0 4px 4px 0;}
-.tabs-right>.nav-tabs>li>a:hover{border-color:#eeeeee #eeeeee #eeeeee #dddddd;}
-.tabs-right>.nav-tabs .active>a,.tabs-right>.nav-tabs .active>a:hover{border-color:#ddd #ddd #ddd transparent;*border-left-color:#ffffff;}
-.nav>.disabled>a{color:#999999;}
-.nav>.disabled>a:hover{text-decoration:none;background-color:transparent;cursor:default;}
-.navbar{overflow:visible;margin-bottom:20px;color:#777777;*position:relative;*z-index:2;}
-.navbar-inner{min-height:40px;padding-left:20px;padding-right:20px;background-color:#fafafa;background-image:-moz-linear-gradient(top, #ffffff, #f2f2f2);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#f2f2f2));background-image:-webkit-linear-gradient(top, #ffffff, #f2f2f2);background-image:-o-linear-gradient(top, #ffffff, #f2f2f2);background-image:linear-gradient(to bottom, #ffffff, #f2f2f2);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff2f2f2', GradientType=0);border:1px solid #d4d4d4;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);-moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);box-shadow:0 1px 4px rgba(0, 0, 0, 0.065);*zoom:1;}.navbar-inner:before,.navbar-inner:after{display:table;content:"";line-height:0;}
-.navbar-inner:after{clear:both;}
-.navbar .container{width:auto;}
-.nav-collapse.collapse{height:auto;}
-.navbar .brand{float:left;display:block;padding:10px 20px 10px;margin-left:-20px;font-size:20px;font-weight:200;color:#777777;text-shadow:0 1px 0 #ffffff;}.navbar .brand:hover{text-decoration:none;}
-.navbar-text{margin-bottom:0;line-height:40px;}
-.navbar-link{color:#777777;}.navbar-link:hover{color:#333333;}
-.navbar .divider-vertical{height:40px;margin:0 9px;border-left:1px solid #f2f2f2;border-right:1px solid #ffffff;}
-.navbar .btn,.navbar .btn-group{margin-top:5px;}
-.navbar .btn-group .btn,.navbar .input-prepend .btn,.navbar .input-append .btn{margin-top:0;}
-.navbar-form{margin-bottom:0;*zoom:1;}.navbar-form:before,.navbar-form:after{display:table;content:"";line-height:0;}
-.navbar-form:after{clear:both;}
-.navbar-form input,.navbar-form select,.navbar-form .radio,.navbar-form .checkbox{margin-top:5px;}
-.navbar-form input,.navbar-form select,.navbar-form .btn{display:inline-block;margin-bottom:0;}
-.navbar-form input[type="image"],.navbar-form input[type="checkbox"],.navbar-form input[type="radio"]{margin-top:3px;}
-.navbar-form .input-append,.navbar-form .input-prepend{margin-top:6px;white-space:nowrap;}.navbar-form .input-append input,.navbar-form .input-prepend input{margin-top:0;}
-.navbar-search{position:relative;float:left;margin-top:5px;margin-bottom:0;}.navbar-search .search-query{margin-bottom:0;padding:4px 14px;font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:13px;font-weight:normal;line-height:1;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;}
-.navbar-static-top{position:static;width:100%;margin-bottom:0;}.navbar-static-top .navbar-inner{-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;margin-bottom:0;}
-.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{border-width:0 0 1px;}
-.navbar-fixed-bottom .navbar-inner{border-width:1px 0 0;}
-.navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding-left:0;padding-right:0;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;}
-.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:940px;}
-.navbar-fixed-top{top:0;}
-.navbar-fixed-top .navbar-inner,.navbar-static-top .navbar-inner{-webkit-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1);box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.1), 0 1px 10px rgba(0, 0, 0, 0.1);}
-.navbar-fixed-bottom{bottom:0;}.navbar-fixed-bottom .navbar-inner{-webkit-box-shadow:inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1);box-shadow:inset 0 1px 0 rgba(0, 0, 0, 0.1), 0 -1px 10px rgba(0, 0, 0, 0.1);}
-.navbar .nav{position:relative;left:0;display:block;float:left;margin:0 10px 0 0;}
-.navbar .nav.pull-right{float:right;margin-right:0;}
-.navbar .nav>li{float:left;}
-.navbar .nav>li>a{float:none;padding:10px 15px 10px;color:#777777;text-decoration:none;text-shadow:0 1px 0 #ffffff;}
-.navbar .nav .dropdown-toggle .caret{margin-top:8px;}
-.navbar .nav>li>a:focus,.navbar .nav>li>a:hover{background-color:transparent;color:#333333;text-decoration:none;}
-.navbar .nav>.active>a,.navbar .nav>.active>a:hover,.navbar .nav>.active>a:focus{color:#555555;text-decoration:none;background-color:#e5e5e5;-webkit-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);-moz-box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);box-shadow:inset 0 3px 8px rgba(0, 0, 0, 0.125);}
-.navbar .btn-navbar{display:none;float:right;padding:7px 10px;margin-left:5px;margin-right:5px;color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#ededed;background-image:-moz-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f2f2f2), to(#e5e5e5));background-image:-webkit-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:-o-linear-gradient(top, #f2f2f2, #e5e5e5);background-image:linear-gradient(to bottom, #f2f2f2, #e5e5e5);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2f2f2', endColorstr='#ffe5e5e5', GradientType=0);border-color:#e5e5e5 #e5e5e5 #bfbfbf;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#e5e5e5;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.075);}.navbar .btn-navbar:hover,.navbar .btn-navbar:active,.navbar .btn-navbar.active,.navbar .btn-navbar.disabled,.navbar .btn-navbar[disabled]{color:#ffffff;background-color:#e5e5e5;*background-color:#d9d9d9;}
-.navbar .btn-navbar:active,.navbar .btn-navbar.active{background-color:#cccccc \9;}
-.navbar .btn-navbar .icon-bar{display:block;width:18px;height:2px;background-color:#f5f5f5;-webkit-border-radius:1px;-moz-border-radius:1px;border-radius:1px;-webkit-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);-moz-box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);box-shadow:0 1px 0 rgba(0, 0, 0, 0.25);}
-.btn-navbar .icon-bar+.icon-bar{margin-top:3px;}
-.navbar .nav>li>.dropdown-menu:before{content:'';display:inline-block;border-left:7px solid transparent;border-right:7px solid transparent;border-bottom:7px solid #ccc;border-bottom-color:rgba(0, 0, 0, 0.2);position:absolute;top:-7px;left:9px;}
-.navbar .nav>li>.dropdown-menu:after{content:'';display:inline-block;border-left:6px solid transparent;border-right:6px solid transparent;border-bottom:6px solid #ffffff;position:absolute;top:-6px;left:10px;}
-.navbar-fixed-bottom .nav>li>.dropdown-menu:before{border-top:7px solid #ccc;border-top-color:rgba(0, 0, 0, 0.2);border-bottom:0;bottom:-7px;top:auto;}
-.navbar-fixed-bottom .nav>li>.dropdown-menu:after{border-top:6px solid #ffffff;border-bottom:0;bottom:-6px;top:auto;}
-.navbar .nav li.dropdown.open>.dropdown-toggle,.navbar .nav li.dropdown.active>.dropdown-toggle,.navbar .nav li.dropdown.open.active>.dropdown-toggle{background-color:#e5e5e5;color:#555555;}
-.navbar .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#777777;border-bottom-color:#777777;}
-.navbar .nav li.dropdown.open>.dropdown-toggle .caret,.navbar .nav li.dropdown.active>.dropdown-toggle .caret,.navbar .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#555555;border-bottom-color:#555555;}
-.navbar .pull-right>li>.dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right{left:auto;right:0;}.navbar .pull-right>li>.dropdown-menu:before,.navbar .nav>li>.dropdown-menu.pull-right:before{left:auto;right:12px;}
-.navbar .pull-right>li>.dropdown-menu:after,.navbar .nav>li>.dropdown-menu.pull-right:after{left:auto;right:13px;}
-.navbar .pull-right>li>.dropdown-menu .dropdown-menu,.navbar .nav>li>.dropdown-menu.pull-right .dropdown-menu{left:auto;right:100%;margin-left:0;margin-right:-1px;-webkit-border-radius:6px 0 6px 6px;-moz-border-radius:6px 0 6px 6px;border-radius:6px 0 6px 6px;}
-.navbar-inverse{color:#999999;}.navbar-inverse .navbar-inner{background-color:#1b1b1b;background-image:-moz-linear-gradient(top, #222222, #111111);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#222222), to(#111111));background-image:-webkit-linear-gradient(top, #222222, #111111);background-image:-o-linear-gradient(top, #222222, #111111);background-image:linear-gradient(to bottom, #222222, #111111);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff111111', GradientType=0);border-color:#252525;}
-.navbar-inverse .brand,.navbar-inverse .nav>li>a{color:#999999;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);}.navbar-inverse .brand:hover,.navbar-inverse .nav>li>a:hover{color:#ffffff;}
-.navbar-inverse .nav>li>a:focus,.navbar-inverse .nav>li>a:hover{background-color:transparent;color:#ffffff;}
-.navbar-inverse .nav .active>a,.navbar-inverse .nav .active>a:hover,.navbar-inverse .nav .active>a:focus{color:#ffffff;background-color:#111111;}
-.navbar-inverse .navbar-link{color:#999999;}.navbar-inverse .navbar-link:hover{color:#ffffff;}
-.navbar-inverse .divider-vertical{border-left-color:#111111;border-right-color:#222222;}
-.navbar-inverse .nav li.dropdown.open>.dropdown-toggle,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle{background-color:#111111;color:#ffffff;}
-.navbar-inverse .nav li.dropdown>.dropdown-toggle .caret{border-top-color:#999999;border-bottom-color:#999999;}
-.navbar-inverse .nav li.dropdown.open>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.active>.dropdown-toggle .caret,.navbar-inverse .nav li.dropdown.open.active>.dropdown-toggle .caret{border-top-color:#ffffff;border-bottom-color:#ffffff;}
-.navbar-inverse .navbar-search .search-query{color:#ffffff;background-color:#515151;border-color:#111111;-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1), 0 1px 0 rgba(255, 255, 255, 0.15);-webkit-transition:none;-moz-transition:none;-o-transition:none;transition:none;}.navbar-inverse .navbar-search .search-query:-moz-placeholder{color:#cccccc;}
-.navbar-inverse .navbar-search .search-query:-ms-input-placeholder{color:#cccccc;}
-.navbar-inverse .navbar-search .search-query::-webkit-input-placeholder{color:#cccccc;}
-.navbar-inverse .navbar-search .search-query:focus,.navbar-inverse .navbar-search .search-query.focused{padding:5px 15px;color:#333333;text-shadow:0 1px 0 #ffffff;background-color:#ffffff;border:0;-webkit-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);-moz-box-shadow:0 0 3px rgba(0, 0, 0, 0.15);box-shadow:0 0 3px rgba(0, 0, 0, 0.15);outline:0;}
-.navbar-inverse .btn-navbar{color:#ffffff;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e0e0e;background-image:-moz-linear-gradient(top, #151515, #040404);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#151515), to(#040404));background-image:-webkit-linear-gradient(top, #151515, #040404);background-image:-o-linear-gradient(top, #151515, #040404);background-image:linear-gradient(to bottom, #151515, #040404);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff151515', endColorstr='#ff040404', GradientType=0);border-color:#040404 #040404 #000000;border-color:rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);*background-color:#040404;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);}.navbar-inverse .btn-navbar:hover,.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active,.navbar-inverse .btn-navbar.disabled,.navbar-inverse .btn-navbar[disabled]{color:#ffffff;background-color:#040404;*background-color:#000000;}
-.navbar-inverse .btn-navbar:active,.navbar-inverse .btn-navbar.active{background-color:#000000 \9;}
-.breadcrumb{padding:8px 15px;margin:0 0 20px;list-style:none;background-color:#f5f5f5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}.breadcrumb li{display:inline-block;*display:inline;*zoom:1;text-shadow:0 1px 0 #ffffff;}
-.breadcrumb .divider{padding:0 5px;color:#ccc;}
-.breadcrumb .active{color:#999999;}
-.pagination{height:40px;margin:20px 0;}
-.pagination ul{display:inline-block;*display:inline;*zoom:1;margin-left:0;margin-bottom:0;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);-moz-box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);box-shadow:0 1px 2px rgba(0, 0, 0, 0.05);}
-.pagination ul>li{display:inline;}
-.pagination ul>li>a,.pagination ul>li>span{float:left;padding:0 14px;line-height:38px;text-decoration:none;background-color:#ffffff;border:1px solid #dddddd;border-left-width:0;}
-.pagination ul>li>a:hover,.pagination ul>.active>a,.pagination ul>.active>span{background-color:#f5f5f5;}
-.pagination ul>.active>a,.pagination ul>.active>span{color:#999999;cursor:default;}
-.pagination ul>.disabled>span,.pagination ul>.disabled>a,.pagination ul>.disabled>a:hover{color:#999999;background-color:transparent;cursor:default;}
-.pagination ul>li:first-child>a,.pagination ul>li:first-child>span{border-left-width:1px;-webkit-border-radius:3px 0 0 3px;-moz-border-radius:3px 0 0 3px;border-radius:3px 0 0 3px;}
-.pagination ul>li:last-child>a,.pagination ul>li:last-child>span{-webkit-border-radius:0 3px 3px 0;-moz-border-radius:0 3px 3px 0;border-radius:0 3px 3px 0;}
-.pagination-centered{text-align:center;}
-.pagination-right{text-align:right;}
-.pager{margin:20px 0;list-style:none;text-align:center;*zoom:1;}.pager:before,.pager:after{display:table;content:"";line-height:0;}
-.pager:after{clear:both;}
-.pager li{display:inline;}
-.pager a,.pager span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;-webkit-border-radius:15px;-moz-border-radius:15px;border-radius:15px;}
-.pager a:hover{text-decoration:none;background-color:#f5f5f5;}
-.pager .next a,.pager .next span{float:right;}
-.pager .previous a{float:left;}
-.pager .disabled a,.pager .disabled a:hover,.pager .disabled span{color:#999999;background-color:#fff;cursor:default;}
-.thumbnails{margin-left:-20px;list-style:none;*zoom:1;}.thumbnails:before,.thumbnails:after{display:table;content:"";line-height:0;}
-.thumbnails:after{clear:both;}
-.row-fluid .thumbnails{margin-left:0;}
-.thumbnails>li{float:left;margin-bottom:20px;margin-left:20px;}
-.thumbnail{display:block;padding:4px;line-height:20px;border:1px solid #ddd;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-moz-box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);box-shadow:0 1px 3px rgba(0, 0, 0, 0.055);-webkit-transition:all 0.2s ease-in-out;-moz-transition:all 0.2s ease-in-out;-o-transition:all 0.2s ease-in-out;transition:all 0.2s ease-in-out;}
-a.thumbnail:hover{border-color:#0088cc;-webkit-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);-moz-box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);box-shadow:0 1px 4px rgba(0, 105, 214, 0.25);}
-.thumbnail>img{display:block;max-width:100%;margin-left:auto;margin-right:auto;}
-.thumbnail .caption{padding:9px;color:#555555;}
-.alert{padding:8px 35px 8px 14px;margin-bottom:20px;text-shadow:0 1px 0 rgba(255, 255, 255, 0.5);background-color:#fcf8e3;border:1px solid #fbeed5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;color:#c09853;}
-.alert h4{margin:0;}
-.alert .close{position:relative;top:-2px;right:-21px;line-height:20px;}
-.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#468847;}
-.alert-danger,.alert-error{background-color:#f2dede;border-color:#eed3d7;color:#b94a48;}
-.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#3a87ad;}
-.alert-block{padding-top:14px;padding-bottom:14px;}
-.alert-block>p,.alert-block>ul{margin-bottom:0;}
-.alert-block p+p{margin-top:5px;}
-@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-moz-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-ms-keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}@-o-keyframes progress-bar-stripes{from{background-position:0 0;} to{background-position:40px 0;}}@keyframes progress-bar-stripes{from{background-position:40px 0;} to{background-position:0 0;}}.progress{overflow:hidden;height:20px;margin-bottom:20px;background-color:#f7f7f7;background-image:-moz-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#f5f5f5), to(#f9f9f9));background-image:-webkit-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:-o-linear-gradient(top, #f5f5f5, #f9f9f9);background-image:linear-gradient(to bottom, #f5f5f5, #f9f9f9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#fff9f9f9', GradientType=0);-webkit-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-moz-box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);box-shadow:inset 0 1px 2px rgba(0, 0, 0, 0.1);-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
-.progress .bar{width:0%;height:100%;color:#ffffff;float:left;font-size:12px;text-align:center;text-shadow:0 -1px 0 rgba(0, 0, 0, 0.25);background-color:#0e90d2;background-image:-moz-linear-gradient(top, #149bdf, #0480be);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#149bdf), to(#0480be));background-image:-webkit-linear-gradient(top, #149bdf, #0480be);background-image:-o-linear-gradient(top, #149bdf, #0480be);background-image:linear-gradient(to bottom, #149bdf, #0480be);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff149bdf', endColorstr='#ff0480be', GradientType=0);-webkit-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-moz-box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);box-shadow:inset 0 -1px 0 rgba(0, 0, 0, 0.15);-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;-webkit-transition:width 0.6s ease;-moz-transition:width 0.6s ease;-o-transition:width 0.6s ease;transition:width 0.6s ease;}
-.progress .bar+.bar{-webkit-box-shadow:inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15);-moz-box-shadow:inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15);box-shadow:inset 1px 0 0 rgba(0, 0, 0, 0.15), inset 0 -1px 0 rgba(0, 0, 0, 0.15);}
-.progress-striped .bar{background-color:#149bdf;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);-webkit-background-size:40px 40px;-moz-background-size:40px 40px;-o-background-size:40px 40px;background-size:40px 40px;}
-.progress.active .bar{-webkit-animation:progress-bar-stripes 2s linear infinite;-moz-animation:progress-bar-stripes 2s linear infinite;-ms-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite;}
-.progress-danger .bar,.progress .bar-danger{background-color:#dd514c;background-image:-moz-linear-gradient(top, #ee5f5b, #c43c35);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#ee5f5b), to(#c43c35));background-image:-webkit-linear-gradient(top, #ee5f5b, #c43c35);background-image:-o-linear-gradient(top, #ee5f5b, #c43c35);background-image:linear-gradient(to bottom, #ee5f5b, #c43c35);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffee5f5b', endColorstr='#ffc43c35', GradientType=0);}
-.progress-danger.progress-striped .bar,.progress-striped .bar-danger{background-color:#ee5f5b;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);}
-.progress-success .bar,.progress .bar-success{background-color:#5eb95e;background-image:-moz-linear-gradient(top, #62c462, #57a957);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#62c462), to(#57a957));background-image:-webkit-linear-gradient(top, #62c462, #57a957);background-image:-o-linear-gradient(top, #62c462, #57a957);background-image:linear-gradient(to bottom, #62c462, #57a957);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff62c462', endColorstr='#ff57a957', GradientType=0);}
-.progress-success.progress-striped .bar,.progress-striped .bar-success{background-color:#62c462;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);}
-.progress-info .bar,.progress .bar-info{background-color:#4bb1cf;background-image:-moz-linear-gradient(top, #5bc0de, #339bb9);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#5bc0de), to(#339bb9));background-image:-webkit-linear-gradient(top, #5bc0de, #339bb9);background-image:-o-linear-gradient(top, #5bc0de, #339bb9);background-image:linear-gradient(to bottom, #5bc0de, #339bb9);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff339bb9', GradientType=0);}
-.progress-info.progress-striped .bar,.progress-striped .bar-info{background-color:#5bc0de;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);}
-.progress-warning .bar,.progress .bar-warning{background-color:#faa732;background-image:-moz-linear-gradient(top, #fbb450, #f89406);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#fbb450), to(#f89406));background-image:-webkit-linear-gradient(top, #fbb450, #f89406);background-image:-o-linear-gradient(top, #fbb450, #f89406);background-image:linear-gradient(to bottom, #fbb450, #f89406);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffbb450', endColorstr='#fff89406', GradientType=0);}
-.progress-warning.progress-striped .bar,.progress-striped .bar-warning{background-color:#fbb450;background-image:-webkit-gradient(linear, 0 100%, 100% 0, color-stop(0.25, rgba(255, 255, 255, 0.15)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.15)), color-stop(0.75, rgba(255, 255, 255, 0.15)), color-stop(0.75, transparent), to(transparent));background-image:-webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-moz-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:-o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);background-image:linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);}
-.hero-unit{padding:60px;margin-bottom:30px;background-color:#eeeeee;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}.hero-unit h1{margin-bottom:0;font-size:60px;line-height:1;color:inherit;letter-spacing:-1px;}
-.hero-unit p{font-size:18px;font-weight:200;line-height:30px;color:inherit;}
-.tooltip{position:absolute;z-index:1030;display:block;visibility:visible;padding:5px;font-size:11px;opacity:0;filter:alpha(opacity=0);}.tooltip.in{opacity:0.8;filter:alpha(opacity=80);}
-.tooltip.top{margin-top:-3px;}
-.tooltip.right{margin-left:3px;}
-.tooltip.bottom{margin-top:3px;}
-.tooltip.left{margin-left:-3px;}
-.tooltip-inner{max-width:200px;padding:3px 8px;color:#ffffff;text-align:center;text-decoration:none;background-color:#000000;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
-.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid;}
-.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000000;}
-.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000000;}
-.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000000;}
-.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000000;}
-.popover{position:absolute;top:0;left:0;z-index:1010;display:none;width:236px;padding:1px;background-color:#ffffff;-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);}.popover.top{margin-bottom:10px;}
-.popover.right{margin-left:10px;}
-.popover.bottom{margin-top:10px;}
-.popover.left{margin-right:10px;}
-.popover-title{margin:0;padding:8px 14px;font-size:14px;font-weight:normal;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;-webkit-border-radius:5px 5px 0 0;-moz-border-radius:5px 5px 0 0;border-radius:5px 5px 0 0;}
-.popover-content{padding:9px 14px;}.popover-content p,.popover-content ul,.popover-content ol{margin-bottom:0;}
-.popover .arrow,.popover .arrow:after{position:absolute;display:inline-block;width:0;height:0;border-color:transparent;border-style:solid;}
-.popover .arrow:after{content:"";z-index:-1;}
-.popover.top .arrow{bottom:-10px;left:50%;margin-left:-10px;border-width:10px 10px 0;border-top-color:#ffffff;}.popover.top .arrow:after{border-width:11px 11px 0;border-top-color:rgba(0, 0, 0, 0.25);bottom:-1px;left:-11px;}
-.popover.right .arrow{top:50%;left:-10px;margin-top:-10px;border-width:10px 10px 10px 0;border-right-color:#ffffff;}.popover.right .arrow:after{border-width:11px 11px 11px 0;border-right-color:rgba(0, 0, 0, 0.25);bottom:-11px;left:-1px;}
-.popover.bottom .arrow{top:-10px;left:50%;margin-left:-10px;border-width:0 10px 10px;border-bottom-color:#ffffff;}.popover.bottom .arrow:after{border-width:0 11px 11px;border-bottom-color:rgba(0, 0, 0, 0.25);top:-1px;left:-11px;}
-.popover.left .arrow{top:50%;right:-10px;margin-top:-10px;border-width:10px 0 10px 10px;border-left-color:#ffffff;}.popover.left .arrow:after{border-width:11px 0 11px 11px;border-left-color:rgba(0, 0, 0, 0.25);bottom:-11px;right:-1px;}
-.modal-open .modal .dropdown-menu{z-index:2050;}
-.modal-open .modal .dropdown.open{*z-index:2050;}
-.modal-open .modal .popover{z-index:2060;}
-.modal-open .modal .tooltip{z-index:2080;}
-.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000000;}.modal-backdrop.fade{opacity:0;}
-.modal-backdrop,.modal-backdrop.fade.in{opacity:0.8;filter:alpha(opacity=80);}
-.modal{position:fixed;top:50%;left:50%;z-index:1050;overflow:auto;width:560px;margin:-250px 0 0 -280px;background-color:#ffffff;border:1px solid #999;border:1px solid rgba(0, 0, 0, 0.3);*border:1px solid #999;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-moz-box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);box-shadow:0 3px 7px rgba(0, 0, 0, 0.3);-webkit-background-clip:padding-box;-moz-background-clip:padding-box;background-clip:padding-box;}.modal.fade{-webkit-transition:opacity .3s linear, top .3s ease-out;-moz-transition:opacity .3s linear, top .3s ease-out;-o-transition:opacity .3s linear, top .3s ease-out;transition:opacity .3s linear, top .3s ease-out;top:-25%;}
-.modal.fade.in{top:50%;}
-.modal-header{padding:9px 15px;border-bottom:1px solid #eee;}.modal-header .close{margin-top:2px;}
-.modal-header h3{margin:0;line-height:30px;}
-.modal-body{overflow-y:auto;max-height:400px;padding:15px;}
-.modal-form{margin-bottom:0;}
-.modal-footer{padding:14px 15px 15px;margin-bottom:0;text-align:right;background-color:#f5f5f5;border-top:1px solid #ddd;-webkit-border-radius:0 0 6px 6px;-moz-border-radius:0 0 6px 6px;border-radius:0 0 6px 6px;-webkit-box-shadow:inset 0 1px 0 #ffffff;-moz-box-shadow:inset 0 1px 0 #ffffff;box-shadow:inset 0 1px 0 #ffffff;*zoom:1;}.modal-footer:before,.modal-footer:after{display:table;content:"";line-height:0;}
-.modal-footer:after{clear:both;}
-.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0;}
-.modal-footer .btn-group .btn+.btn{margin-left:-1px;}
-.dropup,.dropdown{position:relative;}
-.dropdown-toggle{*margin-bottom:-3px;}
-.dropdown-toggle:active,.open .dropdown-toggle{outline:0;}
-.caret{display:inline-block;width:0;height:0;vertical-align:top;border-top:4px solid #000000;border-right:4px solid transparent;border-left:4px solid transparent;content:"";}
-.dropdown .caret{margin-top:8px;margin-left:2px;}
-.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;background-color:#ffffff;border:1px solid #ccc;border:1px solid rgba(0, 0, 0, 0.2);*border-right-width:2px;*border-bottom-width:2px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-moz-box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);box-shadow:0 5px 10px rgba(0, 0, 0, 0.2);-webkit-background-clip:padding-box;-moz-background-clip:padding;background-clip:padding-box;}.dropdown-menu.pull-right{right:0;left:auto;}
-.dropdown-menu .divider{*width:100%;height:1px;margin:9px 1px;*margin:-5px 0 5px;overflow:hidden;background-color:#e5e5e5;border-bottom:1px solid #ffffff;}
-.dropdown-menu a{display:block;padding:3px 20px;clear:both;font-weight:normal;line-height:20px;color:#333333;white-space:nowrap;}
-.dropdown-menu li>a:hover,.dropdown-menu li>a:focus,.dropdown-submenu:hover>a{text-decoration:none;color:#ffffff;background-color:#0088cc;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);}
-.dropdown-menu .active>a,.dropdown-menu .active>a:hover{color:#ffffff;text-decoration:none;outline:0;background-color:#0088cc;background-color:#0081c2;background-image:-moz-linear-gradient(top, #0088cc, #0077b3);background-image:-webkit-gradient(linear, 0 0, 0 100%, from(#0088cc), to(#0077b3));background-image:-webkit-linear-gradient(top, #0088cc, #0077b3);background-image:-o-linear-gradient(top, #0088cc, #0077b3);background-image:linear-gradient(to bottom, #0088cc, #0077b3);background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff0088cc', endColorstr='#ff0077b3', GradientType=0);}
-.dropdown-menu .disabled>a,.dropdown-menu .disabled>a:hover{color:#999999;}
-.dropdown-menu .disabled>a:hover{text-decoration:none;background-color:transparent;cursor:default;}
-.open{*z-index:1000;}.open >.dropdown-menu{display:block;}
-.pull-right>.dropdown-menu{right:0;left:auto;}
-.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px solid #000000;content:"";}
-.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px;}
-.dropdown-submenu{position:relative;}
-.dropdown-submenu>.dropdown-menu{top:0;left:100%;margin-top:-6px;margin-left:-1px;-webkit-border-radius:0 6px 6px 6px;-moz-border-radius:0 6px 6px 6px;border-radius:0 6px 6px 6px;}
-.dropdown-submenu:hover>.dropdown-menu{display:block;}
-.dropdown-submenu>a:after{display:block;content:" ";float:right;width:0;height:0;border-color:transparent;border-style:solid;border-width:5px 0 5px 5px;border-left-color:#cccccc;margin-top:5px;margin-right:-10px;}
-.dropdown-submenu:hover>a:after{border-left-color:#ffffff;}
-.dropdown .dropdown-menu .nav-header{padding-left:20px;padding-right:20px;}
-.typeahead{margin-top:2px;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
-.accordion{margin-bottom:20px;}
-.accordion-group{margin-bottom:2px;border:1px solid #e5e5e5;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;}
-.accordion-heading{border-bottom:0;}
-.accordion-heading .accordion-toggle{display:block;padding:8px 15px;}
-.accordion-toggle{cursor:pointer;}
-.accordion-inner{padding:9px 15px;border-top:1px solid #e5e5e5;}
-.carousel{position:relative;margin-bottom:20px;line-height:1;}
-.carousel-inner{overflow:hidden;width:100%;position:relative;}
-.carousel .item{display:none;position:relative;-webkit-transition:0.6s ease-in-out left;-moz-transition:0.6s ease-in-out left;-o-transition:0.6s ease-in-out left;transition:0.6s ease-in-out left;}
-.carousel .item>img{display:block;line-height:1;}
-.carousel .active,.carousel .next,.carousel .prev{display:block;}
-.carousel .active{left:0;}
-.carousel .next,.carousel .prev{position:absolute;top:0;width:100%;}
-.carousel .next{left:100%;}
-.carousel .prev{left:-100%;}
-.carousel .next.left,.carousel .prev.right{left:0;}
-.carousel .active.left{left:-100%;}
-.carousel .active.right{left:100%;}
-.carousel-control{position:absolute;top:40%;left:15px;width:40px;height:40px;margin-top:-20px;font-size:60px;font-weight:100;line-height:30px;color:#ffffff;text-align:center;background:#222222;border:3px solid #ffffff;-webkit-border-radius:23px;-moz-border-radius:23px;border-radius:23px;opacity:0.5;filter:alpha(opacity=50);}.carousel-control.right{left:auto;right:15px;}
-.carousel-control:hover{color:#ffffff;text-decoration:none;opacity:0.9;filter:alpha(opacity=90);}
-.carousel-caption{position:absolute;left:0;right:0;bottom:0;padding:15px;background:#333333;background:rgba(0, 0, 0, 0.75);}
-.carousel-caption h4,.carousel-caption p{color:#ffffff;line-height:20px;}
-.carousel-caption h4{margin:0 0 5px;}
-.carousel-caption p{margin-bottom:0;}
-.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.05);}.well blockquote{border-color:#ddd;border-color:rgba(0, 0, 0, 0.15);}
-.well-large{padding:24px;-webkit-border-radius:6px;-moz-border-radius:6px;border-radius:6px;}
-.well-small{padding:9px;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;}
-.close{float:right;font-size:20px;font-weight:bold;line-height:20px;color:#000000;text-shadow:0 1px 0 #ffffff;opacity:0.2;filter:alpha(opacity=20);}.close:hover{color:#000000;text-decoration:none;cursor:pointer;opacity:0.4;filter:alpha(opacity=40);}
-button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none;}
-.pull-right{float:right;}
-.pull-left{float:left;}
-.hide{display:none;}
-.show{display:block;}
-.invisible{visibility:hidden;}
-.affix{position:fixed;}
-.fade{opacity:0;-webkit-transition:opacity 0.15s linear;-moz-transition:opacity 0.15s linear;-o-transition:opacity 0.15s linear;transition:opacity 0.15s linear;}.fade.in{opacity:1;}
-.collapse{position:relative;height:0;overflow:hidden;-webkit-transition:height 0.35s ease;-moz-transition:height 0.35s ease;-o-transition:height 0.35s ease;transition:height 0.35s ease;}.collapse.in{height:auto;}
-.hidden{display:none;visibility:hidden;}
-.visible-phone{display:none !important;}
-.visible-tablet{display:none !important;}
-.hidden-desktop{display:none !important;}
-.visible-desktop{display:inherit !important;}
-@media (min-width:768px) and (max-width:979px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important ;} .visible-tablet{display:inherit !important;} .hidden-tablet{display:none !important;}}@media (max-width:767px){.hidden-desktop{display:inherit !important;} .visible-desktop{display:none !important;} .visible-phone{display:inherit !important;} .hidden-phone{display:none !important;}}@media (max-width:767px){body{padding-left:20px;padding-right:20px;} .navbar-fixed-top,.navbar-fixed-bottom,.navbar-static-top{margin-left:-20px;margin-right:-20px;} .container-fluid{padding:0;} .dl-horizontal dt{float:none;clear:none;width:auto;text-align:left;} .dl-horizontal dd{margin-left:0;} .container{width:auto;} .row-fluid{width:100%;} .row,.thumbnails{margin-left:0;} .thumbnails>li{float:none;margin-left:0;} [class*="span"],.row-fluid [class*="span"]{float:none;display:block;width:100%;margin-left:0;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .span12,.row-fluid .span12{width:100%;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .input-large,.input-xlarge,.input-xxlarge,input[class*="span"],select[class*="span"],textarea[class*="span"],.uneditable-input{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;} .input-prepend input,.input-append input,.input-prepend input[class*="span"],.input-append input[class*="span"]{display:inline-block;width:auto;} .controls-row [class*="span"]+[class*="span"]{margin-left:0;} .modal{position:fixed;top:20px;left:20px;right:20px;width:auto;margin:0;}.modal.fade.in{top:auto;}}@media (max-width:480px){.nav-collapse{-webkit-transform:translate3d(0, 0, 0);} .page-header h1 small{display:block;line-height:20px;} input[type="checkbox"],input[type="radio"]{border:1px solid #ccc;} .form-horizontal .control-label{float:none;width:auto;padding-top:0;text-align:left;} .form-horizontal .controls{margin-left:0;} .form-horizontal .control-list{padding-top:0;} .form-horizontal .form-actions{padding-left:10px;padding-right:10px;} .modal{top:10px;left:10px;right:10px;} .modal-header .close{padding:10px;margin:-10px;} .carousel-caption{position:static;}}@media (min-width:768px) and (max-width:979px){.row{margin-left:-20px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:20px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:724px;} .span12{width:724px;} .span11{width:662px;} .span10{width:600px;} .span9{width:538px;} .span8{width:476px;} .span7{width:414px;} .span6{width:352px;} .span5{width:290px;} .span4{width:228px;} .span3{width:166px;} .span2{width:104px;} .span1{width:42px;} .offset12{margin-left:764px;} .offset11{margin-left:702px;} .offset10{margin-left:640px;} .offset9{margin-left:578px;} .offset8{margin-left:516px;} .offset7{margin-left:454px;} .offset6{margin-left:392px;} .offset5{margin-left:330px;} .offset4{margin-left:268px;} .offset3{margin-left:206px;} .offset2{margin-left:144px;} .offset1{margin-left:82px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.7624309392265194%;*margin-left:2.709239449864817%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.43646408839778%;*width:91.38327259903608%;} .row-fluid .span10{width:82.87292817679558%;*width:82.81973668743387%;} .row-fluid .span9{width:74.30939226519337%;*width:74.25620077583166%;} .row-fluid .span8{width:65.74585635359117%;*width:65.69266486422946%;} .row-fluid .span7{width:57.18232044198895%;*width:57.12912895262725%;} .row-fluid .span6{width:48.61878453038674%;*width:48.56559304102504%;} .row-fluid .span5{width:40.05524861878453%;*width:40.00205712942283%;} .row-fluid .span4{width:31.491712707182323%;*width:31.43852121782062%;} .row-fluid .span3{width:22.92817679558011%;*width:22.87498530621841%;} .row-fluid .span2{width:14.3646408839779%;*width:14.311449394616199%;} .row-fluid .span1{width:5.801104972375691%;*width:5.747913483013988%;} .row-fluid .offset12{margin-left:105.52486187845304%;*margin-left:105.41847889972962%;} .row-fluid .offset12:first-child{margin-left:102.76243093922652%;*margin-left:102.6560479605031%;} .row-fluid .offset11{margin-left:96.96132596685082%;*margin-left:96.8549429881274%;} .row-fluid .offset11:first-child{margin-left:94.1988950276243%;*margin-left:94.09251204890089%;} .row-fluid .offset10{margin-left:88.39779005524862%;*margin-left:88.2914070765252%;} .row-fluid .offset10:first-child{margin-left:85.6353591160221%;*margin-left:85.52897613729868%;} .row-fluid .offset9{margin-left:79.8342541436464%;*margin-left:79.72787116492299%;} .row-fluid .offset9:first-child{margin-left:77.07182320441989%;*margin-left:76.96544022569647%;} .row-fluid .offset8{margin-left:71.2707182320442%;*margin-left:71.16433525332079%;} .row-fluid .offset8:first-child{margin-left:68.50828729281768%;*margin-left:68.40190431409427%;} .row-fluid .offset7{margin-left:62.70718232044199%;*margin-left:62.600799341718584%;} .row-fluid .offset7:first-child{margin-left:59.94475138121547%;*margin-left:59.838368402492065%;} .row-fluid .offset6{margin-left:54.14364640883978%;*margin-left:54.037263430116376%;} .row-fluid .offset6:first-child{margin-left:51.38121546961326%;*margin-left:51.27483249088986%;} .row-fluid .offset5{margin-left:45.58011049723757%;*margin-left:45.47372751851417%;} .row-fluid .offset5:first-child{margin-left:42.81767955801105%;*margin-left:42.71129657928765%;} .row-fluid .offset4{margin-left:37.01657458563536%;*margin-left:36.91019160691196%;} .row-fluid .offset4:first-child{margin-left:34.25414364640884%;*margin-left:34.14776066768544%;} .row-fluid .offset3{margin-left:28.45303867403315%;*margin-left:28.346655695309746%;} .row-fluid .offset3:first-child{margin-left:25.69060773480663%;*margin-left:25.584224756083227%;} .row-fluid .offset2{margin-left:19.88950276243094%;*margin-left:19.783119783707537%;} .row-fluid .offset2:first-child{margin-left:17.12707182320442%;*margin-left:17.02068884448102%;} .row-fluid .offset1{margin-left:11.32596685082873%;*margin-left:11.219583872105325%;} .row-fluid .offset1:first-child{margin-left:8.56353591160221%;*margin-left:8.457152932878806%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:20px;} input.span12, textarea.span12, .uneditable-input.span12{width:710px;} input.span11, textarea.span11, .uneditable-input.span11{width:648px;} input.span10, textarea.span10, .uneditable-input.span10{width:586px;} input.span9, textarea.span9, .uneditable-input.span9{width:524px;} input.span8, textarea.span8, .uneditable-input.span8{width:462px;} input.span7, textarea.span7, .uneditable-input.span7{width:400px;} input.span6, textarea.span6, .uneditable-input.span6{width:338px;} input.span5, textarea.span5, .uneditable-input.span5{width:276px;} input.span4, textarea.span4, .uneditable-input.span4{width:214px;} input.span3, textarea.span3, .uneditable-input.span3{width:152px;} input.span2, textarea.span2, .uneditable-input.span2{width:90px;} input.span1, textarea.span1, .uneditable-input.span1{width:28px;}}@media (min-width:1200px){.row{margin-left:-30px;*zoom:1;}.row:before,.row:after{display:table;content:"";line-height:0;} .row:after{clear:both;} [class*="span"]{float:left;min-height:1px;margin-left:30px;} .container,.navbar-static-top .container,.navbar-fixed-top .container,.navbar-fixed-bottom .container{width:1170px;} .span12{width:1170px;} .span11{width:1070px;} .span10{width:970px;} .span9{width:870px;} .span8{width:770px;} .span7{width:670px;} .span6{width:570px;} .span5{width:470px;} .span4{width:370px;} .span3{width:270px;} .span2{width:170px;} .span1{width:70px;} .offset12{margin-left:1230px;} .offset11{margin-left:1130px;} .offset10{margin-left:1030px;} .offset9{margin-left:930px;} .offset8{margin-left:830px;} .offset7{margin-left:730px;} .offset6{margin-left:630px;} .offset5{margin-left:530px;} .offset4{margin-left:430px;} .offset3{margin-left:330px;} .offset2{margin-left:230px;} .offset1{margin-left:130px;} .row-fluid{width:100%;*zoom:1;}.row-fluid:before,.row-fluid:after{display:table;content:"";line-height:0;} .row-fluid:after{clear:both;} .row-fluid [class*="span"]{display:block;width:100%;min-height:30px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;float:left;margin-left:2.564102564102564%;*margin-left:2.5109110747408616%;} .row-fluid [class*="span"]:first-child{margin-left:0;} .row-fluid .span12{width:100%;*width:99.94680851063829%;} .row-fluid .span11{width:91.45299145299145%;*width:91.39979996362975%;} .row-fluid .span10{width:82.90598290598291%;*width:82.8527914166212%;} .row-fluid .span9{width:74.35897435897436%;*width:74.30578286961266%;} .row-fluid .span8{width:65.81196581196582%;*width:65.75877432260411%;} .row-fluid .span7{width:57.26495726495726%;*width:57.21176577559556%;} .row-fluid .span6{width:48.717948717948715%;*width:48.664757228587014%;} .row-fluid .span5{width:40.17094017094017%;*width:40.11774868157847%;} .row-fluid .span4{width:31.623931623931625%;*width:31.570740134569924%;} .row-fluid .span3{width:23.076923076923077%;*width:23.023731587561375%;} .row-fluid .span2{width:14.52991452991453%;*width:14.476723040552828%;} .row-fluid .span1{width:5.982905982905983%;*width:5.929714493544281%;} .row-fluid .offset12{margin-left:105.12820512820512%;*margin-left:105.02182214948171%;} .row-fluid .offset12:first-child{margin-left:102.56410256410257%;*margin-left:102.45771958537915%;} .row-fluid .offset11{margin-left:96.58119658119658%;*margin-left:96.47481360247316%;} .row-fluid .offset11:first-child{margin-left:94.01709401709402%;*margin-left:93.91071103837061%;} .row-fluid .offset10{margin-left:88.03418803418803%;*margin-left:87.92780505546462%;} .row-fluid .offset10:first-child{margin-left:85.47008547008548%;*margin-left:85.36370249136206%;} .row-fluid .offset9{margin-left:79.48717948717949%;*margin-left:79.38079650845607%;} .row-fluid .offset9:first-child{margin-left:76.92307692307693%;*margin-left:76.81669394435352%;} .row-fluid .offset8{margin-left:70.94017094017094%;*margin-left:70.83378796144753%;} .row-fluid .offset8:first-child{margin-left:68.37606837606839%;*margin-left:68.26968539734497%;} .row-fluid .offset7{margin-left:62.393162393162385%;*margin-left:62.28677941443899%;} .row-fluid .offset7:first-child{margin-left:59.82905982905982%;*margin-left:59.72267685033642%;} .row-fluid .offset6{margin-left:53.84615384615384%;*margin-left:53.739770867430444%;} .row-fluid .offset6:first-child{margin-left:51.28205128205128%;*margin-left:51.175668303327875%;} .row-fluid .offset5{margin-left:45.299145299145295%;*margin-left:45.1927623204219%;} .row-fluid .offset5:first-child{margin-left:42.73504273504273%;*margin-left:42.62865975631933%;} .row-fluid .offset4{margin-left:36.75213675213675%;*margin-left:36.645753773413354%;} .row-fluid .offset4:first-child{margin-left:34.18803418803419%;*margin-left:34.081651209310785%;} .row-fluid .offset3{margin-left:28.205128205128204%;*margin-left:28.0987452264048%;} .row-fluid .offset3:first-child{margin-left:25.641025641025642%;*margin-left:25.53464266230224%;} .row-fluid .offset2{margin-left:19.65811965811966%;*margin-left:19.551736679396257%;} .row-fluid .offset2:first-child{margin-left:17.094017094017094%;*margin-left:16.98763411529369%;} .row-fluid .offset1{margin-left:11.11111111111111%;*margin-left:11.004728132387708%;} .row-fluid .offset1:first-child{margin-left:8.547008547008547%;*margin-left:8.440625568285142%;} input,textarea,.uneditable-input{margin-left:0;} .controls-row [class*="span"]+[class*="span"]{margin-left:30px;} input.span12, textarea.span12, .uneditable-input.span12{width:1156px;} input.span11, textarea.span11, .uneditable-input.span11{width:1056px;} input.span10, textarea.span10, .uneditable-input.span10{width:956px;} input.span9, textarea.span9, .uneditable-input.span9{width:856px;} input.span8, textarea.span8, .uneditable-input.span8{width:756px;} input.span7, textarea.span7, .uneditable-input.span7{width:656px;} input.span6, textarea.span6, .uneditable-input.span6{width:556px;} input.span5, textarea.span5, .uneditable-input.span5{width:456px;} input.span4, textarea.span4, .uneditable-input.span4{width:356px;} input.span3, textarea.span3, .uneditable-input.span3{width:256px;} input.span2, textarea.span2, .uneditable-input.span2{width:156px;} input.span1, textarea.span1, .uneditable-input.span1{width:56px;} .thumbnails{margin-left:-30px;} .thumbnails>li{margin-left:30px;} .row-fluid .thumbnails{margin-left:0;}}@media (max-width:979px){body{padding-top:0;} .navbar-fixed-top,.navbar-fixed-bottom{position:static;} .navbar-fixed-top{margin-bottom:20px;} .navbar-fixed-bottom{margin-top:20px;} .navbar-fixed-top .navbar-inner,.navbar-fixed-bottom .navbar-inner{padding:5px;} .navbar .container{width:auto;padding:0;} .navbar .brand{padding-left:10px;padding-right:10px;margin:0 0 0 -5px;} .nav-collapse{clear:both;} .nav-collapse .nav{float:none;margin:0 0 10px;} .nav-collapse .nav>li{float:none;} .nav-collapse .nav>li>a{margin-bottom:2px;} .nav-collapse .nav>.divider-vertical{display:none;} .nav-collapse .nav .nav-header{color:#777777;text-shadow:none;} .nav-collapse .nav>li>a,.nav-collapse .dropdown-menu a{padding:9px 15px;font-weight:bold;color:#777777;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;} .nav-collapse .btn{padding:4px 10px 4px;font-weight:normal;-webkit-border-radius:4px;-moz-border-radius:4px;border-radius:4px;} .nav-collapse .dropdown-menu li+li a{margin-bottom:2px;} .nav-collapse .nav>li>a:hover,.nav-collapse .dropdown-menu a:hover{background-color:#f2f2f2;} .navbar-inverse .nav-collapse .nav>li>a:hover,.navbar-inverse .nav-collapse .dropdown-menu a:hover{background-color:#111111;} .nav-collapse.in .btn-group{margin-top:5px;padding:0;} .nav-collapse .dropdown-menu{position:static;top:auto;left:auto;float:none;display:block;max-width:none;margin:0 15px;padding:0;background-color:transparent;border:none;-webkit-border-radius:0;-moz-border-radius:0;border-radius:0;-webkit-box-shadow:none;-moz-box-shadow:none;box-shadow:none;} .nav-collapse .dropdown-menu:before,.nav-collapse .dropdown-menu:after{display:none;} .nav-collapse .dropdown-menu .divider{display:none;} .nav-collapse .nav>li>.dropdown-menu:before,.nav-collapse .nav>li>.dropdown-menu:after{display:none;} .nav-collapse .navbar-form,.nav-collapse .navbar-search{float:none;padding:10px 15px;margin:10px 0;border-top:1px solid #f2f2f2;border-bottom:1px solid #f2f2f2;-webkit-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);-moz-box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);box-shadow:inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);} .navbar-inverse .nav-collapse .navbar-form,.navbar-inverse .nav-collapse .navbar-search{border-top-color:#111111;border-bottom-color:#111111;} .navbar .nav-collapse .nav.pull-right{float:none;margin-left:0;} .nav-collapse,.nav-collapse.collapse{overflow:hidden;height:0;} .navbar .btn-navbar{display:block;} .navbar-static .navbar-inner{padding-left:10px;padding-right:10px;}}@media (min-width:980px){.nav-collapse.collapse{height:auto !important;overflow:visible !important;}}
+ * Bootstrap v3.2.0 (http://getbootstrap.com)
+ * Copyright 2011-2014 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ *//*! normalize.css v3.0.1 | MIT License | git.io/normalize */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background:0 0}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{margin:.67em 0;font-size:2em}mark{color:#000;background:#ff0}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{height:0;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{margin:0;font:inherit;color:inherit}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{padding:0;border:0}input{line-height:normal}input[type=checkbox],input[type=radio]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;-webkit-appearance:textfield}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{padding:.35em .625em .75em;margin:0 2px;border:1px solid silver}legend{padding:0;border:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-spacing:0;border-collapse:collapse}td,th{padding:0}@media print{*{color:#000!important;text-shadow:none!important;background:transparent!important;-webkit-box-shadow:none!important;box-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100%!important}p,h2,h3{orphans:3;widows:3}h2,h3{page-break-after:avoid}select{background:#fff!important}.navbar{display:none}.table td,.table th{background-color:#fff!important}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table-bordered th,.table-bordered td{border:1px solid #ddd!important}}@font-face{font-family:'Glyphicons Halflings';src:url(../fonts/glyphicons-halflings-regular.eot);src:url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'),url(../fonts/glyphicons-halflings-regular.woff) format('woff'),url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'),url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg')}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"\2a"}.glyphicon-plus:before{content:"\2b"}.glyphicon-euro:before{content:"\20ac"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270f"}.glyphicon-glass:before{content:"\e001"}.glyphicon-music:before{content:"\e002"}.glyphicon-search:before{content:"\e003"}.glyphicon-heart:before{content:"\e005"}.glyphicon-star:before{content:"\e006"}.glyphicon-star-empty:before{content:"\e007"}.glyphicon-user:before{content:"\e008"}.glyphicon-film:before{content:"\e009"}.glyphicon-th-large:before{content:"\e010"}.glyphicon-th:before{content:"\e011"}.glyphicon-th-list:before{content:"\e012"}.glyphicon-ok:before{content:"\e013"}.glyphicon-remove:before{content:"\e014"}.glyphicon-zoom-in:before{content:"\e015"}.glyphicon-zoom-out:before{content:"\e016"}.glyphicon-off:before{content:"\e017"}.glyphicon-signal:before{content:"\e018"}.glyphicon-cog:before{content:"\e019"}.glyphicon-trash:before{content:"\e020"}.glyphicon-home:before{content:"\e021"}.glyphicon-file:before{content:"\e022"}.glyphicon-time:before{content:"\e023"}.glyphicon-road:before{content:"\e024"}.glyphicon-download-alt:before{content:"\e025"}.glyphicon-download:before{content:"\e026"}.glyphicon-upload:before{content:"\e027"}.glyphicon-inbox:before{content:"\e028"}.glyphicon-play-circle:before{content:"\e029"}.glyphicon-repeat:before{content:"\e030"}.glyphicon-refresh:before{content:"\e031"}.glyphicon-list-alt:before{content:"\e032"}.glyphicon-lock:before{content:"\e033"}.glyphicon-flag:before{content:"\e034"}.glyphicon-headphones:before{content:"\e035"}.glyphicon-volume-off:before{content:"\e036"}.glyphicon-volume-down:before{content:"\e037"}.glyphicon-volume-up:before{content:"\e038"}.glyphicon-qrcode:before{content:"\e039"}.glyphicon-barcode:before{content:"\e040"}.glyphicon-tag:before{content:"\e041"}.glyphicon-tags:before{content:"\e042"}.glyphicon-book:before{content:"\e043"}.glyphicon-bookmark:before{content:"\e044"}.glyphicon-print:before{content:"\e045"}.glyphicon-camera:before{content:"\e046"}.glyphicon-font:before{content:"\e047"}.glyphicon-bold:before{content:"\e048"}.glyphicon-italic:before{content:"\e049"}.glyphicon-text-height:before{content:"\e050"}.glyphicon-text-width:before{content:"\e051"}.glyphicon-align-left:before{content:"\e052"}.glyphicon-align-center:before{content:"\e053"}.glyphicon-align-right:before{content:"\e054"}.glyphicon-align-justify:before{content:"\e055"}.glyphicon-list:before{content:"\e056"}.glyphicon-indent-left:before{content:"\e057"}.glyphicon-indent-right:before{content:"\e058"}.glyphicon-facetime-video:before{content:"\e059"}.glyphicon-picture:before{content:"\e060"}.glyphicon-map-marker:before{content:"\e062"}.glyphicon-adjust:before{content:"\e063"}.glyphicon-tint:before{content:"\e064"}.glyphicon-edit:before{content:"\e065"}.glyphicon-share:before{content:"\e066"}.glyphicon-check:before{content:"\e067"}.glyphicon-move:before{content:"\e068"}.glyphicon-step-backward:before{content:"\e069"}.glyphicon-fast-backward:before{content:"\e070"}.glyphicon-backward:before{content:"\e071"}.glyphicon-play:before{content:"\e072"}.glyphicon-pause:before{content:"\e073"}.glyphicon-stop:before{content:"\e074"}.glyphicon-forward:before{content:"\e075"}.glyphicon-fast-forward:before{content:"\e076"}.glyphicon-step-forward:before{content:"\e077"}.glyphicon-eject:before{content:"\e078"}.glyphicon-chevron-left:before{content:"\e079"}.glyphicon-chevron-right:before{content:"\e080"}.glyphicon-plus-sign:before{content:"\e081"}.glyphicon-minus-sign:before{content:"\e082"}.glyphicon-remove-sign:before{content:"\e083"}.glyphicon-ok-sign:before{content:"\e084"}.glyphicon-question-sign:before{content:"\e085"}.glyphicon-info-sign:before{content:"\e086"}.glyphicon-screenshot:before{content:"\e087"}.glyphicon-remove-circle:before{content:"\e088"}.glyphicon-ok-circle:before{content:"\e089"}.glyphicon-ban-circle:before{content:"\e090"}.glyphicon-arrow-left:before{content:"\e091"}.glyphicon-arrow-right:before{content:"\e092"}.glyphicon-arrow-up:before{content:"\e093"}.glyphicon-arrow-down:before{content:"\e094"}.glyphicon-share-alt:before{content:"\e095"}.glyphicon-resize-full:before{content:"\e096"}.glyphicon-resize-small:before{content:"\e097"}.glyphicon-exclamation-sign:before{content:"\e101"}.glyphicon-gift:before{content:"\e102"}.glyphicon-leaf:before{content:"\e103"}.glyphicon-fire:before{content:"\e104"}.glyphicon-eye-open:before{content:"\e105"}.glyphicon-eye-close:before{content:"\e106"}.glyphicon-warning-sign:before{content:"\e107"}.glyphicon-plane:before{content:"\e108"}.glyphicon-calendar:before{content:"\e109"}.glyphicon-random:before{content:"\e110"}.glyphicon-comment:before{content:"\e111"}.glyphicon-magnet:before{content:"\e112"}.glyphicon-chevron-up:before{content:"\e113"}.glyphicon-chevron-down:before{content:"\e114"}.glyphicon-retweet:before{content:"\e115"}.glyphicon-shopping-cart:before{content:"\e116"}.glyphicon-folder-close:before{content:"\e117"}.glyphicon-folder-open:before{content:"\e118"}.glyphicon-resize-vertical:before{content:"\e119"}.glyphicon-resize-horizontal:before{content:"\e120"}.glyphicon-hdd:before{content:"\e121"}.glyphicon-bullhorn:before{content:"\e122"}.glyphicon-bell:before{content:"\e123"}.glyphicon-certificate:before{content:"\e124"}.glyphicon-thumbs-up:before{content:"\e125"}.glyphicon-thumbs-down:before{content:"\e126"}.glyphicon-hand-right:before{content:"\e127"}.glyphicon-hand-left:before{content:"\e128"}.glyphicon-hand-up:before{content:"\e129"}.glyphicon-hand-down:before{content:"\e130"}.glyphicon-circle-arrow-right:before{content:"\e131"}.glyphicon-circle-arrow-left:before{content:"\e132"}.glyphicon-circle-arrow-up:before{content:"\e133"}.glyphicon-circle-arrow-down:before{content:"\e134"}.glyphicon-globe:before{content:"\e135"}.glyphicon-wrench:before{content:"\e136"}.glyphicon-tasks:before{content:"\e137"}.glyphicon-filter:before{content:"\e138"}.glyphicon-briefcase:before{content:"\e139"}.glyphicon-fullscreen:before{content:"\e140"}.glyphicon-dashboard:before{content:"\e141"}.glyphicon-paperclip:before{content:"\e142"}.glyphicon-heart-empty:before{content:"\e143"}.glyphicon-link:before{content:"\e144"}.glyphicon-phone:before{content:"\e145"}.glyphicon-pushpin:before{content:"\e146"}.glyphicon-usd:before{content:"\e148"}.glyphicon-gbp:before{content:"\e149"}.glyphicon-sort:before{content:"\e150"}.glyphicon-sort-by-alphabet:before{content:"\e151"}.glyphicon-sort-by-alphabet-alt:before{content:"\e152"}.glyphicon-sort-by-order:before{content:"\e153"}.glyphicon-sort-by-order-alt:before{content:"\e154"}.glyphicon-sort-by-attributes:before{content:"\e155"}.glyphicon-sort-by-attributes-alt:before{content:"\e156"}.glyphicon-unchecked:before{content:"\e157"}.glyphicon-expand:before{content:"\e158"}.glyphicon-collapse-down:before{content:"\e159"}.glyphicon-collapse-up:before{content:"\e160"}.glyphicon-log-in:before{content:"\e161"}.glyphicon-flash:before{content:"\e162"}.glyphicon-log-out:before{content:"\e163"}.glyphicon-new-window:before{content:"\e164"}.glyphicon-record:before{content:"\e165"}.glyphicon-save:before{content:"\e166"}.glyphicon-open:before{content:"\e167"}.glyphicon-saved:before{content:"\e168"}.glyphicon-import:before{content:"\e169"}.glyphicon-export:before{content:"\e170"}.glyphicon-send:before{content:"\e171"}.glyphicon-floppy-disk:before{content:"\e172"}.glyphicon-floppy-saved:before{content:"\e173"}.glyphicon-floppy-remove:before{content:"\e174"}.glyphicon-floppy-save:before{content:"\e175"}.glyphicon-floppy-open:before{content:"\e176"}.glyphicon-credit-card:before{content:"\e177"}.glyphicon-transfer:before{content:"\e178"}.glyphicon-cutlery:before{content:"\e179"}.glyphicon-header:before{content:"\e180"}.glyphicon-compressed:before{content:"\e181"}.glyphicon-earphone:before{content:"\e182"}.glyphicon-phone-alt:before{content:"\e183"}.glyphicon-tower:before{content:"\e184"}.glyphicon-stats:before{content:"\e185"}.glyphicon-sd-video:before{content:"\e186"}.glyphicon-hd-video:before{content:"\e187"}.glyphicon-subtitles:before{content:"\e188"}.glyphicon-sound-stereo:before{content:"\e189"}.glyphicon-sound-dolby:before{content:"\e190"}.glyphicon-sound-5-1:before{content:"\e191"}.glyphicon-sound-6-1:before{content:"\e192"}.glyphicon-sound-7-1:before{content:"\e193"}.glyphicon-copyright-mark:before{content:"\e194"}.glyphicon-registration-mark:before{content:"\e195"}.glyphicon-cloud-download:before{content:"\e197"}.glyphicon-cloud-upload:before{content:"\e198"}.glyphicon-tree-conifer:before{content:"\e199"}.glyphicon-tree-deciduous:before{content:"\e200"}*{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}:before,:after{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:rgba(0,0,0,0)}body{font-family:"Helvetica Neue",Helvetica,Arial,sans-serif;font-size:14px;line-height:1.42857143;color:#333;background-color:#fff}input,button,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#428bca;text-decoration:none}a:hover,a:focus{color:#2a6496;text-decoration:underline}a:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.img-responsive,.thumbnail>img,.thumbnail a>img,.carousel-inner>.item>img,.carousel-inner>.item>a>img{display:block;width:100% \9;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{display:inline-block;width:100% \9;max-width:100%;height:auto;padding:4px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.img-circle{border-radius:50%}hr{margin-top:20px;margin-bottom:20px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}h1,h2,h3,h4,h5,h6,.h1,.h2,.h3,.h4,.h5,.h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}h1 small,h2 small,h3 small,h4 small,h5 small,h6 small,.h1 small,.h2 small,.h3 small,.h4 small,.h5 small,.h6 small,h1 .small,h2 .small,h3 .small,h4 .small,h5 .small,h6 .small,.h1 .small,.h2 .small,.h3 .small,.h4 .small,.h5 .small,.h6 .small{font-weight:400;line-height:1;color:#777}h1,.h1,h2,.h2,h3,.h3{margin-top:20px;margin-bottom:10px}h1 small,.h1 small,h2 small,.h2 small,h3 small,.h3 small,h1 .small,.h1 .small,h2 .small,.h2 .small,h3 .small,.h3 .small{font-size:65%}h4,.h4,h5,.h5,h6,.h6{margin-top:10px;margin-bottom:10px}h4 small,.h4 small,h5 small,.h5 small,h6 small,.h6 small,h4 .small,.h4 .small,h5 .small,.h5 .small,h6 .small,.h6 .small{font-size:75%}h1,.h1{font-size:36px}h2,.h2{font-size:30px}h3,.h3{font-size:24px}h4,.h4{font-size:18px}h5,.h5{font-size:14px}h6,.h6{font-size:12px}p{margin:0 0 10px}.lead{margin-bottom:20px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}small,.small{font-size:85%}cite{font-style:normal}mark,.mark{padding:.2em;background-color:#fcf8e3}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#428bca}a.text-primary:hover{color:#3071a9}.text-success{color:#3c763d}a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#428bca}a.bg-primary:hover{background-color:#3071a9}.bg-success{background-color:#dff0d8}a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:9px;margin:40px 0 20px;border-bottom:1px solid #eee}ul,ol{margin-top:0;margin-bottom:10px}ul ul,ol ul,ul ol,ol ol{margin-bottom:0}.list-unstyled{padding-left:0;list-style:none}.list-inline{padding-left:0;margin-left:-5px;list-style:none}.list-inline>li{display:inline-block;padding-right:5px;padding-left:5px}dl{margin-top:0;margin-bottom:20px}dt,dd{line-height:1.42857143}dt{font-weight:700}dd{margin-left:0}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;overflow:hidden;clear:left;text-align:right;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[title],abbr[data-original-title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%;text-transform:uppercase}blockquote{padding:10px 20px;margin:0 0 20px;font-size:17.5px;border-left:5px solid #eee}blockquote p:last-child,blockquote ul:last-child,blockquote ol:last-child{margin-bottom:0}blockquote footer,blockquote small,blockquote .small{display:block;font-size:80%;line-height:1.42857143;color:#777}blockquote footer:before,blockquote small:before,blockquote .small:before{content:'\2014 \00A0'}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;text-align:right;border-right:5px solid #eee;border-left:0}.blockquote-reverse footer:before,blockquote.pull-right footer:before,.blockquote-reverse small:before,blockquote.pull-right small:before,.blockquote-reverse .small:before,blockquote.pull-right .small:before{content:''}.blockquote-reverse footer:after,blockquote.pull-right footer:after,.blockquote-reverse small:after,blockquote.pull-right small:after,.blockquote-reverse .small:after,blockquote.pull-right .small:after{content:'\00A0 \2014'}blockquote:before,blockquote:after{content:""}address{margin-bottom:20px;font-style:normal;line-height:1.42857143}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,"Courier New",monospace}code{padding:2px 4px;font-size:90%;color:#c7254e;background-color:#f9f2f4;border-radius:4px}kbd{padding:2px 4px;font-size:90%;color:#fff;background-color:#333;border-radius:3px;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.25);box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;-webkit-box-shadow:none;box-shadow:none}pre{display:block;padding:9.5px;margin:0 0 10px;font-size:13px;line-height:1.42857143;color:#333;word-break:break-all;word-wrap:break-word;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{padding-right:15px;padding-left:15px;margin-right:auto;margin-left:auto}.row{margin-right:-15px;margin-left:-15px}.col-xs-1,.col-sm-1,.col-md-1,.col-lg-1,.col-xs-2,.col-sm-2,.col-md-2,.col-lg-2,.col-xs-3,.col-sm-3,.col-md-3,.col-lg-3,.col-xs-4,.col-sm-4,.col-md-4,.col-lg-4,.col-xs-5,.col-sm-5,.col-md-5,.col-lg-5,.col-xs-6,.col-sm-6,.col-md-6,.col-lg-6,.col-xs-7,.col-sm-7,.col-md-7,.col-lg-7,.col-xs-8,.col-sm-8,.col-md-8,.col-lg-8,.col-xs-9,.col-sm-9,.col-md-9,.col-lg-9,.col-xs-10,.col-sm-10,.col-md-10,.col-lg-10,.col-xs-11,.col-sm-11,.col-md-11,.col-lg-11,.col-xs-12,.col-sm-12,.col-md-12,.col-lg-12{position:relative;min-height:1px;padding-right:15px;padding-left:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.col-xs-pull-12{right:100%}.col-xs-pull-11{right:91.66666667%}.col-xs-pull-10{right:83.33333333%}.col-xs-pull-9{right:75%}.col-xs-pull-8{right:66.66666667%}.col-xs-pull-7{right:58.33333333%}.col-xs-pull-6{right:50%}.col-xs-pull-5{right:41.66666667%}.col-xs-pull-4{right:33.33333333%}.col-xs-pull-3{right:25%}.col-xs-pull-2{right:16.66666667%}.col-xs-pull-1{right:8.33333333%}.col-xs-pull-0{right:auto}.col-xs-push-12{left:100%}.col-xs-push-11{left:91.66666667%}.col-xs-push-10{left:83.33333333%}.col-xs-push-9{left:75%}.col-xs-push-8{left:66.66666667%}.col-xs-push-7{left:58.33333333%}.col-xs-push-6{left:50%}.col-xs-push-5{left:41.66666667%}.col-xs-push-4{left:33.33333333%}.col-xs-push-3{left:25%}.col-xs-push-2{left:16.66666667%}.col-xs-push-1{left:8.33333333%}.col-xs-push-0{left:auto}.col-xs-offset-12{margin-left:100%}.col-xs-offset-11{margin-left:91.66666667%}.col-xs-offset-10{margin-left:83.33333333%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-8{margin-left:66.66666667%}.col-xs-offset-7{margin-left:58.33333333%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-5{margin-left:41.66666667%}.col-xs-offset-4{margin-left:33.33333333%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-2{margin-left:16.66666667%}.col-xs-offset-1{margin-left:8.33333333%}.col-xs-offset-0{margin-left:0}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.col-sm-pull-12{right:100%}.col-sm-pull-11{right:91.66666667%}.col-sm-pull-10{right:83.33333333%}.col-sm-pull-9{right:75%}.col-sm-pull-8{right:66.66666667%}.col-sm-pull-7{right:58.33333333%}.col-sm-pull-6{right:50%}.col-sm-pull-5{right:41.66666667%}.col-sm-pull-4{right:33.33333333%}.col-sm-pull-3{right:25%}.col-sm-pull-2{right:16.66666667%}.col-sm-pull-1{right:8.33333333%}.col-sm-pull-0{right:auto}.col-sm-push-12{left:100%}.col-sm-push-11{left:91.66666667%}.col-sm-push-10{left:83.33333333%}.col-sm-push-9{left:75%}.col-sm-push-8{left:66.66666667%}.col-sm-push-7{left:58.33333333%}.col-sm-push-6{left:50%}.col-sm-push-5{left:41.66666667%}.col-sm-push-4{left:33.33333333%}.col-sm-push-3{left:25%}.col-sm-push-2{left:16.66666667%}.col-sm-push-1{left:8.33333333%}.col-sm-push-0{left:auto}.col-sm-offset-12{margin-left:100%}.col-sm-offset-11{margin-left:91.66666667%}.col-sm-offset-10{margin-left:83.33333333%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-8{margin-left:66.66666667%}.col-sm-offset-7{margin-left:58.33333333%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-5{margin-left:41.66666667%}.col-sm-offset-4{margin-left:33.33333333%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-2{margin-left:16.66666667%}.col-sm-offset-1{margin-left:8.33333333%}.col-sm-offset-0{margin-left:0}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.col-md-pull-12{right:100%}.col-md-pull-11{right:91.66666667%}.col-md-pull-10{right:83.33333333%}.col-md-pull-9{right:75%}.col-md-pull-8{right:66.66666667%}.col-md-pull-7{right:58.33333333%}.col-md-pull-6{right:50%}.col-md-pull-5{right:41.66666667%}.col-md-pull-4{right:33.33333333%}.col-md-pull-3{right:25%}.col-md-pull-2{right:16.66666667%}.col-md-pull-1{right:8.33333333%}.col-md-pull-0{right:auto}.col-md-push-12{left:100%}.col-md-push-11{left:91.66666667%}.col-md-push-10{left:83.33333333%}.col-md-push-9{left:75%}.col-md-push-8{left:66.66666667%}.col-md-push-7{left:58.33333333%}.col-md-push-6{left:50%}.col-md-push-5{left:41.66666667%}.col-md-push-4{left:33.33333333%}.col-md-push-3{left:25%}.col-md-push-2{left:16.66666667%}.col-md-push-1{left:8.33333333%}.col-md-push-0{left:auto}.col-md-offset-12{margin-left:100%}.col-md-offset-11{margin-left:91.66666667%}.col-md-offset-10{margin-left:83.33333333%}.col-md-offset-9{margin-left:75%}.col-md-offset-8{margin-left:66.66666667%}.col-md-offset-7{margin-left:58.33333333%}.col-md-offset-6{margin-left:50%}.col-md-offset-5{margin-left:41.66666667%}.col-md-offset-4{margin-left:33.33333333%}.col-md-offset-3{margin-left:25%}.col-md-offset-2{margin-left:16.66666667%}.col-md-offset-1{margin-left:8.33333333%}.col-md-offset-0{margin-left:0}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.col-lg-pull-12{right:100%}.col-lg-pull-11{right:91.66666667%}.col-lg-pull-10{right:83.33333333%}.col-lg-pull-9{right:75%}.col-lg-pull-8{right:66.66666667%}.col-lg-pull-7{right:58.33333333%}.col-lg-pull-6{right:50%}.col-lg-pull-5{right:41.66666667%}.col-lg-pull-4{right:33.33333333%}.col-lg-pull-3{right:25%}.col-lg-pull-2{right:16.66666667%}.col-lg-pull-1{right:8.33333333%}.col-lg-pull-0{right:auto}.col-lg-push-12{left:100%}.col-lg-push-11{left:91.66666667%}.col-lg-push-10{left:83.33333333%}.col-lg-push-9{left:75%}.col-lg-push-8{left:66.66666667%}.col-lg-push-7{left:58.33333333%}.col-lg-push-6{left:50%}.col-lg-push-5{left:41.66666667%}.col-lg-push-4{left:33.33333333%}.col-lg-push-3{left:25%}.col-lg-push-2{left:16.66666667%}.col-lg-push-1{left:8.33333333%}.col-lg-push-0{left:auto}.col-lg-offset-12{margin-left:100%}.col-lg-offset-11{margin-left:91.66666667%}.col-lg-offset-10{margin-left:83.33333333%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-8{margin-left:66.66666667%}.col-lg-offset-7{margin-left:58.33333333%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-5{margin-left:41.66666667%}.col-lg-offset-4{margin-left:33.33333333%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-2{margin-left:16.66666667%}.col-lg-offset-1{margin-left:8.33333333%}.col-lg-offset-0{margin-left:0}}table{background-color:transparent}th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:20px}.table>thead>tr>th,.table>tbody>tr>th,.table>tfoot>tr>th,.table>thead>tr>td,.table>tbody>tr>td,.table>tfoot>tr>td{padding:8px;line-height:1.42857143;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>th,.table>caption+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>td,.table>thead:first-child>tr:first-child>td{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#fff}.table-condensed>thead>tr>th,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>tbody>tr>td,.table-condensed>tfoot>tr>td{padding:5px}.table-bordered{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>tbody>tr>td,.table-bordered>tfoot>tr>td{border:1px solid #ddd}.table-bordered>thead>tr>th,.table-bordered>thead>tr>td{border-bottom-width:2px}.table-striped>tbody>tr:nth-child(odd)>td,.table-striped>tbody>tr:nth-child(odd)>th{background-color:#f9f9f9}.table-hover>tbody>tr:hover>td,.table-hover>tbody>tr:hover>th{background-color:#f5f5f5}table col[class*=col-]{position:static;display:table-column;float:none}table td[class*=col-],table th[class*=col-]{position:static;display:table-cell;float:none}.table>thead>tr>td.active,.table>tbody>tr>td.active,.table>tfoot>tr>td.active,.table>thead>tr>th.active,.table>tbody>tr>th.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>tbody>tr.active>td,.table>tfoot>tr.active>td,.table>thead>tr.active>th,.table>tbody>tr.active>th,.table>tfoot>tr.active>th{background-color:#f5f5f5}.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover,.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr.active:hover>th{background-color:#e8e8e8}.table>thead>tr>td.success,.table>tbody>tr>td.success,.table>tfoot>tr>td.success,.table>thead>tr>th.success,.table>tbody>tr>th.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>tbody>tr.success>td,.table>tfoot>tr.success>td,.table>thead>tr.success>th,.table>tbody>tr.success>th,.table>tfoot>tr.success>th{background-color:#dff0d8}.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover,.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr.success:hover>th{background-color:#d0e9c6}.table>thead>tr>td.info,.table>tbody>tr>td.info,.table>tfoot>tr>td.info,.table>thead>tr>th.info,.table>tbody>tr>th.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>tbody>tr.info>td,.table>tfoot>tr.info>td,.table>thead>tr.info>th,.table>tbody>tr.info>th,.table>tfoot>tr.info>th{background-color:#d9edf7}.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover,.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr.info:hover>th{background-color:#c4e3f3}.table>thead>tr>td.warning,.table>tbody>tr>td.warning,.table>tfoot>tr>td.warning,.table>thead>tr>th.warning,.table>tbody>tr>th.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>tbody>tr.warning>td,.table>tfoot>tr.warning>td,.table>thead>tr.warning>th,.table>tbody>tr.warning>th,.table>tfoot>tr.warning>th{background-color:#fcf8e3}.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover,.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr.warning:hover>th{background-color:#faf2cc}.table>thead>tr>td.danger,.table>tbody>tr>td.danger,.table>tfoot>tr>td.danger,.table>thead>tr>th.danger,.table>tbody>tr>th.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>tbody>tr.danger>td,.table>tfoot>tr.danger>td,.table>thead>tr.danger>th,.table>tbody>tr.danger>th,.table>tfoot>tr.danger>th{background-color:#f2dede}.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover,.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr.danger:hover>th{background-color:#ebcccc}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:15px;overflow-x:auto;overflow-y:hidden;-webkit-overflow-scrolling:touch;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>thead>tr>th,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tfoot>tr>td{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>thead>tr>th:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.table-responsive>.table-bordered>thead>tr>th:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>th,.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>td{border-bottom:0}}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;padding:0;margin-bottom:20px;font-size:21px;line-height:inherit;color:#333;border:0;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}input[type=radio],input[type=checkbox]{margin:4px 0 0;margin-top:1px \9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=file]:focus,input[type=radio]:focus,input[type=checkbox]:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{display:block;padding-top:7px;font-size:14px;line-height:1.42857143;color:#555}.form-control{display:block;width:100%;height:34px;padding:6px 12px;font-size:14px;line-height:1.42857143;color:#555;background-color:#fff;background-image:none;border:1px solid #ccc;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color ease-in-out .15s,-webkit-box-shadow ease-in-out .15s;-o-transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s;transition:border-color ease-in-out .15s,box-shadow ease-in-out .15s}.form-control:focus{border-color:#66afe9;outline:0;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(102,175,233,.6)}.form-control::-moz-placeholder{color:#777;opacity:1}.form-control:-ms-input-placeholder{color:#777}.form-control::-webkit-input-placeholder{color:#777}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{cursor:not-allowed;background-color:#eee;opacity:1}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}input[type=date],input[type=time],input[type=datetime-local],input[type=month]{line-height:34px;line-height:1.42857143 \0}input[type=date].input-sm,input[type=time].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm{line-height:30px}input[type=date].input-lg,input[type=time].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg{line-height:46px}.form-group{margin-bottom:15px}.radio,.checkbox{position:relative;display:block;min-height:20px;margin-top:10px;margin-bottom:10px}.radio label,.checkbox label{padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.radio input[type=radio],.radio-inline input[type=radio],.checkbox input[type=checkbox],.checkbox-inline input[type=checkbox]{position:absolute;margin-top:4px \9;margin-left:-20px}.radio+.radio,.checkbox+.checkbox{margin-top:-5px}.radio-inline,.checkbox-inline{display:inline-block;padding-left:20px;margin-bottom:0;font-weight:400;vertical-align:middle;cursor:pointer}.radio-inline+.radio-inline,.checkbox-inline+.checkbox-inline{margin-top:0;margin-left:10px}input[type=radio][disabled],input[type=checkbox][disabled],input[type=radio].disabled,input[type=checkbox].disabled,fieldset[disabled] input[type=radio],fieldset[disabled] input[type=checkbox]{cursor:not-allowed}.radio-inline.disabled,.checkbox-inline.disabled,fieldset[disabled] .radio-inline,fieldset[disabled] .checkbox-inline{cursor:not-allowed}.radio.disabled label,.checkbox.disabled label,fieldset[disabled] .radio label,fieldset[disabled] .checkbox label{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0}.form-control-static.input-lg,.form-control-static.input-sm{padding-right:0;padding-left:0}.input-sm,.form-horizontal .form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-sm{height:30px;line-height:30px}textarea.input-sm,select[multiple].input-sm{height:auto}.input-lg,.form-horizontal .form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-lg{height:46px;line-height:46px}textarea.input-lg,select[multiple].input-lg{height:auto}.has-feedback{position:relative}.has-feedback .form-control{padding-right:42.5px}.form-control-feedback{position:absolute;top:25px;right:0;z-index:2;display:block;width:34px;height:34px;line-height:34px;text-align:center}.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .help-block,.has-success .control-label,.has-success .radio,.has-success .checkbox,.has-success .radio-inline,.has-success .checkbox-inline{color:#3c763d}.has-success .form-control{border-color:#3c763d;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;background-color:#dff0d8;border-color:#3c763d}.has-success .form-control-feedback{color:#3c763d}.has-warning .help-block,.has-warning .control-label,.has-warning .radio,.has-warning .checkbox,.has-warning .radio-inline,.has-warning .checkbox-inline{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;background-color:#fcf8e3;border-color:#8a6d3b}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .help-block,.has-error .control-label,.has-error .radio,.has-error .checkbox,.has-error .radio-inline,.has-error .checkbox-inline{color:#a94442}.has-error .form-control{border-color:#a94442;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075);box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;background-color:#f2dede;border-color:#a94442}.has-error .form-control-feedback{color:#a94442}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#737373}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn,.form-inline .input-group .form-control{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .radio,.form-inline .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .radio label,.form-inline .checkbox label{padding-left:0}.form-inline .radio input[type=radio],.form-inline .checkbox input[type=checkbox]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .radio,.form-horizontal .checkbox,.form-horizontal .radio-inline,.form-horizontal .checkbox-inline{padding-top:7px;margin-top:0;margin-bottom:0}.form-horizontal .radio,.form-horizontal .checkbox{min-height:27px}.form-horizontal .form-group{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.form-horizontal .control-label{padding-top:7px;margin-bottom:0;text-align:right}}.form-horizontal .has-feedback .form-control-feedback{top:0;right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:14.3px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px}}.btn{display:inline-block;padding:6px 12px;margin-bottom:0;font-size:14px;font-weight:400;line-height:1.42857143;text-align:center;white-space:nowrap;vertical-align:middle;cursor:pointer;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;background-image:none;border:1px solid transparent;border-radius:4px}.btn:focus,.btn:active:focus,.btn.active:focus{outline:thin dotted;outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn:hover,.btn:focus{color:#333;text-decoration:none}.btn:active,.btn.active{background-image:none;outline:0;-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{pointer-events:none;cursor:not-allowed;filter:alpha(opacity=65);-webkit-box-shadow:none;box-shadow:none;opacity:.65}.btn-default{color:#333;background-color:#fff;border-color:#ccc}.btn-default:hover,.btn-default:focus,.btn-default:active,.btn-default.active,.open>.dropdown-toggle.btn-default{color:#333;background-color:#e6e6e6;border-color:#adadad}.btn-default:active,.btn-default.active,.open>.dropdown-toggle.btn-default{background-image:none}.btn-default.disabled,.btn-default[disabled],fieldset[disabled] .btn-default,.btn-default.disabled:hover,.btn-default[disabled]:hover,fieldset[disabled] .btn-default:hover,.btn-default.disabled:focus,.btn-default[disabled]:focus,fieldset[disabled] .btn-default:focus,.btn-default.disabled:active,.btn-default[disabled]:active,fieldset[disabled] .btn-default:active,.btn-default.disabled.active,.btn-default[disabled].active,fieldset[disabled] .btn-default.active{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#333}.btn-primary{color:#fff;background-color:#428bca;border-color:#357ebd}.btn-primary:hover,.btn-primary:focus,.btn-primary:active,.btn-primary.active,.open>.dropdown-toggle.btn-primary{color:#fff;background-color:#3071a9;border-color:#285e8e}.btn-primary:active,.btn-primary.active,.open>.dropdown-toggle.btn-primary{background-image:none}.btn-primary.disabled,.btn-primary[disabled],fieldset[disabled] .btn-primary,.btn-primary.disabled:hover,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary:hover,.btn-primary.disabled:focus,.btn-primary[disabled]:focus,fieldset[disabled] .btn-primary:focus,.btn-primary.disabled:active,.btn-primary[disabled]:active,fieldset[disabled] .btn-primary:active,.btn-primary.disabled.active,.btn-primary[disabled].active,fieldset[disabled] .btn-primary.active{background-color:#428bca;border-color:#357ebd}.btn-primary .badge{color:#428bca;background-color:#fff}.btn-success{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.btn-success:hover,.btn-success:focus,.btn-success:active,.btn-success.active,.open>.dropdown-toggle.btn-success{color:#fff;background-color:#449d44;border-color:#398439}.btn-success:active,.btn-success.active,.open>.dropdown-toggle.btn-success{background-image:none}.btn-success.disabled,.btn-success[disabled],fieldset[disabled] .btn-success,.btn-success.disabled:hover,.btn-success[disabled]:hover,fieldset[disabled] .btn-success:hover,.btn-success.disabled:focus,.btn-success[disabled]:focus,fieldset[disabled] .btn-success:focus,.btn-success.disabled:active,.btn-success[disabled]:active,fieldset[disabled] .btn-success:active,.btn-success.disabled.active,.btn-success[disabled].active,fieldset[disabled] .btn-success.active{background-color:#5cb85c;border-color:#4cae4c}.btn-success .badge{color:#5cb85c;background-color:#fff}.btn-info{color:#fff;background-color:#5bc0de;border-color:#46b8da}.btn-info:hover,.btn-info:focus,.btn-info:active,.btn-info.active,.open>.dropdown-toggle.btn-info{color:#fff;background-color:#31b0d5;border-color:#269abc}.btn-info:active,.btn-info.active,.open>.dropdown-toggle.btn-info{background-image:none}.btn-info.disabled,.btn-info[disabled],fieldset[disabled] .btn-info,.btn-info.disabled:hover,.btn-info[disabled]:hover,fieldset[disabled] .btn-info:hover,.btn-info.disabled:focus,.btn-info[disabled]:focus,fieldset[disabled] .btn-info:focus,.btn-info.disabled:active,.btn-info[disabled]:active,fieldset[disabled] .btn-info:active,.btn-info.disabled.active,.btn-info[disabled].active,fieldset[disabled] .btn-info.active{background-color:#5bc0de;border-color:#46b8da}.btn-info .badge{color:#5bc0de;background-color:#fff}.btn-warning{color:#fff;background-color:#f0ad4e;border-color:#eea236}.btn-warning:hover,.btn-warning:focus,.btn-warning:active,.btn-warning.active,.open>.dropdown-toggle.btn-warning{color:#fff;background-color:#ec971f;border-color:#d58512}.btn-warning:active,.btn-warning.active,.open>.dropdown-toggle.btn-warning{background-image:none}.btn-warning.disabled,.btn-warning[disabled],fieldset[disabled] .btn-warning,.btn-warning.disabled:hover,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning:hover,.btn-warning.disabled:focus,.btn-warning[disabled]:focus,fieldset[disabled] .btn-warning:focus,.btn-warning.disabled:active,.btn-warning[disabled]:active,fieldset[disabled] .btn-warning:active,.btn-warning.disabled.active,.btn-warning[disabled].active,fieldset[disabled] .btn-warning.active{background-color:#f0ad4e;border-color:#eea236}.btn-warning .badge{color:#f0ad4e;background-color:#fff}.btn-danger{color:#fff;background-color:#d9534f;border-color:#d43f3a}.btn-danger:hover,.btn-danger:focus,.btn-danger:active,.btn-danger.active,.open>.dropdown-toggle.btn-danger{color:#fff;background-color:#c9302c;border-color:#ac2925}.btn-danger:active,.btn-danger.active,.open>.dropdown-toggle.btn-danger{background-image:none}.btn-danger.disabled,.btn-danger[disabled],fieldset[disabled] .btn-danger,.btn-danger.disabled:hover,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger:hover,.btn-danger.disabled:focus,.btn-danger[disabled]:focus,fieldset[disabled] .btn-danger:focus,.btn-danger.disabled:active,.btn-danger[disabled]:active,fieldset[disabled] .btn-danger:active,.btn-danger.disabled.active,.btn-danger[disabled].active,fieldset[disabled] .btn-danger.active{background-color:#d9534f;border-color:#d43f3a}.btn-danger .badge{color:#d9534f;background-color:#fff}.btn-link{font-weight:400;color:#428bca;cursor:pointer;border-radius:0}.btn-link,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;-webkit-box-shadow:none;box-shadow:none}.btn-link,.btn-link:hover,.btn-link:focus,.btn-link:active{border-color:transparent}.btn-link:hover,.btn-link:focus{color:#2a6496;text-decoration:underline;background-color:transparent}.btn-link[disabled]:hover,fieldset[disabled] .btn-link:hover,.btn-link[disabled]:focus,fieldset[disabled] .btn-link:focus{color:#777;text-decoration:none}.btn-lg,.btn-group-lg>.btn{padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}.btn-sm,.btn-group-sm>.btn{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-xs,.btn-group-xs>.btn{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=submit].btn-block,input[type=reset].btn-block,input[type=button].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;-o-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition:height .35s ease;-o-transition:height .35s ease;transition:height .35s ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px solid;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;font-size:14px;text-align:left;list-style:none;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;-webkit-box-shadow:0 6px 12px rgba(0,0,0,.175);box-shadow:0 6px 12px rgba(0,0,0,.175)}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.42857143;color:#333;white-space:nowrap}.dropdown-menu>li>a:hover,.dropdown-menu>li>a:focus{color:#262626;text-decoration:none;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:hover,.dropdown-menu>.active>a:focus{color:#fff;text-decoration:none;background-color:#428bca;outline:0}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{color:#777}.dropdown-menu>.disabled>a:hover,.dropdown-menu>.disabled>a:focus{text-decoration:none;cursor:not-allowed;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled=false)}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{right:0;left:auto}.dropdown-menu-left{right:auto;left:0}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.42857143;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{content:"";border-top:0;border-bottom:4px solid}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:1px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{right:auto;left:0}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group>.btn,.btn-group-vertical>.btn{position:relative;float:left}.btn-group>.btn:hover,.btn-group-vertical>.btn:hover,.btn-group>.btn:focus,.btn-group-vertical>.btn:focus,.btn-group>.btn:active,.btn-group-vertical>.btn:active,.btn-group>.btn.active,.btn-group-vertical>.btn.active{z-index:2}.btn-group>.btn:focus,.btn-group-vertical>.btn:focus{outline:0}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child>.btn:last-child,.btn-group>.btn-group:first-child>.dropdown-toggle{border-top-right-radius:0;border-bottom-right-radius:0}.btn-group>.btn-group:last-child>.btn:first-child{border-top-left-radius:0;border-bottom-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-right:8px;padding-left:8px}.btn-group>.btn-lg+.dropdown-toggle{padding-right:12px;padding-left:12px}.btn-group.open .dropdown-toggle{-webkit-box-shadow:inset 0 3px 5px rgba(0,0,0,.125);box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{-webkit-box-shadow:none;box-shadow:none}.btn .caret{margin-left:0}.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-left-radius:0;border-top-right-radius:0;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-left-radius:0;border-top-right-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{display:table-cell;float:none;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn>input[type=radio],[data-toggle=buttons]>.btn>input[type=checkbox]{position:absolute;z-index:-1;filter:alpha(opacity=0);opacity:0}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-right:0;padding-left:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn{height:46px;padding:10px 16px;font-size:18px;line-height:1.33;border-radius:6px}select.input-group-lg>.form-control,select.input-group-lg>.input-group-addon,select.input-group-lg>.input-group-btn>.btn{height:46px;line-height:46px}textarea.input-group-lg>.form-control,textarea.input-group-lg>.input-group-addon,textarea.input-group-lg>.input-group-btn>.btn,select[multiple].input-group-lg>.form-control,select[multiple].input-group-lg>.input-group-addon,select[multiple].input-group-lg>.input-group-btn>.btn{height:auto}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}select.input-group-sm>.form-control,select.input-group-sm>.input-group-addon,select.input-group-sm>.input-group-btn>.btn{height:30px;line-height:30px}textarea.input-group-sm>.form-control,textarea.input-group-sm>.input-group-addon,textarea.input-group-sm>.input-group-btn>.btn,select[multiple].input-group-sm>.form-control,select[multiple].input-group-sm>.input-group-addon,select[multiple].input-group-sm>.input-group-btn>.btn{height:auto}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccc;border-radius:4px}.input-group-addon.input-sm{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=radio],.input-group-addon input[type=checkbox]{margin-top:0}.input-group .form-control:first-child,.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group-btn:last-child>.btn-group:not(:last-child)>.btn{border-top-right-radius:0;border-bottom-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group .form-control:last-child,.input-group-addon:last-child,.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:first-child>.btn-group:not(:first-child)>.btn{border-top-left-radius:0;border-bottom-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{position:relative;font-size:0;white-space:nowrap}.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:hover,.input-group-btn>.btn:focus,.input-group-btn>.btn:active{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{margin-left:-1px}.nav{padding-left:0;margin-bottom:0;list-style:none}.nav>li{position:relative;display:block}.nav>li>a{position:relative;display:block;padding:10px 15px}.nav>li>a:hover,.nav>li>a:focus{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:hover,.nav>li.disabled>a:focus{color:#777;text-decoration:none;cursor:not-allowed;background-color:transparent}.nav .open>a,.nav .open>a:hover,.nav .open>a:focus{background-color:#eee;border-color:#428bca}.nav .nav-divider{height:1px;margin:9px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.42857143;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:hover,.nav-tabs>li.active>a:focus{color:#555;cursor:default;background-color:#fff;border:1px solid #ddd;border-bottom-color:transparent}.nav-tabs.nav-justified{width:100%;border-bottom:0}.nav-tabs.nav-justified>li{float:none}.nav-tabs.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-tabs.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a:focus{border-bottom-color:#fff}}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:hover,.nav-pills>li.active>a:focus{color:#fff;background-color:#428bca}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified{width:100%}.nav-justified>li{float:none}.nav-justified>li>a{margin-bottom:5px;text-align:center}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified{border-bottom:0}.nav-tabs-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:hover,.nav-tabs-justified>.active>a:focus{border-bottom-color:#fff}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-left-radius:0;border-top-right-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:20px;border:1px solid transparent}@media (min-width:768px){.navbar{border-radius:4px}}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{padding-right:15px;padding-left:15px;overflow-x:visible;-webkit-overflow-scrolling:touch;border-top:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1)}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;-webkit-box-shadow:none;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{padding-right:0;padding-left:0}}.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{max-height:340px}@media (max-width:480px) and (orientation:landscape){.navbar-fixed-top .navbar-collapse,.navbar-fixed-bottom .navbar-collapse{max-height:200px}}.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container>.navbar-header,.container-fluid>.navbar-header,.container>.navbar-collapse,.container-fluid>.navbar-collapse{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-top,.navbar-fixed-bottom{position:fixed;right:0;left:0;z-index:1030;-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}@media (min-width:768px){.navbar-fixed-top,.navbar-fixed-bottom{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;height:50px;padding:15px 15px;font-size:18px;line-height:20px}.navbar-brand:hover,.navbar-brand:focus{text-decoration:none}@media (min-width:768px){.navbar>.container .navbar-brand,.navbar>.container-fluid .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;padding:9px 10px;margin-top:8px;margin-right:15px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7.5px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:20px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-nav .open .dropdown-menu>li>a,.navbar-nav .open .dropdown-menu .dropdown-header{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:20px}.navbar-nav .open .dropdown-menu>li>a:hover,.navbar-nav .open .dropdown-menu>li>a:focus{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:15px;padding-bottom:15px}.navbar-nav.navbar-right:last-child{margin-right:-15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important}}.navbar-form{padding:10px 15px;margin-top:8px;margin-right:-15px;margin-bottom:8px;margin-left:-15px;border-top:1px solid transparent;border-bottom:1px solid transparent;-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1);box-shadow:inset 0 1px 0 rgba(255,255,255,.1),0 1px 0 rgba(255,255,255,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn,.navbar-form .input-group .form-control{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .radio,.navbar-form .checkbox{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .radio label,.navbar-form .checkbox label{padding-left:0}.navbar-form .radio input[type=radio],.navbar-form .checkbox input[type=checkbox]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}}@media (min-width:768px){.navbar-form{width:auto;padding-top:0;padding-bottom:0;margin-right:0;margin-left:0;border:0;-webkit-box-shadow:none;box-shadow:none}.navbar-form.navbar-right:last-child{margin-right:-15px}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-left-radius:0;border-top-right-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:8px;margin-bottom:8px}.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.navbar-btn.btn-xs{margin-top:14px;margin-bottom:14px}.navbar-text{margin-top:15px;margin-bottom:15px}@media (min-width:768px){.navbar-text{float:left;margin-right:15px;margin-left:15px}.navbar-text.navbar-right:last-child{margin-right:0}}.navbar-default{background-color:#f8f8f8;border-color:#e7e7e7}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:hover,.navbar-default .navbar-brand:focus{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a{color:#777}.navbar-default .navbar-nav>li>a:hover,.navbar-default .navbar-nav>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:hover,.navbar-default .navbar-nav>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:hover,.navbar-default .navbar-nav>.disabled>a:focus{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:hover,.navbar-default .navbar-toggle:focus{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#e7e7e7}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:hover,.navbar-default .navbar-nav>.open>a:focus{color:#555;background-color:#e7e7e7}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus{color:#555;background-color:#e7e7e7}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:hover,.navbar-default .btn-link:focus{color:#333}.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:hover,.navbar-default .btn-link[disabled]:focus,fieldset[disabled] .navbar-default .btn-link:focus{color:#ccc}.navbar-inverse{background-color:#222;border-color:#080808}.navbar-inverse .navbar-brand{color:#777}.navbar-inverse .navbar-brand:hover,.navbar-inverse .navbar-brand:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-text{color:#777}.navbar-inverse .navbar-nav>li>a{color:#777}.navbar-inverse .navbar-nav>li>a:hover,.navbar-inverse .navbar-nav>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:hover,.navbar-inverse .navbar-nav>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:hover,.navbar-inverse .navbar-nav>.disabled>a:focus{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:hover,.navbar-inverse .navbar-toggle:focus{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:hover,.navbar-inverse .navbar-nav>.open>a:focus{color:#fff;background-color:#080808}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus{color:#fff;background-color:#080808}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#777}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#777}.navbar-inverse .btn-link:hover,.navbar-inverse .btn-link:focus{color:#fff}.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:hover,.navbar-inverse .btn-link[disabled]:focus,fieldset[disabled] .navbar-inverse .btn-link:focus{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:20px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{padding:0 5px;color:#ccc;content:"/\00a0"}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:20px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;margin-left:-1px;line-height:1.42857143;color:#428bca;text-decoration:none;background-color:#fff;border:1px solid #ddd}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-top-left-radius:4px;border-bottom-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-top-right-radius:4px;border-bottom-right-radius:4px}.pagination>li>a:hover,.pagination>li>span:hover,.pagination>li>a:focus,.pagination>li>span:focus{color:#2a6496;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>span,.pagination>.active>a:hover,.pagination>.active>span:hover,.pagination>.active>a:focus,.pagination>.active>span:focus{z-index:2;color:#fff;cursor:default;background-color:#428bca;border-color:#428bca}.pagination>.disabled>span,.pagination>.disabled>span:hover,.pagination>.disabled>span:focus,.pagination>.disabled>a,.pagination>.disabled>a:hover,.pagination>.disabled>a:focus{color:#777;cursor:not-allowed;background-color:#fff;border-color:#ddd}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-top-left-radius:6px;border-bottom-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-top-right-radius:6px;border-bottom-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-top-left-radius:3px;border-bottom-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-top-right-radius:3px;border-bottom-right-radius:3px}.pager{padding-left:0;margin:20px 0;text-align:center;list-style:none}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:hover,.pager li>a:focus{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:hover,.pager .disabled>a:focus,.pager .disabled>span{color:#777;cursor:not-allowed;background-color:#fff}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}a.label:hover,a.label:focus{color:#fff;text-decoration:none;cursor:pointer}.label:empty{display:none}.btn .label{position:relative;top:-1px}.label-default{background-color:#777}.label-default[href]:hover,.label-default[href]:focus{background-color:#5e5e5e}.label-primary{background-color:#428bca}.label-primary[href]:hover,.label-primary[href]:focus{background-color:#3071a9}.label-success{background-color:#5cb85c}.label-success[href]:hover,.label-success[href]:focus{background-color:#449d44}.label-info{background-color:#5bc0de}.label-info[href]:hover,.label-info[href]:focus{background-color:#31b0d5}.label-warning{background-color:#f0ad4e}.label-warning[href]:hover,.label-warning[href]:focus{background-color:#ec971f}.label-danger{background-color:#d9534f}.label-danger[href]:hover,.label-danger[href]:focus{background-color:#c9302c}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-xs .badge{top:0;padding:1px 5px}a.badge:hover,a.badge:focus{color:#fff;text-decoration:none;cursor:pointer}a.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#428bca;background-color:#fff}.nav-pills>li>a>.badge{margin-left:3px}.jumbotron{padding:30px;margin-bottom:30px;color:inherit;background-color:#eee}.jumbotron h1,.jumbotron .h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container .jumbotron{border-radius:6px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container .jumbotron{padding-right:60px;padding-left:60px}.jumbotron h1,.jumbotron .h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:20px;line-height:1.42857143;background-color:#fff;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;-o-transition:all .2s ease-in-out;transition:all .2s ease-in-out}.thumbnail>img,.thumbnail a>img{margin-right:auto;margin-left:auto}a.thumbnail:hover,a.thumbnail:focus,a.thumbnail.active{border-color:#428bca}.thumbnail .caption{padding:9px;color:#333}.alert{padding:15px;margin-bottom:20px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@-o-keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{from{background-position:40px 0}to{background-position:0 0}}.progress{height:20px;margin-bottom:20px;overflow:hidden;background-color:#f5f5f5;border-radius:4px;-webkit-box-shadow:inset 0 1px 2px rgba(0,0,0,.1);box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:20px;color:#fff;text-align:center;background-color:#428bca;-webkit-box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;-o-transition:width .6s ease;transition:width .6s ease}.progress-striped .progress-bar,.progress-bar-striped{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);-webkit-background-size:40px 40px;background-size:40px 40px}.progress.active .progress-bar,.progress-bar.active{-webkit-animation:progress-bar-stripes 2s linear infinite;-o-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar[aria-valuenow="1"],.progress-bar[aria-valuenow="2"]{min-width:30px}.progress-bar[aria-valuenow="0"]{min-width:30px;color:#777;background-color:transparent;background-image:none;-webkit-box-shadow:none;box-shadow:none}.progress-bar-success{background-color:#5cb85c}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-info{background-color:#5bc0de}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-warning{background-color:#f0ad4e}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.progress-bar-danger{background-color:#d9534f}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:-o-linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent);background-image:linear-gradient(45deg,rgba(255,255,255,.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,.15) 50%,rgba(255,255,255,.15) 75%,transparent 75%,transparent)}.media,.media-body{overflow:hidden;zoom:1}.media,.media .media{margin-top:15px}.media:first-child{margin-top:0}.media-object{display:block}.media-heading{margin:0 0 5px}.media>.pull-left{margin-right:10px}.media>.pull-right{margin-left:10px}.media-list{padding-left:0;list-style:none}.list-group{padding-left:0;margin-bottom:20px}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #ddd}.list-group-item:first-child{border-top-left-radius:4px;border-top-right-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}a.list-group-item{color:#555}a.list-group-item .list-group-item-heading{color:#333}a.list-group-item:hover,a.list-group-item:focus{color:#555;text-decoration:none;background-color:#f5f5f5}.list-group-item.disabled,.list-group-item.disabled:hover,.list-group-item.disabled:focus{color:#777;background-color:#eee}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:hover,.list-group-item.active:focus{z-index:2;color:#fff;background-color:#428bca;border-color:#428bca}.list-group-item.active .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>.small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:hover .list-group-item-text,.list-group-item.active:focus .list-group-item-text{color:#e1edf7}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:hover,a.list-group-item-success:focus{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:hover,a.list-group-item-success.active:focus{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:hover,a.list-group-item-info:focus{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:hover,a.list-group-item-info.active:focus{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:hover,a.list-group-item-warning:focus{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:hover,a.list-group-item-warning.active:focus{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:hover,a.list-group-item-danger:focus{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:hover,a.list-group-item-danger.active:focus{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:20px;background-color:#fff;border:1px solid transparent;border-radius:4px;-webkit-box-shadow:0 1px 1px rgba(0,0,0,.05);box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-left-radius:3px;border-top-right-radius:3px}.panel-heading>.dropdown .dropdown-toggle{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px;color:inherit}.panel-title>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #ddd;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group{margin-bottom:0}.panel>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-left-radius:3px;border-top-right-radius:3px}.panel>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.list-group+.panel-footer{border-top-width:0}.panel>.table,.panel>.table-responsive>.table,.panel>.panel-collapse>.table{margin-bottom:0}.panel>.table:first-child,.panel>.table-responsive:first-child>.table:first-child{border-top-left-radius:3px;border-top-right-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table:last-child,.panel>.table-responsive:last-child>.table:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child th,.panel>.table>tbody:first-child>tr:first-child td{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child{border-left:0}.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child{border-right:0}.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th{border-bottom:0}.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}.panel>.table-responsive{margin-bottom:0;border:0}.panel-group{margin-bottom:20px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #ddd}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #ddd}.panel-default{border-color:#ddd}.panel-default>.panel-heading{color:#333;background-color:#f5f5f5;border-color:#ddd}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ddd}.panel-default>.panel-heading .badge{color:#f5f5f5;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ddd}.panel-primary{border-color:#428bca}.panel-primary>.panel-heading{color:#fff;background-color:#428bca;border-color:#428bca}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#428bca}.panel-primary>.panel-heading .badge{color:#428bca;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#428bca}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive iframe,.embed-responsive embed,.embed-responsive object{position:absolute;top:0;bottom:0;left:0;width:100%;height:100%;border:0}.embed-responsive.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.05);box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;filter:alpha(opacity=20);opacity:.2}.close:hover,.close:focus{color:#000;text-decoration:none;cursor:pointer;filter:alpha(opacity=50);opacity:.5}button.close{-webkit-appearance:none;padding:0;cursor:pointer;background:0 0;border:0}.modal-open{overflow:hidden}.modal{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;display:none;overflow:hidden;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transition:-webkit-transform .3s ease-out;-o-transition:-o-transform .3s ease-out;transition:transform .3s ease-out;-webkit-transform:translate3d(0,-25%,0);-o-transform:translate3d(0,-25%,0);transform:translate3d(0,-25%,0)}.modal.in .modal-dialog{-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;outline:0;-webkit-box-shadow:0 3px 9px rgba(0,0,0,.5);box-shadow:0 3px 9px rgba(0,0,0,.5)}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{filter:alpha(opacity=0);opacity:0}.modal-backdrop.in{filter:alpha(opacity=50);opacity:.5}.modal-header{min-height:16.43px;padding:15px;border-bottom:1px solid #e5e5e5}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.42857143}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer .btn+.btn{margin-bottom:0;margin-left:5px}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{-webkit-box-shadow:0 5px 15px rgba(0,0,0,.5);box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-size:12px;line-height:1.4;visibility:visible;filter:alpha(opacity=0);opacity:0}.tooltip.in{filter:alpha(opacity=90);opacity:.9}.tooltip.top{padding:5px 0;margin-top:-3px}.tooltip.right{padding:0 5px;margin-left:3px}.tooltip.bottom{padding:5px 0;margin-top:3px}.tooltip.left{padding:0 5px;margin-left:-3px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;text-decoration:none;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{bottom:0;left:5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{right:5px;bottom:0;border-width:5px 5px 0;border-top-color:#000}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;left:5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;right:5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;text-align:left;white-space:normal;background-color:#fff;-webkit-background-clip:padding-box;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;-webkit-box-shadow:0 5px 10px rgba(0,0,0,.2);box-shadow:0 5px 10px rgba(0,0,0,.2)}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{padding:8px 14px;margin:0;font-size:14px;font-weight:400;line-height:18px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{content:"";border-width:10px}.popover.top>.arrow{bottom:-11px;left:50%;margin-left:-11px;border-top-color:#999;border-top-color:rgba(0,0,0,.25);border-bottom-width:0}.popover.top>.arrow:after{bottom:1px;margin-left:-10px;content:" ";border-top-color:#fff;border-bottom-width:0}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-right-color:#999;border-right-color:rgba(0,0,0,.25);border-left-width:0}.popover.right>.arrow:after{bottom:-10px;left:1px;content:" ";border-right-color:#fff;border-left-width:0}.popover.bottom>.arrow{top:-11px;left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25)}.popover.bottom>.arrow:after{top:1px;margin-left:-10px;content:" ";border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{right:1px;bottom:-10px;content:" ";border-right-width:0;border-left-color:#fff}.carousel{position:relative}.carousel-inner{position:relative;width:100%;overflow:hidden}.carousel-inner>.item{position:relative;display:none;-webkit-transition:.6s ease-in-out left;-o-transition:.6s ease-in-out left;transition:.6s ease-in-out left}.carousel-inner>.item>img,.carousel-inner>.item>a>img{line-height:1}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;bottom:0;left:0;width:15%;font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);filter:alpha(opacity=50);opacity:.5}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.5)),to(rgba(0,0,0,.0001)));background-image:linear-gradient(to right,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);background-repeat:repeat-x}.carousel-control.right{right:0;left:auto;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-o-linear-gradient(left,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);background-image:-webkit-gradient(linear,left top,right top,from(rgba(0,0,0,.0001)),to(rgba(0,0,0,.5)));background-image:linear-gradient(to right,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5) 100%);filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);background-repeat:repeat-x}.carousel-control:hover,.carousel-control:focus{color:#fff;text-decoration:none;filter:alpha(opacity=90);outline:0;opacity:.9}.carousel-control .icon-prev,.carousel-control .icon-next,.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right{position:absolute;top:50%;z-index:5;display:inline-block}.carousel-control .icon-prev,.carousel-control .glyphicon-chevron-left{left:50%;margin-left:-10px}.carousel-control .icon-next,.carousel-control .glyphicon-chevron-right{right:50%;margin-right:-10px}.carousel-control .icon-prev,.carousel-control .icon-next{width:20px;height:20px;margin-top:-10px;font-family:serif}.carousel-control .icon-prev:before{content:'\2039'}.carousel-control .icon-next:before{content:'\203a'}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;padding-left:0;margin-left:-30%;text-align:center;list-style:none}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;cursor:pointer;background-color:#000 \9;background-color:rgba(0,0,0,0);border:1px solid #fff;border-radius:10px}.carousel-indicators .active{width:12px;height:12px;margin:0;background-color:#fff}.carousel-caption{position:absolute;right:15%;bottom:20px;left:15%;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-prev,.carousel-control .icon-next{width:30px;height:30px;margin-top:-15px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-15px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-15px}.carousel-caption{right:20%;left:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:before,.clearfix:after,.dl-horizontal dd:before,.dl-horizontal dd:after,.container:before,.container:after,.container-fluid:before,.container-fluid:after,.row:before,.row:after,.form-horizontal .form-group:before,.form-horizontal .form-group:after,.btn-toolbar:before,.btn-toolbar:after,.btn-group-vertical>.btn-group:before,.btn-group-vertical>.btn-group:after,.nav:before,.nav:after,.navbar:before,.navbar:after,.navbar-header:before,.navbar-header:after,.navbar-collapse:before,.navbar-collapse:after,.pager:before,.pager:after,.panel-body:before,.panel-body:after,.modal-footer:before,.modal-footer:after{display:table;content:" "}.clearfix:after,.dl-horizontal dd:after,.container:after,.container-fluid:after,.row:after,.form-horizontal .form-group:after,.btn-toolbar:after,.btn-group-vertical>.btn-group:after,.nav:after,.navbar:after,.navbar-header:after,.navbar-collapse:after,.pager:after,.panel-body:after,.modal-footer:after{clear:both}.center-block{display:block;margin-right:auto;margin-left:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important;visibility:hidden!important}.affix{position:fixed;-webkit-transform:translate3d(0,0,0);-o-transform:translate3d(0,0,0);transform:translate3d(0,0,0)}@-ms-viewport{width:device-width}.visible-xs,.visible-sm,.visible-md,.visible-lg{display:none!important}.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table}tr.visible-xs{display:table-row!important}th.visible-xs,td.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table}tr.visible-sm{display:table-row!important}th.visible-sm,td.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table}tr.visible-md{display:table-row!important}th.visible-md,td.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table}tr.visible-lg{display:table-row!important}th.visible-lg,td.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table}tr.visible-print{display:table-row!important}th.visible-print,td.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}} \ No newline at end of file
diff --git a/rest_framework/static/rest_framework/css/default.css b/rest_framework/static/rest_framework/css/default.css
index 461cdfe5..4f52cc56 100644
--- a/rest_framework/static/rest_framework/css/default.css
+++ b/rest_framework/static/rest_framework/css/default.css
@@ -33,7 +33,11 @@ h2, h3 {
}
ul.breadcrumb {
- margin: 80px 0 0 0;
+ margin: 70px 0 0 0;
+}
+
+.breadcrumb li.active a {
+ color: #777;
}
form select, form input, form textarea {
@@ -67,5 +71,4 @@ pre {
.page-header {
border-bottom: none;
padding-bottom: 0px;
- margin-bottom: 20px;
}
diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.eot b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.eot
new file mode 100644
index 00000000..4a4ca865
--- /dev/null
+++ b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.eot
Binary files differ
diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg
new file mode 100644
index 00000000..25691af8
--- /dev/null
+++ b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.svg
@@ -0,0 +1,229 @@
+<?xml version="1.0" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" >
+<svg xmlns="http://www.w3.org/2000/svg">
+<metadata></metadata>
+<defs>
+<font id="glyphicons_halflingsregular" horiz-adv-x="1200" >
+<font-face units-per-em="1200" ascent="960" descent="-240" />
+<missing-glyph horiz-adv-x="500" />
+<glyph />
+<glyph />
+<glyph unicode="&#xd;" />
+<glyph unicode=" " />
+<glyph unicode="*" d="M100 500v200h259l-183 183l141 141l183 -183v259h200v-259l183 183l141 -141l-183 -183h259v-200h-259l183 -183l-141 -141l-183 183v-259h-200v259l-183 -183l-141 141l183 183h-259z" />
+<glyph unicode="+" d="M0 400v300h400v400h300v-400h400v-300h-400v-400h-300v400h-400z" />
+<glyph unicode="&#xa0;" />
+<glyph unicode="&#x2000;" horiz-adv-x="652" />
+<glyph unicode="&#x2001;" horiz-adv-x="1304" />
+<glyph unicode="&#x2002;" horiz-adv-x="652" />
+<glyph unicode="&#x2003;" horiz-adv-x="1304" />
+<glyph unicode="&#x2004;" horiz-adv-x="434" />
+<glyph unicode="&#x2005;" horiz-adv-x="326" />
+<glyph unicode="&#x2006;" horiz-adv-x="217" />
+<glyph unicode="&#x2007;" horiz-adv-x="217" />
+<glyph unicode="&#x2008;" horiz-adv-x="163" />
+<glyph unicode="&#x2009;" horiz-adv-x="260" />
+<glyph unicode="&#x200a;" horiz-adv-x="72" />
+<glyph unicode="&#x202f;" horiz-adv-x="260" />
+<glyph unicode="&#x205f;" horiz-adv-x="326" />
+<glyph unicode="&#x20ac;" d="M100 500l100 100h113q0 47 5 100h-218l100 100h135q37 167 112 257q117 141 297 141q242 0 354 -189q60 -103 66 -209h-181q0 55 -25.5 99t-63.5 68t-75 36.5t-67 12.5q-24 0 -52.5 -10t-62.5 -32t-65.5 -67t-50.5 -107h379l-100 -100h-300q-6 -46 -6 -100h406l-100 -100 h-300q9 -74 33 -132t52.5 -91t62 -54.5t59 -29t46.5 -7.5q29 0 66 13t75 37t63.5 67.5t25.5 96.5h174q-31 -172 -128 -278q-107 -117 -274 -117q-205 0 -324 158q-36 46 -69 131.5t-45 205.5h-217z" />
+<glyph unicode="&#x2212;" d="M200 400h900v300h-900v-300z" />
+<glyph unicode="&#x25fc;" horiz-adv-x="500" d="M0 0z" />
+<glyph unicode="&#x2601;" d="M-14 494q0 -80 56.5 -137t135.5 -57h750q120 0 205 86.5t85 207.5t-85 207t-205 86q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5z" />
+<glyph unicode="&#x2709;" d="M0 100l400 400l200 -200l200 200l400 -400h-1200zM0 300v600l300 -300zM0 1100l600 -603l600 603h-1200zM900 600l300 300v-600z" />
+<glyph unicode="&#x270f;" d="M-13 -13l333 112l-223 223zM187 403l214 -214l614 614l-214 214zM887 1103l214 -214l99 92q13 13 13 32.5t-13 33.5l-153 153q-15 13 -33 13t-33 -13z" />
+<glyph unicode="&#xe001;" d="M0 1200h1200l-500 -550v-550h300v-100h-800v100h300v550z" />
+<glyph unicode="&#xe002;" d="M14 84q18 -55 86 -75.5t147 5.5q65 21 109 69t44 90v606l600 155v-521q-64 16 -138 -7q-79 -26 -122.5 -83t-25.5 -111q18 -55 86 -75.5t147 4.5q70 23 111.5 63.5t41.5 95.5v881q0 10 -7 15.5t-17 2.5l-752 -193q-10 -3 -17 -12.5t-7 -19.5v-689q-64 17 -138 -7 q-79 -25 -122.5 -82t-25.5 -112z" />
+<glyph unicode="&#xe003;" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233z" />
+<glyph unicode="&#xe005;" d="M100 784q0 64 28 123t73 100.5t104.5 64t119 20.5t120 -38.5t104.5 -104.5q48 69 109.5 105t121.5 38t118.5 -20.5t102.5 -64t71 -100.5t27 -123q0 -57 -33.5 -117.5t-94 -124.5t-126.5 -127.5t-150 -152.5t-146 -174q-62 85 -145.5 174t-149.5 152.5t-126.5 127.5 t-94 124.5t-33.5 117.5z" />
+<glyph unicode="&#xe006;" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1z" />
+<glyph unicode="&#xe007;" d="M-72 800h479l146 400h2l146 -400h472l-382 -278l145 -449l-384 275l-382 -275l146 447zM168 71l2 1zM237 700l196 -142l-73 -226l192 140l195 -141l-74 229l193 140h-235l-77 211l-78 -211h-239z" />
+<glyph unicode="&#xe008;" d="M0 0v143l400 257v100q-37 0 -68.5 74.5t-31.5 125.5v200q0 124 88 212t212 88t212 -88t88 -212v-200q0 -51 -31.5 -125.5t-68.5 -74.5v-100l400 -257v-143h-1200z" />
+<glyph unicode="&#xe009;" d="M0 0v1100h1200v-1100h-1200zM100 100h100v100h-100v-100zM100 300h100v100h-100v-100zM100 500h100v100h-100v-100zM100 700h100v100h-100v-100zM100 900h100v100h-100v-100zM300 100h600v400h-600v-400zM300 600h600v400h-600v-400zM1000 100h100v100h-100v-100z M1000 300h100v100h-100v-100zM1000 500h100v100h-100v-100zM1000 700h100v100h-100v-100zM1000 900h100v100h-100v-100z" />
+<glyph unicode="&#xe010;" d="M0 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM0 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400 q-21 0 -35.5 14.5t-14.5 35.5zM600 50v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5zM600 650v400q0 21 14.5 35.5t35.5 14.5h400q21 0 35.5 -14.5t14.5 -35.5v-400 q0 -21 -14.5 -35.5t-35.5 -14.5h-400q-21 0 -35.5 14.5t-14.5 35.5z" />
+<glyph unicode="&#xe011;" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200 q-21 0 -35.5 14.5t-14.5 35.5zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 450v200q0 21 14.5 35.5t35.5 14.5h200 q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM800 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5z" />
+<glyph unicode="&#xe012;" d="M0 50v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM0 450q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v200q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5 t-14.5 -35.5v-200zM0 850v200q0 21 14.5 35.5t35.5 14.5h200q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5zM400 50v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5 t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 450v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5zM400 850v200q0 21 14.5 35.5t35.5 14.5h700q21 0 35.5 -14.5t14.5 -35.5 v-200q0 -21 -14.5 -35.5t-35.5 -14.5h-700q-21 0 -35.5 14.5t-14.5 35.5z" />
+<glyph unicode="&#xe013;" d="M29 454l419 -420l818 820l-212 212l-607 -607l-206 207z" />
+<glyph unicode="&#xe014;" d="M106 318l282 282l-282 282l212 212l282 -282l282 282l212 -212l-282 -282l282 -282l-212 -212l-282 282l-282 -282z" />
+<glyph unicode="&#xe015;" d="M23 693q0 200 142 342t342 142t342 -142t142 -342q0 -142 -78 -261l300 -300q7 -8 7 -18t-7 -18l-109 -109q-8 -7 -18 -7t-18 7l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 693q0 -136 97 -233t234 -97t233.5 96.5t96.5 233.5t-96.5 233.5t-233.5 96.5 t-234 -97t-97 -233zM300 600v200h100v100h200v-100h100v-200h-100v-100h-200v100h-100z" />
+<glyph unicode="&#xe016;" d="M23 694q0 200 142 342t342 142t342 -142t142 -342q0 -141 -78 -262l300 -299q7 -7 7 -18t-7 -18l-109 -109q-8 -8 -18 -8t-18 8l-300 300q-119 -78 -261 -78q-200 0 -342 142t-142 342zM176 694q0 -136 97 -233t234 -97t233.5 97t96.5 233t-96.5 233t-233.5 97t-234 -97 t-97 -233zM300 601h400v200h-400v-200z" />
+<glyph unicode="&#xe017;" d="M23 600q0 183 105 331t272 210v-166q-103 -55 -165 -155t-62 -220q0 -177 125 -302t302 -125t302 125t125 302q0 120 -62 220t-165 155v166q167 -62 272 -210t105 -331q0 -118 -45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5 zM500 750q0 -21 14.5 -35.5t35.5 -14.5h100q21 0 35.5 14.5t14.5 35.5v400q0 21 -14.5 35.5t-35.5 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-400z" />
+<glyph unicode="&#xe018;" d="M100 1h200v300h-200v-300zM400 1v500h200v-500h-200zM700 1v800h200v-800h-200zM1000 1v1200h200v-1200h-200z" />
+<glyph unicode="&#xe019;" d="M26 601q0 -33 6 -74l151 -38l2 -6q14 -49 38 -93l3 -5l-80 -134q45 -59 105 -105l133 81l5 -3q45 -26 94 -39l5 -2l38 -151q40 -5 74 -5q27 0 74 5l38 151l6 2q46 13 93 39l5 3l134 -81q56 44 104 105l-80 134l3 5q24 44 39 93l1 6l152 38q5 40 5 74q0 28 -5 73l-152 38 l-1 6q-16 51 -39 93l-3 5l80 134q-44 58 -104 105l-134 -81l-5 3q-45 25 -93 39l-6 1l-38 152q-40 5 -74 5q-27 0 -74 -5l-38 -152l-5 -1q-50 -14 -94 -39l-5 -3l-133 81q-59 -47 -105 -105l80 -134l-3 -5q-25 -47 -38 -93l-2 -6l-151 -38q-6 -48 -6 -73zM385 601 q0 88 63 151t152 63t152 -63t63 -151q0 -89 -63 -152t-152 -63t-152 63t-63 152z" />
+<glyph unicode="&#xe020;" d="M100 1025v50q0 10 7.5 17.5t17.5 7.5h275v100q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5v-100h275q10 0 17.5 -7.5t7.5 -17.5v-50q0 -11 -7 -18t-18 -7h-1050q-11 0 -18 7t-7 18zM200 100v800h900v-800q0 -41 -29.5 -71t-70.5 -30h-700q-41 0 -70.5 30 t-29.5 71zM300 100h100v700h-100v-700zM500 100h100v700h-100v-700zM500 1100h300v100h-300v-100zM700 100h100v700h-100v-700zM900 100h100v700h-100v-700z" />
+<glyph unicode="&#xe021;" d="M1 601l656 644l644 -644h-200v-600h-300v400h-300v-400h-300v600h-200z" />
+<glyph unicode="&#xe022;" d="M100 25v1150q0 11 7 18t18 7h475v-500h400v-675q0 -11 -7 -18t-18 -7h-850q-11 0 -18 7t-7 18zM700 800v300l300 -300h-300z" />
+<glyph unicode="&#xe023;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 500v400h100 v-300h200v-100h-300z" />
+<glyph unicode="&#xe024;" d="M-100 0l431 1200h209l-21 -300h162l-20 300h208l431 -1200h-538l-41 400h-242l-40 -400h-539zM488 500h224l-27 300h-170z" />
+<glyph unicode="&#xe025;" d="M0 0v400h490l-290 300h200v500h300v-500h200l-290 -300h490v-400h-1100zM813 200h175v100h-175v-100z" />
+<glyph unicode="&#xe026;" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM188 600q0 -170 121 -291t291 -121t291 121t121 291t-121 291t-291 121 t-291 -121t-121 -291zM350 600h150v300h200v-300h150l-250 -300z" />
+<glyph unicode="&#xe027;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM350 600l250 300 l250 -300h-150v-300h-200v300h-150z" />
+<glyph unicode="&#xe028;" d="M0 25v475l200 700h800l199 -700l1 -475q0 -11 -7 -18t-18 -7h-1150q-11 0 -18 7t-7 18zM200 500h200l50 -200h300l50 200h200l-97 500h-606z" />
+<glyph unicode="&#xe029;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM500 397v401 l297 -200z" />
+<glyph unicode="&#xe030;" d="M23 600q0 -118 45.5 -224.5t123 -184t184 -123t224.5 -45.5t224.5 45.5t184 123t123 184t45.5 224.5h-150q0 -177 -125 -302t-302 -125t-302 125t-125 302t125 302t302 125q136 0 246 -81l-146 -146h400v400l-145 -145q-157 122 -355 122q-118 0 -224.5 -45.5t-184 -123 t-123 -184t-45.5 -224.5z" />
+<glyph unicode="&#xe031;" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5q198 0 355 -122l145 145v-400h-400l147 147q-112 80 -247 80q-177 0 -302 -125t-125 -302h-150zM100 0v400h400l-147 -147q112 -80 247 -80q177 0 302 125t125 302h150q0 -118 -45.5 -224.5t-123 -184t-184 -123 t-224.5 -45.5q-198 0 -355 122z" />
+<glyph unicode="&#xe032;" d="M100 0h1100v1200h-1100v-1200zM200 100v900h900v-900h-900zM300 200v100h100v-100h-100zM300 400v100h100v-100h-100zM300 600v100h100v-100h-100zM300 800v100h100v-100h-100zM500 200h500v100h-500v-100zM500 400v100h500v-100h-500zM500 600v100h500v-100h-500z M500 800v100h500v-100h-500z" />
+<glyph unicode="&#xe033;" d="M0 100v600q0 41 29.5 70.5t70.5 29.5h100v200q0 82 59 141t141 59h300q82 0 141 -59t59 -141v-200h100q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-900q-41 0 -70.5 29.5t-29.5 70.5zM400 800h300v150q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-150z" />
+<glyph unicode="&#xe034;" d="M100 0v1100h100v-1100h-100zM300 400q60 60 127.5 84t127.5 17.5t122 -23t119 -30t110 -11t103 42t91 120.5v500q-40 -81 -101.5 -115.5t-127.5 -29.5t-138 25t-139.5 40t-125.5 25t-103 -29.5t-65 -115.5v-500z" />
+<glyph unicode="&#xe035;" d="M0 275q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 127 70.5 231.5t184.5 161.5t245 57t245 -57t184.5 -161.5t70.5 -231.5v-300q0 -11 7 -18t18 -7h50q11 0 18 7t7 18v300q0 116 -49.5 227t-131 192.5t-192.5 131t-227 49.5t-227 -49.5t-192.5 -131t-131 -192.5 t-49.5 -227v-300zM200 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14zM800 20v460q0 8 6 14t14 6h160q8 0 14 -6t6 -14v-460q0 -8 -6 -14t-14 -6h-160q-8 0 -14 6t-6 14z" />
+<glyph unicode="&#xe036;" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM688 459l141 141l-141 141l71 71l141 -141l141 141l71 -71l-141 -141l141 -141l-71 -71l-141 141l-141 -141z" />
+<glyph unicode="&#xe037;" d="M0 400h300l300 -200v800l-300 -200h-300v-400zM700 857l69 53q111 -135 111 -310q0 -169 -106 -302l-67 54q86 110 86 248q0 146 -93 257z" />
+<glyph unicode="&#xe038;" d="M0 401v400h300l300 200v-800l-300 200h-300zM702 858l69 53q111 -135 111 -310q0 -170 -106 -303l-67 55q86 110 86 248q0 145 -93 257zM889 951l7 -8q123 -151 123 -344q0 -189 -119 -339l-7 -8l81 -66l6 8q142 178 142 405q0 230 -144 408l-6 8z" />
+<glyph unicode="&#xe039;" d="M0 0h500v500h-200v100h-100v-100h-200v-500zM0 600h100v100h400v100h100v100h-100v300h-500v-600zM100 100v300h300v-300h-300zM100 800v300h300v-300h-300zM200 200v100h100v-100h-100zM200 900h100v100h-100v-100zM500 500v100h300v-300h200v-100h-100v-100h-200v100 h-100v100h100v200h-200zM600 0v100h100v-100h-100zM600 1000h100v-300h200v-300h300v200h-200v100h200v500h-600v-200zM800 800v300h300v-300h-300zM900 0v100h300v-100h-300zM900 900v100h100v-100h-100zM1100 200v100h100v-100h-100z" />
+<glyph unicode="&#xe040;" d="M0 200h100v1000h-100v-1000zM100 0v100h300v-100h-300zM200 200v1000h100v-1000h-100zM500 0v91h100v-91h-100zM500 200v1000h200v-1000h-200zM700 0v91h100v-91h-100zM800 200v1000h100v-1000h-100zM900 0v91h200v-91h-200zM1000 200v1000h200v-1000h-200z" />
+<glyph unicode="&#xe041;" d="M0 700l1 475q0 10 7.5 17.5t17.5 7.5h474l700 -700l-500 -500zM148 953q0 -42 29 -71q30 -30 71.5 -30t71.5 30q29 29 29 71t-29 71q-30 30 -71.5 30t-71.5 -30q-29 -29 -29 -71z" />
+<glyph unicode="&#xe042;" d="M1 700l1 475q0 11 7 18t18 7h474l700 -700l-500 -500zM148 953q0 -42 30 -71q29 -30 71 -30t71 30q30 29 30 71t-30 71q-29 30 -71 30t-71 -30q-30 -29 -30 -71zM701 1200h100l700 -700l-500 -500l-50 50l450 450z" />
+<glyph unicode="&#xe043;" d="M100 0v1025l175 175h925v-1000l-100 -100v1000h-750l-100 -100h750v-1000h-900z" />
+<glyph unicode="&#xe044;" d="M200 0l450 444l450 -443v1150q0 20 -14.5 35t-35.5 15h-800q-21 0 -35.5 -15t-14.5 -35v-1151z" />
+<glyph unicode="&#xe045;" d="M0 100v700h200l100 -200h600l100 200h200v-700h-200v200h-800v-200h-200zM253 829l40 -124h592l62 124l-94 346q-2 11 -10 18t-18 7h-450q-10 0 -18 -7t-10 -18zM281 24l38 152q2 10 11.5 17t19.5 7h500q10 0 19.5 -7t11.5 -17l38 -152q2 -10 -3.5 -17t-15.5 -7h-600 q-10 0 -15.5 7t-3.5 17z" />
+<glyph unicode="&#xe046;" d="M0 200q0 -41 29.5 -70.5t70.5 -29.5h1000q41 0 70.5 29.5t29.5 70.5v600q0 41 -29.5 70.5t-70.5 29.5h-150q-4 8 -11.5 21.5t-33 48t-53 61t-69 48t-83.5 21.5h-200q-41 0 -82 -20.5t-70 -50t-52 -59t-34 -50.5l-12 -20h-150q-41 0 -70.5 -29.5t-29.5 -70.5v-600z M356 500q0 100 72 172t172 72t172 -72t72 -172t-72 -172t-172 -72t-172 72t-72 172zM494 500q0 -44 31 -75t75 -31t75 31t31 75t-31 75t-75 31t-75 -31t-31 -75zM900 700v100h100v-100h-100z" />
+<glyph unicode="&#xe047;" d="M53 0h365v66q-41 0 -72 11t-49 38t1 71l92 234h391l82 -222q16 -45 -5.5 -88.5t-74.5 -43.5v-66h417v66q-34 1 -74 43q-18 19 -33 42t-21 37l-6 13l-385 998h-93l-399 -1006q-24 -48 -52 -75q-12 -12 -33 -25t-36 -20l-15 -7v-66zM416 521l178 457l46 -140l116 -317h-340 z" />
+<glyph unicode="&#xe048;" d="M100 0v89q41 7 70.5 32.5t29.5 65.5v827q0 28 -1 39.5t-5.5 26t-15.5 21t-29 14t-49 14.5v71l471 -1q120 0 213 -88t93 -228q0 -55 -11.5 -101.5t-28 -74t-33.5 -47.5t-28 -28l-12 -7q8 -3 21.5 -9t48 -31.5t60.5 -58t47.5 -91.5t21.5 -129q0 -84 -59 -156.5t-142 -111 t-162 -38.5h-500zM400 200h161q89 0 153 48.5t64 132.5q0 90 -62.5 154.5t-156.5 64.5h-159v-400zM400 700h139q76 0 130 61.5t54 138.5q0 82 -84 130.5t-239 48.5v-379z" />
+<glyph unicode="&#xe049;" d="M200 0v57q77 7 134.5 40.5t65.5 80.5l173 849q10 56 -10 74t-91 37q-6 1 -10.5 2.5t-9.5 2.5v57h425l2 -57q-33 -8 -62 -25.5t-46 -37t-29.5 -38t-17.5 -30.5l-5 -12l-128 -825q-10 -52 14 -82t95 -36v-57h-500z" />
+<glyph unicode="&#xe050;" d="M-75 200h75v800h-75l125 167l125 -167h-75v-800h75l-125 -167zM300 900v300h150h700h150v-300h-50q0 29 -8 48.5t-18.5 30t-33.5 15t-39.5 5.5t-50.5 1h-200v-850l100 -50v-100h-400v100l100 50v850h-200q-34 0 -50.5 -1t-40 -5.5t-33.5 -15t-18.5 -30t-8.5 -48.5h-49z " />
+<glyph unicode="&#xe051;" d="M33 51l167 125v-75h800v75l167 -125l-167 -125v75h-800v-75zM100 901v300h150h700h150v-300h-50q0 29 -8 48.5t-18 30t-33.5 15t-40 5.5t-50.5 1h-200v-650l100 -50v-100h-400v100l100 50v650h-200q-34 0 -50.5 -1t-39.5 -5.5t-33.5 -15t-18.5 -30t-8 -48.5h-50z" />
+<glyph unicode="&#xe052;" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 350q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM0 650q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1000q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 950q0 -20 14.5 -35t35.5 -15h600q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-600q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" />
+<glyph unicode="&#xe053;" d="M0 50q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM0 650q0 -20 14.5 -35t35.5 -15h1100q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5 v-100zM200 350q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM200 950q0 -20 14.5 -35t35.5 -15h700q21 0 35.5 15t14.5 35v100q0 21 -14.5 35.5t-35.5 14.5h-700q-21 0 -35.5 -14.5 t-14.5 -35.5v-100z" />
+<glyph unicode="&#xe054;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM100 650v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1000q-21 0 -35.5 15 t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM500 950v100q0 21 14.5 35.5t35.5 14.5h600q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-600 q-21 0 -35.5 15t-14.5 35z" />
+<glyph unicode="&#xe055;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h1100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-1100 q-21 0 -35.5 15t-14.5 35z" />
+<glyph unicode="&#xe056;" d="M0 50v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 350v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM0 650v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15t-14.5 35zM0 950v100q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-100q-21 0 -35.5 15 t-14.5 35zM300 50v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 350v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800 q-21 0 -35.5 15t-14.5 35zM300 650v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15h-800q-21 0 -35.5 15t-14.5 35zM300 950v100q0 21 14.5 35.5t35.5 14.5h800q21 0 35.5 -14.5t14.5 -35.5v-100q0 -20 -14.5 -35t-35.5 -15 h-800q-21 0 -35.5 15t-14.5 35z" />
+<glyph unicode="&#xe057;" d="M-101 500v100h201v75l166 -125l-166 -125v75h-201zM300 0h100v1100h-100v-1100zM500 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35 v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 650q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM500 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100 q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100z" />
+<glyph unicode="&#xe058;" d="M1 50q0 -20 14.5 -35t35.5 -15h600q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-600q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 350q0 -20 14.5 -35t35.5 -15h300q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-300q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 650 q0 -20 14.5 -35t35.5 -15h500q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-500q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM1 950q0 -20 14.5 -35t35.5 -15h100q20 0 35 15t15 35v100q0 21 -15 35.5t-35 14.5h-100q-21 0 -35.5 -14.5t-14.5 -35.5v-100zM801 0v1100h100v-1100 h-100zM934 550l167 -125v75h200v100h-200v75z" />
+<glyph unicode="&#xe059;" d="M0 275v650q0 31 22 53t53 22h750q31 0 53 -22t22 -53v-650q0 -31 -22 -53t-53 -22h-750q-31 0 -53 22t-22 53zM900 600l300 300v-600z" />
+<glyph unicode="&#xe060;" d="M0 44v1012q0 18 13 31t31 13h1112q19 0 31.5 -13t12.5 -31v-1012q0 -18 -12.5 -31t-31.5 -13h-1112q-18 0 -31 13t-13 31zM100 263l247 182l298 -131l-74 156l293 318l236 -288v500h-1000v-737zM208 750q0 56 39 95t95 39t95 -39t39 -95t-39 -95t-95 -39t-95 39t-39 95z " />
+<glyph unicode="&#xe062;" d="M148 745q0 124 60.5 231.5t165 172t226.5 64.5q123 0 227 -63t164.5 -169.5t60.5 -229.5t-73 -272q-73 -114 -166.5 -237t-150.5 -189l-57 -66q-10 9 -27 26t-66.5 70.5t-96 109t-104 135.5t-100.5 155q-63 139 -63 262zM342 772q0 -107 75.5 -182.5t181.5 -75.5 q107 0 182.5 75.5t75.5 182.5t-75.5 182t-182.5 75t-182 -75.5t-75 -181.5z" />
+<glyph unicode="&#xe063;" d="M1 600q0 122 47.5 233t127.5 191t191 127.5t233 47.5t233 -47.5t191 -127.5t127.5 -191t47.5 -233t-47.5 -233t-127.5 -191t-191 -127.5t-233 -47.5t-233 47.5t-191 127.5t-127.5 191t-47.5 233zM173 600q0 -177 125.5 -302t301.5 -125v854q-176 0 -301.5 -125 t-125.5 -302z" />
+<glyph unicode="&#xe064;" d="M117 406q0 94 34 186t88.5 172.5t112 159t115 177t87.5 194.5q21 -71 57.5 -142.5t76 -130.5t83 -118.5t82 -117t70 -116t50 -125.5t18.5 -136q0 -89 -39 -165.5t-102 -126.5t-140 -79.5t-156 -33.5q-114 6 -211.5 53t-161.5 139t-64 210zM243 414q14 -82 59.5 -136 t136.5 -80l16 98q-7 6 -18 17t-34 48t-33 77q-15 73 -14 143.5t10 122.5l9 51q-92 -110 -119.5 -185t-12.5 -156z" />
+<glyph unicode="&#xe065;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5q366 -6 397 -14l-186 -186h-311q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v125l200 200v-225q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM436 341l161 50l412 412l-114 113l-405 -405zM995 1015l113 -113l113 113l-21 85l-92 28z" />
+<glyph unicode="&#xe066;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h261l2 -80q-133 -32 -218 -120h-145q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5l200 153v-53q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5 zM423 524q30 38 81.5 64t103 35.5t99 14t77.5 3.5l29 -1v-209l360 324l-359 318v-216q-7 0 -19 -1t-48 -8t-69.5 -18.5t-76.5 -37t-76.5 -59t-62 -88t-39.5 -121.5z" />
+<glyph unicode="&#xe067;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q61 0 127 -23l-178 -177h-349q-41 0 -70.5 -29.5t-29.5 -70.5v-500q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v69l200 200v-169q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5 t-117.5 282.5zM342 632l283 -284l567 567l-137 137l-430 -431l-146 147z" />
+<glyph unicode="&#xe068;" d="M0 603l300 296v-198h200v200h-200l300 300l295 -300h-195v-200h200v198l300 -296l-300 -300v198h-200v-200h195l-295 -300l-300 300h200v200h-200v-198z" />
+<glyph unicode="&#xe069;" d="M200 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-1100l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" />
+<glyph unicode="&#xe070;" d="M0 50v1000q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-437l500 487v-487l500 487v-1100l-500 488v-488l-500 488v-438q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5z" />
+<glyph unicode="&#xe071;" d="M136 550l564 550v-487l500 487v-1100l-500 488v-488z" />
+<glyph unicode="&#xe072;" d="M200 0l900 550l-900 550v-1100z" />
+<glyph unicode="&#xe073;" d="M200 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200q-21 0 -35.5 -14.5t-14.5 -35.5v-800zM600 150q0 -21 14.5 -35.5t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v800q0 21 -14.5 35.5t-35.5 14.5h-200 q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" />
+<glyph unicode="&#xe074;" d="M200 150q0 -20 14.5 -35t35.5 -15h800q21 0 35.5 15t14.5 35v800q0 21 -14.5 35.5t-35.5 14.5h-800q-21 0 -35.5 -14.5t-14.5 -35.5v-800z" />
+<glyph unicode="&#xe075;" d="M0 0v1100l500 -487v487l564 -550l-564 -550v488z" />
+<glyph unicode="&#xe076;" d="M0 0v1100l500 -487v487l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438l-500 -488v488z" />
+<glyph unicode="&#xe077;" d="M300 0v1100l500 -487v437q0 21 14.5 35.5t35.5 14.5h100q21 0 35.5 -14.5t14.5 -35.5v-1000q0 -21 -14.5 -35.5t-35.5 -14.5h-100q-21 0 -35.5 14.5t-14.5 35.5v438z" />
+<glyph unicode="&#xe078;" d="M100 250v100q0 21 14.5 35.5t35.5 14.5h1000q21 0 35.5 -14.5t14.5 -35.5v-100q0 -21 -14.5 -35.5t-35.5 -14.5h-1000q-21 0 -35.5 14.5t-14.5 35.5zM100 500h1100l-550 564z" />
+<glyph unicode="&#xe079;" d="M185 599l592 -592l240 240l-353 353l353 353l-240 240z" />
+<glyph unicode="&#xe080;" d="M272 194l353 353l-353 353l241 240l572 -571l21 -22l-1 -1v-1l-592 -591z" />
+<glyph unicode="&#xe081;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM300 500h200v-200h200v200h200v200h-200v200h-200v-200h-200v-200z" />
+<glyph unicode="&#xe082;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM300 500h600v200h-600v-200z" />
+<glyph unicode="&#xe083;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM246 459l213 -213l141 142l141 -142l213 213l-142 141l142 141l-213 212l-141 -141l-141 142l-212 -213l141 -141 z" />
+<glyph unicode="&#xe084;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM270 551l276 -277l411 411l-175 174l-236 -236l-102 102z" />
+<glyph unicode="&#xe085;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM364 700h143q4 0 11.5 -1t11 -1t6.5 3t3 9t1 11t3.5 8.5t3.5 6t5.5 4t6.5 2.5t9 1.5t9 0.5h11.5h12.5 q19 0 30 -10t11 -26q0 -22 -4 -28t-27 -22q-5 -1 -12.5 -3t-27 -13.5t-34 -27t-26.5 -46t-11 -68.5h200q5 3 14 8t31.5 25.5t39.5 45.5t31 69t14 94q0 51 -17.5 89t-42 58t-58.5 32t-58.5 15t-51.5 3q-50 0 -90.5 -12t-75 -38.5t-53.5 -74.5t-19 -114zM500 300h200v100h-200 v-100z" />
+<glyph unicode="&#xe086;" d="M3 600q0 162 80 299.5t217.5 217.5t299.5 80t299.5 -80t217.5 -217.5t80 -299.5t-80 -299.5t-217.5 -217.5t-299.5 -80t-299.5 80t-217.5 217.5t-80 299.5zM400 300h400v100h-100v300h-300v-100h100v-200h-100v-100zM500 800h200v100h-200v-100z" />
+<glyph unicode="&#xe087;" d="M0 500v200h195q31 125 98.5 199.5t206.5 100.5v200h200v-200q54 -20 113 -60t112.5 -105.5t71.5 -134.5h203v-200h-203q-25 -102 -116.5 -186t-180.5 -117v-197h-200v197q-140 27 -208 102.5t-98 200.5h-194zM290 500q24 -73 79.5 -127.5t130.5 -78.5v206h200v-206 q149 48 201 206h-201v200h200q-25 74 -75.5 127t-124.5 77v-204h-200v203q-75 -23 -130 -77t-79 -126h209v-200h-210z" />
+<glyph unicode="&#xe088;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM356 465l135 135 l-135 135l109 109l135 -135l135 135l109 -109l-135 -135l135 -135l-109 -109l-135 135l-135 -135z" />
+<glyph unicode="&#xe089;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM322 537l141 141 l87 -87l204 205l142 -142l-346 -345z" />
+<glyph unicode="&#xe090;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -115 62 -215l568 567q-100 62 -216 62q-171 0 -292.5 -121.5t-121.5 -292.5zM391 245q97 -59 209 -59q171 0 292.5 121.5t121.5 292.5 q0 112 -59 209z" />
+<glyph unicode="&#xe091;" d="M0 547l600 453v-300h600v-300h-600v-301z" />
+<glyph unicode="&#xe092;" d="M0 400v300h600v300l600 -453l-600 -448v301h-600z" />
+<glyph unicode="&#xe093;" d="M204 600l450 600l444 -600h-298v-600h-300v600h-296z" />
+<glyph unicode="&#xe094;" d="M104 600h296v600h300v-600h298l-449 -600z" />
+<glyph unicode="&#xe095;" d="M0 200q6 132 41 238.5t103.5 193t184 138t271.5 59.5v271l600 -453l-600 -448v301q-95 -2 -183 -20t-170 -52t-147 -92.5t-100 -135.5z" />
+<glyph unicode="&#xe096;" d="M0 0v400l129 -129l294 294l142 -142l-294 -294l129 -129h-400zM635 777l142 -142l294 294l129 -129v400h-400l129 -129z" />
+<glyph unicode="&#xe097;" d="M34 176l295 295l-129 129h400v-400l-129 130l-295 -295zM600 600v400l129 -129l295 295l142 -141l-295 -295l129 -130h-400z" />
+<glyph unicode="&#xe101;" d="M23 600q0 118 45.5 224.5t123 184t184 123t224.5 45.5t224.5 -45.5t184 -123t123 -184t45.5 -224.5t-45.5 -224.5t-123 -184t-184 -123t-224.5 -45.5t-224.5 45.5t-184 123t-123 184t-45.5 224.5zM456 851l58 -302q4 -20 21.5 -34.5t37.5 -14.5h54q20 0 37.5 14.5 t21.5 34.5l58 302q4 20 -8 34.5t-32 14.5h-207q-21 0 -33 -14.5t-8 -34.5zM500 300h200v100h-200v-100z" />
+<glyph unicode="&#xe102;" d="M0 800h100v-200h400v300h200v-300h400v200h100v100h-111q1 1 1 6.5t-1.5 15t-3.5 17.5l-34 172q-11 39 -41.5 63t-69.5 24q-32 0 -61 -17l-239 -144q-22 -13 -40 -35q-19 24 -40 36l-238 144q-33 18 -62 18q-39 0 -69.5 -23t-40.5 -61l-35 -177q-2 -8 -3 -18t-1 -15v-6 h-111v-100zM100 0h400v400h-400v-400zM200 900q-3 0 14 48t36 96l18 47l213 -191h-281zM700 0v400h400v-400h-400zM731 900l202 197q5 -12 12 -32.5t23 -64t25 -72t7 -28.5h-269z" />
+<glyph unicode="&#xe103;" d="M0 -22v143l216 193q-9 53 -13 83t-5.5 94t9 113t38.5 114t74 124q47 60 99.5 102.5t103 68t127.5 48t145.5 37.5t184.5 43.5t220 58.5q0 -189 -22 -343t-59 -258t-89 -181.5t-108.5 -120t-122 -68t-125.5 -30t-121.5 -1.5t-107.5 12.5t-87.5 17t-56.5 7.5l-99 -55z M238.5 300.5q19.5 -6.5 86.5 76.5q55 66 367 234q70 38 118.5 69.5t102 79t99 111.5t86.5 148q22 50 24 60t-6 19q-7 5 -17 5t-26.5 -14.5t-33.5 -39.5q-35 -51 -113.5 -108.5t-139.5 -89.5l-61 -32q-369 -197 -458 -401q-48 -111 -28.5 -117.5z" />
+<glyph unicode="&#xe104;" d="M111 408q0 -33 5 -63q9 -56 44 -119.5t105 -108.5q31 -21 64 -16t62 23.5t57 49.5t48 61.5t35 60.5q32 66 39 184.5t-13 157.5q79 -80 122 -164t26 -184q-5 -33 -20.5 -69.5t-37.5 -80.5q-10 -19 -14.5 -29t-12 -26t-9 -23.5t-3 -19t2.5 -15.5t11 -9.5t19.5 -5t30.5 2.5 t42 8q57 20 91 34t87.5 44.5t87 64t65.5 88.5t47 122q38 172 -44.5 341.5t-246.5 278.5q22 -44 43 -129q39 -159 -32 -154q-15 2 -33 9q-79 33 -120.5 100t-44 175.5t48.5 257.5q-13 -8 -34 -23.5t-72.5 -66.5t-88.5 -105.5t-60 -138t-8 -166.5q2 -12 8 -41.5t8 -43t6 -39.5 t3.5 -39.5t-1 -33.5t-6 -31.5t-13.5 -24t-21 -20.5t-31 -12q-38 -10 -67 13t-40.5 61.5t-15 81.5t10.5 75q-52 -46 -83.5 -101t-39 -107t-7.5 -85z" />
+<glyph unicode="&#xe105;" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5t145.5 -23.5t132.5 -59t116.5 -83.5t97 -90t74.5 -85.5t49 -63.5t20 -30l26 -40l-26 -40q-6 -10 -20 -30t-49 -63.5t-74.5 -85.5t-97 -90t-116.5 -83.5t-132.5 -59t-145.5 -23.5 t-145.5 23.5t-132.5 59t-116.5 83.5t-97 90t-74.5 85.5t-49 63.5t-20 30zM120 600q7 -10 40.5 -58t56 -78.5t68 -77.5t87.5 -75t103 -49.5t125 -21.5t123.5 20t100.5 45.5t85.5 71.5t66.5 75.5t58 81.5t47 66q-1 1 -28.5 37.5t-42 55t-43.5 53t-57.5 63.5t-58.5 54 q49 -74 49 -163q0 -124 -88 -212t-212 -88t-212 88t-88 212q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l105 105q-37 24 -75 72t-57 84l-20 36z" />
+<glyph unicode="&#xe106;" d="M-61 600l26 40q6 10 20 30t49 63.5t74.5 85.5t97 90t116.5 83.5t132.5 59t145.5 23.5q61 0 121 -17l37 142h148l-314 -1200h-148l37 143q-82 21 -165 71.5t-140 102t-109.5 112t-72 88.5t-29.5 43zM120 600q210 -282 393 -336l37 141q-107 18 -178.5 101.5t-71.5 193.5 q0 85 46 158q-102 -87 -226 -258zM377 656q49 -124 154 -191l47 47l23 87q-30 28 -59 69t-44 68l-14 26zM780 161l38 145q22 15 44.5 34t46 44t40.5 44t41 50.5t33.5 43.5t33 44t24.5 34q-97 127 -140 175l39 146q67 -54 131.5 -125.5t87.5 -103.5t36 -52l26 -40l-26 -40 q-7 -12 -25.5 -38t-63.5 -79.5t-95.5 -102.5t-124 -100t-146.5 -79z" />
+<glyph unicode="&#xe107;" d="M-97.5 34q13.5 -34 50.5 -34h1294q37 0 50.5 35.5t-7.5 67.5l-642 1056q-20 34 -48 36.5t-48 -29.5l-642 -1066q-21 -32 -7.5 -66zM155 200l445 723l445 -723h-345v100h-200v-100h-345zM500 600l100 -300l100 300v100h-200v-100z" />
+<glyph unicode="&#xe108;" d="M100 262v41q0 20 11 44.5t26 38.5l363 325v339q0 62 44 106t106 44t106 -44t44 -106v-339l363 -325q15 -14 26 -38.5t11 -44.5v-41q0 -20 -12 -26.5t-29 5.5l-359 249v-263q100 -91 100 -113v-64q0 -20 -13 -28.5t-32 0.5l-94 78h-222l-94 -78q-19 -9 -32 -0.5t-13 28.5 v64q0 22 100 113v263l-359 -249q-17 -12 -29 -5.5t-12 26.5z" />
+<glyph unicode="&#xe109;" d="M0 50q0 -20 14.5 -35t35.5 -15h1000q21 0 35.5 15t14.5 35v750h-1100v-750zM0 900h1100v150q0 21 -14.5 35.5t-35.5 14.5h-150v100h-100v-100h-500v100h-100v-100h-150q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 100v100h100v-100h-100zM100 300v100h100v-100h-100z M100 500v100h100v-100h-100zM300 100v100h100v-100h-100zM300 300v100h100v-100h-100zM300 500v100h100v-100h-100zM500 100v100h100v-100h-100zM500 300v100h100v-100h-100zM500 500v100h100v-100h-100zM700 100v100h100v-100h-100zM700 300v100h100v-100h-100zM700 500 v100h100v-100h-100zM900 100v100h100v-100h-100zM900 300v100h100v-100h-100zM900 500v100h100v-100h-100z" />
+<glyph unicode="&#xe110;" d="M0 200v200h259l600 600h241v198l300 -295l-300 -300v197h-159l-600 -600h-341zM0 800h259l122 -122l141 142l-181 180h-341v-200zM678 381l141 142l122 -123h159v198l300 -295l-300 -300v197h-241z" />
+<glyph unicode="&#xe111;" d="M0 400v600q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-600q0 -41 -29.5 -70.5t-70.5 -29.5h-596l-304 -300v300h-100q-41 0 -70.5 29.5t-29.5 70.5z" />
+<glyph unicode="&#xe112;" d="M100 600v200h300v-250q0 -113 6 -145q17 -92 102 -117q39 -11 92 -11q37 0 66.5 5.5t50 15.5t36 24t24 31.5t14 37.5t7 42t2.5 45t0 47v25v250h300v-200q0 -42 -3 -83t-15 -104t-31.5 -116t-58 -109.5t-89 -96.5t-129 -65.5t-174.5 -25.5t-174.5 25.5t-129 65.5t-89 96.5 t-58 109.5t-31.5 116t-15 104t-3 83zM100 900v300h300v-300h-300zM800 900v300h300v-300h-300z" />
+<glyph unicode="&#xe113;" d="M-30 411l227 -227l352 353l353 -353l226 227l-578 579z" />
+<glyph unicode="&#xe114;" d="M70 797l580 -579l578 579l-226 227l-353 -353l-352 353z" />
+<glyph unicode="&#xe115;" d="M-198 700l299 283l300 -283h-203v-400h385l215 -200h-800v600h-196zM402 1000l215 -200h381v-400h-198l299 -283l299 283h-200v600h-796z" />
+<glyph unicode="&#xe116;" d="M18 939q-5 24 10 42q14 19 39 19h896l38 162q5 17 18.5 27.5t30.5 10.5h94q20 0 35 -14.5t15 -35.5t-15 -35.5t-35 -14.5h-54l-201 -961q-2 -4 -6 -10.5t-19 -17.5t-33 -11h-31v-50q0 -20 -14.5 -35t-35.5 -15t-35.5 15t-14.5 35v50h-300v-50q0 -20 -14.5 -35t-35.5 -15 t-35.5 15t-14.5 35v50h-50q-21 0 -35.5 15t-14.5 35q0 21 14.5 35.5t35.5 14.5h535l48 200h-633q-32 0 -54.5 21t-27.5 43z" />
+<glyph unicode="&#xe117;" d="M0 0v800h1200v-800h-1200zM0 900v100h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-100h-1200z" />
+<glyph unicode="&#xe118;" d="M1 0l300 700h1200l-300 -700h-1200zM1 400v600h200q0 41 29.5 70.5t70.5 29.5h300q41 0 70.5 -29.5t29.5 -70.5h500v-200h-1000z" />
+<glyph unicode="&#xe119;" d="M302 300h198v600h-198l298 300l298 -300h-198v-600h198l-298 -300z" />
+<glyph unicode="&#xe120;" d="M0 600l300 298v-198h600v198l300 -298l-300 -297v197h-600v-197z" />
+<glyph unicode="&#xe121;" d="M0 100v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM31 400l172 739q5 22 23 41.5t38 19.5h672q19 0 37.5 -22.5t23.5 -45.5l172 -732h-1138zM800 100h100v100h-100v-100z M1000 100h100v100h-100v-100z" />
+<glyph unicode="&#xe122;" d="M-101 600v50q0 24 25 49t50 38l25 13v-250l-11 5.5t-24 14t-30 21.5t-24 27.5t-11 31.5zM100 500v250v8v8v7t0.5 7t1.5 5.5t2 5t3 4t4.5 3.5t6 1.5t7.5 0.5h200l675 250v-850l-675 200h-38l47 -276q2 -12 -3 -17.5t-11 -6t-21 -0.5h-8h-83q-20 0 -34.5 14t-18.5 35 q-55 337 -55 351zM1100 200v850q0 21 14.5 35.5t35.5 14.5q20 0 35 -14.5t15 -35.5v-850q0 -20 -15 -35t-35 -15q-21 0 -35.5 15t-14.5 35z" />
+<glyph unicode="&#xe123;" d="M74 350q0 21 13.5 35.5t33.5 14.5h18l117 173l63 327q15 77 76 140t144 83l-18 32q-6 19 3 32t29 13h94q20 0 29 -10.5t3 -29.5q-18 -36 -18 -37q83 -19 144 -82.5t76 -140.5l63 -327l118 -173h17q20 0 33.5 -14.5t13.5 -35.5q0 -20 -13 -40t-31 -27q-8 -3 -23 -8.5 t-65 -20t-103 -25t-132.5 -19.5t-158.5 -9q-125 0 -245.5 20.5t-178.5 40.5l-58 20q-18 7 -31 27.5t-13 40.5zM497 110q12 -49 40 -79.5t63 -30.5t63 30.5t39 79.5q-48 -6 -102 -6t-103 6z" />
+<glyph unicode="&#xe124;" d="M21 445l233 -45l-78 -224l224 78l45 -233l155 179l155 -179l45 233l224 -78l-78 224l234 45l-180 155l180 156l-234 44l78 225l-224 -78l-45 233l-155 -180l-155 180l-45 -233l-224 78l78 -225l-233 -44l179 -156z" />
+<glyph unicode="&#xe125;" d="M0 200h200v600h-200v-600zM300 275q0 -75 100 -75h61q124 -100 139 -100h250q46 0 83 57l238 344q29 31 29 74v100q0 44 -30.5 84.5t-69.5 40.5h-328q28 118 28 125v150q0 44 -30.5 84.5t-69.5 40.5h-50q-27 0 -51 -20t-38 -48l-96 -198l-145 -196q-20 -26 -20 -63v-400z M400 300v375l150 213l100 212h50v-175l-50 -225h450v-125l-250 -375h-214l-136 100h-100z" />
+<glyph unicode="&#xe126;" d="M0 400v600h200v-600h-200zM300 525v400q0 75 100 75h61q124 100 139 100h250q46 0 83 -57l238 -344q29 -31 29 -74v-100q0 -44 -30.5 -84.5t-69.5 -40.5h-328q28 -118 28 -125v-150q0 -44 -30.5 -84.5t-69.5 -40.5h-50q-27 0 -51 20t-38 48l-96 198l-145 196 q-20 26 -20 63zM400 525l150 -212l100 -213h50v175l-50 225h450v125l-250 375h-214l-136 -100h-100v-375z" />
+<glyph unicode="&#xe127;" d="M8 200v600h200v-600h-200zM308 275v525q0 17 14 35.5t28 28.5l14 9l362 230q14 6 25 6q17 0 29 -12l109 -112q14 -14 14 -34q0 -18 -11 -32l-85 -121h302q85 0 138.5 -38t53.5 -110t-54.5 -111t-138.5 -39h-107l-130 -339q-7 -22 -20.5 -41.5t-28.5 -19.5h-341 q-7 0 -90 81t-83 94zM408 289l100 -89h293l131 339q6 21 19.5 41t28.5 20h203q16 0 25 15t9 36q0 20 -9 34.5t-25 14.5h-457h-6.5h-7.5t-6.5 0.5t-6 1t-5 1.5t-5.5 2.5t-4 4t-4 5.5q-5 12 -5 20q0 14 10 27l147 183l-86 83l-339 -236v-503z" />
+<glyph unicode="&#xe128;" d="M-101 651q0 72 54 110t139 38l302 -1l-85 121q-11 16 -11 32q0 21 14 34l109 113q13 12 29 12q11 0 25 -6l365 -230q7 -4 17 -10.5t26.5 -26t16.5 -36.5v-526q0 -13 -86 -93.5t-94 -80.5h-341q-16 0 -29.5 20t-19.5 41l-130 339h-107q-84 0 -139 39t-55 111zM-1 601h222 q15 0 28.5 -20.5t19.5 -40.5l131 -339h293l107 89v502l-343 237l-87 -83l145 -184q10 -11 10 -26q0 -11 -5 -20q-1 -3 -3.5 -5.5l-4 -4t-5 -2.5t-5.5 -1.5t-6.5 -1t-6.5 -0.5h-7.5h-6.5h-476v-100zM1000 201v600h200v-600h-200z" />
+<glyph unicode="&#xe129;" d="M97 719l230 -363q4 -6 10.5 -15.5t26 -25t36.5 -15.5h525q13 0 94 83t81 90v342q0 15 -20 28.5t-41 19.5l-339 131v106q0 84 -39 139t-111 55t-110 -53.5t-38 -138.5v-302l-121 84q-15 12 -33.5 11.5t-32.5 -13.5l-112 -110q-22 -22 -6 -53zM172 739l83 86l183 -146 q22 -18 47 -5q3 1 5.5 3.5l4 4t2.5 5t1.5 5.5t1 6.5t0.5 6.5v7.5v6.5v456q0 22 25 31t50 -0.5t25 -30.5v-202q0 -16 20 -29.5t41 -19.5l339 -130v-294l-89 -100h-503zM400 0v200h600v-200h-600z" />
+<glyph unicode="&#xe130;" d="M2 585q-16 -31 6 -53l112 -110q13 -13 32 -13.5t34 10.5l121 85q0 -51 -0.5 -153.5t-0.5 -148.5q0 -84 38.5 -138t110.5 -54t111 55t39 139v106l339 131q20 6 40.5 19.5t20.5 28.5v342q0 7 -81 90t-94 83h-525q-17 0 -35.5 -14t-28.5 -28l-10 -15zM77 565l236 339h503 l89 -100v-294l-340 -130q-20 -6 -40 -20t-20 -29v-202q0 -22 -25 -31t-50 0t-25 31v456v14.5t-1.5 11.5t-5 12t-9.5 7q-24 13 -46 -5l-184 -146zM305 1104v200h600v-200h-600z" />
+<glyph unicode="&#xe131;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM298 701l2 -201h300l-2 -194l402 294l-402 298v-197h-300z" />
+<glyph unicode="&#xe132;" d="M0 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t231.5 47.5q122 0 232.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-218 -217.5t-300 -80t-299.5 80t-217.5 217.5t-80 299.5zM200 600l402 -294l-2 194h300l2 201h-300v197z" />
+<glyph unicode="&#xe133;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600h200v-300h200v300h200l-300 400z" />
+<glyph unicode="&#xe134;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q162 0 299.5 -80t217.5 -218t80 -300t-80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM300 600l300 -400l300 400h-200v300h-200v-300h-200z" />
+<glyph unicode="&#xe135;" d="M5 597q0 122 47.5 232.5t127.5 190.5t190.5 127.5t232.5 47.5q121 0 231.5 -47.5t190.5 -127.5t127.5 -190.5t47.5 -232.5q0 -162 -80 -299.5t-217.5 -217.5t-299.5 -80t-300 80t-218 217.5t-80 299.5zM254 780q-8 -33 5.5 -92.5t7.5 -87.5q0 -9 17 -44t16 -60 q12 0 23 -5.5t23 -15t20 -13.5q24 -12 108 -42q22 -8 53 -31.5t59.5 -38.5t57.5 -11q8 -18 -15 -55t-20 -57q42 -71 87 -80q0 -6 -3 -15.5t-3.5 -14.5t4.5 -17q104 -3 221 112q30 29 47 47t34.5 49t20.5 62q-14 9 -37 9.5t-36 7.5q-14 7 -49 15t-52 19q-9 0 -39.5 -0.5 t-46.5 -1.5t-39 -6.5t-39 -16.5q-50 -35 -66 -12q-4 2 -3.5 25.5t0.5 25.5q-6 13 -26.5 17t-24.5 7q2 22 -2 41t-16.5 28t-38.5 -20q-23 -25 -42 4q-19 28 -8 58q6 16 22 22q6 -1 26 -1.5t33.5 -4t19.5 -13.5q12 -19 32 -37.5t34 -27.5l14 -8q0 3 9.5 39.5t5.5 57.5 q-4 23 14.5 44.5t22.5 31.5q5 14 10 35t8.5 31t15.5 22.5t34 21.5q-6 18 10 37q8 0 23.5 -1.5t24.5 -1.5t20.5 4.5t20.5 15.5q-10 23 -30.5 42.5t-38 30t-49 26.5t-43.5 23q11 39 2 44q31 -13 58 -14.5t39 3.5l11 4q7 36 -16.5 53.5t-64.5 28.5t-56 23q-19 -3 -37 0 q-15 -12 -36.5 -21t-34.5 -12t-44 -8t-39 -6q-15 -3 -45.5 0.5t-45.5 -2.5q-21 -7 -52 -26.5t-34 -34.5q-3 -11 6.5 -22.5t8.5 -18.5q-3 -34 -27.5 -90.5t-29.5 -79.5zM518 916q3 12 16 30t16 25q10 -10 18.5 -10t14 6t14.5 14.5t16 12.5q0 -24 17 -66.5t17 -43.5 q-9 2 -31 5t-36 5t-32 8t-30 14zM692 1003h1h-1z" />
+<glyph unicode="&#xe136;" d="M0 164.5q0 21.5 15 37.5l600 599q-33 101 6 201.5t135 154.5q164 92 306 -9l-259 -138l145 -232l251 126q13 -175 -151 -267q-123 -70 -253 -23l-596 -596q-15 -16 -36.5 -16t-36.5 16l-111 110q-15 15 -15 36.5z" />
+<glyph unicode="&#xe137;" horiz-adv-x="1220" d="M0 196v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 596v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000 q-41 0 -70.5 29.5t-29.5 70.5zM0 996v100q0 41 29.5 70.5t70.5 29.5h1000q41 0 70.5 -29.5t29.5 -70.5v-100q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM600 596h500v100h-500v-100zM800 196h300v100h-300v-100zM900 996h200v100h-200v-100z" />
+<glyph unicode="&#xe138;" d="M100 1100v100h1000v-100h-1000zM150 1000h900l-350 -500v-300l-200 -200v500z" />
+<glyph unicode="&#xe139;" d="M0 200v200h1200v-200q0 -41 -29.5 -70.5t-70.5 -29.5h-1000q-41 0 -70.5 29.5t-29.5 70.5zM0 500v400q0 41 29.5 70.5t70.5 29.5h300v100q0 41 29.5 70.5t70.5 29.5h200q41 0 70.5 -29.5t29.5 -70.5v-100h300q41 0 70.5 -29.5t29.5 -70.5v-400h-500v100h-200v-100h-500z M500 1000h200v100h-200v-100z" />
+<glyph unicode="&#xe140;" d="M0 0v400l129 -129l200 200l142 -142l-200 -200l129 -129h-400zM0 800l129 129l200 -200l142 142l-200 200l129 129h-400v-400zM729 329l142 142l200 -200l129 129v-400h-400l129 129zM729 871l200 200l-129 129h400v-400l-129 129l-200 -200z" />
+<glyph unicode="&#xe141;" d="M0 596q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 596q0 -172 121.5 -293t292.5 -121t292.5 121t121.5 293q0 171 -121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM291 655 q0 23 15.5 38.5t38.5 15.5t39 -16t16 -38q0 -23 -16 -39t-39 -16q-22 0 -38 16t-16 39zM400 850q0 22 16 38.5t39 16.5q22 0 38 -16t16 -39t-16 -39t-38 -16q-23 0 -39 16.5t-16 38.5zM514 609q0 32 20.5 56.5t51.5 29.5l122 126l1 1q-9 14 -9 28q0 22 16 38.5t39 16.5 q22 0 38 -16t16 -39t-16 -39t-38 -16q-14 0 -29 10l-55 -145q17 -22 17 -51q0 -36 -25.5 -61.5t-61.5 -25.5t-61.5 25.5t-25.5 61.5zM800 655q0 22 16 38t39 16t38.5 -15.5t15.5 -38.5t-16 -39t-38 -16q-23 0 -39 16t-16 39z" />
+<glyph unicode="&#xe142;" d="M-40 375q-13 -95 35 -173q35 -57 94 -89t129 -32q63 0 119 28q33 16 65 40.5t52.5 45.5t59.5 64q40 44 57 61l394 394q35 35 47 84t-3 96q-27 87 -117 104q-20 2 -29 2q-46 0 -78.5 -16.5t-67.5 -51.5l-389 -396l-7 -7l69 -67l377 373q20 22 39 38q23 23 50 23 q38 0 53 -36q16 -39 -20 -75l-547 -547q-52 -52 -125 -52q-55 0 -100 33t-54 96q-5 35 2.5 66t31.5 63t42 50t56 54q24 21 44 41l348 348q52 52 82.5 79.5t84 54t107.5 26.5q25 0 48 -4q95 -17 154 -94.5t51 -175.5q-7 -101 -98 -192l-252 -249l-253 -256l7 -7l69 -60 l517 511q67 67 95 157t11 183q-16 87 -67 154t-130 103q-69 33 -152 33q-107 0 -197 -55q-40 -24 -111 -95l-512 -512q-68 -68 -81 -163z" />
+<glyph unicode="&#xe143;" d="M80 784q0 131 98.5 229.5t230.5 98.5q143 0 241 -129q103 129 246 129q129 0 226 -98.5t97 -229.5q0 -46 -17.5 -91t-61 -99t-77 -89.5t-104.5 -105.5q-197 -191 -293 -322l-17 -23l-16 23q-43 58 -100 122.5t-92 99.5t-101 100q-71 70 -104.5 105.5t-77 89.5t-61 99 t-17.5 91zM250 784q0 -27 30.5 -70t61.5 -75.5t95 -94.5l22 -22q93 -90 190 -201q82 92 195 203l12 12q64 62 97.5 97t64.5 79t31 72q0 71 -48 119.5t-105 48.5q-74 0 -132 -83l-118 -171l-114 174q-51 80 -123 80q-60 0 -109.5 -49.5t-49.5 -118.5z" />
+<glyph unicode="&#xe144;" d="M57 353q0 -95 66 -159l141 -142q68 -66 159 -66q93 0 159 66l283 283q66 66 66 159t-66 159l-141 141q-8 9 -19 17l-105 -105l212 -212l-389 -389l-247 248l95 95l-18 18q-46 45 -75 101l-55 -55q-66 -66 -66 -159zM269 706q0 -93 66 -159l141 -141q7 -7 19 -17l105 105 l-212 212l389 389l247 -247l-95 -96l18 -17q47 -49 77 -100l29 29q35 35 62.5 88t27.5 96q0 93 -66 159l-141 141q-66 66 -159 66q-95 0 -159 -66l-283 -283q-66 -64 -66 -159z" />
+<glyph unicode="&#xe145;" d="M200 100v953q0 21 30 46t81 48t129 38t163 15t162 -15t127 -38t79 -48t29 -46v-953q0 -41 -29.5 -70.5t-70.5 -29.5h-600q-41 0 -70.5 29.5t-29.5 70.5zM300 300h600v700h-600v-700zM496 150q0 -43 30.5 -73.5t73.5 -30.5t73.5 30.5t30.5 73.5t-30.5 73.5t-73.5 30.5 t-73.5 -30.5t-30.5 -73.5z" />
+<glyph unicode="&#xe146;" d="M0 0l303 380l207 208l-210 212h300l267 279l-35 36q-15 14 -15 35t15 35q14 15 35 15t35 -15l283 -282q15 -15 15 -36t-15 -35q-14 -15 -35 -15t-35 15l-36 35l-279 -267v-300l-212 210l-208 -207z" />
+<glyph unicode="&#xe148;" d="M295 433h139q5 -77 48.5 -126.5t117.5 -64.5v335q-6 1 -15.5 4t-11.5 3q-46 14 -79 26.5t-72 36t-62.5 52t-40 72.5t-16.5 99q0 92 44 159.5t109 101t144 40.5v78h100v-79q38 -4 72.5 -13.5t75.5 -31.5t71 -53.5t51.5 -84t24.5 -118.5h-159q-8 72 -35 109.5t-101 50.5 v-307l64 -14q34 -7 64 -16.5t70 -31.5t67.5 -52t47.5 -80.5t20 -112.5q0 -139 -89 -224t-244 -96v-77h-100v78q-152 17 -237 104q-40 40 -52.5 93.5t-15.5 139.5zM466 889q0 -29 8 -51t16.5 -34t29.5 -22.5t31 -13.5t38 -10q7 -2 11 -3v274q-61 -8 -97.5 -37.5t-36.5 -102.5 zM700 237q170 18 170 151q0 64 -44 99.5t-126 60.5v-311z" />
+<glyph unicode="&#xe149;" d="M100 600v100h166q-24 49 -44 104q-10 26 -14.5 55.5t-3 72.5t25 90t68.5 87q97 88 263 88q129 0 230 -89t101 -208h-153q0 52 -34 89.5t-74 51.5t-76 14q-37 0 -79 -14.5t-62 -35.5q-41 -44 -41 -101q0 -28 16.5 -69.5t28 -62.5t41.5 -72h241v-100h-197q8 -50 -2.5 -115 t-31.5 -94q-41 -59 -99 -113q35 11 84 18t70 7q33 1 103 -16t103 -17q76 0 136 30l50 -147q-41 -25 -80.5 -36.5t-59 -13t-61.5 -1.5q-23 0 -128 33t-155 29q-39 -4 -82 -17t-66 -25l-24 -11l-55 145l16.5 11t15.5 10t13.5 9.5t14.5 12t14.5 14t17.5 18.5q48 55 54 126.5 t-30 142.5h-221z" />
+<glyph unicode="&#xe150;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM602 900l298 300l298 -300h-198v-900h-200v900h-198z" />
+<glyph unicode="&#xe151;" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v200h100v-100h200v-100h-300zM700 400v100h300v-200h-99v-100h-100v100h99v100h-200zM700 700v500h300v-500h-100v100h-100v-100h-100zM801 900h100v200h-100v-200z" />
+<glyph unicode="&#xe152;" d="M2 300h198v900h200v-900h198l-298 -300zM700 0v500h300v-500h-100v100h-100v-100h-100zM700 700v200h100v-100h200v-100h-300zM700 1100v100h300v-200h-99v-100h-100v100h99v100h-200zM801 200h100v200h-100v-200z" />
+<glyph unicode="&#xe153;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 100v400h300v-500h-100v100h-200zM800 1100v100h200v-500h-100v400h-100zM901 200h100v200h-100v-200z" />
+<glyph unicode="&#xe154;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM800 400v100h200v-500h-100v400h-100zM800 800v400h300v-500h-100v100h-200zM901 900h100v200h-100v-200z" />
+<glyph unicode="&#xe155;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h500v-200h-500zM700 400v200h400v-200h-400zM700 700v200h300v-200h-300zM700 1000v200h200v-200h-200z" />
+<glyph unicode="&#xe156;" d="M2 300l298 -300l298 300h-198v900h-200v-900h-198zM700 100v200h200v-200h-200zM700 400v200h300v-200h-300zM700 700v200h400v-200h-400zM700 1000v200h500v-200h-500z" />
+<glyph unicode="&#xe157;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q162 0 281 -118.5t119 -281.5v-300q0 -165 -118.5 -282.5t-281.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500z" />
+<glyph unicode="&#xe158;" d="M0 400v300q0 163 119 281.5t281 118.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-163 0 -281.5 117.5t-118.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM400 300l333 250l-333 250v-500z" />
+<glyph unicode="&#xe159;" d="M0 400v300q0 163 117.5 281.5t282.5 118.5h300q163 0 281.5 -119t118.5 -281v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-300q-165 0 -282.5 117.5t-117.5 282.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 700l250 -333l250 333h-500z" />
+<glyph unicode="&#xe160;" d="M0 400v300q0 165 117.5 282.5t282.5 117.5h300q165 0 282.5 -117.5t117.5 -282.5v-300q0 -162 -118.5 -281t-281.5 -119h-300q-165 0 -282.5 118.5t-117.5 281.5zM200 300q0 -41 29.5 -70.5t70.5 -29.5h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5 h-500q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM300 400h500l-250 333z" />
+<glyph unicode="&#xe161;" d="M0 400v300h300v200l400 -350l-400 -350v200h-300zM500 0v200h500q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-500v200h400q165 0 282.5 -117.5t117.5 -282.5v-300q0 -165 -117.5 -282.5t-282.5 -117.5h-400z" />
+<glyph unicode="&#xe162;" d="M217 519q8 -19 31 -19h302q-155 -438 -160 -458q-5 -21 4 -32l9 -8h9q14 0 26 15q11 13 274.5 321.5t264.5 308.5q14 19 5 36q-8 17 -31 17l-301 -1q1 4 78 219.5t79 227.5q2 15 -5 27l-9 9h-9q-15 0 -25 -16q-4 -6 -98 -111.5t-228.5 -257t-209.5 -237.5q-16 -19 -6 -41 z" />
+<glyph unicode="&#xe163;" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q47 0 100 15v185h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h500v185q-14 4 -114 7.5t-193 5.5l-93 2q-165 0 -282.5 -117.5t-117.5 -282.5v-300zM600 400v300h300v200l400 -350l-400 -350v200h-300z " />
+<glyph unicode="&#xe164;" d="M0 400q0 -165 117.5 -282.5t282.5 -117.5h300q163 0 281.5 117.5t118.5 282.5v98l-78 73l-122 -123v-148q0 -41 -29.5 -70.5t-70.5 -29.5h-500q-41 0 -70.5 29.5t-29.5 70.5v500q0 41 29.5 70.5t70.5 29.5h156l118 122l-74 78h-100q-165 0 -282.5 -117.5t-117.5 -282.5 v-300zM496 709l353 342l-149 149h500v-500l-149 149l-342 -353z" />
+<glyph unicode="&#xe165;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM406 600 q0 80 57 137t137 57t137 -57t57 -137t-57 -137t-137 -57t-137 57t-57 137z" />
+<glyph unicode="&#xe166;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 800l445 -500l450 500h-295v400h-300v-400h-300zM900 150h100v50h-100v-50z" />
+<glyph unicode="&#xe167;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 700h300v-300h300v300h295l-445 500zM900 150h100v50h-100v-50z" />
+<glyph unicode="&#xe168;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 705l305 -305l596 596l-154 155l-442 -442l-150 151zM900 150h100v50h-100v-50z" />
+<glyph unicode="&#xe169;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM100 988l97 -98l212 213l-97 97zM200 400l697 1l3 699l-250 -239l-149 149l-212 -212l149 -149zM900 150h100v50h-100v-50z" />
+<glyph unicode="&#xe170;" d="M0 0v275q0 11 7 18t18 7h1048q11 0 19 -7.5t8 -17.5v-275h-1100zM200 612l212 -212l98 97l-213 212zM300 1200l239 -250l-149 -149l212 -212l149 148l249 -237l-1 697zM900 150h100v50h-100v-50z" />
+<glyph unicode="&#xe171;" d="M23 415l1177 784v-1079l-475 272l-310 -393v416h-392zM494 210l672 938l-672 -712v-226z" />
+<glyph unicode="&#xe172;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-850q0 -21 -15 -35.5t-35 -14.5h-150v400h-700v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200z" />
+<glyph unicode="&#xe173;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-218l-276 -275l-120 120l-126 -127h-378v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM581 306l123 123l120 -120l353 352l123 -123l-475 -476zM600 1000h100v200h-100v-200z" />
+<glyph unicode="&#xe174;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-269l-103 -103l-170 170l-298 -298h-329v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 1000h100v200h-100v-200zM700 133l170 170l-170 170l127 127l170 -170l170 170l127 -128l-170 -169l170 -170 l-127 -127l-170 170l-170 -170z" />
+<glyph unicode="&#xe175;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-300h-400v-200h-500v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300l300 -300l300 300h-200v300h-200v-300h-200zM600 1000v200h100v-200h-100z" />
+<glyph unicode="&#xe176;" d="M0 150v1000q0 20 14.5 35t35.5 15h250v-300h500v300h100l200 -200v-402l-200 200l-298 -298h-402v-400h-150q-21 0 -35.5 14.5t-14.5 35.5zM600 300h200v-300h200v300h200l-300 300zM600 1000v200h100v-200h-100z" />
+<glyph unicode="&#xe177;" d="M0 250q0 -21 14.5 -35.5t35.5 -14.5h1100q21 0 35.5 14.5t14.5 35.5v550h-1200v-550zM0 900h1200v150q0 21 -14.5 35.5t-35.5 14.5h-1100q-21 0 -35.5 -14.5t-14.5 -35.5v-150zM100 300v200h400v-200h-400z" />
+<glyph unicode="&#xe178;" d="M0 400l300 298v-198h400v-200h-400v-198zM100 800v200h100v-200h-100zM300 800v200h100v-200h-100zM500 800v200h400v198l300 -298l-300 -298v198h-400zM800 300v200h100v-200h-100zM1000 300h100v200h-100v-200z" />
+<glyph unicode="&#xe179;" d="M100 700v400l50 100l50 -100v-300h100v300l50 100l50 -100v-300h100v300l50 100l50 -100v-400l-100 -203v-447q0 -21 -14.5 -35.5t-35.5 -14.5h-200q-21 0 -35.5 14.5t-14.5 35.5v447zM800 597q0 -29 10.5 -55.5t25 -43t29 -28.5t25.5 -18l10 -5v-397q0 -21 14.5 -35.5 t35.5 -14.5h200q21 0 35.5 14.5t14.5 35.5v1106q0 31 -18 40.5t-44 -7.5l-276 -116q-25 -17 -43.5 -51.5t-18.5 -65.5v-359z" />
+<glyph unicode="&#xe180;" d="M100 0h400v56q-75 0 -87.5 6t-12.5 44v394h500v-394q0 -38 -12.5 -44t-87.5 -6v-56h400v56q-4 0 -11 0.5t-24 3t-30 7t-24 15t-11 24.5v888q0 22 25 34.5t50 13.5l25 2v56h-400v-56q75 0 87.5 -6t12.5 -44v-394h-500v394q0 38 12.5 44t87.5 6v56h-400v-56q4 0 11 -0.5 t24 -3t30 -7t24 -15t11 -24.5v-888q0 -22 -25 -34.5t-50 -13.5l-25 -2v-56z" />
+<glyph unicode="&#xe181;" d="M0 300q0 -41 29.5 -70.5t70.5 -29.5h300q41 0 70.5 29.5t29.5 70.5v500q0 41 -29.5 70.5t-70.5 29.5h-300q-41 0 -70.5 -29.5t-29.5 -70.5v-500zM100 100h400l200 200h105l295 98v-298h-425l-100 -100h-375zM100 300v200h300v-200h-300zM100 600v200h300v-200h-300z M100 1000h400l200 -200v-98l295 98h105v200h-425l-100 100h-375zM700 402v163l400 133v-163z" />
+<glyph unicode="&#xe182;" d="M16.5 974.5q0.5 -21.5 16 -90t46.5 -140t104 -177.5t175 -208q103 -103 207.5 -176t180 -103.5t137 -47t92.5 -16.5l31 1l163 162q17 18 13.5 41t-22.5 37l-192 136q-19 14 -45 12t-42 -19l-118 -118q-142 101 -268 227t-227 268l118 118q17 17 20 41.5t-11 44.5 l-139 194q-14 19 -36.5 22t-40.5 -14l-162 -162q-1 -11 -0.5 -32.5z" />
+<glyph unicode="&#xe183;" d="M0 50v212q0 20 10.5 45.5t24.5 39.5l365 303v50q0 4 1 10.5t12 22.5t30 28.5t60 23t97 10.5t97 -10t60 -23.5t30 -27.5t12 -24l1 -10v-50l365 -303q14 -14 24.5 -39.5t10.5 -45.5v-212q0 -21 -14.5 -35.5t-35.5 -14.5h-1100q-20 0 -35 14.5t-15 35.5zM0 712 q0 -21 14.5 -33.5t34.5 -8.5l202 33q20 4 34.5 21t14.5 38v146q141 24 300 24t300 -24v-146q0 -21 14.5 -38t34.5 -21l202 -33q20 -4 34.5 8.5t14.5 33.5v200q-6 8 -19 20.5t-63 45t-112 57t-171 45t-235 20.5q-92 0 -175 -10.5t-141.5 -27t-108.5 -36.5t-81.5 -40 t-53.5 -36.5t-31 -27.5l-9 -10v-200z" />
+<glyph unicode="&#xe184;" d="M100 0v100h1100v-100h-1100zM175 200h950l-125 150v250l100 100v400h-100v-200h-100v200h-200v-200h-100v200h-200v-200h-100v200h-100v-400l100 -100v-250z" />
+<glyph unicode="&#xe185;" d="M100 0h300v400q0 41 -29.5 70.5t-70.5 29.5h-100q-41 0 -70.5 -29.5t-29.5 -70.5v-400zM500 0v1000q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-1000h-300zM900 0v700q0 41 29.5 70.5t70.5 29.5h100q41 0 70.5 -29.5t29.5 -70.5v-700h-300z" />
+<glyph unicode="&#xe186;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" />
+<glyph unicode="&#xe187;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h100v200h100v-200h100v500h-100v-200h-100v200h-100v-500zM600 300h200v100h100v300h-100v100h-200v-500 zM700 400v300h100v-300h-100z" />
+<glyph unicode="&#xe188;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v100h-200v300h200v100h-300v-500zM600 300h300v100h-200v300h200v100h-300v-500z" />
+<glyph unicode="&#xe189;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 550l300 -150v300zM600 400l300 150l-300 150v-300z" />
+<glyph unicode="&#xe190;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300v500h700v-500h-700zM300 400h130q41 0 68 42t27 107t-28.5 108t-66.5 43h-130v-300zM575 549 q0 -65 27 -107t68 -42h130v300h-130q-38 0 -66.5 -43t-28.5 -108z" />
+<glyph unicode="&#xe191;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v300h-200v100h200v100h-300v-300h200v-100h-200v-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" />
+<glyph unicode="&#xe192;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 300h300v400h-200v100h-100v-500zM301 400v200h100v-200h-100zM601 300h100v100h-100v-100zM700 700h100 v-400h100v500h-200v-100z" />
+<glyph unicode="&#xe193;" d="M-100 300v500q0 124 88 212t212 88h700q124 0 212 -88t88 -212v-500q0 -124 -88 -212t-212 -88h-700q-124 0 -212 88t-88 212zM100 200h900v700h-900v-700zM200 700v100h300v-300h-99v-100h-100v100h99v200h-200zM201 300v100h100v-100h-100zM601 300v100h100v-100h-100z M700 700v100h200v-500h-100v400h-100z" />
+<glyph unicode="&#xe194;" d="M4 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM186 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 500v200 l100 100h300v-100h-300v-200h300v-100h-300z" />
+<glyph unicode="&#xe195;" d="M0 600q0 162 80 299t217 217t299 80t299 -80t217 -217t80 -299t-80 -299t-217 -217t-299 -80t-299 80t-217 217t-80 299zM182 600q0 -171 121.5 -292.5t292.5 -121.5t292.5 121.5t121.5 292.5t-121.5 292.5t-292.5 121.5t-292.5 -121.5t-121.5 -292.5zM400 400v400h300 l100 -100v-100h-100v100h-200v-100h200v-100h-200v-100h-100zM700 400v100h100v-100h-100z" />
+<glyph unicode="&#xe197;" d="M-14 494q0 -80 56.5 -137t135.5 -57h222v300h400v-300h128q120 0 205 86.5t85 207.5t-85 207t-205 86q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200h200v300h200v-300h200 l-300 -300z" />
+<glyph unicode="&#xe198;" d="M-14 494q0 -80 56.5 -137t135.5 -57h8l414 414l403 -403q94 26 154.5 104.5t60.5 178.5q0 120 -85 206.5t-205 86.5q-46 0 -90 -14q-44 97 -134.5 156.5t-200.5 59.5q-152 0 -260 -107.5t-108 -260.5q0 -25 2 -37q-66 -14 -108.5 -67.5t-42.5 -122.5zM300 200l300 300 l300 -300h-200v-300h-200v300h-200z" />
+<glyph unicode="&#xe199;" d="M100 200h400v-155l-75 -45h350l-75 45v155h400l-270 300h170l-270 300h170l-300 333l-300 -333h170l-270 -300h170z" />
+<glyph unicode="&#xe200;" d="M121 700q0 -53 28.5 -97t75.5 -65q-4 -16 -4 -38q0 -74 52.5 -126.5t126.5 -52.5q56 0 100 30v-306l-75 -45h350l-75 45v306q46 -30 100 -30q74 0 126.5 52.5t52.5 126.5q0 24 -9 55q50 32 79.5 83t29.5 112q0 90 -61.5 155.5t-150.5 71.5q-26 89 -99.5 145.5 t-167.5 56.5q-116 0 -197.5 -81.5t-81.5 -197.5q0 -4 1 -11.5t1 -11.5q-14 2 -23 2q-74 0 -126.5 -52.5t-52.5 -126.5z" />
+</font>
+</defs></svg> \ No newline at end of file
diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.ttf b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.ttf
new file mode 100644
index 00000000..67fa00bf
--- /dev/null
+++ b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.ttf
Binary files differ
diff --git a/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.woff b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.woff
new file mode 100644
index 00000000..8c54182a
--- /dev/null
+++ b/rest_framework/static/rest_framework/fonts/glyphicons-halflings-regular.woff
Binary files differ
diff --git a/rest_framework/static/rest_framework/js/bootstrap.min.js b/rest_framework/static/rest_framework/js/bootstrap.min.js
index e0b220f4..7c1561a8 100644
--- a/rest_framework/static/rest_framework/js/bootstrap.min.js
+++ b/rest_framework/static/rest_framework/js/bootstrap.min.js
@@ -1,7 +1,6 @@
-/**
-* Bootstrap.js by @fat & @mdo
-* plugins: bootstrap-transition.js, bootstrap-modal.js, bootstrap-dropdown.js, bootstrap-scrollspy.js, bootstrap-tab.js, bootstrap-tooltip.js, bootstrap-popover.js, bootstrap-affix.js, bootstrap-alert.js, bootstrap-button.js, bootstrap-collapse.js, bootstrap-carousel.js, bootstrap-typeahead.js
-* Copyright 2012 Twitter, Inc.
-* http://www.apache.org/licenses/LICENSE-2.0.txt
-*/
-!function(a){a(function(){a.support.transition=function(){var a=function(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},c;for(c in b)if(a.style[c]!==undefined)return b[c]}();return a&&{end:a}}()})}(window.jQuery),!function(a){var b=function(b,c){this.options=c,this.$element=a(b).delegate('[data-dismiss="modal"]',"click.dismiss.modal",a.proxy(this.hide,this)),this.options.remote&&this.$element.find(".modal-body").load(this.options.remote)};b.prototype={constructor:b,toggle:function(){return this[this.isShown?"hide":"show"]()},show:function(){var b=this,c=a.Event("show");this.$element.trigger(c);if(this.isShown||c.isDefaultPrevented())return;a("body").addClass("modal-open"),this.isShown=!0,this.escape(),this.backdrop(function(){var c=a.support.transition&&b.$element.hasClass("fade");b.$element.parent().length||b.$element.appendTo(document.body),b.$element.show(),c&&b.$element[0].offsetWidth,b.$element.addClass("in").attr("aria-hidden",!1).focus(),b.enforceFocus(),c?b.$element.one(a.support.transition.end,function(){b.$element.trigger("shown")}):b.$element.trigger("shown")})},hide:function(b){b&&b.preventDefault();var c=this;b=a.Event("hide"),this.$element.trigger(b);if(!this.isShown||b.isDefaultPrevented())return;this.isShown=!1,a("body").removeClass("modal-open"),this.escape(),a(document).off("focusin.modal"),this.$element.removeClass("in").attr("aria-hidden",!0),a.support.transition&&this.$element.hasClass("fade")?this.hideWithTransition():this.hideModal()},enforceFocus:function(){var b=this;a(document).on("focusin.modal",function(a){b.$element[0]!==a.target&&!b.$element.has(a.target).length&&b.$element.focus()})},escape:function(){var a=this;this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.modal",function(b){b.which==27&&a.hide()}):this.isShown||this.$element.off("keyup.dismiss.modal")},hideWithTransition:function(){var b=this,c=setTimeout(function(){b.$element.off(a.support.transition.end),b.hideModal()},500);this.$element.one(a.support.transition.end,function(){clearTimeout(c),b.hideModal()})},hideModal:function(a){this.$element.hide().trigger("hidden"),this.backdrop()},removeBackdrop:function(){this.$backdrop.remove(),this.$backdrop=null},backdrop:function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(document.body),this.options.backdrop!="static"&&this.$backdrop.click(a.proxy(this.hide,this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),e?this.$backdrop.one(a.support.transition.end,b):b()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(a.support.transition.end,a.proxy(this.removeBackdrop,this)):this.removeBackdrop()):b&&b()}},a.fn.modal=function(c){return this.each(function(){var d=a(this),e=d.data("modal"),f=a.extend({},a.fn.modal.defaults,d.data(),typeof c=="object"&&c);e||d.data("modal",e=new b(this,f)),typeof c=="string"?e[c]():f.show&&e.show()})},a.fn.modal.defaults={backdrop:!0,keyboard:!0,show:!0},a.fn.modal.Constructor=b,a(function(){a("body").on("click.modal.data-api",'[data-toggle="modal"]',function(b){var c=a(this),d=c.attr("href"),e=a(c.attr("data-target")||d&&d.replace(/.*(?=#[^\s]+$)/,"")),f=e.data("modal")?"toggle":a.extend({remote:!/#/.test(d)&&d},e.data(),c.data());b.preventDefault(),e.modal(f).one("hide",function(){c.focus()})})})}(window.jQuery),!function(a){function d(){e(a(b)).removeClass("open")}function e(b){var c=b.attr("data-target"),d;return c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,"")),d=a(c),d.length||(d=b.parent()),d}var b="[data-toggle=dropdown]",c=function(b){var c=a(b).on("click.dropdown.data-api",this.toggle);a("html").on("click.dropdown.data-api",function(){c.parent().removeClass("open")})};c.prototype={constructor:c,toggle:function(b){var c=a(this),f,g;if(c.is(".disabled, :disabled"))return;return f=e(c),g=f.hasClass("open"),d(),g||(f.toggleClass("open"),c.focus()),!1},keydown:function(b){var c,d,f,g,h,i;if(!/(38|40|27)/.test(b.keyCode))return;c=a(this),b.preventDefault(),b.stopPropagation();if(c.is(".disabled, :disabled"))return;g=e(c),h=g.hasClass("open");if(!h||h&&b.keyCode==27)return c.click();d=a("[role=menu] li:not(.divider) a",g);if(!d.length)return;i=d.index(d.filter(":focus")),b.keyCode==38&&i>0&&i--,b.keyCode==40&&i<d.length-1&&i++,~i||(i=0),d.eq(i).focus()}},a.fn.dropdown=function(b){return this.each(function(){var d=a(this),e=d.data("dropdown");e||d.data("dropdown",e=new c(this)),typeof b=="string"&&e[b].call(d)})},a.fn.dropdown.Constructor=c,a(function(){a("html").on("click.dropdown.data-api touchstart.dropdown.data-api",d),a("body").on("click.dropdown touchstart.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.dropdown.data-api touchstart.dropdown.data-api",b,c.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api",b+", [role=menu]",c.prototype.keydown)})}(window.jQuery),!function(a){function b(b,c){var d=a.proxy(this.process,this),e=a(b).is("body")?a(window):a(b),f;this.options=a.extend({},a.fn.scrollspy.defaults,c),this.$scrollElement=e.on("scroll.scroll-spy.data-api",d),this.selector=(this.options.target||(f=a(b).attr("href"))&&f.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.$body=a("body"),this.refresh(),this.process()}b.prototype={constructor:b,refresh:function(){var b=this,c;this.offsets=a([]),this.targets=a([]),c=this.$body.find(this.selector).map(function(){var b=a(this),c=b.data("target")||b.attr("href"),d=/^#\w/.test(c)&&a(c);return d&&d.length&&[[d.position().top,c]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},process:function(){var a=this.$scrollElement.scrollTop()+this.options.offset,b=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,c=b-this.$scrollElement.height(),d=this.offsets,e=this.targets,f=this.activeTarget,g;if(a>=c)return f!=(g=e.last()[0])&&this.activate(g);for(g=d.length;g--;)f!=e[g]&&a>=d[g]&&(!d[g+1]||a<=d[g+1])&&this.activate(e[g])},activate:function(b){var c,d;this.activeTarget=b,a(this.selector).parent(".active").removeClass("active"),d=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',c=a(d).parent("li").addClass("active"),c.parent(".dropdown-menu").length&&(c=c.closest("li.dropdown").addClass("active")),c.trigger("activate")}},a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("scrollspy"),f=typeof c=="object"&&c;e||d.data("scrollspy",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.defaults={offset:10},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(window.jQuery),!function(a){var b=function(b){this.element=a(b)};b.prototype={constructor:b,show:function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.attr("data-target"),e,f,g;d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,""));if(b.parent("li").hasClass("active"))return;e=c.find(".active a").last()[0],g=a.Event("show",{relatedTarget:e}),b.trigger(g);if(g.isDefaultPrevented())return;f=a(d),this.activate(b.parent("li"),c),this.activate(f,f.parent(),function(){b.trigger({type:"shown",relatedTarget:e})})},activate:function(b,c,d){function g(){e.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),f?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var e=c.find("> .active"),f=d&&a.support.transition&&e.hasClass("fade");f?e.one(a.support.transition.end,g):g(),e.removeClass("in")}},a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("tab");e||d.data("tab",e=new b(this)),typeof c=="string"&&e[c]()})},a.fn.tab.Constructor=b,a(function(){a("body").on("click.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})})}(window.jQuery),!function(a){var b=function(a,b){this.init("tooltip",a,b)};b.prototype={constructor:b,init:function(b,c,d){var e,f;this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.enabled=!0,this.options.trigger=="click"?this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this)):this.options.trigger!="manual"&&(e=this.options.trigger=="hover"?"mouseenter":"focus",f=this.options.trigger=="hover"?"mouseleave":"blur",this.$element.on(e+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(f+"."+this.type,this.options.selector,a.proxy(this.leave,this))),this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},getOptions:function(b){return b=a.extend({},a.fn[this.type].defaults,b,this.$element.data()),b.delay&&typeof b.delay=="number"&&(b.delay={show:b.delay,hide:b.delay}),b},enter:function(b){var c=a(b.currentTarget)[this.type](this._options).data(this.type);if(!c.options.delay||!c.options.delay.show)return c.show();clearTimeout(this.timeout),c.hoverState="in",this.timeout=setTimeout(function(){c.hoverState=="in"&&c.show()},c.options.delay.show)},leave:function(b){var c=a(b.currentTarget)[this.type](this._options).data(this.type);this.timeout&&clearTimeout(this.timeout);if(!c.options.delay||!c.options.delay.hide)return c.hide();c.hoverState="out",this.timeout=setTimeout(function(){c.hoverState=="out"&&c.hide()},c.options.delay.hide)},show:function(){var a,b,c,d,e,f,g;if(this.hasContent()&&this.enabled){a=this.tip(),this.setContent(),this.options.animation&&a.addClass("fade"),f=typeof this.options.placement=="function"?this.options.placement.call(this,a[0],this.$element[0]):this.options.placement,b=/in/.test(f),a.remove().css({top:0,left:0,display:"block"}).appendTo(b?this.$element:document.body),c=this.getPosition(b),d=a[0].offsetWidth,e=a[0].offsetHeight;switch(b?f.split(" ")[1]:f){case"bottom":g={top:c.top+c.height,left:c.left+c.width/2-d/2};break;case"top":g={top:c.top-e,left:c.left+c.width/2-d/2};break;case"left":g={top:c.top+c.height/2-e/2,left:c.left-d};break;case"right":g={top:c.top+c.height/2-e/2,left:c.left+c.width}}a.css(g).addClass(f).addClass("in")}},setContent:function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},hide:function(){function d(){var b=setTimeout(function(){c.off(a.support.transition.end).remove()},500);c.one(a.support.transition.end,function(){clearTimeout(b),c.remove()})}var b=this,c=this.tip();return c.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d():c.remove(),this},fixTitle:function(){var a=this.$element;(a.attr("title")||typeof a.attr("data-original-title")!="string")&&a.attr("data-original-title",a.attr("title")||"").removeAttr("title")},hasContent:function(){return this.getTitle()},getPosition:function(b){return a.extend({},b?{top:0,left:0}:this.$element.offset(),{width:this.$element[0].offsetWidth,height:this.$element[0].offsetHeight})},getTitle:function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||(typeof c.title=="function"?c.title.call(b[0]):c.title),a},tip:function(){return this.$tip=this.$tip||a(this.options.template)},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled},toggle:function(){this[this.tip().hasClass("in")?"hide":"show"]()},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}},a.fn.tooltip=function(c){return this.each(function(){var d=a(this),e=d.data("tooltip"),f=typeof c=="object"&&c;e||d.data("tooltip",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.tooltip.Constructor=b,a.fn.tooltip.defaults={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover",title:"",delay:0,html:!0}}(window.jQuery),!function(a){var b=function(a,b){this.init("popover",a,b)};b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype,{constructor:b,setContent:function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content > *")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in")},hasContent:function(){return this.getTitle()||this.getContent()},getContent:function(){var a,b=this.$element,c=this.options;return a=b.attr("data-content")||(typeof c.content=="function"?c.content.call(b[0]):c.content),a},tip:function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip},destroy:function(){this.hide().$element.off("."+this.type).removeData(this.type)}}),a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("popover"),f=typeof c=="object"&&c;e||d.data("popover",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.defaults=a.extend({},a.fn.tooltip.defaults,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'})}(window.jQuery),!function(a){var b=function(b,c){this.options=a.extend({},a.fn.affix.defaults,c),this.$window=a(window).on("scroll.affix.data-api",a.proxy(this.checkPosition,this)),this.$element=a(b),this.checkPosition()};b.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var b=a(document).height(),c=this.$window.scrollTop(),d=this.$element.offset(),e=this.options.offset,f=e.bottom,g=e.top,h="affix affix-top affix-bottom",i;typeof e!="object"&&(f=g=e),typeof g=="function"&&(g=e.top()),typeof f=="function"&&(f=e.bottom()),i=this.unpin!=null&&c+this.unpin<=d.top?!1:f!=null&&d.top+this.$element.height()>=b-f?"bottom":g!=null&&c<=g?"top":!1;if(this.affixed===i)return;this.affixed=i,this.unpin=i=="bottom"?d.top-c:null,this.$element.removeClass(h).addClass("affix"+(i?"-"+i:""))},a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("affix"),f=typeof c=="object"&&c;e||d.data("affix",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.defaults={offset:0},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery),!function(a){var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function f(){e.trigger("closed").remove()}var c=a(this),d=c.attr("data-target"),e;d||(d=c.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),e=a(d),b&&b.preventDefault(),e.length||(e=c.hasClass("alert")?c:c.parent()),e.trigger(b=a.Event("close"));if(b.isDefaultPrevented())return;e.removeClass("in"),a.support.transition&&e.hasClass("fade")?e.on(a.support.transition.end,f):f()},a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("alert");e||d.data("alert",e=new c(this)),typeof b=="string"&&e[b].call(d)})},a.fn.alert.Constructor=c,a(function(){a("body").on("click.alert.data-api",b,c.prototype.close)})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.button.defaults,c)};b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.data(),e=c.is("input")?"val":"html";a+="Text",d.resetText||c.data("resetText",c[e]()),c[e](d[a]||this.options[a]),setTimeout(function(){a=="loadingText"?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons-radio"]');a&&a.find(".active").removeClass("active"),this.$element.toggleClass("active")},a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("button"),f=typeof c=="object"&&c;e||d.data("button",e=new b(this,f)),c=="toggle"?e.toggle():c&&e.setState(c)})},a.fn.button.defaults={loadingText:"loading..."},a.fn.button.Constructor=b,a(function(){a("body").on("click.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle")})})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.collapse.defaults,c),this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.prototype={constructor:b,dimension:function(){var a=this.$element.hasClass("width");return a?"width":"height"},show:function(){var b,c,d,e;if(this.transitioning)return;b=this.dimension(),c=a.camelCase(["scroll",b].join("-")),d=this.$parent&&this.$parent.find("> .accordion-group > .in");if(d&&d.length){e=d.data("collapse");if(e&&e.transitioning)return;d.collapse("hide"),e||d.data("collapse",null)}this.$element[b](0),this.transition("addClass",a.Event("show"),"shown"),a.support.transition&&this.$element[b](this.$element[0][c])},hide:function(){var b;if(this.transitioning)return;b=this.dimension(),this.reset(this.$element[b]()),this.transition("removeClass",a.Event("hide"),"hidden"),this.$element[b](0)},reset:function(a){var b=this.dimension();return this.$element.removeClass("collapse")[b](a||"auto")[0].offsetWidth,this.$element[a!==null?"addClass":"removeClass"]("collapse"),this},transition:function(b,c,d){var e=this,f=function(){c.type=="show"&&e.reset(),e.transitioning=0,e.$element.trigger(d)};this.$element.trigger(c);if(c.isDefaultPrevented())return;this.transitioning=1,this.$element[b]("in"),a.support.transition&&this.$element.hasClass("collapse")?this.$element.one(a.support.transition.end,f):f()},toggle:function(){this[this.$element.hasClass("in")?"hide":"show"]()}},a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("collapse"),f=typeof c=="object"&&c;e||d.data("collapse",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.collapse.defaults={toggle:!0},a.fn.collapse.Constructor=b,a(function(){a("body").on("click.collapse.data-api","[data-toggle=collapse]",function(b){var c=a(this),d,e=c.attr("data-target")||b.preventDefault()||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),f=a(e).data("collapse")?"toggle":c.data();c[a(e).hasClass("in")?"addClass":"removeClass"]("collapsed"),a(e).collapse(f)})})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=c,this.options.slide&&this.slide(this.options.slide),this.options.pause=="hover"&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.prototype={cycle:function(b){return b||(this.paused=!1),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},to:function(b){var c=this.$element.find(".item.active"),d=c.parent().children(),e=d.index(c),f=this;if(b>d.length-1||b<0)return;return this.sliding?this.$element.one("slid",function(){f.to(b)}):e==b?this.pause().cycle():this.slide(b>e?"next":"prev",a(d[b]))},pause:function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle()),clearInterval(this.interval),this.interval=null,this},next:function(){if(this.sliding)return;return this.slide("next")},prev:function(){if(this.sliding)return;return this.slide("prev")},slide:function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g=b=="next"?"left":"right",h=b=="next"?"first":"last",i=this,j=a.Event("slide",{relatedTarget:e[0]});this.sliding=!0,f&&this.pause(),e=e.length?e:this.$element.find(".item")[h]();if(e.hasClass("active"))return;if(a.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(j);if(j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),this.$element.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)})}else{this.$element.trigger(j);if(j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this}},a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("carousel"),f=a.extend({},a.fn.carousel.defaults,typeof c=="object"&&c),g=typeof c=="string"?c:f.slide;e||d.data("carousel",e=new b(this,f)),typeof c=="number"?e.to(c):g?e[g]():f.interval&&e.cycle()})},a.fn.carousel.defaults={interval:5e3,pause:"hover"},a.fn.carousel.Constructor=b,a(function(){a("body").on("click.carousel.data-api","[data-slide]",function(b){var c=a(this),d,e=a(c.attr("data-target")||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,"")),f=!e.data("modal")&&a.extend({},e.data(),c.data());e.carousel(f),b.preventDefault()})})}(window.jQuery),!function(a){var b=function(b,c){this.$element=a(b),this.options=a.extend({},a.fn.typeahead.defaults,c),this.matcher=this.options.matcher||this.matcher,this.sorter=this.options.sorter||this.sorter,this.highlighter=this.options.highlighter||this.highlighter,this.updater=this.options.updater||this.updater,this.$menu=a(this.options.menu).appendTo("body"),this.source=this.options.source,this.shown=!1,this.listen()};b.prototype={constructor:b,select:function(){var a=this.$menu.find(".active").attr("data-value");return this.$element.val(this.updater(a)).change(),this.hide()},updater:function(a){return a},show:function(){var b=a.extend({},this.$element.offset(),{height:this.$element[0].offsetHeight});return this.$menu.css({top:b.top+b.height,left:b.left}),this.$menu.show(),this.shown=!0,this},hide:function(){return this.$menu.hide(),this.shown=!1,this},lookup:function(b){var c;return this.query=this.$element.val(),!this.query||this.query.length<this.options.minLength?this.shown?this.hide():this:(c=a.isFunction(this.source)?this.source(this.query,a.proxy(this.process,this)):this.source,c?this.process(c):this)},process:function(b){var c=this;return b=a.grep(b,function(a){return c.matcher(a)}),b=this.sorter(b),b.length?this.render(b.slice(0,this.options.items)).show():this.shown?this.hide():this},matcher:function(a){return~a.toLowerCase().indexOf(this.query.toLowerCase())},sorter:function(a){var b=[],c=[],d=[],e;while(e=a.shift())e.toLowerCase().indexOf(this.query.toLowerCase())?~e.indexOf(this.query)?c.push(e):d.push(e):b.push(e);return b.concat(c,d)},highlighter:function(a){var b=this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&");return a.replace(new RegExp("("+b+")","ig"),function(a,b){return"<strong>"+b+"</strong>"})},render:function(b){var c=this;return b=a(b).map(function(b,d){return b=a(c.options.item).attr("data-value",d),b.find("a").html(c.highlighter(d)),b[0]}),b.first().addClass("active"),this.$menu.html(b),this},next:function(b){var c=this.$menu.find(".active").removeClass("active"),d=c.next();d.length||(d=a(this.$menu.find("li")[0])),d.addClass("active")},prev:function(a){var b=this.$menu.find(".active").removeClass("active"),c=b.prev();c.length||(c=this.$menu.find("li").last()),c.addClass("active")},listen:function(){this.$element.on("blur",a.proxy(this.blur,this)).on("keypress",a.proxy(this.keypress,this)).on("keyup",a.proxy(this.keyup,this)),(a.browser.chrome||a.browser.webkit||a.browser.msie)&&this.$element.on("keydown",a.proxy(this.keydown,this)),this.$menu.on("click",a.proxy(this.click,this)).on("mouseenter","li",a.proxy(this.mouseenter,this))},move:function(a){if(!this.shown)return;switch(a.keyCode){case 9:case 13:case 27:a.preventDefault();break;case 38:a.preventDefault(),this.prev();break;case 40:a.preventDefault(),this.next()}a.stopPropagation()},keydown:function(b){this.suppressKeyPressRepeat=!~a.inArray(b.keyCode,[40,38,9,13,27]),this.move(b)},keypress:function(a){if(this.suppressKeyPressRepeat)return;this.move(a)},keyup:function(a){switch(a.keyCode){case 40:case 38:break;case 9:case 13:if(!this.shown)return;this.select();break;case 27:if(!this.shown)return;this.hide();break;default:this.lookup()}a.stopPropagation(),a.preventDefault()},blur:function(a){var b=this;setTimeout(function(){b.hide()},150)},click:function(a){a.stopPropagation(),a.preventDefault(),this.select()},mouseenter:function(b){this.$menu.find(".active").removeClass("active"),a(b.currentTarget).addClass("active")}},a.fn.typeahead=function(c){return this.each(function(){var d=a(this),e=d.data("typeahead"),f=typeof c=="object"&&c;e||d.data("typeahead",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.typeahead.defaults={source:[],items:8,menu:'<ul class="typeahead dropdown-menu"></ul>',item:'<li><a href="#"></a></li>',minLength:1},a.fn.typeahead.Constructor=b,a(function(){a("body").on("focus.typeahead.data-api",'[data-provide="typeahead"]',function(b){var c=a(this);if(c.data("typeahead"))return;b.preventDefault(),c.typeahead(c.data())})})}(window.jQuery) \ No newline at end of file
+/*!
+ * Bootstrap v3.2.0 (http://getbootstrap.com)
+ * Copyright 2011-2014 Twitter, Inc.
+ * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
+ */
+if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.2.0",d.prototype.close=function(b){function c(){f.detach().trigger("closed.bs.alert").remove()}var d=a(this),e=d.attr("data-target");e||(e=d.attr("href"),e=e&&e.replace(/.*(?=#[^\s]*$)/,""));var f=a(e);b&&b.preventDefault(),f.length||(f=d.hasClass("alert")?d:d.parent()),f.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(f.removeClass("in"),a.support.transition&&f.hasClass("fade")?f.one("bsTransitionEnd",c).emulateTransitionEnd(150):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.2.0",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),d[e](null==f[b]?this.options[b]:f[b]),setTimeout(a.proxy(function(){"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")&&(c.prop("checked")&&this.$element.hasClass("active")?a=!1:b.find(".active").removeClass("active")),a&&c.prop("checked",!this.$element.hasClass("active")).trigger("change")}a&&this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),c.preventDefault()})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b).on("keydown.bs.carousel",a.proxy(this.keydown,this)),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,"hover"==this.options.pause&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.2.0",c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},c.prototype.keydown=function(a){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.to=function(b){var c=this,d=this.getItemIndex(this.$active=this.$element.find(".item.active"));return b>this.$items.length-1||0>b?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g="next"==b?"left":"right",h="next"==b?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}if(e.hasClass("active"))return this.sliding=!1;var j=e[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:g});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,f&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(e)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:g});return a.support.transition&&this.$element.hasClass("slide")?(e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one("bsTransitionEnd",function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(1e3*d.css("transition-duration").slice(0,-1))):(d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger(m)),f&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b);!e&&f.toggle&&"show"==b&&(b=!b),e||d.data("bs.collapse",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};c.VERSION="3.2.0",c.DEFAULTS={toggle:!0},c.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},c.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var c=a.Event("show.bs.collapse");if(this.$element.trigger(c),!c.isDefaultPrevented()){var d=this.$parent&&this.$parent.find("> .panel > .in");if(d&&d.length){var e=d.data("bs.collapse");if(e&&e.transitioning)return;b.call(d,"hide"),e||d.data("bs.collapse",null)}var f=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[f](0),this.transitioning=1;var g=function(){this.$element.removeClass("collapsing").addClass("collapse in")[f](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return g.call(this);var h=a.camelCase(["scroll",f].join("-"));this.$element.one("bsTransitionEnd",a.proxy(g,this)).emulateTransitionEnd(350)[f](this.$element[0][h])}}},c.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(d,this)).emulateTransitionEnd(350):d.call(this)}}},c.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var d=a.fn.collapse;a.fn.collapse=b,a.fn.collapse.Constructor=c,a.fn.collapse.noConflict=function(){return a.fn.collapse=d,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(c){var d,e=a(this),f=e.attr("data-target")||c.preventDefault()||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),g=a(f),h=g.data("bs.collapse"),i=h?"toggle":e.data(),j=e.attr("data-parent"),k=j&&a(j);h&&h.transitioning||(k&&k.find('[data-toggle="collapse"][data-parent="'+j+'"]').not(e).addClass("collapsed"),e[g.hasClass("in")?"addClass":"removeClass"]("collapsed")),b.call(g,i)})}(jQuery),+function(a){"use strict";function b(b){b&&3===b.which||(a(e).remove(),a(f).each(function(){var d=c(a(this)),e={relatedTarget:this};d.hasClass("open")&&(d.trigger(b=a.Event("hide.bs.dropdown",e)),b.isDefaultPrevented()||d.removeClass("open").trigger("hidden.bs.dropdown",e))}))}function c(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.2.0",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=c(e),g=f.hasClass("open");if(b(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",b);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus"),f.toggleClass("open").trigger("shown.bs.dropdown",h)}return!1}},g.prototype.keydown=function(b){if(/(38|40|27)/.test(b.keyCode)){var d=a(this);if(b.preventDefault(),b.stopPropagation(),!d.is(".disabled, :disabled")){var e=c(d),g=e.hasClass("open");if(!g||g&&27==b.keyCode)return 27==b.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.divider):visible a",i=e.find('[role="menu"]'+h+', [role="listbox"]'+h);if(i.length){var j=i.index(i.filter(":focus"));38==b.keyCode&&j>0&&j--,40==b.keyCode&&j<i.length-1&&j++,~j||(j=0),i.eq(j).trigger("focus")}}}};var h=a.fn.dropdown;a.fn.dropdown=d,a.fn.dropdown.Constructor=g,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=h,this},a(document).on("click.bs.dropdown.data-api",b).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",f,g.prototype.toggle).on("keydown.bs.dropdown.data-api",f+', [role="menu"], [role="listbox"]',g.prototype.keydown)}(jQuery),+function(a){"use strict";function b(b,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},c.DEFAULTS,e.data(),"object"==typeof b&&b);f||e.data("bs.modal",f=new c(this,g)),"string"==typeof b?f[b](d):g.show&&f.show(d)})}var c=function(b,c){this.options=c,this.$body=a(document.body),this.$element=a(b),this.$backdrop=this.isShown=null,this.scrollbarWidth=0,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,a.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};c.VERSION="3.2.0",c.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},c.prototype.toggle=function(a){return this.isShown?this.hide():this.show(a)},c.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d),this.isShown||d.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.$body.addClass("modal-open"),this.setScrollbar(),this.escape(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(c.$body),c.$element.show().scrollTop(0),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one("bsTransitionEnd",function(){c.$element.trigger("focus").trigger(e)}).emulateTransitionEnd(300):c.$element.trigger("focus").trigger(e)}))},c.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b),this.isShown&&!b.isDefaultPrevented()&&(this.isShown=!1,this.$body.removeClass("modal-open"),this.resetScrollbar(),this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.bs.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal())},c.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]===a.target||this.$element.has(a.target).length||this.$element.trigger("focus")},this))},c.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){27==a.which&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},c.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.$element.trigger("hidden.bs.modal")})},c.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},c.prototype.backdrop=function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;if(this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",a.proxy(function(a){a.target===a.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus.call(this.$element[0]):this.hide.call(this))},this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!b)return;e?this.$backdrop.one("bsTransitionEnd",b).emulateTransitionEnd(150):b()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var f=function(){c.removeBackdrop(),b&&b()};a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",f).emulateTransitionEnd(150):f()}else b&&b()},c.prototype.checkScrollbar=function(){document.body.clientWidth>=window.innerWidth||(this.scrollbarWidth=this.scrollbarWidth||this.measureScrollbar())},c.prototype.setScrollbar=function(){var a=parseInt(this.$body.css("padding-right")||0,10);this.scrollbarWidth&&this.$body.css("padding-right",a+this.scrollbarWidth)},c.prototype.resetScrollbar=function(){this.$body.css("padding-right","")},c.prototype.measureScrollbar=function(){var a=document.createElement("div");a.className="modal-scrollbar-measure",this.$body.append(a);var b=a.offsetWidth-a.clientWidth;return this.$body[0].removeChild(a),b};var d=a.fn.modal;a.fn.modal=b,a.fn.modal.Constructor=c,a.fn.modal.noConflict=function(){return a.fn.modal=d,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(c){var d=a(this),e=d.attr("href"),f=a(d.attr("data-target")||e&&e.replace(/.*(?=#[^\s]+$)/,"")),g=f.data("bs.modal")?"toggle":a.extend({remote:!/#/.test(e)&&e},f.data(),d.data());d.is("a")&&c.preventDefault(),f.one("show.bs.modal",function(a){a.isDefaultPrevented()||f.one("hidden.bs.modal",function(){d.is(":visible")&&d.trigger("focus")})}),b.call(f,g,this)})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.tooltip",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};c.VERSION="3.2.0",c.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(this.options.viewport.selector||this.options.viewport);for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show()},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide()},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var c=a.contains(document.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!c)return;var d=this,e=this.tip(),f=this.getUID(this.type);this.setContent(),e.attr("id",f),this.$element.attr("aria-describedby",f),this.options.animation&&e.addClass("fade");var g="function"==typeof this.options.placement?this.options.placement.call(this,e[0],this.$element[0]):this.options.placement,h=/\s?auto?\s?/i,i=h.test(g);i&&(g=g.replace(h,"")||"top"),e.detach().css({top:0,left:0,display:"block"}).addClass(g).data("bs."+this.type,this),this.options.container?e.appendTo(this.options.container):e.insertAfter(this.$element);var j=this.getPosition(),k=e[0].offsetWidth,l=e[0].offsetHeight;if(i){var m=g,n=this.$element.parent(),o=this.getPosition(n);g="bottom"==g&&j.top+j.height+l-o.scroll>o.height?"top":"top"==g&&j.top-o.scroll-l<0?"bottom":"right"==g&&j.right+k>o.width?"left":"left"==g&&j.left-k<o.left?"right":g,e.removeClass(m).addClass(g)}var p=this.getCalculatedOffset(g,j,k,l);this.applyPlacement(p,g);var q=function(){d.$element.trigger("shown.bs."+d.type),d.hoverState=null};a.support.transition&&this.$tip.hasClass("fade")?e.one("bsTransitionEnd",q).emulateTransitionEnd(150):q()}},c.prototype.applyPlacement=function(b,c){var d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),b.top=b.top+g,b.left=b.left+h,a.offset.setOffset(d[0],a.extend({using:function(a){d.css({top:Math.round(a.top),left:Math.round(a.left)})}},b),0),d.addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;"top"==c&&j!=f&&(b.top=b.top+f-j);var k=this.getViewportAdjustedDelta(c,b,i,j);k.left?b.left+=k.left:b.top+=k.top;var l=k.left?2*k.left-e+i:2*k.top-f+j,m=k.left?"left":"top",n=k.left?"offsetWidth":"offsetHeight";d.offset(b),this.replaceArrow(l,d[0][n],m)},c.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},c.prototype.hide=function(){function b(){"in"!=c.hoverState&&d.detach(),c.$element.trigger("hidden.bs."+c.type)}var c=this,d=this.tip(),e=a.Event("hide.bs."+this.type);return this.$element.removeAttr("aria-describedby"),this.$element.trigger(e),e.isDefaultPrevented()?void 0:(d.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?d.one("bsTransitionEnd",b).emulateTransitionEnd(150):b(),this.hoverState=null,this)},c.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||"string"!=typeof a.attr("data-original-title"))&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},c.prototype.hasContent=function(){return this.getTitle()},c.prototype.getPosition=function(b){b=b||this.$element;var c=b[0],d="BODY"==c.tagName;return a.extend({},"function"==typeof c.getBoundingClientRect?c.getBoundingClientRect():null,{scroll:d?document.documentElement.scrollTop||document.body.scrollTop:b.scrollTop(),width:d?a(window).width():b.outerWidth(),height:d?a(window).height():b.outerHeight()},d?{top:0,left:0}:b.offset())},c.prototype.getCalculatedOffset=function(a,b,c,d){return"bottom"==a?{top:b.top+b.height,left:b.left+b.width/2-c/2}:"top"==a?{top:b.top-d,left:b.left+b.width/2-c/2}:"left"==a?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},c.prototype.getViewportAdjustedDelta=function(a,b,c,d){var e={top:0,left:0};if(!this.$viewport)return e;var f=this.options.viewport&&this.options.viewport.padding||0,g=this.getPosition(this.$viewport);if(/right|left/.test(a)){var h=b.top-f-g.scroll,i=b.top+f-g.scroll+d;h<g.top?e.top=g.top-h:i>g.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;j<g.left?e.left=g.left-j:k>g.width&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){clearTimeout(this.timeout),this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||"destroy"!=b)&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.2.0",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").empty()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},c.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){var e=a.proxy(this.process,this);this.$body=a("body"),this.$scrollElement=a(a(c).is("body")?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",e),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.2.0",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b="offset",c=0;a.isWindow(this.$scrollElement[0])||(b="position",c=this.$scrollElement.scrollTop()),this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight();var d=this;this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[b]().top+c,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){d.offsets.push(this[0]),d.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b<=e[0])return g!=(a=f[0])&&this.activate(a);for(a=e.length;a--;)g!=f[a]&&b>=e[a]&&(!e[a+1]||b<=e[a+1])&&this.activate(f[a])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parentsUntil(this.options.target,".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate.bs.scrollspy")};var d=a.fn.scrollspy;a.fn.scrollspy=c,a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=d,this},a(window).on("load.bs.scrollspy.data-api",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);c.call(b,b.data())})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new c(this)),"string"==typeof b&&e[b]()})}var c=function(b){this.element=a(b)};c.VERSION="3.2.0",c.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.data("target");if(d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,"")),!b.parent("li").hasClass("active")){var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});if(b.trigger(f),!f.isDefaultPrevented()){var g=a(d);this.activate(b.closest("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})}}},c.prototype.activate=function(b,c,d){function e(){f.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),g?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var f=c.find("> .active"),g=d&&a.support.transition&&f.hasClass("fade");g?f.one("bsTransitionEnd",e).emulateTransitionEnd(150):e(),f.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(c){c.preventDefault(),b.call(a(this),"show")})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=this.unpin=this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.2.0",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=a(document).height(),d=this.$target.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;"object"!=typeof f&&(h=g=f),"function"==typeof g&&(g=f.top(this.$element)),"function"==typeof h&&(h=f.bottom(this.$element));var i=null!=this.unpin&&d+this.unpin<=e.top?!1:null!=h&&e.top+this.$element.height()>=b-h?"bottom":null!=g&&g>=d?"top":!1;if(this.affixed!==i){null!=this.unpin&&this.$element.css("top","");var j="affix"+(i?"-"+i:""),k=a.Event(j+".bs.affix");this.$element.trigger(k),k.isDefaultPrevented()||(this.affixed=i,this.unpin="bottom"==i?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(j).trigger(a.Event(j.replace("affix","affixed"))),"bottom"==i&&this.$element.offset({top:b-this.$element.height()-h}))}}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},d.offsetBottom&&(d.offset.bottom=d.offsetBottom),d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery); \ No newline at end of file
diff --git a/rest_framework/templates/rest_framework/api_form.html b/rest_framework/templates/rest_framework/api_form.html
new file mode 100644
index 00000000..96f924ed
--- /dev/null
+++ b/rest_framework/templates/rest_framework/api_form.html
@@ -0,0 +1,8 @@
+{% load rest_framework %}
+{% csrf_token %}
+{% for field in form %}
+ {% if not field.read_only %}
+ {% render_field field style=style %}
+ {% endif %}
+{% endfor %}
+<!-- form.non_field_errors -->
diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html
index a84ccf26..e9668193 100644
--- a/rest_framework/templates/rest_framework/base.html
+++ b/rest_framework/templates/rest_framework/base.html
@@ -26,44 +26,42 @@
</head>
{% block body %}
- <body class="{% block bodyclass %}{% endblock %} container">
+ <body class="{% block bodyclass %}{% endblock %}">
<div class="wrapper">
{% block navbar %}
- <div class="navbar {% block bootstrap_navbar_variant %}navbar-inverse{% endblock %}">
- <div class="navbar-inner">
- <div class="container-fluid">
- <span>
- {% block branding %}
- <a class='brand' rel="nofollow" href='http://www.django-rest-framework.org'>
- Django REST framework <span class="version">{{ version }}</span>
- </a>
- {% endblock %}
- </span>
- <ul class="nav pull-right">
- {% block userlinks %}
- {% if user.is_authenticated %}
- {% optional_logout request user %}
- {% else %}
- {% optional_login request %}
- {% endif %}
- {% endblock %}
- </ul>
- </div>
+ <div class="navbar navbar-static-top {% block bootstrap_navbar_variant %}navbar-inverse{% endblock %}">
+ <div class="container">
+ <span>
+ {% block branding %}
+ <a class='navbar-brand' rel="nofollow" href='http://www.django-rest-framework.org'>
+ Django REST framework <span class="version">{{ version }}</span>
+ </a>
+ {% endblock %}
+ </span>
+ <ul class="nav navbar-nav pull-right">
+ {% block userlinks %}
+ {% if user.is_authenticated %}
+ {% optional_logout request user %}
+ {% else %}
+ {% optional_login request %}
+ {% endif %}
+ {% endblock %}
+ </ul>
</div>
</div>
{% endblock %}
+ <div class="container">
{% block breadcrumbs %}
<ul class="breadcrumb">
{% for breadcrumb_name, breadcrumb_url in breadcrumblist %}
- <li>
- <a href="{{ breadcrumb_url }}" {% if forloop.last %}class="active"{% endif %}>
- {{ breadcrumb_name }}
- </a>
- {% if not forloop.last %}<span class="divider">&rsaquo;</span>{% endif %}
- </li>
+ {% if forloop.last %}
+ <li class="active"><a href="{{ breadcrumb_url }}">{{ breadcrumb_name }}</a></li>
+ {% else %}
+ <li><a href="{{ breadcrumb_url }}">{{ breadcrumb_name }}</a></li>
+ {% endif %}
{% endfor %}
</ul>
{% endblock %}
@@ -142,19 +140,19 @@
{% if post_form %}
<ul class="nav nav-tabs form-switcher">
<li>
- <a name='html-tab' href="#object-form" data-toggle="tab">HTML form</a>
+ <a name='html-tab' href="#post-object-form" data-toggle="tab">HTML form</a>
</li>
<li>
- <a name='raw-tab' href="#generic-content-form" data-toggle="tab">Raw data</a>
+ <a name='raw-tab' href="#post-generic-content-form" data-toggle="tab">Raw data</a>
</li>
</ul>
{% endif %}
<div class="well tab-content">
{% if post_form %}
- <div class="tab-pane" id="object-form">
+ <div class="tab-pane" id="post-object-form">
{% with form=post_form %}
<form action="{{ request.get_full_path }}"
- method="POST" enctype="multipart/form-data" class="form-horizontal">
+ method="POST" enctype="multipart/form-data" class="form-horizontal" novalidate>
<fieldset>
{{ post_form }}
<div class="form-actions">
@@ -166,7 +164,7 @@
{% endwith %}
</div>
{% endif %}
- <div {% if post_form %}class="tab-pane"{% endif %} id="generic-content-form">
+ <div {% if post_form %}class="tab-pane"{% endif %} id="post-generic-content-form">
{% with form=raw_data_post_form %}
<form action="{{ request.get_full_path }}" method="POST" class="form-horizontal">
<fieldset>
@@ -188,18 +186,18 @@
{% if put_form %}
<ul class="nav nav-tabs form-switcher">
<li>
- <a name='html-tab' href="#object-form" data-toggle="tab">HTML form</a>
+ <a name='html-tab' href="#put-object-form" data-toggle="tab">HTML form</a>
</li>
<li>
- <a name='raw-tab' href="#generic-content-form" data-toggle="tab">Raw data</a>
+ <a name='raw-tab' href="#put-generic-content-form" data-toggle="tab">Raw data</a>
</li>
</ul>
{% endif %}
<div class="well tab-content">
{% if put_form %}
- <div class="tab-pane" id="object-form">
+ <div class="tab-pane" id="put-object-form">
<form action="{{ request.get_full_path }}"
- method="POST" enctype="multipart/form-data" class="form-horizontal">
+ method="POST" enctype="multipart/form-data" class="form-horizontal" novalidate>
<fieldset>
{{ put_form }}
<div class="form-actions">
@@ -211,7 +209,7 @@
</form>
</div>
{% endif %}
- <div {% if put_form %}class="tab-pane"{% endif %} id="generic-content-form">
+ <div {% if put_form %}class="tab-pane"{% endif %} id="put-generic-content-form">
{% with form=raw_data_put_or_patch_form %}
<form action="{{ request.get_full_path }}" method="POST" class="form-horizontal">
<fieldset>
@@ -238,13 +236,7 @@
{% endif %}
</div>
<!-- END Content -->
-
- <footer>
- {% block footer %}
- <p>Sponsored by <a href="http://dabapps.com/">DabApps</a>.</p>
- {% endblock %}
- </footer>
-
+ </div><!-- /.container -->
</div><!-- ./wrapper -->
{% block script %}
diff --git a/rest_framework/templates/rest_framework/form.html b/rest_framework/templates/rest_framework/form.html
deleted file mode 100644
index b1e148df..00000000
--- a/rest_framework/templates/rest_framework/form.html
+++ /dev/null
@@ -1,15 +0,0 @@
-{% load rest_framework %}
-{% csrf_token %}
-{{ form.non_field_errors }}
-{% for field in form.fields.values %}
- {% if not field.read_only %}
- <div class="control-group {% if field.errors %}error{% endif %}">
- {{ field.label_tag|add_class:"control-label" }}
- <div class="controls">
- {{ field.widget_html }}
- {% if field.help_text %}<span class="help-block">{{ field.help_text }}</span>{% endif %}
- {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
- </div>
- </div>
- {% endif %}
-{% endfor %}
diff --git a/rest_framework/templates/rest_framework/horizontal/checkbox.html b/rest_framework/templates/rest_framework/horizontal/checkbox.html
new file mode 100644
index 00000000..07a7308f
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/checkbox.html
@@ -0,0 +1,16 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ <div class="col-sm-offset-2 col-sm-10">
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" name="{{ field.name }}" value="true" {% if field.value %}checked{% endif %}>
+ {% if field.label %}{{ field.label }}{% endif %}
+ </label>
+ </div>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/horizontal/checkbox_multiple.html b/rest_framework/templates/rest_framework/horizontal/checkbox_multiple.html
new file mode 100644
index 00000000..ec7d5935
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/checkbox_multiple.html
@@ -0,0 +1,30 @@
+<div class="form-group">
+ {% if field.label %}
+ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>
+ {% endif %}
+ <div class="col-sm-10">
+ {% if style.inline %}
+ {% for key, text in field.choices.items %}
+ <label class="checkbox-inline">
+ <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ {% endfor %}
+ {% else %}
+ {% for key, text in field.choices.items %}
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ </div>
+ {% endfor %}
+ {% endif %}
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/horizontal/fieldset.html b/rest_framework/templates/rest_framework/horizontal/fieldset.html
new file mode 100644
index 00000000..ba3e3aba
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/fieldset.html
@@ -0,0 +1,13 @@
+{% load rest_framework %}
+<fieldset>
+ {% if field.label %}
+ <div class="form-group" style="border-bottom: 1px solid #e5e5e5">
+ <legend class="control-label col-sm-2 {% if style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend>
+ </div>
+ {% endif %}
+ {% for nested_field in field %}
+ {% if not nested_field.read_only %}
+ {% render_field nested_field style=style %}
+ {% endif %}
+ {% endfor %}
+</fieldset>
diff --git a/rest_framework/templates/rest_framework/horizontal/form.html b/rest_framework/templates/rest_framework/horizontal/form.html
new file mode 100644
index 00000000..fd15b626
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/form.html
@@ -0,0 +1,15 @@
+{% load rest_framework %}
+<form class="form-horizontal" role="form" action="." method="POST" novalidate>
+ {% csrf_token %}
+ {% for field in form %}
+ {% if not field.read_only %}
+ {% render_field field style=style %}
+ {% endif %}
+ {% endfor %}
+ <!-- form.non_field_errors -->
+ <div class="form-group">
+ <div class="col-sm-offset-2 col-sm-10">
+ <button type="submit" class="btn btn-default">Submit</button>
+ </div>
+ </div>
+</form>
diff --git a/rest_framework/templates/rest_framework/horizontal/input.html b/rest_framework/templates/rest_framework/horizontal/input.html
new file mode 100644
index 00000000..c41cd523
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/input.html
@@ -0,0 +1,14 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>
+ {% endif %}
+ <div class="col-sm-10">
+ <input name="{{ field.name }}" {% if style.input_type != "file" %}class="form-control"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/horizontal/list_fieldset.html b/rest_framework/templates/rest_framework/horizontal/list_fieldset.html
new file mode 100644
index 00000000..a9ff04a6
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/list_fieldset.html
@@ -0,0 +1,16 @@
+{% load rest_framework %}
+<fieldset>
+ {% if field.label %}
+ <div class="form-group" style="border-bottom: 1px solid #e5e5e5">
+ <legend class="control-label col-sm-2 {% if style.hide_label %}sr-only{% endif %}" style="border-bottom: 0">{{ field.label }}</legend>
+ </div>
+ {% endif %}
+ <!--
+ <ul>
+ {% for child in field.value %}
+ <li>TODO</li>
+ {% endfor %}
+ </ul>
+ -->
+ <p>Lists are not currently supported in HTML input.</p>
+</fieldset>
diff --git a/rest_framework/templates/rest_framework/horizontal/radio.html b/rest_framework/templates/rest_framework/horizontal/radio.html
new file mode 100644
index 00000000..52238bb1
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/radio.html
@@ -0,0 +1,30 @@
+<div class="form-group">
+ {% if field.label %}
+ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>
+ {% endif %}
+ <div class="col-sm-10">
+ {% if style.inline %}
+ {% for key, text in field.choices.items %}
+ <label class="radio-inline">
+ <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ {% endfor %}
+ {% else %}
+ {% for key, text in field.choices.items %}
+ <div class="radio">
+ <label>
+ <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ </div>
+ {% endfor %}
+ {% endif %}
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/horizontal/select.html b/rest_framework/templates/rest_framework/horizontal/select.html
new file mode 100644
index 00000000..380b38e9
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/select.html
@@ -0,0 +1,21 @@
+<div class="form-group">
+ {% if field.label %}
+ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>
+ {% endif %}
+ <div class="col-sm-10">
+ <select class="form-control" name="{{ field.name }}">
+ {% if field.allow_null %}
+ <option value="" {% if not field.value %}selected{% endif %}>--------</option>
+ {% endif %}
+ {% for key, text in field.choices.items %}
+ <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option>
+ {% endfor %}
+ </select>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/horizontal/select_multiple.html b/rest_framework/templates/rest_framework/horizontal/select_multiple.html
new file mode 100644
index 00000000..01c251fb
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/select_multiple.html
@@ -0,0 +1,18 @@
+<div class="form-group">
+ {% if field.label %}
+ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>
+ {% endif %}
+ <div class="col-sm-10">
+ <select multiple class="form-control" name="{{ field.name }}">
+ {% for key, text in field.choices.items %}
+ <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option>
+ {% endfor %}
+ </select>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/horizontal/textarea.html b/rest_framework/templates/rest_framework/horizontal/textarea.html
new file mode 100644
index 00000000..ec107549
--- /dev/null
+++ b/rest_framework/templates/rest_framework/horizontal/textarea.html
@@ -0,0 +1,14 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="col-sm-2 control-label {% if style.hide_label %}sr-only{% endif %}">{{ field.label }}</label>
+ {% endif %}
+ <div class="col-sm-10">
+ <textarea name="{{ field.name }}" class="form-control" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if style.rows %}rows="{{ style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/inline/checkbox.html b/rest_framework/templates/rest_framework/inline/checkbox.html
new file mode 100644
index 00000000..71737f15
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/checkbox.html
@@ -0,0 +1,8 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" name="{{ field.name }}" value="true" {% if field.value %}checked{% endif %}>
+ {% if field.label %}{{ field.label }}{% endif %}
+ </label>
+ </div>
+</div>
diff --git a/rest_framework/templates/rest_framework/inline/checkbox_multiple.html b/rest_framework/templates/rest_framework/inline/checkbox_multiple.html
new file mode 100644
index 00000000..6caf6440
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/checkbox_multiple.html
@@ -0,0 +1,13 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="sr-only">{{ field.label }}</label>
+ {% endif %}
+ {% for key, text in field.choices.items %}
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" name="{{ rest_framework/field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ </div>
+ {% endfor %}
+</div>
diff --git a/rest_framework/templates/rest_framework/inline/fieldset.html b/rest_framework/templates/rest_framework/inline/fieldset.html
new file mode 100644
index 00000000..e49b42fd
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/fieldset.html
@@ -0,0 +1,6 @@
+{% load rest_framework %}
+{% for nested_field in field %}
+ {% if not nested_field.read_only %}
+ {% render_field nested_field style=style %}
+ {% endif %}
+{% endfor %}
diff --git a/rest_framework/templates/rest_framework/inline/form.html b/rest_framework/templates/rest_framework/inline/form.html
new file mode 100644
index 00000000..6a0ea81d
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/form.html
@@ -0,0 +1,11 @@
+{% load rest_framework %}
+<form class="form-inline" role="form" action="." method="POST" novalidate>
+ {% csrf_token %}
+ {% for field in form %}
+ {% if not field.read_only %}
+ {% render_field field style=style %}
+ {% endif %}
+ {% endfor %}
+ <!-- form.non_field_errors -->
+ <button type="submit" class="btn btn-default">Submit</button>
+</form>
diff --git a/rest_framework/templates/rest_framework/inline/input.html b/rest_framework/templates/rest_framework/inline/input.html
new file mode 100644
index 00000000..de85ba48
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/input.html
@@ -0,0 +1,6 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="sr-only">{{ field.label }}</label>
+ {% endif %}
+ <input name="{{ field.name }}" {% if style.input_type != "file" %}class="form-control"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}>
+</div>
diff --git a/rest_framework/templates/rest_framework/inline/list_fieldset.html b/rest_framework/templates/rest_framework/inline/list_fieldset.html
new file mode 100644
index 00000000..2ae56d7c
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/list_fieldset.html
@@ -0,0 +1 @@
+<span>Lists are not currently supported in HTML input.</span>
diff --git a/rest_framework/templates/rest_framework/inline/radio.html b/rest_framework/templates/rest_framework/inline/radio.html
new file mode 100644
index 00000000..1915f4f8
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/radio.html
@@ -0,0 +1,13 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="sr-only">{{ field.label }}</label>
+ {% endif %}
+ {% for key, text in field.choices.items %}
+ <div class="radio">
+ <label>
+ <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ </div>
+ {% endfor %}
+</div>
diff --git a/rest_framework/templates/rest_framework/inline/select.html b/rest_framework/templates/rest_framework/inline/select.html
new file mode 100644
index 00000000..53af2772
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/select.html
@@ -0,0 +1,13 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="sr-only">{{ field.label }}</label>
+ {% endif %}
+ <select class="form-control" name="{{ field.name }}">
+ {% if field.allow_null %}
+ <option value="" {% if not field.value %}selected{% endif %}>--------</option>
+ {% endif %}
+ {% for key, text in field.choices.items %}
+ <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option>
+ {% endfor %}
+ </select>
+</div>
diff --git a/rest_framework/templates/rest_framework/inline/select_multiple.html b/rest_framework/templates/rest_framework/inline/select_multiple.html
new file mode 100644
index 00000000..feddf7ab
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/select_multiple.html
@@ -0,0 +1,10 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="sr-only">{{ field.label }}</label>
+ {% endif %}
+ <select multiple class="form-control" name="{{ field.name }}">
+ {% for key, text in field.choices.items %}
+ <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option>
+ {% endfor %}
+ </select>
+</div>
diff --git a/rest_framework/templates/rest_framework/inline/textarea.html b/rest_framework/templates/rest_framework/inline/textarea.html
new file mode 100644
index 00000000..0766a01c
--- /dev/null
+++ b/rest_framework/templates/rest_framework/inline/textarea.html
@@ -0,0 +1,6 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label class="sr-only">{{ field.label }}</label>
+ {% endif %}
+ <input name="{{ field.name }}" type="text" class="form-control" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}>
+</div>
diff --git a/rest_framework/templates/rest_framework/login_base.html b/rest_framework/templates/rest_framework/login_base.html
index 8ab682ac..e050cbdc 100644
--- a/rest_framework/templates/rest_framework/login_base.html
+++ b/rest_framework/templates/rest_framework/login_base.html
@@ -22,7 +22,7 @@
<div id="div_id_username"
class="clearfix control-group {% if form.username.errors %}error{% endif %}">
<div class="controls">
- <Label class="span4">Username:</label>
+ <label class="span4">Username:</label>
<input style="height: 25px" type="text" name="username" maxlength="100"
autocapitalize="off"
autocorrect="off" class="span12 textinput textInput"
@@ -36,9 +36,10 @@
</div>
</div>
<div id="div_id_password"
- class="clearfix control-group {% if form.password.errors %}error{% endif %}">
+ class="clearfix control-group {% if form.password.errors %}error{% endif %}"
+ style="margin-top: 10px">
<div class="controls">
- <Label class="span4">Password:</label>
+ <label class="span4">Password:</label>
<input style="height: 25px" type="password" name="password" maxlength="100"
autocapitalize="off" autocorrect="off" class="span12 textinput textInput"
id="id_password" required>
@@ -55,7 +56,7 @@
<div class="well well-small text-error" style="border: none">{{ error }}</div>
{% endfor %}
{% endif %}
- <div class="form-actions-no-box">
+ <div class="form-actions-no-box" style="margin-top: 20px">
<input type="submit" name="submit" value="Log in" class="btn btn-primary" id="submit-id-submit">
</div>
</form>
diff --git a/rest_framework/templates/rest_framework/vertical/checkbox.html b/rest_framework/templates/rest_framework/vertical/checkbox.html
new file mode 100644
index 00000000..e21a8e90
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/checkbox.html
@@ -0,0 +1,14 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" name="{{ field.name }}" value="true" {% if value %}checked{% endif %}>
+ {% if field.label %}{{ field.label }}{% endif %}
+ </label>
+ </div>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+</div> \ No newline at end of file
diff --git a/rest_framework/templates/rest_framework/vertical/checkbox_multiple.html b/rest_framework/templates/rest_framework/vertical/checkbox_multiple.html
new file mode 100644
index 00000000..134cca66
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/checkbox_multiple.html
@@ -0,0 +1,30 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>
+ {% endif %}
+ {% if style.inline %}
+ <div>
+ {% for key, text in field.choices.items %}
+ <label class="checkbox-inline">
+ <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ {% endfor %}
+ </div>
+ {% else %}
+ {% for key, text in field.choices.items %}
+ <div class="checkbox">
+ <label>
+ <input type="checkbox" name="{{ field.name }}" value="{{ key }}" {% if key in field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ </div>
+ {% endfor %}
+ {% endif %}
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+</div>
diff --git a/rest_framework/templates/rest_framework/vertical/fieldset.html b/rest_framework/templates/rest_framework/vertical/fieldset.html
new file mode 100644
index 00000000..3eb5191c
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/fieldset.html
@@ -0,0 +1,9 @@
+{% load rest_framework %}
+<fieldset>
+ {% if field.label %}<legend {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %}
+ {% for nested_field in field %}
+ {% if not nested_field.read_only %}
+ {% render_field nested_field style=style %}
+ {% endif %}
+ {% endfor %}
+</fieldset>
diff --git a/rest_framework/templates/rest_framework/vertical/form.html b/rest_framework/templates/rest_framework/vertical/form.html
new file mode 100644
index 00000000..e68835c0
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/form.html
@@ -0,0 +1,11 @@
+{% load rest_framework %}
+<form role="form" action="." method="POST" novalidate>
+ {% csrf_token %}
+ {% for field in form %}
+ {% if not field.read_only %}
+ {% render_field field style=style %}
+ {% endif %}
+ {% endfor %}
+ <!-- form.non_field_errors -->
+ <button type="submit" class="btn btn-default">Submit</button>
+</form>
diff --git a/rest_framework/templates/rest_framework/vertical/input.html b/rest_framework/templates/rest_framework/vertical/input.html
new file mode 100644
index 00000000..43cccd3e
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/input.html
@@ -0,0 +1,12 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>
+ {% endif %}
+ <input name="{{ field.name }}" {% if style.input_type != "file" %}class="form-control"{% endif %} type="{{ style.input_type }}" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if field.value %}value="{{ field.value }}"{% endif %}>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+</div>
diff --git a/rest_framework/templates/rest_framework/vertical/list_fieldset.html b/rest_framework/templates/rest_framework/vertical/list_fieldset.html
new file mode 100644
index 00000000..1d86c7f2
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/list_fieldset.html
@@ -0,0 +1,8 @@
+<fieldset>
+ {% if field.label %}<legend {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %}
+<!-- {% if field.label %}<legend {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</legend>{% endif %}
+ {% for field_item in field.value.field_items.values() %}
+ {{ renderer.render_field(field_item, layout=layout) }}
+ {% endfor %} -->
+ <p>Lists are not currently supported in HTML input.</p>
+</fieldset>
diff --git a/rest_framework/templates/rest_framework/vertical/radio.html b/rest_framework/templates/rest_framework/vertical/radio.html
new file mode 100644
index 00000000..ed9f9ddb
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/radio.html
@@ -0,0 +1,30 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>
+ {% endif %}
+ {% if style.inline %}
+ <div>
+ {% for key, text in field.choices.items %}
+ <label class="radio-inline">
+ <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ {% endfor %}
+ </div>
+ {% else %}
+ {% for key, text in field.choices.items %}
+ <div class="radio">
+ <label>
+ <input type="radio" name="{{ field.name }}" value="{{ key }}" {% if key == field.value %}checked{% endif %}>
+ {{ text }}
+ </label>
+ </div>
+ {% endfor %}
+ {% endif %}
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+</div>
diff --git a/rest_framework/templates/rest_framework/vertical/select.html b/rest_framework/templates/rest_framework/vertical/select.html
new file mode 100644
index 00000000..de72e1dd
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/select.html
@@ -0,0 +1,19 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>
+ {% endif %}
+ <select class="form-control" name="{{ field.name }}">
+ {% if field.allow_null %}
+ <option value="" {% if not field.value %}selected{% endif %}>--------</option>
+ {% endif %}
+ {% for key, text in field.choices.items %}
+ <option value="{{ key }}" {% if key == field.value %}selected{% endif %}>{{ text }}</option>
+ {% endfor %}
+ </select>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+</div>
diff --git a/rest_framework/templates/rest_framework/vertical/select_multiple.html b/rest_framework/templates/rest_framework/vertical/select_multiple.html
new file mode 100644
index 00000000..54839294
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/select_multiple.html
@@ -0,0 +1,16 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>
+ {% endif %}
+ <select multiple class="form-control" name="{{ field.name }}">
+ {% for key, text in field.choices.items %}
+ <option value="{{ key }}" {% if key in field.value %}selected{% endif %}>{{ text }}</option>
+ {% endfor %}
+ </select>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+</div>
diff --git a/rest_framework/templates/rest_framework/vertical/textarea.html b/rest_framework/templates/rest_framework/vertical/textarea.html
new file mode 100644
index 00000000..840ea853
--- /dev/null
+++ b/rest_framework/templates/rest_framework/vertical/textarea.html
@@ -0,0 +1,12 @@
+<div class="form-group {% if field.errors %}has-error{% endif %}">
+ {% if field.label %}
+ <label {% if style.hide_label %}class="sr-only"{% endif %}>{{ field.label }}</label>
+ {% endif %}
+ <textarea name="{{ field.name }}" class="form-control" {% if style.placeholder %}placeholder="{{ style.placeholder }}"{% endif %} {% if style.rows %}rows="{{ style.rows }}"{% endif %}>{% if field.value %}{{ field.value }}{% endif %}</textarea>
+ {% if field.errors %}
+ {% for error in field.errors %}<span class="help-block">{{ error }}</span>{% endfor %}
+ {% endif %}
+ {% if field.help_text %}
+ <span class="help-block">{{ field.help_text }}</span>
+ {% endif %}
+</div>
diff --git a/rest_framework/templatetags/rest_framework.py b/rest_framework/templatetags/rest_framework.py
index 864d64dd..f1825a24 100644
--- a/rest_framework/templatetags/rest_framework.py
+++ b/rest_framework/templatetags/rest_framework.py
@@ -8,6 +8,7 @@ from django.utils.html import escape
from django.utils.safestring import SafeData, mark_safe
from django.utils.html import smart_urlquote
from rest_framework.compat import urlparse, force_text
+from rest_framework.renderers import HTMLFormRenderer
import re
register = template.Library()
@@ -32,6 +33,13 @@ class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
# And the template tags themselves...
@register.simple_tag
+def render_field(field, style=None):
+ style = style or {}
+ renderer = style.get('renderer', HTMLFormRenderer())
+ return renderer.render_field(field, style)
+
+
+@register.simple_tag
def optional_login(request):
"""
Include a login snippet if REST framework's login view is in the URLconf.
@@ -75,7 +83,7 @@ def add_query_param(request, key, val):
"""
iri = request.get_full_path()
uri = iri_to_uri(iri)
- return replace_query_param(uri, key, val)
+ return escape(replace_query_param(uri, key, val))
@register.filter
diff --git a/rest_framework/test.py b/rest_framework/test.py
index 9b40353a..74d2c868 100644
--- a/rest_framework/test.py
+++ b/rest_framework/test.py
@@ -156,6 +156,52 @@ class APIClient(APIRequestFactory, DjangoClient):
kwargs.update(self._credentials)
return super(APIClient, self).request(**kwargs)
+ def get(self, path, data=None, follow=False, **extra):
+ response = super(APIClient, self).get(path, data=data, **extra)
+ if follow:
+ response = self._handle_redirects(response, **extra)
+ return response
+
+ def post(self, path, data=None, format=None, content_type=None,
+ follow=False, **extra):
+ response = super(APIClient, self).post(
+ path, data=data, format=format, content_type=content_type, **extra)
+ if follow:
+ response = self._handle_redirects(response, **extra)
+ return response
+
+ def put(self, path, data=None, format=None, content_type=None,
+ follow=False, **extra):
+ response = super(APIClient, self).put(
+ path, data=data, format=format, content_type=content_type, **extra)
+ if follow:
+ response = self._handle_redirects(response, **extra)
+ return response
+
+ def patch(self, path, data=None, format=None, content_type=None,
+ follow=False, **extra):
+ response = super(APIClient, self).patch(
+ path, data=data, format=format, content_type=content_type, **extra)
+ if follow:
+ response = self._handle_redirects(response, **extra)
+ return response
+
+ def delete(self, path, data=None, format=None, content_type=None,
+ follow=False, **extra):
+ response = super(APIClient, self).delete(
+ path, data=data, format=format, content_type=content_type, **extra)
+ if follow:
+ response = self._handle_redirects(response, **extra)
+ return response
+
+ def options(self, path, data=None, format=None, content_type=None,
+ follow=False, **extra):
+ response = super(APIClient, self).options(
+ path, data=data, format=format, content_type=content_type, **extra)
+ if follow:
+ response = self._handle_redirects(response, **extra)
+ return response
+
def logout(self):
self._credentials = {}
return super(APIClient, self).logout()
diff --git a/rest_framework/utils/encoders.py b/rest_framework/utils/encoders.py
index 174b08b8..4d6bb3a3 100644
--- a/rest_framework/utils/encoders.py
+++ b/rest_framework/utils/encoders.py
@@ -2,11 +2,10 @@
Helper classes for parsers.
"""
from __future__ import unicode_literals
-from django.utils import timezone
from django.db.models.query import QuerySet
-from django.utils.datastructures import SortedDict
+from django.utils import six, timezone
from django.utils.functional import Promise
-from rest_framework.compat import force_text
+from rest_framework.compat import force_text, OrderedDict
import datetime
import decimal
import types
@@ -40,12 +39,12 @@ class JSONEncoder(json.JSONEncoder):
representation = representation[:12]
return representation
elif isinstance(obj, datetime.timedelta):
- return str(obj.total_seconds())
+ return six.text_type(obj.total_seconds())
elif isinstance(obj, decimal.Decimal):
# Serializers will coerce decimals to strings by default.
return float(obj)
elif isinstance(obj, QuerySet):
- return list(obj)
+ return tuple(obj)
elif hasattr(obj, 'tolist'):
# Numpy arrays and array scalars.
return obj.tolist()
@@ -55,7 +54,7 @@ class JSONEncoder(json.JSONEncoder):
except:
pass
elif hasattr(obj, '__iter__'):
- return [item for item in obj]
+ return tuple(item for item in obj)
return super(JSONEncoder, self).default(obj)
@@ -68,11 +67,11 @@ else:
class SafeDumper(yaml.SafeDumper):
"""
Handles decimals as strings.
- Handles SortedDicts as usual dicts, but preserves field order, rather
+ Handles OrderedDicts as usual dicts, but preserves field order, rather
than the usual behaviour of sorting the keys.
"""
def represent_decimal(self, data):
- return self.represent_scalar('tag:yaml.org,2002:str', str(data))
+ return self.represent_scalar('tag:yaml.org,2002:str', six.text_type(data))
def represent_mapping(self, tag, mapping, flow_style=None):
value = []
@@ -82,7 +81,7 @@ else:
best_style = True
if hasattr(mapping, 'items'):
mapping = list(mapping.items())
- if not isinstance(mapping, SortedDict):
+ if not isinstance(mapping, OrderedDict):
mapping.sort()
for item_key, item_value in mapping:
node_key = self.represent_data(item_key)
@@ -104,7 +103,7 @@ else:
SafeDumper.represent_decimal
)
SafeDumper.add_representer(
- SortedDict,
+ OrderedDict,
yaml.representer.SafeRepresenter.represent_dict
)
# SafeDumper.add_representer(
@@ -112,7 +111,7 @@ else:
# yaml.representer.SafeRepresenter.represent_dict
# )
# SafeDumper.add_representer(
- # SortedDictWithMetadata,
+ # OrderedDictWithMetadata,
# yaml.representer.SafeRepresenter.represent_dict
# )
SafeDumper.add_representer(
diff --git a/rest_framework/utils/field_mapping.py b/rest_framework/utils/field_mapping.py
index be72e444..9c187176 100644
--- a/rest_framework/utils/field_mapping.py
+++ b/rest_framework/utils/field_mapping.py
@@ -6,20 +6,32 @@ from django.core import validators
from django.db import models
from django.utils.text import capfirst
from rest_framework.compat import clean_manytomany_helptext
+from rest_framework.validators import UniqueValidator
import inspect
-def lookup_class(mapping, instance):
+class ClassLookupDict(object):
"""
- Takes a dictionary with classes as keys, and an object.
- Traverses the object's inheritance hierarchy in method
- resolution order, and returns the first matching value
+ Takes a dictionary with classes as keys.
+ Lookups against this object will traverses the object's inheritance
+ hierarchy in method resolution order, and returns the first matching value
from the dictionary or raises a KeyError if nothing matches.
"""
- for cls in inspect.getmro(instance.__class__):
- if cls in mapping:
- return mapping[cls]
- raise KeyError('Class %s not found in lookup.', cls.__name__)
+ def __init__(self, mapping):
+ self.mapping = mapping
+
+ def __getitem__(self, key):
+ if hasattr(key, '_proxy_class'):
+ # Deal with proxy classes. Ie. BoundField behaves as if it
+ # is a Field instance when using ClassLookupDict.
+ base_class = key._proxy_class
+ else:
+ base_class = key.__class__
+
+ for cls in inspect.getmro(base_class):
+ if cls in self.mapping:
+ return self.mapping[cls]
+ raise KeyError('Class %s not found in lookup.', cls.__name__)
def needs_label(model_field, field_name):
@@ -49,8 +61,9 @@ def get_field_kwargs(field_name, model_field):
kwargs = {}
validator_kwarg = model_field.validators
- if model_field.null or model_field.blank:
- kwargs['required'] = False
+ # The following will only be used by ModelField classes.
+ # Gets removed for everything else.
+ kwargs['model_field'] = model_field
if model_field.verbose_name and needs_label(model_field, field_name):
kwargs['label'] = capfirst(model_field.verbose_name)
@@ -58,24 +71,38 @@ def get_field_kwargs(field_name, model_field):
if model_field.help_text:
kwargs['help_text'] = model_field.help_text
+ max_digits = getattr(model_field, 'max_digits', None)
+ if max_digits is not None:
+ kwargs['max_digits'] = max_digits
+
+ decimal_places = getattr(model_field, 'decimal_places', None)
+ if decimal_places is not None:
+ kwargs['decimal_places'] = decimal_places
+
+ if isinstance(model_field, models.TextField):
+ kwargs['style'] = {'type': 'textarea'}
+
if isinstance(model_field, models.AutoField) or not model_field.editable:
+ # If this field is read-only, then return early.
+ # Further keyword arguments are not valid.
kwargs['read_only'] = True
- # Read only implies that the field is not required.
- # We have a cleaner repr on the instance if we don't set it.
- kwargs.pop('required', None)
+ return kwargs
- if model_field.has_default():
- kwargs['default'] = model_field.get_default()
- # Having a default implies that the field is not required.
- # We have a cleaner repr on the instance if we don't set it.
- kwargs.pop('required', None)
+ if model_field.has_default() or model_field.blank or model_field.null:
+ kwargs['required'] = False
if model_field.flatchoices:
- # If this model field contains choices, then return now,
- # any further keyword arguments are not valid.
+ # If this model field contains choices, then return early.
+ # Further keyword arguments are not valid.
kwargs['choices'] = model_field.flatchoices
return kwargs
+ if model_field.null and not isinstance(model_field, models.NullBooleanField):
+ kwargs['allow_null'] = True
+
+ if model_field.blank:
+ kwargs['allow_blank'] = True
+
# Ensure that max_length is passed explicitly as a keyword arg,
# rather than as a validator.
max_length = getattr(model_field, 'max_length', None)
@@ -88,7 +115,10 @@ def get_field_kwargs(field_name, model_field):
# Ensure that min_length is passed explicitly as a keyword arg,
# rather than as a validator.
- min_length = getattr(model_field, 'min_length', None)
+ min_length = next((
+ validator.limit_value for validator in validator_kwarg
+ if isinstance(validator, validators.MinLengthValidator)
+ ), None)
if min_length is not None:
kwargs['min_length'] = min_length
validator_kwarg = [
@@ -145,28 +175,13 @@ def get_field_kwargs(field_name, model_field):
if validator is not validators.validate_slug
]
- max_digits = getattr(model_field, 'max_digits', None)
- if max_digits is not None:
- kwargs['max_digits'] = max_digits
-
- decimal_places = getattr(model_field, 'decimal_places', None)
- if decimal_places is not None:
- kwargs['decimal_places'] = decimal_places
-
- if isinstance(model_field, models.BooleanField):
- # models.BooleanField has `blank=True`, but *is* actually
- # required *unless* a default is provided.
- # Also note that Django<1.6 uses `default=False` for
- # models.BooleanField, but Django>=1.6 uses `default=None`.
- kwargs.pop('required', None)
+ if getattr(model_field, 'unique', False):
+ validator = UniqueValidator(queryset=model_field.model._default_manager)
+ validator_kwarg.append(validator)
if validator_kwarg:
kwargs['validators'] = validator_kwarg
- # The following will only be used by ModelField classes.
- # Gets removed for everything else.
- kwargs['model_field'] = model_field
-
return kwargs
@@ -188,16 +203,27 @@ def get_relation_kwargs(field_name, relation_info):
kwargs.pop('queryset', None)
if model_field:
- if model_field.null or model_field.blank:
- kwargs['required'] = False
if model_field.verbose_name and needs_label(model_field, field_name):
kwargs['label'] = capfirst(model_field.verbose_name)
- if not model_field.editable:
- kwargs['read_only'] = True
- kwargs.pop('queryset', None)
help_text = clean_manytomany_helptext(model_field.help_text)
if help_text:
kwargs['help_text'] = help_text
+ if not model_field.editable:
+ kwargs['read_only'] = True
+ kwargs.pop('queryset', None)
+ if kwargs.get('read_only', False):
+ # If this field is read-only, then return early.
+ # No further keyword arguments are valid.
+ return kwargs
+ if model_field.has_default() or model_field.null:
+ kwargs['required'] = False
+ if model_field.null:
+ kwargs['allow_null'] = True
+ if model_field.validators:
+ kwargs['validators'] = model_field.validators
+ if getattr(model_field, 'unique', False):
+ validator = UniqueValidator(queryset=model_field.model._default_manager)
+ kwargs['validators'] = kwargs.get('validators', []) + [validator]
return kwargs
diff --git a/rest_framework/utils/html.py b/rest_framework/utils/html.py
index edc591e9..d773952d 100644
--- a/rest_framework/utils/html.py
+++ b/rest_framework/utils/html.py
@@ -2,6 +2,7 @@
Helpers for dealing with HTML input.
"""
import re
+from django.utils.datastructures import MultiValueDict
def is_html_input(dictionary):
@@ -35,7 +36,7 @@ def parse_html_list(dictionary, prefix=''):
'[0]foo': 'abc',
'[0]bar': 'def',
'[1]foo': 'hij',
- '[2]bar': 'klm',
+ '[1]bar': 'klm',
}
-->
[
@@ -43,7 +44,6 @@ def parse_html_list(dictionary, prefix=''):
{'foo': 'hij', 'bar': 'klm'}
]
"""
- Dict = type(dictionary)
ret = {}
regex = re.compile(r'^%s\[([0-9]+)\](.*)$' % re.escape(prefix))
for field, value in dictionary.items():
@@ -57,7 +57,7 @@ def parse_html_list(dictionary, prefix=''):
elif isinstance(ret.get(index), dict):
ret[index][key] = value
else:
- ret[index] = Dict({key: value})
+ ret[index] = MultiValueDict({key: [value]})
return [ret[item] for item in sorted(ret.keys())]
@@ -72,7 +72,7 @@ def parse_html_dict(dictionary, prefix):
-->
{
'profile': {
- 'username': 'example,
+ 'username': 'example',
'email': 'example@example.com'
}
}
diff --git a/rest_framework/utils/model_meta.py b/rest_framework/utils/model_meta.py
index b6c41174..c98725c6 100644
--- a/rest_framework/utils/model_meta.py
+++ b/rest_framework/utils/model_meta.py
@@ -6,9 +6,10 @@ relationships and their associated metadata.
Usage: `get_field_info(model)` returns a `FieldInfo` instance.
"""
from collections import namedtuple
+from django.core.exceptions import ImproperlyConfigured
from django.db import models
from django.utils import six
-from django.utils.datastructures import SortedDict
+from rest_framework.compat import OrderedDict
import inspect
@@ -43,7 +44,11 @@ def _resolve_model(obj):
"""
if isinstance(obj, six.string_types) and len(obj.split('.')) == 2:
app_name, model_name = obj.split('.')
- return models.get_model(app_name, model_name)
+ resolved_model = models.get_model(app_name, model_name)
+ if resolved_model is None:
+ msg = "Django did not return a model for {0}.{1}"
+ raise ImproperlyConfigured(msg.format(app_name, model_name))
+ return resolved_model
elif inspect.isclass(obj) and issubclass(obj, models.Model):
return obj
raise ValueError("{0} is not a Django model".format(obj))
@@ -63,12 +68,12 @@ def get_field_info(model):
pk = pk.rel.to._meta.pk
# Deal with regular fields.
- fields = SortedDict()
+ fields = OrderedDict()
for field in [field for field in opts.fields if field.serialize and not field.rel]:
fields[field.name] = field
# Deal with forward relationships.
- forward_relations = SortedDict()
+ forward_relations = OrderedDict()
for field in [field for field in opts.fields if field.serialize and field.rel]:
forward_relations[field.name] = RelationInfo(
model_field=field,
@@ -89,7 +94,7 @@ def get_field_info(model):
)
# Deal with reverse relationships.
- reverse_relations = SortedDict()
+ reverse_relations = OrderedDict()
for relation in opts.get_all_related_objects():
accessor_name = relation.get_accessor_name()
reverse_relations[accessor_name] = RelationInfo(
@@ -107,21 +112,21 @@ def get_field_info(model):
related=relation.model,
to_many=True,
has_through_model=(
- hasattr(relation.field.rel, 'through') and
- not relation.field.rel.through._meta.auto_created
+ (getattr(relation.field.rel, 'through', None) is not None)
+ and not relation.field.rel.through._meta.auto_created
)
)
# Shortcut that merges both regular fields and the pk,
# for simplifying regular field lookup.
- fields_and_pk = SortedDict()
+ fields_and_pk = OrderedDict()
fields_and_pk['pk'] = pk
fields_and_pk[pk.name] = pk
fields_and_pk.update(fields)
# Shortcut that merges both forward and reverse relationships
- relations = SortedDict(
+ relations = OrderedDict(
list(forward_relations.items()) +
list(reverse_relations.items())
)
diff --git a/rest_framework/utils/representation.py b/rest_framework/utils/representation.py
index e64fdd22..2a7c4675 100644
--- a/rest_framework/utils/representation.py
+++ b/rest_framework/utils/representation.py
@@ -3,6 +3,8 @@ Helper functions for creating user-friendly representations
of serializer classes and serializer fields.
"""
from django.db import models
+from django.utils.functional import Promise
+from rest_framework.compat import force_text
import re
@@ -19,6 +21,9 @@ def smart_repr(value):
if isinstance(value, models.Manager):
return manager_repr(value)
+ if isinstance(value, Promise) and value._delegate_text:
+ value = force_text(value)
+
value = repr(value)
# Representations like u'help text'
@@ -77,6 +82,11 @@ def serializer_repr(serializer, indent, force_many=None):
ret += field_repr(field.child_relation, force_many=field.child_relation)
else:
ret += field_repr(field)
+
+ if serializer.validators:
+ ret += '\n' + indent_str + 'class Meta:'
+ ret += '\n' + indent_str + ' validators = ' + smart_repr(serializer.validators)
+
return ret
diff --git a/rest_framework/utils/serializer_helpers.py b/rest_framework/utils/serializer_helpers.py
new file mode 100644
index 00000000..92d19857
--- /dev/null
+++ b/rest_framework/utils/serializer_helpers.py
@@ -0,0 +1,102 @@
+from rest_framework.compat import OrderedDict
+
+
+class ReturnDict(OrderedDict):
+ """
+ Return object from `serialier.data` for the `Serializer` class.
+ Includes a backlink to the serializer instance for renderers
+ to use if they need richer field information.
+ """
+ def __init__(self, *args, **kwargs):
+ self.serializer = kwargs.pop('serializer')
+ super(ReturnDict, self).__init__(*args, **kwargs)
+
+ def copy(self):
+ return ReturnDict(self, serializer=self.serializer)
+
+
+class ReturnList(list):
+ """
+ Return object from `serialier.data` for the `SerializerList` class.
+ Includes a backlink to the serializer instance for renderers
+ to use if they need richer field information.
+ """
+ def __init__(self, *args, **kwargs):
+ self.serializer = kwargs.pop('serializer')
+ super(ReturnList, self).__init__(*args, **kwargs)
+
+
+class BoundField(object):
+ """
+ A field object that also includes `.value` and `.error` properties.
+ Returned when iterating over a serializer instance,
+ providing an API similar to Django forms and form fields.
+ """
+ def __init__(self, field, value, errors, prefix=''):
+ self._field = field
+ self.value = value
+ self.errors = errors
+ self.name = prefix + self.field_name
+
+ def __getattr__(self, attr_name):
+ return getattr(self._field, attr_name)
+
+ @property
+ def _proxy_class(self):
+ return self._field.__class__
+
+ def __repr__(self):
+ return '<%s value=%s errors=%s>' % (
+ self.__class__.__name__, self.value, self.errors
+ )
+
+
+class NestedBoundField(BoundField):
+ """
+ This `BoundField` additionally implements __iter__ and __getitem__
+ in order to support nested bound fields. This class is the type of
+ `BoundField` that is used for serializer fields.
+ """
+ def __iter__(self):
+ for field in self.fields.values():
+ yield self[field.field_name]
+
+ def __getitem__(self, key):
+ field = self.fields[key]
+ value = self.value.get(key) if self.value else None
+ error = self.errors.get(key) if self.errors else None
+ if hasattr(field, 'fields'):
+ return NestedBoundField(field, value, error, prefix=self.name + '.')
+ return BoundField(field, value, error, prefix=self.name + '.')
+
+
+class BindingDict(object):
+ """
+ This dict-like object is used to store fields on a serializer.
+
+ This ensures that whenever fields are added to the serializer we call
+ `field.bind()` so that the `field_name` and `parent` attributes
+ can be set correctly.
+ """
+ def __init__(self, serializer):
+ self.serializer = serializer
+ self.fields = OrderedDict()
+
+ def __setitem__(self, key, field):
+ self.fields[key] = field
+ field.bind(field_name=key, parent=self.serializer)
+
+ def __getitem__(self, key):
+ return self.fields[key]
+
+ def __delitem__(self, key):
+ del self.fields[key]
+
+ def items(self):
+ return self.fields.items()
+
+ def keys(self):
+ return self.fields.keys()
+
+ def values(self):
+ return self.fields.values()
diff --git a/rest_framework/validators.py b/rest_framework/validators.py
new file mode 100644
index 00000000..7ca4e6a9
--- /dev/null
+++ b/rest_framework/validators.py
@@ -0,0 +1,254 @@
+"""
+We perform uniqueness checks explicitly on the serializer class, rather
+the using Django's `.full_clean()`.
+
+This gives us better separation of concerns, allows us to use single-step
+object creation, and makes it possible to switch between using the implicit
+`ModelSerializer` class and an equivelent explicit `Serializer` class.
+"""
+from django.utils.translation import ugettext_lazy as _
+from rest_framework.exceptions import ValidationError
+from rest_framework.utils.representation import smart_repr
+
+
+class UniqueValidator:
+ """
+ Validator that corresponds to `unique=True` on a model field.
+
+ Should be applied to an individual field on the serializer.
+ """
+ message = _('This field must be unique.')
+
+ def __init__(self, queryset, message=None):
+ self.queryset = queryset
+ self.serializer_field = None
+ self.message = message or self.message
+
+ def set_context(self, serializer_field):
+ """
+ This hook is called by the serializer instance,
+ prior to the validation call being made.
+ """
+ # Determine the underlying model field name. This may not be the
+ # same as the serializer field name if `source=<>` is set.
+ self.field_name = serializer_field.source_attrs[0]
+ # Determine the existing instance, if this is an update operation.
+ self.instance = getattr(serializer_field.parent, 'instance', None)
+
+ def filter_queryset(self, value, queryset):
+ """
+ Filter the queryset to all instances matching the given attribute.
+ """
+ filter_kwargs = {self.field_name: value}
+ return queryset.filter(**filter_kwargs)
+
+ def exclude_current_instance(self, queryset):
+ """
+ If an instance is being updated, then do not include
+ that instance itself as a uniqueness conflict.
+ """
+ if self.instance is not None:
+ return queryset.exclude(pk=self.instance.pk)
+ return queryset
+
+ def __call__(self, value):
+ queryset = self.queryset
+ queryset = self.filter_queryset(value, queryset)
+ queryset = self.exclude_current_instance(queryset)
+ if queryset.exists():
+ raise ValidationError(self.message)
+
+ def __repr__(self):
+ return '<%s(queryset=%s)>' % (
+ self.__class__.__name__,
+ smart_repr(self.queryset)
+ )
+
+
+class UniqueTogetherValidator:
+ """
+ Validator that corresponds to `unique_together = (...)` on a model class.
+
+ Should be applied to the serializer class, not to an individual field.
+ """
+ message = _('The fields {field_names} must make a unique set.')
+ missing_message = _('This field is required.')
+
+ def __init__(self, queryset, fields, message=None):
+ self.queryset = queryset
+ self.fields = fields
+ self.serializer_field = None
+ self.message = message or self.message
+
+ def set_context(self, serializer):
+ """
+ This hook is called by the serializer instance,
+ prior to the validation call being made.
+ """
+ # Determine the existing instance, if this is an update operation.
+ self.instance = getattr(serializer, 'instance', None)
+
+ def enforce_required_fields(self, attrs):
+ """
+ The `UniqueTogetherValidator` always forces an implied 'required'
+ state on the fields it applies to.
+ """
+ if self.instance is not None:
+ return
+
+ missing = dict([
+ (field_name, self.missing_message)
+ for field_name in self.fields
+ if field_name not in attrs
+ ])
+ if missing:
+ raise ValidationError(missing)
+
+ def filter_queryset(self, attrs, queryset):
+ """
+ Filter the queryset to all instances matching the given attributes.
+ """
+ # If this is an update, then any unprovided field should
+ # have it's value set based on the existing instance attribute.
+ if self.instance is not None:
+ for field_name in self.fields:
+ if field_name not in attrs:
+ attrs[field_name] = getattr(self.instance, field_name)
+
+ # Determine the filter keyword arguments and filter the queryset.
+ filter_kwargs = dict([
+ (field_name, attrs[field_name])
+ for field_name in self.fields
+ ])
+ return queryset.filter(**filter_kwargs)
+
+ def exclude_current_instance(self, attrs, queryset):
+ """
+ If an instance is being updated, then do not include
+ that instance itself as a uniqueness conflict.
+ """
+ if self.instance is not None:
+ return queryset.exclude(pk=self.instance.pk)
+ return queryset
+
+ def __call__(self, attrs):
+ self.enforce_required_fields(attrs)
+ queryset = self.queryset
+ queryset = self.filter_queryset(attrs, queryset)
+ queryset = self.exclude_current_instance(attrs, queryset)
+ if queryset.exists():
+ field_names = ', '.join(self.fields)
+ raise ValidationError(self.message.format(field_names=field_names))
+
+ def __repr__(self):
+ return '<%s(queryset=%s, fields=%s)>' % (
+ self.__class__.__name__,
+ smart_repr(self.queryset),
+ smart_repr(self.fields)
+ )
+
+
+class BaseUniqueForValidator:
+ message = None
+ missing_message = _('This field is required.')
+
+ def __init__(self, queryset, field, date_field, message=None):
+ self.queryset = queryset
+ self.field = field
+ self.date_field = date_field
+ self.message = message or self.message
+
+ def set_context(self, serializer):
+ """
+ This hook is called by the serializer instance,
+ prior to the validation call being made.
+ """
+ # Determine the underlying model field names. These may not be the
+ # same as the serializer field names if `source=<>` is set.
+ self.field_name = serializer.fields[self.field].source_attrs[0]
+ self.date_field_name = serializer.fields[self.date_field].source_attrs[0]
+ # Determine the existing instance, if this is an update operation.
+ self.instance = getattr(serializer, 'instance', None)
+
+ def enforce_required_fields(self, attrs):
+ """
+ The `UniqueFor<Range>Validator` classes always force an implied
+ 'required' state on the fields they are applied to.
+ """
+ missing = dict([
+ (field_name, self.missing_message)
+ for field_name in [self.field, self.date_field]
+ if field_name not in attrs
+ ])
+ if missing:
+ raise ValidationError(missing)
+
+ def filter_queryset(self, attrs, queryset):
+ raise NotImplementedError('`filter_queryset` must be implemented.')
+
+ def exclude_current_instance(self, attrs, queryset):
+ """
+ If an instance is being updated, then do not include
+ that instance itself as a uniqueness conflict.
+ """
+ if self.instance is not None:
+ return queryset.exclude(pk=self.instance.pk)
+ return queryset
+
+ def __call__(self, attrs):
+ self.enforce_required_fields(attrs)
+ queryset = self.queryset
+ queryset = self.filter_queryset(attrs, queryset)
+ queryset = self.exclude_current_instance(attrs, queryset)
+ if queryset.exists():
+ message = self.message.format(date_field=self.date_field)
+ raise ValidationError({self.field: message})
+
+ def __repr__(self):
+ return '<%s(queryset=%s, field=%s, date_field=%s)>' % (
+ self.__class__.__name__,
+ smart_repr(self.queryset),
+ smart_repr(self.field),
+ smart_repr(self.date_field)
+ )
+
+
+class UniqueForDateValidator(BaseUniqueForValidator):
+ message = _('This field must be unique for the "{date_field}" date.')
+
+ def filter_queryset(self, attrs, queryset):
+ value = attrs[self.field]
+ date = attrs[self.date_field]
+
+ filter_kwargs = {}
+ filter_kwargs[self.field_name] = value
+ filter_kwargs['%s__day' % self.date_field_name] = date.day
+ filter_kwargs['%s__month' % self.date_field_name] = date.month
+ filter_kwargs['%s__year' % self.date_field_name] = date.year
+ return queryset.filter(**filter_kwargs)
+
+
+class UniqueForMonthValidator(BaseUniqueForValidator):
+ message = _('This field must be unique for the "{date_field}" month.')
+
+ def filter_queryset(self, attrs, queryset):
+ value = attrs[self.field]
+ date = attrs[self.date_field]
+
+ filter_kwargs = {}
+ filter_kwargs[self.field_name] = value
+ filter_kwargs['%s__month' % self.date_field_name] = date.month
+ return queryset.filter(**filter_kwargs)
+
+
+class UniqueForYearValidator(BaseUniqueForValidator):
+ message = _('This field must be unique for the "{date_field}" year.')
+
+ def filter_queryset(self, attrs, queryset):
+ value = attrs[self.field]
+ date = attrs[self.date_field]
+
+ filter_kwargs = {}
+ filter_kwargs[self.field_name] = value
+ filter_kwargs['%s__year' % self.date_field_name] = date.year
+ return queryset.filter(**filter_kwargs)
diff --git a/rest_framework/views.py b/rest_framework/views.py
index 9f08a4ad..292431c8 100644
--- a/rest_framework/views.py
+++ b/rest_framework/views.py
@@ -3,9 +3,8 @@ Provides an APIView class that is the base of all views in REST framework.
"""
from __future__ import unicode_literals
-from django.core.exceptions import PermissionDenied, ValidationError, NON_FIELD_ERRORS
+from django.core.exceptions import PermissionDenied
from django.http import Http404
-from django.utils.datastructures import SortedDict
from django.views.decorators.csrf import csrf_exempt
from rest_framework import status, exceptions
from rest_framework.compat import smart_text, HttpResponseBase, View
@@ -64,27 +63,20 @@ def exception_handler(exc):
if getattr(exc, 'wait', None):
headers['Retry-After'] = '%d' % exc.wait
- return Response({'detail': exc.detail},
- status=exc.status_code,
- headers=headers)
+ if isinstance(exc.detail, (list, dict)):
+ data = exc.detail
+ else:
+ data = {'detail': exc.detail}
- elif isinstance(exc, ValidationError):
- # ValidationErrors may include the non-field key named '__all__'.
- # When returning a response we map this to a key name that can be
- # modified in settings.
- if NON_FIELD_ERRORS in exc.message_dict:
- errors = exc.message_dict.pop(NON_FIELD_ERRORS)
- exc.message_dict[api_settings.NON_FIELD_ERRORS_KEY] = errors
- return Response(exc.message_dict,
- status=status.HTTP_400_BAD_REQUEST)
+ return Response(data, status=exc.status_code, headers=headers)
elif isinstance(exc, Http404):
- return Response({'detail': 'Not found'},
- status=status.HTTP_404_NOT_FOUND)
+ data = {'detail': 'Not found'}
+ return Response(data, status=status.HTTP_404_NOT_FOUND)
elif isinstance(exc, PermissionDenied):
- return Response({'detail': 'Permission denied'},
- status=status.HTTP_403_FORBIDDEN)
+ data = {'detail': 'Permission denied'}
+ return Response(data, status=status.HTTP_403_FORBIDDEN)
# Note: Unhandled exceptions will raise a 500 error.
return None
@@ -99,8 +91,9 @@ class APIView(View):
throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES
permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES
content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS
+ metadata_class = api_settings.DEFAULT_METADATA_CLASS
- # Allow dependancy injection of other settings to make testing easier.
+ # Allow dependency injection of other settings to make testing easier.
settings = api_settings
@classmethod
@@ -418,22 +411,8 @@ class APIView(View):
def options(self, request, *args, **kwargs):
"""
Handler method for HTTP 'OPTIONS' request.
- We may as well implement this as Django will otherwise provide
- a less useful default implementation.
"""
- return Response(self.metadata(request), status=status.HTTP_200_OK)
-
- def metadata(self, request):
- """
- Return a dictionary of metadata about the view.
- Used to return responses for OPTIONS requests.
- """
- # By default we can't provide any form-like information, however the
- # generic views override this implementation and add additional
- # information for POST and PUT methods, based on the serializer.
- ret = SortedDict()
- ret['name'] = self.get_view_name()
- ret['description'] = self.get_view_description()
- ret['renders'] = [renderer.media_type for renderer in self.renderer_classes]
- ret['parses'] = [parser.media_type for parser in self.parser_classes]
- return ret
+ if self.metadata_class is None:
+ return self.http_method_not_allowed(request, *args, **kwargs)
+ data = self.metadata_class().determine_metadata(request, self)
+ return Response(data, status=status.HTTP_200_OK)
diff --git a/tests/accounts/__init__.py b/tests/accounts/__init__.py
deleted file mode 100644
index e69de29b..00000000
--- a/tests/accounts/__init__.py
+++ /dev/null
diff --git a/tests/accounts/models.py b/tests/accounts/models.py
deleted file mode 100644
index 3bf4a0c3..00000000
--- a/tests/accounts/models.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from django.db import models
-
-from tests.users.models import User
-
-
-class Account(models.Model):
- owner = models.ForeignKey(User, related_name='accounts_owned')
- admins = models.ManyToManyField(User, blank=True, null=True, related_name='accounts_administered')
diff --git a/tests/accounts/serializers.py b/tests/accounts/serializers.py
deleted file mode 100644
index 57a91b92..00000000
--- a/tests/accounts/serializers.py
+++ /dev/null
@@ -1,11 +0,0 @@
-from rest_framework import serializers
-
-from tests.accounts.models import Account
-from tests.users.serializers import UserSerializer
-
-
-class AccountSerializer(serializers.ModelSerializer):
- admins = UserSerializer(many=True)
-
- class Meta:
- model = Account
diff --git a/tests/conftest.py b/tests/conftest.py
index 67986621..44ed070b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -33,9 +33,6 @@ def pytest_configure():
'rest_framework',
'rest_framework.authtoken',
'tests',
- 'tests.accounts',
- 'tests.records',
- 'tests.users',
),
PASSWORD_HASHERS=(
'django.contrib.auth.hashers.SHA1PasswordHasher',
diff --git a/tests/put_as_create_workspace.txt b/tests/put_as_create_workspace.txt
deleted file mode 100644
index 6bc5218e..00000000
--- a/tests/put_as_create_workspace.txt
+++ /dev/null
@@ -1,33 +0,0 @@
-# From test_validation...
-
-class TestPreSaveValidationExclusions(TestCase):
- def test_pre_save_validation_exclusions(self):
- """
- Somewhat weird test case to ensure that we don't perform model
- validation on read only fields.
- """
- obj = ValidationModel.objects.create(blank_validated_field='')
- request = factory.put('/', {}, format='json')
- view = UpdateValidationModel().as_view()
- response = view(request, pk=obj.pk).render()
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
-
-# From test_permissions...
-
-class ModelPermissionsIntegrationTests(TestCase):
- def setUp(...):
- ...
-
- def test_has_put_as_create_permissions(self):
- # User only has update permissions - should be able to update an entity.
- request = factory.put('/1', {'text': 'foobar'}, format='json',
- HTTP_AUTHORIZATION=self.updateonly_credentials)
- response = instance_view(request, pk='1')
- self.assertEqual(response.status_code, status.HTTP_200_OK)
-
- # But if PUTing to a new entity, permission should be denied.
- request = factory.put('/2', {'text': 'foobar'}, format='json',
- HTTP_AUTHORIZATION=self.updateonly_credentials)
- response = instance_view(request, pk='2')
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
diff --git a/tests/records/__init__.py b/tests/records/__init__.py
deleted file mode 100644
index e69de29b..00000000
--- a/tests/records/__init__.py
+++ /dev/null
diff --git a/tests/records/models.py b/tests/records/models.py
deleted file mode 100644
index 76954807..00000000
--- a/tests/records/models.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from django.db import models
-
-
-class Record(models.Model):
- account = models.ForeignKey('accounts.Account', blank=True, null=True)
- owner = models.ForeignKey('users.User', blank=True, null=True)
diff --git a/tests/settings.py b/tests/settings.py
deleted file mode 100644
index 6a01669c..00000000
--- a/tests/settings.py
+++ /dev/null
@@ -1,144 +0,0 @@
-# Django settings for testproject project.
-
-DEBUG = True
-TEMPLATE_DEBUG = DEBUG
-DEBUG_PROPAGATE_EXCEPTIONS = True
-
-ALLOWED_HOSTS = ['*']
-
-ADMINS = (
- # ('Your Name', 'your_email@domain.com'),
-)
-
-MANAGERS = ADMINS
-
-DATABASES = {
- 'default': {
- 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
- 'NAME': 'sqlite.db', # Or path to database file if using sqlite3.
- 'USER': '', # Not used with sqlite3.
- 'PASSWORD': '', # Not used with sqlite3.
- 'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
- 'PORT': '', # Set to empty string for default. Not used with sqlite3.
- }
-}
-
-CACHES = {
- 'default': {
- 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
- }
-}
-
-# Local time zone for this installation. Choices can be found here:
-# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
-# although not all choices may be available on all operating systems.
-# On Unix systems, a value of None will cause Django to use the same
-# timezone as the operating system.
-# If running in a Windows environment this must be set to the same as your
-# system time zone.
-TIME_ZONE = 'Europe/London'
-
-# Language code for this installation. All choices can be found here:
-# http://www.i18nguy.com/unicode/language-identifiers.html
-LANGUAGE_CODE = 'en-uk'
-
-SITE_ID = 1
-
-# If you set this to False, Django will make some optimizations so as not
-# to load the internationalization machinery.
-USE_I18N = True
-
-# If you set this to False, Django will not format dates, numbers and
-# calendars according to the current locale
-USE_L10N = True
-
-# Absolute filesystem path to the directory that will hold user-uploaded files.
-# Example: "/home/media/media.lawrence.com/"
-MEDIA_ROOT = ''
-
-# URL that handles the media served from MEDIA_ROOT. Make sure to use a
-# trailing slash if there is a path component (optional in other cases).
-# Examples: "http://media.lawrence.com", "http://example.com/media/"
-MEDIA_URL = ''
-
-# Make this unique, and don't share it with anybody.
-SECRET_KEY = 'u@x-aj9(hoh#rb-^ymf#g2jx_hp0vj7u5#b@ag1n^seu9e!%cy'
-
-# List of callables that know how to import templates from various sources.
-TEMPLATE_LOADERS = (
- 'django.template.loaders.filesystem.Loader',
- 'django.template.loaders.app_directories.Loader',
-)
-
-MIDDLEWARE_CLASSES = (
- 'django.middleware.common.CommonMiddleware',
- 'django.contrib.sessions.middleware.SessionMiddleware',
- 'django.middleware.csrf.CsrfViewMiddleware',
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
- 'django.contrib.messages.middleware.MessageMiddleware',
-)
-
-ROOT_URLCONF = 'tests.urls'
-
-TEMPLATE_DIRS = (
- # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
- # Always use forward slashes, even on Windows.
- # Don't forget to use absolute paths, not relative paths.
-)
-
-INSTALLED_APPS = (
- 'django.contrib.auth',
- 'django.contrib.contenttypes',
- 'django.contrib.sessions',
- 'django.contrib.sites',
- 'django.contrib.messages',
- 'django.contrib.staticfiles',
- 'rest_framework',
- 'rest_framework.authtoken',
- 'tests',
- 'tests.accounts',
- 'tests.records',
- 'tests.users',
-)
-
-# guardian is optional
-try:
- import guardian # NOQA
-except ImportError:
- pass
-else:
- ANONYMOUS_USER_ID = -1
- AUTHENTICATION_BACKENDS = (
- 'django.contrib.auth.backends.ModelBackend', # default
- 'guardian.backends.ObjectPermissionBackend',
- )
- INSTALLED_APPS += (
- 'guardian',
- )
-
-STATIC_URL = '/static/'
-
-PASSWORD_HASHERS = (
- 'django.contrib.auth.hashers.SHA1PasswordHasher',
- 'django.contrib.auth.hashers.PBKDF2PasswordHasher',
- 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
- 'django.contrib.auth.hashers.BCryptPasswordHasher',
- 'django.contrib.auth.hashers.MD5PasswordHasher',
- 'django.contrib.auth.hashers.CryptPasswordHasher',
-)
-
-AUTH_USER_MODEL = 'auth.User'
-
-import django
-
-if django.VERSION < (1, 3):
- INSTALLED_APPS += ('staticfiles',)
-
-
-# If we're running on the Jenkins server we want to archive the coverage reports as XML.
-import os
-if os.environ.get('HUDSON_URL', None):
- TEST_RUNNER = 'xmlrunner.extra.djangotestrunner.XMLTestRunner'
- TEST_OUTPUT_VERBOSE = True
- TEST_OUTPUT_DESCRIPTIONS = True
- TEST_OUTPUT_DIR = 'xmlrunner'
diff --git a/tests/test_authentication.py b/tests/test_authentication.py
index ece6eff5..bf0fd6fb 100644
--- a/tests/test_authentication.py
+++ b/tests/test_authentication.py
@@ -108,7 +108,7 @@ class SessionAuthTests(TestCase):
cf. [#1810](https://github.com/tomchristie/django-rest-framework/pull/1810)
"""
response = self.csrf_client.get('/auth/login/')
- self.assertContains(response, '<Label class="span4">Username:</label>')
+ self.assertContains(response, '<label class="span4">Username:</label>')
def test_post_form_session_auth_failing_csrf(self):
"""
diff --git a/tests/test_bound_fields.py b/tests/test_bound_fields.py
new file mode 100644
index 00000000..469437e4
--- /dev/null
+++ b/tests/test_bound_fields.py
@@ -0,0 +1,69 @@
+from rest_framework import serializers
+
+
+class TestSimpleBoundField:
+ def test_empty_bound_field(self):
+ class ExampleSerializer(serializers.Serializer):
+ text = serializers.CharField(max_length=100)
+ amount = serializers.IntegerField()
+
+ serializer = ExampleSerializer()
+
+ assert serializer['text'].value == ''
+ assert serializer['text'].errors is None
+ assert serializer['text'].name == 'text'
+ assert serializer['amount'].value is None
+ assert serializer['amount'].errors is None
+ assert serializer['amount'].name == 'amount'
+
+ def test_populated_bound_field(self):
+ class ExampleSerializer(serializers.Serializer):
+ text = serializers.CharField(max_length=100)
+ amount = serializers.IntegerField()
+
+ serializer = ExampleSerializer(data={'text': 'abc', 'amount': 123})
+
+ assert serializer['text'].value == 'abc'
+ assert serializer['text'].errors is None
+ assert serializer['text'].name == 'text'
+ assert serializer['amount'].value is 123
+ assert serializer['amount'].errors is None
+ assert serializer['amount'].name == 'amount'
+
+ def test_error_bound_field(self):
+ class ExampleSerializer(serializers.Serializer):
+ text = serializers.CharField(max_length=100)
+ amount = serializers.IntegerField()
+
+ serializer = ExampleSerializer(data={'text': 'x' * 1000, 'amount': 123})
+ serializer.is_valid()
+
+ assert serializer['text'].value == 'x' * 1000
+ assert serializer['text'].errors == ['Ensure this field has no more than 100 characters.']
+ assert serializer['text'].name == 'text'
+ assert serializer['amount'].value is 123
+ assert serializer['amount'].errors is None
+ assert serializer['amount'].name == 'amount'
+
+
+class TestNestedBoundField:
+ def test_nested_empty_bound_field(self):
+ class Nested(serializers.Serializer):
+ more_text = serializers.CharField(max_length=100)
+ amount = serializers.IntegerField()
+
+ class ExampleSerializer(serializers.Serializer):
+ text = serializers.CharField(max_length=100)
+ nested = Nested()
+
+ serializer = ExampleSerializer()
+
+ assert serializer['text'].value == ''
+ assert serializer['text'].errors is None
+ assert serializer['text'].name == 'text'
+ assert serializer['nested']['more_text'].value == ''
+ assert serializer['nested']['more_text'].errors is None
+ assert serializer['nested']['more_text'].name == 'nested.more_text'
+ assert serializer['nested']['amount'].value is None
+ assert serializer['nested']['amount'].errors is None
+ assert serializer['nested']['amount'].name == 'nested.amount'
diff --git a/tests/test_fields.py b/tests/test_fields.py
index a92fafbc..13525632 100644
--- a/tests/test_fields.py
+++ b/tests/test_fields.py
@@ -1,1042 +1,1028 @@
-# """
-# General serializer field tests.
-# """
-# from __future__ import unicode_literals
-
-# import datetime
-# import re
-# from decimal import Decimal
-# from uuid import uuid4
-# from django.core import validators
-# from django.db import models
-# from django.test import TestCase
-# from django.utils.datastructures import SortedDict
-# from rest_framework import serializers
-# from tests.models import RESTFrameworkModel
-
-
-# class TimestampedModel(models.Model):
-# added = models.DateTimeField(auto_now_add=True)
-# updated = models.DateTimeField(auto_now=True)
-
-
-# class CharPrimaryKeyModel(models.Model):
-# id = models.CharField(max_length=20, primary_key=True)
-
-
-# class TimestampedModelSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = TimestampedModel
-
-
-# class CharPrimaryKeyModelSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = CharPrimaryKeyModel
-
-
-# class TimeFieldModel(models.Model):
-# clock = models.TimeField()
-
-
-# class TimeFieldModelSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = TimeFieldModel
-
-
-# SAMPLE_CHOICES = [
-# ('red', 'Red'),
-# ('green', 'Green'),
-# ('blue', 'Blue'),
-# ]
-
-
-# class ChoiceFieldModel(models.Model):
-# choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, max_length=255)
-
-
-# class ChoiceFieldModelSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ChoiceFieldModel
-
-
-# class ChoiceFieldModelWithNull(models.Model):
-# choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, null=True, max_length=255)
-
-
-# class ChoiceFieldModelWithNullSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ChoiceFieldModelWithNull
-
-
-# class BasicFieldTests(TestCase):
-# def test_auto_now_fields_read_only(self):
-# """
-# auto_now and auto_now_add fields should be read_only by default.
-# """
-# serializer = TimestampedModelSerializer()
-# self.assertEqual(serializer.fields['added'].read_only, True)
-
-# def test_auto_pk_fields_read_only(self):
-# """
-# AutoField fields should be read_only by default.
-# """
-# serializer = TimestampedModelSerializer()
-# self.assertEqual(serializer.fields['id'].read_only, True)
-
-# def test_non_auto_pk_fields_not_read_only(self):
-# """
-# PK fields other than AutoField fields should not be read_only by default.
-# """
-# serializer = CharPrimaryKeyModelSerializer()
-# self.assertEqual(serializer.fields['id'].read_only, False)
-
-# def test_dict_field_ordering(self):
-# """
-# Field should preserve dictionary ordering, if it exists.
-# See: https://github.com/tomchristie/django-rest-framework/issues/832
-# """
-# ret = SortedDict()
-# ret['c'] = 1
-# ret['b'] = 1
-# ret['a'] = 1
-# ret['z'] = 1
-# field = serializers.Field()
-# keys = list(field.to_native(ret).keys())
-# self.assertEqual(keys, ['c', 'b', 'a', 'z'])
-
-# def test_widget_html_attributes(self):
-# """
-# Make sure widget_html() renders the correct attributes
-# """
-# r = re.compile('(\S+)=["\']?((?:.(?!["\']?\s+(?:\S+)=|[>"\']))+.)["\']?')
-# form = TimeFieldModelSerializer().data
-# attributes = r.findall(form.fields['clock'].widget_html())
-# self.assertIn(('name', 'clock'), attributes)
-# self.assertIn(('id', 'clock'), attributes)
-
-
-# class DateFieldTest(TestCase):
-# """
-# Tests for the DateFieldTest from_native() and to_native() behavior
-# """
-
-# def test_from_native_string(self):
-# """
-# Make sure from_native() accepts default iso input formats.
-# """
-# f = serializers.DateField()
-# result_1 = f.from_native('1984-07-31')
-
-# self.assertEqual(datetime.date(1984, 7, 31), result_1)
-
-# def test_from_native_datetime_date(self):
-# """
-# Make sure from_native() accepts a datetime.date instance.
-# """
-# f = serializers.DateField()
-# result_1 = f.from_native(datetime.date(1984, 7, 31))
-
-# self.assertEqual(result_1, datetime.date(1984, 7, 31))
-
-# def test_from_native_custom_format(self):
-# """
-# Make sure from_native() accepts custom input formats.
-# """
-# f = serializers.DateField(input_formats=['%Y -- %d'])
-# result = f.from_native('1984 -- 31')
-
-# self.assertEqual(datetime.date(1984, 1, 31), result)
-
-# def test_from_native_invalid_default_on_custom_format(self):
-# """
-# Make sure from_native() don't accept default formats if custom format is preset
-# """
-# f = serializers.DateField(input_formats=['%Y -- %d'])
-
-# try:
-# f.from_native('1984-07-31')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY -- DD"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_from_native_empty(self):
-# """
-# Make sure from_native() returns None on empty param.
-# """
-# f = serializers.DateField()
-# result = f.from_native('')
-
-# self.assertEqual(result, None)
-
-# def test_from_native_none(self):
-# """
-# Make sure from_native() returns None on None param.
-# """
-# f = serializers.DateField()
-# result = f.from_native(None)
-
-# self.assertEqual(result, None)
-
-# def test_from_native_invalid_date(self):
-# """
-# Make sure from_native() raises a ValidationError on passing an invalid date.
-# """
-# f = serializers.DateField()
-
-# try:
-# f.from_native('1984-13-31')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_from_native_invalid_format(self):
-# """
-# Make sure from_native() raises a ValidationError on passing an invalid format.
-# """
-# f = serializers.DateField()
-
-# try:
-# f.from_native('1984 -- 31')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_to_native(self):
-# """
-# Make sure to_native() returns datetime as default.
-# """
-# f = serializers.DateField()
-
-# result_1 = f.to_native(datetime.date(1984, 7, 31))
-
-# self.assertEqual(datetime.date(1984, 7, 31), result_1)
-
-# def test_to_native_iso(self):
-# """
-# Make sure to_native() with 'iso-8601' returns iso formated date.
-# """
-# f = serializers.DateField(format='iso-8601')
-
-# result_1 = f.to_native(datetime.date(1984, 7, 31))
-
-# self.assertEqual('1984-07-31', result_1)
-
-# def test_to_native_custom_format(self):
-# """
-# Make sure to_native() returns correct custom format.
-# """
-# f = serializers.DateField(format="%Y - %m.%d")
-
-# result_1 = f.to_native(datetime.date(1984, 7, 31))
-
-# self.assertEqual('1984 - 07.31', result_1)
-
-# def test_to_native_none(self):
-# """
-# Make sure from_native() returns None on None param.
-# """
-# f = serializers.DateField(required=False)
-# self.assertEqual(None, f.to_native(None))
-
-
-# class DateTimeFieldTest(TestCase):
-# """
-# Tests for the DateTimeField from_native() and to_native() behavior
-# """
-
-# def test_from_native_string(self):
-# """
-# Make sure from_native() accepts default iso input formats.
-# """
-# f = serializers.DateTimeField()
-# result_1 = f.from_native('1984-07-31 04:31')
-# result_2 = f.from_native('1984-07-31 04:31:59')
-# result_3 = f.from_native('1984-07-31 04:31:59.000200')
-
-# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_1)
-# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_2)
-# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_3)
-
-# def test_from_native_datetime_datetime(self):
-# """
-# Make sure from_native() accepts a datetime.datetime instance.
-# """
-# f = serializers.DateTimeField()
-# result_1 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31))
-# result_2 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59))
-# result_3 = f.from_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200))
-
-# self.assertEqual(result_1, datetime.datetime(1984, 7, 31, 4, 31))
-# self.assertEqual(result_2, datetime.datetime(1984, 7, 31, 4, 31, 59))
-# self.assertEqual(result_3, datetime.datetime(1984, 7, 31, 4, 31, 59, 200))
-
-# def test_from_native_custom_format(self):
-# """
-# Make sure from_native() accepts custom input formats.
-# """
-# f = serializers.DateTimeField(input_formats=['%Y -- %H:%M'])
-# result = f.from_native('1984 -- 04:59')
-
-# self.assertEqual(datetime.datetime(1984, 1, 1, 4, 59), result)
-
-# def test_from_native_invalid_default_on_custom_format(self):
-# """
-# Make sure from_native() don't accept default formats if custom format is preset
-# """
-# f = serializers.DateTimeField(input_formats=['%Y -- %H:%M'])
-
-# try:
-# f.from_native('1984-07-31 04:31:59')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: YYYY -- hh:mm"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_from_native_empty(self):
-# """
-# Make sure from_native() returns None on empty param.
-# """
-# f = serializers.DateTimeField()
-# result = f.from_native('')
-
-# self.assertEqual(result, None)
-
-# def test_from_native_none(self):
-# """
-# Make sure from_native() returns None on None param.
-# """
-# f = serializers.DateTimeField()
-# result = f.from_native(None)
-
-# self.assertEqual(result, None)
-
-# def test_from_native_invalid_datetime(self):
-# """
-# Make sure from_native() raises a ValidationError on passing an invalid datetime.
-# """
-# f = serializers.DateTimeField()
-
-# try:
-# f.from_native('04:61:59')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: "
-# "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_from_native_invalid_format(self):
-# """
-# Make sure from_native() raises a ValidationError on passing an invalid format.
-# """
-# f = serializers.DateTimeField()
-
-# try:
-# f.from_native('04 -- 31')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Datetime has wrong format. Use one of these formats instead: "
-# "YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_to_native(self):
-# """
-# Make sure to_native() returns isoformat as default.
-# """
-# f = serializers.DateTimeField()
-
-# result_1 = f.to_native(datetime.datetime(1984, 7, 31))
-# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31))
-# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59))
-# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200))
-
-# self.assertEqual(datetime.datetime(1984, 7, 31), result_1)
-# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31), result_2)
-# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59), result_3)
-# self.assertEqual(datetime.datetime(1984, 7, 31, 4, 31, 59, 200), result_4)
-
-# def test_to_native_iso(self):
-# """
-# Make sure to_native() with format=iso-8601 returns iso formatted datetime.
-# """
-# f = serializers.DateTimeField(format='iso-8601')
-
-# result_1 = f.to_native(datetime.datetime(1984, 7, 31))
-# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31))
-# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59))
-# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200))
-
-# self.assertEqual('1984-07-31T00:00:00', result_1)
-# self.assertEqual('1984-07-31T04:31:00', result_2)
-# self.assertEqual('1984-07-31T04:31:59', result_3)
-# self.assertEqual('1984-07-31T04:31:59.000200', result_4)
-
-# def test_to_native_custom_format(self):
-# """
-# Make sure to_native() returns correct custom format.
-# """
-# f = serializers.DateTimeField(format="%Y - %H:%M")
-
-# result_1 = f.to_native(datetime.datetime(1984, 7, 31))
-# result_2 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31))
-# result_3 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59))
-# result_4 = f.to_native(datetime.datetime(1984, 7, 31, 4, 31, 59, 200))
-
-# self.assertEqual('1984 - 00:00', result_1)
-# self.assertEqual('1984 - 04:31', result_2)
-# self.assertEqual('1984 - 04:31', result_3)
-# self.assertEqual('1984 - 04:31', result_4)
-
-# def test_to_native_none(self):
-# """
-# Make sure from_native() returns None on None param.
-# """
-# f = serializers.DateTimeField(required=False)
-# self.assertEqual(None, f.to_native(None))
-
-
-# class TimeFieldTest(TestCase):
-# """
-# Tests for the TimeField from_native() and to_native() behavior
-# """
-
-# def test_from_native_string(self):
-# """
-# Make sure from_native() accepts default iso input formats.
-# """
-# f = serializers.TimeField()
-# result_1 = f.from_native('04:31')
-# result_2 = f.from_native('04:31:59')
-# result_3 = f.from_native('04:31:59.000200')
-
-# self.assertEqual(datetime.time(4, 31), result_1)
-# self.assertEqual(datetime.time(4, 31, 59), result_2)
-# self.assertEqual(datetime.time(4, 31, 59, 200), result_3)
-
-# def test_from_native_datetime_time(self):
-# """
-# Make sure from_native() accepts a datetime.time instance.
-# """
-# f = serializers.TimeField()
-# result_1 = f.from_native(datetime.time(4, 31))
-# result_2 = f.from_native(datetime.time(4, 31, 59))
-# result_3 = f.from_native(datetime.time(4, 31, 59, 200))
-
-# self.assertEqual(result_1, datetime.time(4, 31))
-# self.assertEqual(result_2, datetime.time(4, 31, 59))
-# self.assertEqual(result_3, datetime.time(4, 31, 59, 200))
-
-# def test_from_native_custom_format(self):
-# """
-# Make sure from_native() accepts custom input formats.
-# """
-# f = serializers.TimeField(input_formats=['%H -- %M'])
-# result = f.from_native('04 -- 31')
-
-# self.assertEqual(datetime.time(4, 31), result)
-
-# def test_from_native_invalid_default_on_custom_format(self):
-# """
-# Make sure from_native() don't accept default formats if custom format is preset
-# """
-# f = serializers.TimeField(input_formats=['%H -- %M'])
-
-# try:
-# f.from_native('04:31:59')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: hh -- mm"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_from_native_empty(self):
-# """
-# Make sure from_native() returns None on empty param.
-# """
-# f = serializers.TimeField()
-# result = f.from_native('')
-
-# self.assertEqual(result, None)
-
-# def test_from_native_none(self):
-# """
-# Make sure from_native() returns None on None param.
-# """
-# f = serializers.TimeField()
-# result = f.from_native(None)
-
-# self.assertEqual(result, None)
-
-# def test_from_native_invalid_time(self):
-# """
-# Make sure from_native() raises a ValidationError on passing an invalid time.
-# """
-# f = serializers.TimeField()
-
-# try:
-# f.from_native('04:61:59')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: "
-# "hh:mm[:ss[.uuuuuu]]"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_from_native_invalid_format(self):
-# """
-# Make sure from_native() raises a ValidationError on passing an invalid format.
-# """
-# f = serializers.TimeField()
-
-# try:
-# f.from_native('04 -- 31')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Time has wrong format. Use one of these formats instead: "
-# "hh:mm[:ss[.uuuuuu]]"])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_to_native(self):
-# """
-# Make sure to_native() returns time object as default.
-# """
-# f = serializers.TimeField()
-# result_1 = f.to_native(datetime.time(4, 31))
-# result_2 = f.to_native(datetime.time(4, 31, 59))
-# result_3 = f.to_native(datetime.time(4, 31, 59, 200))
-
-# self.assertEqual(datetime.time(4, 31), result_1)
-# self.assertEqual(datetime.time(4, 31, 59), result_2)
-# self.assertEqual(datetime.time(4, 31, 59, 200), result_3)
-
-# def test_to_native_iso(self):
-# """
-# Make sure to_native() with format='iso-8601' returns iso formatted time.
-# """
-# f = serializers.TimeField(format='iso-8601')
-# result_1 = f.to_native(datetime.time(4, 31))
-# result_2 = f.to_native(datetime.time(4, 31, 59))
-# result_3 = f.to_native(datetime.time(4, 31, 59, 200))
-
-# self.assertEqual('04:31:00', result_1)
-# self.assertEqual('04:31:59', result_2)
-# self.assertEqual('04:31:59.000200', result_3)
-
-# def test_to_native_custom_format(self):
-# """
-# Make sure to_native() returns correct custom format.
-# """
-# f = serializers.TimeField(format="%H - %S [%f]")
-# result_1 = f.to_native(datetime.time(4, 31))
-# result_2 = f.to_native(datetime.time(4, 31, 59))
-# result_3 = f.to_native(datetime.time(4, 31, 59, 200))
-
-# self.assertEqual('04 - 00 [000000]', result_1)
-# self.assertEqual('04 - 59 [000000]', result_2)
-# self.assertEqual('04 - 59 [000200]', result_3)
-
-
-# class DecimalFieldTest(TestCase):
-# """
-# Tests for the DecimalField from_native() and to_native() behavior
-# """
-
-# def test_from_native_string(self):
-# """
-# Make sure from_native() accepts string values
-# """
-# f = serializers.DecimalField()
-# result_1 = f.from_native('9000')
-# result_2 = f.from_native('1.00000001')
-
-# self.assertEqual(Decimal('9000'), result_1)
-# self.assertEqual(Decimal('1.00000001'), result_2)
-
-# def test_from_native_invalid_string(self):
-# """
-# Make sure from_native() raises ValidationError on passing invalid string
-# """
-# f = serializers.DecimalField()
-
-# try:
-# f.from_native('123.45.6')
-# except validators.ValidationError as e:
-# self.assertEqual(e.messages, ["Enter a number."])
-# else:
-# self.fail("ValidationError was not properly raised")
-
-# def test_from_native_integer(self):
-# """
-# Make sure from_native() accepts integer values
-# """
-# f = serializers.DecimalField()
-# result = f.from_native(9000)
-
-# self.assertEqual(Decimal('9000'), result)
-
-# def test_from_native_float(self):
-# """
-# Make sure from_native() accepts float values
-# """
-# f = serializers.DecimalField()
-# result = f.from_native(1.00000001)
-
-# self.assertEqual(Decimal('1.00000001'), result)
-
-# def test_from_native_empty(self):
-# """
-# Make sure from_native() returns None on empty param.
-# """
-# f = serializers.DecimalField()
-# result = f.from_native('')
-
-# self.assertEqual(result, None)
-
-# def test_from_native_none(self):
-# """
-# Make sure from_native() returns None on None param.
-# """
-# f = serializers.DecimalField()
-# result = f.from_native(None)
-
-# self.assertEqual(result, None)
-
-# def test_to_native(self):
-# """
-# Make sure to_native() returns Decimal as string.
-# """
-# f = serializers.DecimalField()
-
-# result_1 = f.to_native(Decimal('9000'))
-# result_2 = f.to_native(Decimal('1.00000001'))
-
-# self.assertEqual(Decimal('9000'), result_1)
-# self.assertEqual(Decimal('1.00000001'), result_2)
-
-# def test_to_native_none(self):
-# """
-# Make sure from_native() returns None on None param.
-# """
-# f = serializers.DecimalField(required=False)
-# self.assertEqual(None, f.to_native(None))
-
-# def test_valid_serialization(self):
-# """
-# Make sure the serializer works correctly
-# """
-# class DecimalSerializer(serializers.Serializer):
-# decimal_field = serializers.DecimalField(max_value=9010,
-# min_value=9000,
-# max_digits=6,
-# decimal_places=2)
-
-# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001'}).is_valid())
-# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.2'}).is_valid())
-# self.assertTrue(DecimalSerializer(data={'decimal_field': '9001.23'}).is_valid())
-
-# self.assertFalse(DecimalSerializer(data={'decimal_field': '8000'}).is_valid())
-# self.assertFalse(DecimalSerializer(data={'decimal_field': '9900'}).is_valid())
-# self.assertFalse(DecimalSerializer(data={'decimal_field': '9001.234'}).is_valid())
-
-# def test_raise_max_value(self):
-# """
-# Make sure max_value violations raises ValidationError
-# """
-# class DecimalSerializer(serializers.Serializer):
-# decimal_field = serializers.DecimalField(max_value=100)
-
-# s = DecimalSerializer(data={'decimal_field': '123'})
-
-# self.assertFalse(s.is_valid())
-# self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is less than or equal to 100.']})
-
-# def test_raise_min_value(self):
-# """
-# Make sure min_value violations raises ValidationError
-# """
-# class DecimalSerializer(serializers.Serializer):
-# decimal_field = serializers.DecimalField(min_value=100)
-
-# s = DecimalSerializer(data={'decimal_field': '99'})
-
-# self.assertFalse(s.is_valid())
-# self.assertEqual(s.errors, {'decimal_field': ['Ensure this value is greater than or equal to 100.']})
-
-# def test_raise_max_digits(self):
-# """
-# Make sure max_digits violations raises ValidationError
-# """
-# class DecimalSerializer(serializers.Serializer):
-# decimal_field = serializers.DecimalField(max_digits=5)
-
-# s = DecimalSerializer(data={'decimal_field': '123.456'})
-
-# self.assertFalse(s.is_valid())
-# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 5 digits in total.']})
-
-# def test_raise_max_decimal_places(self):
-# """
-# Make sure max_decimal_places violations raises ValidationError
-# """
-# class DecimalSerializer(serializers.Serializer):
-# decimal_field = serializers.DecimalField(decimal_places=3)
-
-# s = DecimalSerializer(data={'decimal_field': '123.4567'})
-
-# self.assertFalse(s.is_valid())
-# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 3 decimal places.']})
-
-# def test_raise_max_whole_digits(self):
-# """
-# Make sure max_whole_digits violations raises ValidationError
-# """
-# class DecimalSerializer(serializers.Serializer):
-# decimal_field = serializers.DecimalField(max_digits=4, decimal_places=3)
-
-# s = DecimalSerializer(data={'decimal_field': '12345.6'})
-
-# self.assertFalse(s.is_valid())
-# self.assertEqual(s.errors, {'decimal_field': ['Ensure that there are no more than 4 digits in total.']})
-
-
-# class ChoiceFieldTests(TestCase):
-# """
-# Tests for the ChoiceField options generator
-# """
-# def test_choices_required(self):
-# """
-# Make sure proper choices are rendered if field is required
-# """
-# f = serializers.ChoiceField(required=True, choices=SAMPLE_CHOICES)
-# self.assertEqual(f.choices, SAMPLE_CHOICES)
-
-# def test_choices_not_required(self):
-# """
-# Make sure proper choices (plus blank) are rendered if the field isn't required
-# """
-# f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES)
-# self.assertEqual(f.choices, models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES)
-
-# def test_blank_choice_display(self):
-# blank = 'No Preference'
-# f = serializers.ChoiceField(
-# required=False,
-# choices=SAMPLE_CHOICES,
-# blank_display_value=blank,
-# )
-# self.assertEqual(f.choices, [('', blank)] + SAMPLE_CHOICES)
-
-# def test_invalid_choice_model(self):
-# s = ChoiceFieldModelSerializer(data={'choice': 'wrong_value'})
-# self.assertFalse(s.is_valid())
-# self.assertEqual(s.errors, {'choice': ['Select a valid choice. wrong_value is not one of the available choices.']})
-# self.assertEqual(s.data['choice'], '')
-
-# def test_empty_choice_model(self):
-# """
-# Test that the 'empty' value is correctly passed and used depending on
-# the 'null' property on the model field.
-# """
-# s = ChoiceFieldModelSerializer(data={'choice': ''})
-# self.assertTrue(s.is_valid())
-# self.assertEqual(s.data['choice'], '')
-
-# s = ChoiceFieldModelWithNullSerializer(data={'choice': ''})
-# self.assertTrue(s.is_valid())
-# self.assertEqual(s.data['choice'], None)
-
-# def test_from_native_empty(self):
-# """
-# Make sure from_native() returns an empty string on empty param by default.
-# """
-# f = serializers.ChoiceField(choices=SAMPLE_CHOICES)
-# self.assertEqual(f.from_native(''), '')
-# self.assertEqual(f.from_native(None), '')
-
-# def test_from_native_empty_override(self):
-# """
-# Make sure you can override from_native() behavior regarding empty values.
-# """
-# f = serializers.ChoiceField(choices=SAMPLE_CHOICES, empty=None)
-# self.assertEqual(f.from_native(''), None)
-# self.assertEqual(f.from_native(None), None)
-
-# def test_metadata_choices(self):
-# """
-# Make sure proper choices are included in the field's metadata.
-# """
-# choices = [{'value': v, 'display_name': n} for v, n in SAMPLE_CHOICES]
-# f = serializers.ChoiceField(choices=SAMPLE_CHOICES)
-# self.assertEqual(f.metadata()['choices'], choices)
-
-# def test_metadata_choices_not_required(self):
-# """
-# Make sure proper choices are included in the field's metadata.
-# """
-# choices = [{'value': v, 'display_name': n}
-# for v, n in models.fields.BLANK_CHOICE_DASH + SAMPLE_CHOICES]
-# f = serializers.ChoiceField(required=False, choices=SAMPLE_CHOICES)
-# self.assertEqual(f.metadata()['choices'], choices)
-
-
-# class EmailFieldTests(TestCase):
-# """
-# Tests for EmailField attribute values
-# """
-
-# class EmailFieldModel(RESTFrameworkModel):
-# email_field = models.EmailField(blank=True)
-
-# class EmailFieldWithGivenMaxLengthModel(RESTFrameworkModel):
-# email_field = models.EmailField(max_length=150, blank=True)
-
-# def test_default_model_value(self):
-# class EmailFieldSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = self.EmailFieldModel
-
-# serializer = EmailFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 75)
-
-# def test_given_model_value(self):
-# class EmailFieldSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = self.EmailFieldWithGivenMaxLengthModel
-
-# serializer = EmailFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 150)
-
-# def test_given_serializer_value(self):
-# class EmailFieldSerializer(serializers.ModelSerializer):
-# email_field = serializers.EmailField(source='email_field', max_length=20, required=False)
-
-# class Meta:
-# model = self.EmailFieldModel
-
-# serializer = EmailFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['email_field'], 'max_length'), 20)
-
-
-# class SlugFieldTests(TestCase):
-# """
-# Tests for SlugField attribute values
-# """
-
-# class SlugFieldModel(RESTFrameworkModel):
-# slug_field = models.SlugField(blank=True)
-
-# class SlugFieldWithGivenMaxLengthModel(RESTFrameworkModel):
-# slug_field = models.SlugField(max_length=84, blank=True)
-
-# def test_default_model_value(self):
-# class SlugFieldSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = self.SlugFieldModel
-
-# serializer = SlugFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 50)
-
-# def test_given_model_value(self):
-# class SlugFieldSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = self.SlugFieldWithGivenMaxLengthModel
-
-# serializer = SlugFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['slug_field'], 'max_length'), 84)
-
-# def test_given_serializer_value(self):
-# class SlugFieldSerializer(serializers.ModelSerializer):
-# slug_field = serializers.SlugField(source='slug_field',
-# max_length=20, required=False)
-
-# class Meta:
-# model = self.SlugFieldModel
-
-# serializer = SlugFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['slug_field'],
-# 'max_length'), 20)
-
-# def test_invalid_slug(self):
-# """
-# Make sure an invalid slug raises ValidationError
-# """
-# class SlugFieldSerializer(serializers.ModelSerializer):
-# slug_field = serializers.SlugField(source='slug_field', max_length=20, required=True)
-
-# class Meta:
-# model = self.SlugFieldModel
-
-# s = SlugFieldSerializer(data={'slug_field': 'a b'})
-
-# self.assertEqual(s.is_valid(), False)
-# self.assertEqual(s.errors, {'slug_field': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]})
-
-
-# class URLFieldTests(TestCase):
-# """
-# Tests for URLField attribute values.
-
-# (Includes test for #1210, checking that validators can be overridden.)
-# """
-
-# class URLFieldModel(RESTFrameworkModel):
-# url_field = models.URLField(blank=True)
-
-# class URLFieldWithGivenMaxLengthModel(RESTFrameworkModel):
-# url_field = models.URLField(max_length=128, blank=True)
-
-# def test_default_model_value(self):
-# class URLFieldSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = self.URLFieldModel
-
-# serializer = URLFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['url_field'],
-# 'max_length'), 200)
-
-# def test_given_model_value(self):
-# class URLFieldSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = self.URLFieldWithGivenMaxLengthModel
-
-# serializer = URLFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['url_field'],
-# 'max_length'), 128)
-
-# def test_given_serializer_value(self):
-# class URLFieldSerializer(serializers.ModelSerializer):
-# url_field = serializers.URLField(source='url_field',
-# max_length=20, required=False)
-
-# class Meta:
-# model = self.URLFieldWithGivenMaxLengthModel
-
-# serializer = URLFieldSerializer(data={})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(getattr(serializer.fields['url_field'],
-# 'max_length'), 20)
-
-# def test_validators_can_be_overridden(self):
-# url_field = serializers.URLField(validators=[])
-# validators = url_field.validators
-# self.assertEqual([], validators, 'Passing `validators` kwarg should have overridden default validators')
-
-
-# class FieldMetadata(TestCase):
-# def setUp(self):
-# self.required_field = serializers.Field()
-# self.required_field.label = uuid4().hex
-# self.required_field.required = True
-
-# self.optional_field = serializers.Field()
-# self.optional_field.label = uuid4().hex
-# self.optional_field.required = False
-
-# def test_required(self):
-# self.assertEqual(self.required_field.metadata()['required'], True)
-
-# def test_optional(self):
-# self.assertEqual(self.optional_field.metadata()['required'], False)
-
-# def test_label(self):
-# for field in (self.required_field, self.optional_field):
-# self.assertEqual(field.metadata()['label'], field.label)
-
-
-# class FieldCallableDefault(TestCase):
-# def setUp(self):
-# self.simple_callable = lambda: 'foo bar'
-
-# def test_default_can_be_simple_callable(self):
-# """
-# Ensure that the 'default' argument can also be a simple callable.
-# """
-# field = serializers.WritableField(default=self.simple_callable)
-# into = {}
-# field.field_from_native({}, {}, 'field', into)
-# self.assertEqual(into, {'field': 'foo bar'})
-
-
-# class CustomIntegerField(TestCase):
-# """
-# Test that custom fields apply min_value and max_value constraints
-# """
-# def test_custom_fields_can_be_validated_for_value(self):
-
-# class MoneyField(models.PositiveIntegerField):
-# pass
-
-# class EntryModel(models.Model):
-# bank = MoneyField(validators=[validators.MaxValueValidator(100)])
-
-# class EntrySerializer(serializers.ModelSerializer):
-# class Meta:
-# model = EntryModel
-
-# entry = EntryModel(bank=1)
-
-# serializer = EntrySerializer(entry, data={"bank": 11})
-# self.assertTrue(serializer.is_valid())
-
-# serializer = EntrySerializer(entry, data={"bank": -1})
-# self.assertFalse(serializer.is_valid())
-
-# serializer = EntrySerializer(entry, data={"bank": 101})
-# self.assertFalse(serializer.is_valid())
-
-
-# class BooleanField(TestCase):
-# """
-# Tests for BooleanField
-# """
-# def test_boolean_required(self):
-# class BooleanRequiredSerializer(serializers.Serializer):
-# bool_field = serializers.BooleanField(required=True)
-
-# self.assertFalse(BooleanRequiredSerializer(data={}).is_valid())
-
-
-# class SerializerMethodFieldTest(TestCase):
-# """
-# Tests for the SerializerMethodField field_to_native() behavior
-# """
-# class SerializerTest(serializers.Serializer):
-# def get_my_test(self, obj):
-# return obj.my_test[0:5]
-
-# class ModelCharField(TestCase):
-# """
-# Tests for CharField
-# """
-# def test_none_serializing(self):
-# class CharFieldSerializer(serializers.Serializer):
-# char = serializers.CharField(allow_none=True, required=False)
-# serializer = CharFieldSerializer(data={'char': None})
-# self.assertTrue(serializer.is_valid())
-# self.assertIsNone(serializer.object['char'])
-
-
-# class SerializerMethodFieldTest(TestCase):
-# """
-# Tests for the SerializerMethodField field_to_native() behavior
-# """
-# class SerializerTest(serializers.Serializer):
-# def get_my_test(self, obj):
-# return obj.my_test[0:5]
-
-# class Example():
-# my_test = 'Hey, this is a test !'
-
-# def test_field_to_native(self):
-# s = serializers.SerializerMethodField('get_my_test')
-# s.initialize(self.SerializerTest(), 'name')
-# result = s.field_to_native(self.Example(), None)
-# self.assertEqual(result, 'Hey, ')
+from decimal import Decimal
+from django.utils import timezone
+from rest_framework import serializers
+import datetime
+import django
+import pytest
+
+
+# Tests for field keyword arguments and core functionality.
+# ---------------------------------------------------------
+
+class TestEmpty:
+ """
+ Tests for `required`, `allow_null`, `allow_blank`, `default`.
+ """
+ def test_required(self):
+ """
+ By default a field must be included in the input.
+ """
+ field = serializers.IntegerField()
+ with pytest.raises(serializers.ValidationError) as exc_info:
+ field.run_validation()
+ assert exc_info.value.detail == ['This field is required.']
+
+ def test_not_required(self):
+ """
+ If `required=False` then a field may be omitted from the input.
+ """
+ field = serializers.IntegerField(required=False)
+ with pytest.raises(serializers.SkipField):
+ field.run_validation()
+
+ def test_disallow_null(self):
+ """
+ By default `None` is not a valid input.
+ """
+ field = serializers.IntegerField()
+ with pytest.raises(serializers.ValidationError) as exc_info:
+ field.run_validation(None)
+ assert exc_info.value.detail == ['This field may not be null.']
+
+ def test_allow_null(self):
+ """
+ If `allow_null=True` then `None` is a valid input.
+ """
+ field = serializers.IntegerField(allow_null=True)
+ output = field.run_validation(None)
+ assert output is None
+
+ def test_disallow_blank(self):
+ """
+ By default '' is not a valid input.
+ """
+ field = serializers.CharField()
+ with pytest.raises(serializers.ValidationError) as exc_info:
+ field.run_validation('')
+ assert exc_info.value.detail == ['This field may not be blank.']
+
+ def test_allow_blank(self):
+ """
+ If `allow_blank=True` then '' is a valid input.
+ """
+ field = serializers.CharField(allow_blank=True)
+ output = field.run_validation('')
+ assert output is ''
+
+ def test_default(self):
+ """
+ If `default` is set, then omitted values get the default input.
+ """
+ field = serializers.IntegerField(default=123)
+ output = field.run_validation()
+ assert output is 123
+
+
+class TestSource:
+ def test_source(self):
+ class ExampleSerializer(serializers.Serializer):
+ example_field = serializers.CharField(source='other')
+ serializer = ExampleSerializer(data={'example_field': 'abc'})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'other': 'abc'}
+
+ def test_redundant_source(self):
+ class ExampleSerializer(serializers.Serializer):
+ example_field = serializers.CharField(source='example_field')
+ with pytest.raises(AssertionError) as exc_info:
+ ExampleSerializer().fields
+ assert str(exc_info.value) == (
+ "It is redundant to specify `source='example_field'` on field "
+ "'CharField' in serializer 'ExampleSerializer', because it is the "
+ "same as the field name. Remove the `source` keyword argument."
+ )
+
+
+class TestReadOnly:
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ read_only = serializers.ReadOnlyField()
+ writable = serializers.IntegerField()
+ self.Serializer = TestSerializer
+
+ def test_validate_read_only(self):
+ """
+ Read-only serializers.should not be included in validation.
+ """
+ data = {'read_only': 123, 'writable': 456}
+ serializer = self.Serializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'writable': 456}
+
+ def test_serialize_read_only(self):
+ """
+ Read-only serializers.should be serialized.
+ """
+ instance = {'read_only': 123, 'writable': 456}
+ serializer = self.Serializer(instance)
+ assert serializer.data == {'read_only': 123, 'writable': 456}
+
+
+class TestWriteOnly:
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ write_only = serializers.IntegerField(write_only=True)
+ readable = serializers.IntegerField()
+ self.Serializer = TestSerializer
+
+ def test_validate_write_only(self):
+ """
+ Write-only serializers.should be included in validation.
+ """
+ data = {'write_only': 123, 'readable': 456}
+ serializer = self.Serializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'write_only': 123, 'readable': 456}
+
+ def test_serialize_write_only(self):
+ """
+ Write-only serializers.should not be serialized.
+ """
+ instance = {'write_only': 123, 'readable': 456}
+ serializer = self.Serializer(instance)
+ assert serializer.data == {'readable': 456}
+
+
+class TestInitial:
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ initial_field = serializers.IntegerField(initial=123)
+ blank_field = serializers.IntegerField()
+ self.serializer = TestSerializer()
+
+ def test_initial(self):
+ """
+ Initial values should be included when serializing a new representation.
+ """
+ assert self.serializer.data == {
+ 'initial_field': 123,
+ 'blank_field': None
+ }
+
+
+class TestLabel:
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ labeled = serializers.IntegerField(label='My label')
+ self.serializer = TestSerializer()
+
+ def test_label(self):
+ """
+ A field's label may be set with the `label` argument.
+ """
+ fields = self.serializer.fields
+ assert fields['labeled'].label == 'My label'
+
+
+class TestInvalidErrorKey:
+ def setup(self):
+ class ExampleField(serializers.Field):
+ def to_native(self, data):
+ self.fail('incorrect')
+ self.field = ExampleField()
+
+ def test_invalid_error_key(self):
+ """
+ If a field raises a validation error, but does not have a corresponding
+ error message, then raise an appropriate assertion error.
+ """
+ with pytest.raises(AssertionError) as exc_info:
+ self.field.to_native(123)
+ expected = (
+ 'ValidationError raised by `ExampleField`, but error key '
+ '`incorrect` does not exist in the `error_messages` dictionary.'
+ )
+ assert str(exc_info.value) == expected
+
+
+class TestBooleanHTMLInput:
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ archived = serializers.BooleanField()
+ self.Serializer = TestSerializer
+
+ def test_empty_html_checkbox(self):
+ """
+ HTML checkboxes do not send any value, but should be treated
+ as `False` by BooleanField.
+ """
+ # This class mocks up a dictionary like object, that behaves
+ # as if it was returned for multipart or urlencoded data.
+ class MockHTMLDict(dict):
+ getlist = None
+ serializer = self.Serializer(data=MockHTMLDict())
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'archived': False}
+
+
+class TestCreateOnlyDefault:
+ def setup(self):
+ default = serializers.CreateOnlyDefault('2001-01-01')
+
+ class TestSerializer(serializers.Serializer):
+ published = serializers.HiddenField(default=default)
+ text = serializers.CharField()
+ self.Serializer = TestSerializer
+
+ def test_create_only_default_is_provided(self):
+ serializer = self.Serializer(data={'text': 'example'})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'text': 'example', 'published': '2001-01-01'
+ }
+
+ def test_create_only_default_is_not_provided_on_update(self):
+ instance = {
+ 'text': 'example', 'published': '2001-01-01'
+ }
+ serializer = self.Serializer(instance, data={'text': 'example'})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'text': 'example',
+ }
+
+
+# Tests for field input and output values.
+# ----------------------------------------
+
+def get_items(mapping_or_list_of_two_tuples):
+ # Tests accept either lists of two tuples, or dictionaries.
+ if isinstance(mapping_or_list_of_two_tuples, dict):
+ # {value: expected}
+ return mapping_or_list_of_two_tuples.items()
+ # [(value, expected), ...]
+ return mapping_or_list_of_two_tuples
+
+
+class FieldValues:
+ """
+ Base class for testing valid and invalid input values.
+ """
+ def test_valid_inputs(self):
+ """
+ Ensure that valid values return the expected validated data.
+ """
+ for input_value, expected_output in get_items(self.valid_inputs):
+ assert self.field.run_validation(input_value) == expected_output
+
+ def test_invalid_inputs(self):
+ """
+ Ensure that invalid values raise the expected validation error.
+ """
+ for input_value, expected_failure in get_items(self.invalid_inputs):
+ with pytest.raises(serializers.ValidationError) as exc_info:
+ self.field.run_validation(input_value)
+ assert exc_info.value.detail == expected_failure
+
+ def test_outputs(self):
+ for output_value, expected_output in get_items(self.outputs):
+ assert self.field.to_representation(output_value) == expected_output
+
+
+# Boolean types...
+
+class TestBooleanField(FieldValues):
+ """
+ Valid and invalid values for `BooleanField`.
+ """
+ valid_inputs = {
+ 'true': True,
+ 'false': False,
+ '1': True,
+ '0': False,
+ 1: True,
+ 0: False,
+ True: True,
+ False: False,
+ }
+ invalid_inputs = {
+ 'foo': ['`foo` is not a valid boolean.'],
+ None: ['This field may not be null.']
+ }
+ outputs = {
+ 'true': True,
+ 'false': False,
+ '1': True,
+ '0': False,
+ 1: True,
+ 0: False,
+ True: True,
+ False: False,
+ 'other': True
+ }
+ field = serializers.BooleanField()
+
+
+class TestNullBooleanField(FieldValues):
+ """
+ Valid and invalid values for `BooleanField`.
+ """
+ valid_inputs = {
+ 'true': True,
+ 'false': False,
+ 'null': None,
+ True: True,
+ False: False,
+ None: None
+ }
+ invalid_inputs = {
+ 'foo': ['`foo` is not a valid boolean.'],
+ }
+ outputs = {
+ 'true': True,
+ 'false': False,
+ 'null': None,
+ True: True,
+ False: False,
+ None: None,
+ 'other': True
+ }
+ field = serializers.NullBooleanField()
+
+
+# String types...
+
+class TestCharField(FieldValues):
+ """
+ Valid and invalid values for `CharField`.
+ """
+ valid_inputs = {
+ 1: '1',
+ 'abc': 'abc'
+ }
+ invalid_inputs = {
+ '': ['This field may not be blank.']
+ }
+ outputs = {
+ 1: '1',
+ 'abc': 'abc'
+ }
+ field = serializers.CharField()
+
+
+class TestEmailField(FieldValues):
+ """
+ Valid and invalid values for `EmailField`.
+ """
+ valid_inputs = {
+ 'example@example.com': 'example@example.com',
+ ' example@example.com ': 'example@example.com',
+ }
+ invalid_inputs = {
+ 'examplecom': ['Enter a valid email address.']
+ }
+ outputs = {}
+ field = serializers.EmailField()
+
+
+class TestRegexField(FieldValues):
+ """
+ Valid and invalid values for `RegexField`.
+ """
+ valid_inputs = {
+ 'a9': 'a9',
+ }
+ invalid_inputs = {
+ 'A9': ["This value does not match the required pattern."]
+ }
+ outputs = {}
+ field = serializers.RegexField(regex='[a-z][0-9]')
+
+
+class TestSlugField(FieldValues):
+ """
+ Valid and invalid values for `SlugField`.
+ """
+ valid_inputs = {
+ 'slug-99': 'slug-99',
+ }
+ invalid_inputs = {
+ 'slug 99': ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]
+ }
+ outputs = {}
+ field = serializers.SlugField()
+
+
+class TestURLField(FieldValues):
+ """
+ Valid and invalid values for `URLField`.
+ """
+ valid_inputs = {
+ 'http://example.com': 'http://example.com',
+ }
+ invalid_inputs = {
+ 'example.com': ['Enter a valid URL.']
+ }
+ outputs = {}
+ field = serializers.URLField()
+
+
+# Number types...
+
+class TestIntegerField(FieldValues):
+ """
+ Valid and invalid values for `IntegerField`.
+ """
+ valid_inputs = {
+ '1': 1,
+ '0': 0,
+ 1: 1,
+ 0: 0,
+ 1.0: 1,
+ 0.0: 0
+ }
+ invalid_inputs = {
+ 'abc': ['A valid integer is required.']
+ }
+ outputs = {
+ '1': 1,
+ '0': 0,
+ 1: 1,
+ 0: 0,
+ 1.0: 1,
+ 0.0: 0
+ }
+ field = serializers.IntegerField()
+
+
+class TestMinMaxIntegerField(FieldValues):
+ """
+ Valid and invalid values for `IntegerField` with min and max limits.
+ """
+ valid_inputs = {
+ '1': 1,
+ '3': 3,
+ 1: 1,
+ 3: 3,
+ }
+ invalid_inputs = {
+ 0: ['Ensure this value is greater than or equal to 1.'],
+ 4: ['Ensure this value is less than or equal to 3.'],
+ '0': ['Ensure this value is greater than or equal to 1.'],
+ '4': ['Ensure this value is less than or equal to 3.'],
+ }
+ outputs = {}
+ field = serializers.IntegerField(min_value=1, max_value=3)
+
+
+class TestFloatField(FieldValues):
+ """
+ Valid and invalid values for `FloatField`.
+ """
+ valid_inputs = {
+ '1': 1.0,
+ '0': 0.0,
+ 1: 1.0,
+ 0: 0.0,
+ 1.0: 1.0,
+ 0.0: 0.0,
+ }
+ invalid_inputs = {
+ 'abc': ["A valid number is required."]
+ }
+ outputs = {
+ '1': 1.0,
+ '0': 0.0,
+ 1: 1.0,
+ 0: 0.0,
+ 1.0: 1.0,
+ 0.0: 0.0,
+ }
+ field = serializers.FloatField()
+
+
+class TestMinMaxFloatField(FieldValues):
+ """
+ Valid and invalid values for `FloatField` with min and max limits.
+ """
+ valid_inputs = {
+ '1': 1,
+ '3': 3,
+ 1: 1,
+ 3: 3,
+ 1.0: 1.0,
+ 3.0: 3.0,
+ }
+ invalid_inputs = {
+ 0.9: ['Ensure this value is greater than or equal to 1.'],
+ 3.1: ['Ensure this value is less than or equal to 3.'],
+ '0.0': ['Ensure this value is greater than or equal to 1.'],
+ '3.1': ['Ensure this value is less than or equal to 3.'],
+ }
+ outputs = {}
+ field = serializers.FloatField(min_value=1, max_value=3)
+
+
+class TestDecimalField(FieldValues):
+ """
+ Valid and invalid values for `DecimalField`.
+ """
+ valid_inputs = {
+ '12.3': Decimal('12.3'),
+ '0.1': Decimal('0.1'),
+ 10: Decimal('10'),
+ 0: Decimal('0'),
+ 12.3: Decimal('12.3'),
+ 0.1: Decimal('0.1'),
+ }
+ invalid_inputs = (
+ ('abc', ["A valid number is required."]),
+ (Decimal('Nan'), ["A valid number is required."]),
+ (Decimal('Inf'), ["A valid number is required."]),
+ ('12.345', ["Ensure that there are no more than 3 digits in total."]),
+ ('0.01', ["Ensure that there are no more than 1 decimal places."]),
+ (123, ["Ensure that there are no more than 2 digits before the decimal point."])
+ )
+ outputs = {
+ '1': '1.0',
+ '0': '0.0',
+ '1.09': '1.1',
+ '0.04': '0.0',
+ 1: '1.0',
+ 0: '0.0',
+ Decimal('1.0'): '1.0',
+ Decimal('0.0'): '0.0',
+ Decimal('1.09'): '1.1',
+ Decimal('0.04'): '0.0'
+ }
+ field = serializers.DecimalField(max_digits=3, decimal_places=1)
+
+
+class TestMinMaxDecimalField(FieldValues):
+ """
+ Valid and invalid values for `DecimalField` with min and max limits.
+ """
+ valid_inputs = {
+ '10.0': Decimal('10.0'),
+ '20.0': Decimal('20.0'),
+ }
+ invalid_inputs = {
+ '9.9': ['Ensure this value is greater than or equal to 10.'],
+ '20.1': ['Ensure this value is less than or equal to 20.'],
+ }
+ outputs = {}
+ field = serializers.DecimalField(
+ max_digits=3, decimal_places=1,
+ min_value=10, max_value=20
+ )
+
+
+class TestNoStringCoercionDecimalField(FieldValues):
+ """
+ Output values for `DecimalField` with `coerce_to_string=False`.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = {
+ 1.09: Decimal('1.1'),
+ 0.04: Decimal('0.0'),
+ '1.09': Decimal('1.1'),
+ '0.04': Decimal('0.0'),
+ Decimal('1.09'): Decimal('1.1'),
+ Decimal('0.04'): Decimal('0.0'),
+ }
+ field = serializers.DecimalField(
+ max_digits=3, decimal_places=1,
+ coerce_to_string=False
+ )
+
+
+# Date & time serializers...
+
+class TestDateField(FieldValues):
+ """
+ Valid and invalid values for `DateField`.
+ """
+ valid_inputs = {
+ '2001-01-01': datetime.date(2001, 1, 1),
+ datetime.date(2001, 1, 1): datetime.date(2001, 1, 1),
+ }
+ invalid_inputs = {
+ 'abc': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'],
+ '2001-99-99': ['Date has wrong format. Use one of these formats instead: YYYY[-MM[-DD]]'],
+ datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'],
+ }
+ outputs = {
+ datetime.date(2001, 1, 1): '2001-01-01'
+ }
+ field = serializers.DateField()
+
+
+class TestCustomInputFormatDateField(FieldValues):
+ """
+ Valid and invalid values for `DateField` with a cutom input format.
+ """
+ valid_inputs = {
+ '1 Jan 2001': datetime.date(2001, 1, 1),
+ }
+ invalid_inputs = {
+ '2001-01-01': ['Date has wrong format. Use one of these formats instead: DD [Jan-Dec] YYYY']
+ }
+ outputs = {}
+ field = serializers.DateField(input_formats=['%d %b %Y'])
+
+
+class TestCustomOutputFormatDateField(FieldValues):
+ """
+ Values for `DateField` with a custom output format.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = {
+ datetime.date(2001, 1, 1): '01 Jan 2001'
+ }
+ field = serializers.DateField(format='%d %b %Y')
+
+
+class TestNoOutputFormatDateField(FieldValues):
+ """
+ Values for `DateField` with no output format.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = {
+ datetime.date(2001, 1, 1): datetime.date(2001, 1, 1)
+ }
+ field = serializers.DateField(format=None)
+
+
+class TestDateTimeField(FieldValues):
+ """
+ Valid and invalid values for `DateTimeField`.
+ """
+ valid_inputs = {
+ '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
+ '2001-01-01T13:00': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
+ '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
+ datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
+ datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
+ # Django 1.4 does not support timezone string parsing.
+ '2001-01-01T14:00+01:00' if (django.VERSION > (1, 4)) else '2001-01-01T13:00Z': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC())
+ }
+ invalid_inputs = {
+ 'abc': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'],
+ '2001-99-99T99:00': ['Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'],
+ datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'],
+ }
+ outputs = {
+ datetime.datetime(2001, 1, 1, 13, 00): '2001-01-01T13:00:00',
+ datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): '2001-01-01T13:00:00Z'
+ }
+ field = serializers.DateTimeField(default_timezone=timezone.UTC())
+
+
+class TestCustomInputFormatDateTimeField(FieldValues):
+ """
+ Valid and invalid values for `DateTimeField` with a cutom input format.
+ """
+ valid_inputs = {
+ '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=timezone.UTC()),
+ }
+ invalid_inputs = {
+ '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY']
+ }
+ outputs = {}
+ field = serializers.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y'])
+
+
+class TestCustomOutputFormatDateTimeField(FieldValues):
+ """
+ Values for `DateTimeField` with a custom output format.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = {
+ datetime.datetime(2001, 1, 1, 13, 00): '01:00PM, 01 Jan 2001',
+ }
+ field = serializers.DateTimeField(format='%I:%M%p, %d %b %Y')
+
+
+class TestNoOutputFormatDateTimeField(FieldValues):
+ """
+ Values for `DateTimeField` with no output format.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = {
+ datetime.datetime(2001, 1, 1, 13, 00): datetime.datetime(2001, 1, 1, 13, 00),
+ }
+ field = serializers.DateTimeField(format=None)
+
+
+class TestNaiveDateTimeField(FieldValues):
+ """
+ Valid and invalid values for `DateTimeField` with naive datetimes.
+ """
+ valid_inputs = {
+ datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00),
+ '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00),
+ }
+ invalid_inputs = {}
+ outputs = {}
+ field = serializers.DateTimeField(default_timezone=None)
+
+
+class TestTimeField(FieldValues):
+ """
+ Valid and invalid values for `TimeField`.
+ """
+ valid_inputs = {
+ '13:00': datetime.time(13, 00),
+ datetime.time(13, 00): datetime.time(13, 00),
+ }
+ invalid_inputs = {
+ 'abc': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'],
+ '99:99': ['Time has wrong format. Use one of these formats instead: hh:mm[:ss[.uuuuuu]]'],
+ }
+ outputs = {
+ datetime.time(13, 00): '13:00:00'
+ }
+ field = serializers.TimeField()
+
+
+class TestCustomInputFormatTimeField(FieldValues):
+ """
+ Valid and invalid values for `TimeField` with a custom input format.
+ """
+ valid_inputs = {
+ '1:00pm': datetime.time(13, 00),
+ }
+ invalid_inputs = {
+ '13:00': ['Time has wrong format. Use one of these formats instead: hh:mm[AM|PM]'],
+ }
+ outputs = {}
+ field = serializers.TimeField(input_formats=['%I:%M%p'])
+
+
+class TestCustomOutputFormatTimeField(FieldValues):
+ """
+ Values for `TimeField` with a custom output format.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = {
+ datetime.time(13, 00): '01:00PM'
+ }
+ field = serializers.TimeField(format='%I:%M%p')
+
+
+class TestNoOutputFormatTimeField(FieldValues):
+ """
+ Values for `TimeField` with a no output format.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = {
+ datetime.time(13, 00): datetime.time(13, 00)
+ }
+ field = serializers.TimeField(format=None)
+
+
+# Choice types...
+
+class TestChoiceField(FieldValues):
+ """
+ Valid and invalid values for `ChoiceField`.
+ """
+ valid_inputs = {
+ 'poor': 'poor',
+ 'medium': 'medium',
+ 'good': 'good',
+ }
+ invalid_inputs = {
+ 'amazing': ['`amazing` is not a valid choice.']
+ }
+ outputs = {
+ 'good': 'good',
+ '': ''
+ }
+ field = serializers.ChoiceField(
+ choices=[
+ ('poor', 'Poor quality'),
+ ('medium', 'Medium quality'),
+ ('good', 'Good quality'),
+ ]
+ )
+
+
+class TestChoiceFieldWithType(FieldValues):
+ """
+ Valid and invalid values for a `Choice` field that uses an integer type,
+ instead of a char type.
+ """
+ valid_inputs = {
+ '1': 1,
+ 3: 3,
+ }
+ invalid_inputs = {
+ 5: ['`5` is not a valid choice.'],
+ 'abc': ['`abc` is not a valid choice.']
+ }
+ outputs = {
+ '1': 1,
+ 1: 1
+ }
+ field = serializers.ChoiceField(
+ choices=[
+ (1, 'Poor quality'),
+ (2, 'Medium quality'),
+ (3, 'Good quality'),
+ ]
+ )
+
+
+class TestChoiceFieldWithListChoices(FieldValues):
+ """
+ Valid and invalid values for a `Choice` field that uses a flat list for the
+ choices, rather than a list of pairs of (`value`, `description`).
+ """
+ valid_inputs = {
+ 'poor': 'poor',
+ 'medium': 'medium',
+ 'good': 'good',
+ }
+ invalid_inputs = {
+ 'awful': ['`awful` is not a valid choice.']
+ }
+ outputs = {
+ 'good': 'good'
+ }
+ field = serializers.ChoiceField(choices=('poor', 'medium', 'good'))
+
+
+class TestMultipleChoiceField(FieldValues):
+ """
+ Valid and invalid values for `MultipleChoiceField`.
+ """
+ valid_inputs = {
+ (): set(),
+ ('aircon',): set(['aircon']),
+ ('aircon', 'manual'): set(['aircon', 'manual']),
+ }
+ invalid_inputs = {
+ 'abc': ['Expected a list of items but got type `str`.'],
+ ('aircon', 'incorrect'): ['`incorrect` is not a valid choice.']
+ }
+ outputs = [
+ (['aircon', 'manual'], set(['aircon', 'manual']))
+ ]
+ field = serializers.MultipleChoiceField(
+ choices=[
+ ('aircon', 'AirCon'),
+ ('manual', 'Manual drive'),
+ ('diesel', 'Diesel'),
+ ]
+ )
+
+
+# File serializers...
+
+class MockFile:
+ def __init__(self, name='', size=0, url=''):
+ self.name = name
+ self.size = size
+ self.url = url
+
+ def __eq__(self, other):
+ return (
+ isinstance(other, MockFile) and
+ self.name == other.name and
+ self.size == other.size and
+ self.url == other.url
+ )
+
+
+class TestFileField(FieldValues):
+ """
+ Values for `FileField`.
+ """
+ valid_inputs = [
+ (MockFile(name='example', size=10), MockFile(name='example', size=10))
+ ]
+ invalid_inputs = [
+ ('invalid', ['The submitted data was not a file. Check the encoding type on the form.']),
+ (MockFile(name='example.txt', size=0), ['The submitted file is empty.']),
+ (MockFile(name='', size=10), ['No filename could be determined.']),
+ (MockFile(name='x' * 100, size=10), ['Ensure this filename has at most 10 characters (it has 100).'])
+ ]
+ outputs = [
+ (MockFile(name='example.txt', url='/example.txt'), '/example.txt'),
+ ('', None)
+ ]
+ field = serializers.FileField(max_length=10)
+
+
+class TestFieldFieldWithName(FieldValues):
+ """
+ Values for `FileField` with a filename output instead of URLs.
+ """
+ valid_inputs = {}
+ invalid_inputs = {}
+ outputs = [
+ (MockFile(name='example.txt', url='/example.txt'), 'example.txt')
+ ]
+ field = serializers.FileField(use_url=False)
+
+
+# Stub out mock Django `forms.ImageField` class so we don't *actually*
+# call into it's regular validation, or require PIL for testing.
+class FailImageValidation(object):
+ def to_python(self, value):
+ raise serializers.ValidationError(self.error_messages['invalid_image'])
+
+
+class PassImageValidation(object):
+ def to_python(self, value):
+ return value
+
+
+class TestInvalidImageField(FieldValues):
+ """
+ Values for an invalid `ImageField`.
+ """
+ valid_inputs = {}
+ invalid_inputs = [
+ (MockFile(name='example.txt', size=10), ['Upload a valid image. The file you uploaded was either not an image or a corrupted image.'])
+ ]
+ outputs = {}
+ field = serializers.ImageField(_DjangoImageField=FailImageValidation)
+
+
+class TestValidImageField(FieldValues):
+ """
+ Values for an valid `ImageField`.
+ """
+ valid_inputs = [
+ (MockFile(name='example.txt', size=10), MockFile(name='example.txt', size=10))
+ ]
+ invalid_inputs = {}
+ outputs = {}
+ field = serializers.ImageField(_DjangoImageField=PassImageValidation)
+
+
+# Composite serializers...
+
+class TestListField(FieldValues):
+ """
+ Values for `ListField`.
+ """
+ valid_inputs = [
+ ([1, 2, 3], [1, 2, 3]),
+ (['1', '2', '3'], [1, 2, 3])
+ ]
+ invalid_inputs = [
+ ('not a list', ['Expected a list of items but got type `str`']),
+ ([1, 2, 'error'], ['A valid integer is required.'])
+ ]
+ outputs = [
+ ([1, 2, 3], [1, 2, 3]),
+ (['1', '2', '3'], [1, 2, 3])
+ ]
+ field = serializers.ListField(child=serializers.IntegerField())
+
+
+# Tests for FieldField.
+# ---------------------
+
+class MockRequest:
+ def build_absolute_uri(self, value):
+ return 'http://example.com' + value
+
+
+class TestFileFieldContext:
+ def test_fully_qualified_when_request_in_context(self):
+ field = serializers.FileField(max_length=10)
+ field._context = {'request': MockRequest()}
+ obj = MockFile(name='example.txt', url='/example.txt')
+ value = field.to_representation(obj)
+ assert value == 'http://example.com/example.txt'
+
+
+# Tests for SerializerMethodField.
+# --------------------------------
+
+class TestSerializerMethodField:
+ def test_serializer_method_field(self):
+ class ExampleSerializer(serializers.Serializer):
+ example_field = serializers.SerializerMethodField()
+
+ def get_example_field(self, obj):
+ return 'ran get_example_field(%d)' % obj['example_field']
+
+ serializer = ExampleSerializer({'example_field': 123})
+ assert serializer.data == {
+ 'example_field': 'ran get_example_field(123)'
+ }
+
+ def test_redundant_method_name(self):
+ class ExampleSerializer(serializers.Serializer):
+ example_field = serializers.SerializerMethodField('get_example_field')
+
+ with pytest.raises(AssertionError) as exc_info:
+ ExampleSerializer().fields
+ assert str(exc_info.value) == (
+ "It is redundant to specify `get_example_field` on "
+ "SerializerMethodField 'example_field' in serializer "
+ "'ExampleSerializer', because it is the same as the default "
+ "method name. Remove the `method_name` argument."
+ )
diff --git a/tests/test_files.py b/tests/test_files.py
deleted file mode 100644
index a5613fcb..00000000
--- a/tests/test_files.py
+++ /dev/null
@@ -1,92 +0,0 @@
-# from __future__ import unicode_literals
-# from django.test import TestCase
-# from django.utils import six
-# from rest_framework import serializers
-# from rest_framework.compat import BytesIO
-# import datetime
-
-
-# class UploadedFile(object):
-# def __init__(self, file=None, created=None):
-# self.file = file
-# self.created = created or datetime.datetime.now()
-
-
-# class UploadedFileSerializer(serializers.Serializer):
-# file = serializers.FileField(required=False)
-# created = serializers.DateTimeField()
-
-# def restore_object(self, attrs, instance=None):
-# if instance:
-# instance.file = attrs['file']
-# instance.created = attrs['created']
-# return instance
-# return UploadedFile(**attrs)
-
-
-# class FileSerializerTests(TestCase):
-# def test_create(self):
-# now = datetime.datetime.now()
-# file = BytesIO(six.b('stuff'))
-# file.name = 'stuff.txt'
-# file.size = len(file.getvalue())
-# serializer = UploadedFileSerializer(data={'created': now}, files={'file': file})
-# uploaded_file = UploadedFile(file=file, created=now)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.object.created, uploaded_file.created)
-# self.assertEqual(serializer.object.file, uploaded_file.file)
-# self.assertFalse(serializer.object is uploaded_file)
-
-# def test_creation_failure(self):
-# """
-# Passing files=None should result in an ValidationError
-
-# Regression test for:
-# https://github.com/tomchristie/django-rest-framework/issues/542
-# """
-# now = datetime.datetime.now()
-
-# serializer = UploadedFileSerializer(data={'created': now})
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.object.created, now)
-# self.assertIsNone(serializer.object.file)
-
-# def test_remove_with_empty_string(self):
-# """
-# Passing empty string as data should cause file to be removed
-
-# Test for:
-# https://github.com/tomchristie/django-rest-framework/issues/937
-# """
-# now = datetime.datetime.now()
-# file = BytesIO(six.b('stuff'))
-# file.name = 'stuff.txt'
-# file.size = len(file.getvalue())
-
-# uploaded_file = UploadedFile(file=file, created=now)
-
-# serializer = UploadedFileSerializer(instance=uploaded_file, data={'created': now, 'file': ''})
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.object.created, uploaded_file.created)
-# self.assertIsNone(serializer.object.file)
-
-# def test_validation_error_with_non_file(self):
-# """
-# Passing non-files should raise a validation error.
-# """
-# now = datetime.datetime.now()
-# errmsg = 'No file was submitted. Check the encoding type on the form.'
-
-# serializer = UploadedFileSerializer(data={'created': now, 'file': 'abc'})
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'file': [errmsg]})
-
-# def test_validation_with_no_data(self):
-# """
-# Validation should still function when no data dictionary is provided.
-# """
-# uploaded_file = BytesIO(six.b('stuff'))
-# uploaded_file.name = 'stuff.txt'
-# uploaded_file.size = len(uploaded_file.getvalue())
-# serializer = UploadedFileSerializer(files={'file': uploaded_file})
-# self.assertFalse(serializer.is_valid())
diff --git a/tests/test_genericrelations.py b/tests/test_genericrelations.py
deleted file mode 100644
index a87ea3fd..00000000
--- a/tests/test_genericrelations.py
+++ /dev/null
@@ -1,151 +0,0 @@
-# from __future__ import unicode_literals
-# from django.contrib.contenttypes.models import ContentType
-# from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey
-# from django.db import models
-# from django.test import TestCase
-# from rest_framework import serializers
-# from rest_framework.compat import python_2_unicode_compatible
-
-
-# @python_2_unicode_compatible
-# class Tag(models.Model):
-# """
-# Tags have a descriptive slug, and are attached to an arbitrary object.
-# """
-# tag = models.SlugField()
-# content_type = models.ForeignKey(ContentType)
-# object_id = models.PositiveIntegerField()
-# tagged_item = GenericForeignKey('content_type', 'object_id')
-
-# def __str__(self):
-# return self.tag
-
-
-# @python_2_unicode_compatible
-# class Bookmark(models.Model):
-# """
-# A URL bookmark that may have multiple tags attached.
-# """
-# url = models.URLField()
-# tags = GenericRelation(Tag)
-
-# def __str__(self):
-# return 'Bookmark: %s' % self.url
-
-
-# @python_2_unicode_compatible
-# class Note(models.Model):
-# """
-# A textual note that may have multiple tags attached.
-# """
-# text = models.TextField()
-# tags = GenericRelation(Tag)
-
-# def __str__(self):
-# return 'Note: %s' % self.text
-
-
-# class TestGenericRelations(TestCase):
-# def setUp(self):
-# self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/')
-# Tag.objects.create(tagged_item=self.bookmark, tag='django')
-# Tag.objects.create(tagged_item=self.bookmark, tag='python')
-# self.note = Note.objects.create(text='Remember the milk')
-# Tag.objects.create(tagged_item=self.note, tag='reminder')
-
-# def test_generic_relation(self):
-# """
-# Test a relationship that spans a GenericRelation field.
-# IE. A reverse generic relationship.
-# """
-
-# class BookmarkSerializer(serializers.ModelSerializer):
-# tags = serializers.RelatedField(many=True)
-
-# class Meta:
-# model = Bookmark
-# exclude = ('id',)
-
-# serializer = BookmarkSerializer(self.bookmark)
-# expected = {
-# 'tags': ['django', 'python'],
-# 'url': 'https://www.djangoproject.com/'
-# }
-# self.assertEqual(serializer.data, expected)
-
-# def test_generic_nested_relation(self):
-# """
-# Test saving a GenericRelation field via a nested serializer.
-# """
-
-# class TagSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Tag
-# exclude = ('content_type', 'object_id')
-
-# class BookmarkSerializer(serializers.ModelSerializer):
-# tags = TagSerializer(many=True)
-
-# class Meta:
-# model = Bookmark
-# exclude = ('id',)
-
-# data = {
-# 'url': 'https://docs.djangoproject.com/',
-# 'tags': [
-# {'tag': 'contenttypes'},
-# {'tag': 'genericrelations'},
-# ]
-# }
-# serializer = BookmarkSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-# self.assertEqual(serializer.object.tags.count(), 2)
-
-# def test_generic_fk(self):
-# """
-# Test a relationship that spans a GenericForeignKey field.
-# IE. A forward generic relationship.
-# """
-
-# class TagSerializer(serializers.ModelSerializer):
-# tagged_item = serializers.RelatedField()
-
-# class Meta:
-# model = Tag
-# exclude = ('id', 'content_type', 'object_id')
-
-# serializer = TagSerializer(Tag.objects.all(), many=True)
-# expected = [
-# {
-# 'tag': 'django',
-# 'tagged_item': 'Bookmark: https://www.djangoproject.com/'
-# },
-# {
-# 'tag': 'python',
-# 'tagged_item': 'Bookmark: https://www.djangoproject.com/'
-# },
-# {
-# 'tag': 'reminder',
-# 'tagged_item': 'Note: Remember the milk'
-# }
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_restore_object_generic_fk(self):
-# """
-# Ensure an object with a generic foreign key can be restored.
-# """
-
-# class TagSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Tag
-# exclude = ('content_type', 'object_id')
-
-# serializer = TagSerializer()
-
-# bookmark = Bookmark(url='http://example.com')
-# attrs = {'tagged_item': bookmark, 'tag': 'example'}
-
-# tag = serializer.restore_object(attrs)
-# self.assertEqual(tag.tagged_item, bookmark)
diff --git a/tests/test_generics.py b/tests/test_generics.py
index 51004edf..2690fb47 100644
--- a/tests/test_generics.py
+++ b/tests/test_generics.py
@@ -23,31 +23,22 @@ class ForeignKeySerializer(serializers.ModelSerializer):
class RootView(generics.ListCreateAPIView):
- """
- Example description for OPTIONS.
- """
queryset = BasicModel.objects.all()
serializer_class = BasicSerializer
class InstanceView(generics.RetrieveUpdateDestroyAPIView):
- """
- Example description for OPTIONS.
- """
queryset = BasicModel.objects.exclude(text='filtered out')
serializer_class = BasicSerializer
class FKInstanceView(generics.RetrieveUpdateDestroyAPIView):
- """
- FK: example description for OPTIONS.
- """
queryset = ForeignKeySource.objects.all()
serializer_class = ForeignKeySerializer
class SlugSerializer(serializers.ModelSerializer):
- slug = serializers.Field(read_only=True)
+ slug = serializers.ReadOnlyField()
class Meta:
model = SlugBasedModel
@@ -122,47 +113,6 @@ class TestRootView(TestCase):
self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)
self.assertEqual(response.data, {"detail": "Method 'DELETE' not allowed."})
- # def test_options_root_view(self):
- # """
- # OPTIONS requests to ListCreateAPIView should return metadata
- # """
- # request = factory.options('/')
- # with self.assertNumQueries(0):
- # response = self.view(request).render()
- # expected = {
- # 'parses': [
- # 'application/json',
- # 'application/x-www-form-urlencoded',
- # 'multipart/form-data'
- # ],
- # 'renders': [
- # 'application/json',
- # 'text/html'
- # ],
- # 'name': 'Root',
- # 'description': 'Example description for OPTIONS.',
- # 'actions': {
- # 'POST': {
- # 'text': {
- # 'max_length': 100,
- # 'read_only': False,
- # 'required': True,
- # 'type': 'string',
- # "label": "Text comes here",
- # "help_text": "Text description."
- # },
- # 'id': {
- # 'read_only': True,
- # 'required': False,
- # 'type': 'integer',
- # 'label': 'ID',
- # },
- # }
- # }
- # }
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertEqual(response.data, expected)
-
def test_post_cannot_set_id(self):
"""
POST requests to create a new object should not be able to set the id.
@@ -256,89 +206,6 @@ class TestInstanceView(TestCase):
ids = [obj.id for obj in self.objects.all()]
self.assertEqual(ids, [2, 3])
- # def test_options_instance_view(self):
- # """
- # OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata
- # """
- # request = factory.options('/1')
- # with self.assertNumQueries(1):
- # response = self.view(request, pk=1).render()
- # expected = {
- # 'parses': [
- # 'application/json',
- # 'application/x-www-form-urlencoded',
- # 'multipart/form-data'
- # ],
- # 'renders': [
- # 'application/json',
- # 'text/html'
- # ],
- # 'name': 'Instance',
- # 'description': 'Example description for OPTIONS.',
- # 'actions': {
- # 'PUT': {
- # 'text': {
- # 'max_length': 100,
- # 'read_only': False,
- # 'required': True,
- # 'type': 'string',
- # 'label': 'Text comes here',
- # 'help_text': 'Text description.'
- # },
- # 'id': {
- # 'read_only': True,
- # 'required': False,
- # 'type': 'integer',
- # 'label': 'ID',
- # },
- # }
- # }
- # }
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertEqual(response.data, expected)
-
- # def test_options_before_instance_create(self):
- # """
- # OPTIONS requests to RetrieveUpdateDestroyAPIView should return metadata
- # before the instance has been created
- # """
- # request = factory.options('/999')
- # with self.assertNumQueries(1):
- # response = self.view(request, pk=999).render()
- # expected = {
- # 'parses': [
- # 'application/json',
- # 'application/x-www-form-urlencoded',
- # 'multipart/form-data'
- # ],
- # 'renders': [
- # 'application/json',
- # 'text/html'
- # ],
- # 'name': 'Instance',
- # 'description': 'Example description for OPTIONS.',
- # 'actions': {
- # 'PUT': {
- # 'text': {
- # 'max_length': 100,
- # 'read_only': False,
- # 'required': True,
- # 'type': 'string',
- # 'label': 'Text comes here',
- # 'help_text': 'Text description.'
- # },
- # 'id': {
- # 'read_only': True,
- # 'required': False,
- # 'type': 'integer',
- # 'label': 'ID',
- # },
- # }
- # }
- # }
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertEqual(response.data, expected)
-
def test_get_instance_view_incorrect_arg(self):
"""
GET requests with an incorrect pk type, should raise 404, not 500.
@@ -415,53 +282,6 @@ class TestFKInstanceView(TestCase):
]
self.view = FKInstanceView.as_view()
- # def test_options_root_view(self):
- # """
- # OPTIONS requests to ListCreateAPIView should return metadata
- # """
- # request = factory.options('/999')
- # with self.assertNumQueries(1):
- # response = self.view(request, pk=999).render()
- # expected = {
- # 'name': 'Fk Instance',
- # 'description': 'FK: example description for OPTIONS.',
- # 'renders': [
- # 'application/json',
- # 'text/html'
- # ],
- # 'parses': [
- # 'application/json',
- # 'application/x-www-form-urlencoded',
- # 'multipart/form-data'
- # ],
- # 'actions': {
- # 'PUT': {
- # 'id': {
- # 'type': 'integer',
- # 'required': False,
- # 'read_only': True,
- # 'label': 'ID'
- # },
- # 'name': {
- # 'type': 'string',
- # 'required': True,
- # 'read_only': False,
- # 'label': 'name',
- # 'max_length': 100
- # },
- # 'target': {
- # 'type': 'field',
- # 'required': True,
- # 'read_only': False,
- # 'label': 'Target',
- # 'help_text': 'Target'
- # }
- # }
- # }
- # }
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertEqual(response.data, expected)
-
class TestOverriddenGetObject(TestCase):
"""
diff --git a/tests/test_hyperlinkedserializers.py b/tests/test_hyperlinkedserializers.py
deleted file mode 100644
index ff3663dd..00000000
--- a/tests/test_hyperlinkedserializers.py
+++ /dev/null
@@ -1,406 +0,0 @@
-# from __future__ import unicode_literals
-# import json
-# from django.test import TestCase
-# from rest_framework import generics, status, serializers
-# from django.conf.urls import patterns, url
-# from rest_framework.settings import api_settings
-# from rest_framework.test import APIRequestFactory
-# from tests.models import (
-# Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment,
-# Album, Photo, OptionalRelationModel
-# )
-
-# factory = APIRequestFactory()
-
-
-# class BlogPostCommentSerializer(serializers.ModelSerializer):
-# url = serializers.HyperlinkedIdentityField(view_name='blogpostcomment-detail')
-# text = serializers.CharField()
-# blog_post_url = serializers.HyperlinkedRelatedField(source='blog_post', view_name='blogpost-detail')
-
-# class Meta:
-# model = BlogPostComment
-# fields = ('text', 'blog_post_url', 'url')
-
-
-# class PhotoSerializer(serializers.Serializer):
-# description = serializers.CharField()
-# album_url = serializers.HyperlinkedRelatedField(source='album', view_name='album-detail', queryset=Album.objects.all(), lookup_field='title')
-
-# def restore_object(self, attrs, instance=None):
-# return Photo(**attrs)
-
-
-# class AlbumSerializer(serializers.ModelSerializer):
-# url = serializers.HyperlinkedIdentityField(view_name='album-detail', lookup_field='title')
-
-# class Meta:
-# model = Album
-# fields = ('title', 'url')
-
-
-# class BasicSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = BasicModel
-
-
-# class AnchorSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = Anchor
-
-
-# class ManyToManySerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = ManyToManyModel
-
-
-# class BlogPostSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = BlogPost
-
-
-# class OptionalRelationSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = OptionalRelationModel
-
-
-# class BasicList(generics.ListCreateAPIView):
-# queryset = BasicModel.objects.all()
-# serializer_class = BasicSerializer
-
-
-# class BasicDetail(generics.RetrieveUpdateDestroyAPIView):
-# queryset = BasicModel.objects.all()
-# serializer_class = BasicSerializer
-
-
-# class AnchorDetail(generics.RetrieveAPIView):
-# queryset = Anchor.objects.all()
-# serializer_class = AnchorSerializer
-
-
-# class ManyToManyList(generics.ListAPIView):
-# queryset = ManyToManyModel.objects.all()
-# serializer_class = ManyToManySerializer
-
-
-# class ManyToManyDetail(generics.RetrieveAPIView):
-# queryset = ManyToManyModel.objects.all()
-# serializer_class = ManyToManySerializer
-
-
-# class BlogPostCommentListCreate(generics.ListCreateAPIView):
-# queryset = BlogPostComment.objects.all()
-# serializer_class = BlogPostCommentSerializer
-
-
-# class BlogPostCommentDetail(generics.RetrieveAPIView):
-# queryset = BlogPostComment.objects.all()
-# serializer_class = BlogPostCommentSerializer
-
-
-# class BlogPostDetail(generics.RetrieveAPIView):
-# queryset = BlogPost.objects.all()
-# serializer_class = BlogPostSerializer
-
-
-# class PhotoListCreate(generics.ListCreateAPIView):
-# queryset = Photo.objects.all()
-# serializer_class = PhotoSerializer
-
-
-# class AlbumDetail(generics.RetrieveAPIView):
-# queryset = Album.objects.all()
-# serializer_class = AlbumSerializer
-# lookup_field = 'title'
-
-
-# class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView):
-# queryset = OptionalRelationModel.objects.all()
-# serializer_class = OptionalRelationSerializer
-
-
-# urlpatterns = patterns(
-# '',
-# url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'),
-# url(r'^basic/(?P<pk>\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'),
-# url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(), name='anchor-detail'),
-# url(r'^manytomany/$', ManyToManyList.as_view(), name='manytomanymodel-list'),
-# url(r'^manytomany/(?P<pk>\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'),
-# url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'),
-# url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'),
-# url(r'^comments/(?P<pk>\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'),
-# url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'),
-# url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'),
-# url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'),
-# )
-
-
-# class TestBasicHyperlinkedView(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# """
-# Create 3 BasicModel instances.
-# """
-# items = ['foo', 'bar', 'baz']
-# for item in items:
-# BasicModel(text=item).save()
-# self.objects = BasicModel.objects
-# self.data = [
-# {'url': 'http://testserver/basic/%d/' % obj.id, 'text': obj.text}
-# for obj in self.objects.all()
-# ]
-# self.list_view = BasicList.as_view()
-# self.detail_view = BasicDetail.as_view()
-
-# def test_get_list_view(self):
-# """
-# GET requests to ListCreateAPIView should return list of objects.
-# """
-# request = factory.get('/basic/')
-# response = self.list_view(request).render()
-# self.assertEqual(response.status_code, status.HTTP_200_OK)
-# self.assertEqual(response.data, self.data)
-
-# def test_get_detail_view(self):
-# """
-# GET requests to ListCreateAPIView should return list of objects.
-# """
-# request = factory.get('/basic/1')
-# response = self.detail_view(request, pk=1).render()
-# self.assertEqual(response.status_code, status.HTTP_200_OK)
-# self.assertEqual(response.data, self.data[0])
-
-
-# class TestManyToManyHyperlinkedView(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# """
-# Create 3 BasicModel instances.
-# """
-# items = ['foo', 'bar', 'baz']
-# anchors = []
-# for item in items:
-# anchor = Anchor(text=item)
-# anchor.save()
-# anchors.append(anchor)
-
-# manytomany = ManyToManyModel()
-# manytomany.save()
-# manytomany.rel.add(*anchors)
-
-# self.data = [{
-# 'url': 'http://testserver/manytomany/1/',
-# 'rel': [
-# 'http://testserver/anchor/1/',
-# 'http://testserver/anchor/2/',
-# 'http://testserver/anchor/3/',
-# ]
-# }]
-# self.list_view = ManyToManyList.as_view()
-# self.detail_view = ManyToManyDetail.as_view()
-
-# def test_get_list_view(self):
-# """
-# GET requests to ListCreateAPIView should return list of objects.
-# """
-# request = factory.get('/manytomany/')
-# response = self.list_view(request)
-# self.assertEqual(response.status_code, status.HTTP_200_OK)
-# self.assertEqual(response.data, self.data)
-
-# def test_get_detail_view(self):
-# """
-# GET requests to ListCreateAPIView should return list of objects.
-# """
-# request = factory.get('/manytomany/1/')
-# response = self.detail_view(request, pk=1)
-# self.assertEqual(response.status_code, status.HTTP_200_OK)
-# self.assertEqual(response.data, self.data[0])
-
-
-# class TestHyperlinkedIdentityFieldLookup(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# """
-# Create 3 Album instances.
-# """
-# titles = ['foo', 'bar', 'baz']
-# for title in titles:
-# album = Album(title=title)
-# album.save()
-# self.detail_view = AlbumDetail.as_view()
-# self.data = {
-# 'foo': {'title': 'foo', 'url': 'http://testserver/albums/foo/'},
-# 'bar': {'title': 'bar', 'url': 'http://testserver/albums/bar/'},
-# 'baz': {'title': 'baz', 'url': 'http://testserver/albums/baz/'}
-# }
-
-# def test_lookup_field(self):
-# """
-# GET requests to AlbumDetail view should return serialized Albums
-# with a url field keyed by `title`.
-# """
-# for album in Album.objects.all():
-# request = factory.get('/albums/{0}/'.format(album.title))
-# response = self.detail_view(request, title=album.title)
-# self.assertEqual(response.status_code, status.HTTP_200_OK)
-# self.assertEqual(response.data, self.data[album.title])
-
-
-# class TestCreateWithForeignKeys(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# """
-# Create a blog post
-# """
-# self.post = BlogPost.objects.create(title="Test post")
-# self.create_view = BlogPostCommentListCreate.as_view()
-
-# def test_create_comment(self):
-
-# data = {
-# 'text': 'A test comment',
-# 'blog_post_url': 'http://testserver/posts/1/'
-# }
-
-# request = factory.post('/comments/', data=data)
-# response = self.create_view(request)
-# self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-# self.assertEqual(response['Location'], 'http://testserver/comments/1/')
-# self.assertEqual(self.post.blogpostcomment_set.count(), 1)
-# self.assertEqual(self.post.blogpostcomment_set.all()[0].text, 'A test comment')
-
-
-# class TestCreateWithForeignKeysAndCustomSlug(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# """
-# Create an Album
-# """
-# self.post = Album.objects.create(title='test-album')
-# self.list_create_view = PhotoListCreate.as_view()
-
-# def test_create_photo(self):
-
-# data = {
-# 'description': 'A test photo',
-# 'album_url': 'http://testserver/albums/test-album/'
-# }
-
-# request = factory.post('/photos/', data=data)
-# response = self.list_create_view(request)
-# self.assertEqual(response.status_code, status.HTTP_201_CREATED)
-# self.assertNotIn('Location', response, msg='Location should only be included if there is a "url" field on the serializer')
-# self.assertEqual(self.post.photo_set.count(), 1)
-# self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo')
-
-
-# class TestOptionalRelationHyperlinkedView(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# """
-# Create 1 OptionalRelationModel instances.
-# """
-# OptionalRelationModel().save()
-# self.objects = OptionalRelationModel.objects
-# self.detail_view = OptionalRelationDetail.as_view()
-# self.data = {"url": "http://testserver/optionalrelation/1/", "other": None}
-
-# def test_get_detail_view(self):
-# """
-# GET requests to RetrieveAPIView with optional relations should return None
-# for non existing relations.
-# """
-# request = factory.get('/optionalrelationmodel-detail/1')
-# response = self.detail_view(request, pk=1)
-# self.assertEqual(response.status_code, status.HTTP_200_OK)
-# self.assertEqual(response.data, self.data)
-
-# def test_put_detail_view(self):
-# """
-# PUT requests to RetrieveUpdateDestroyAPIView with optional relations
-# should accept None for non existing relations.
-# """
-# response = self.client.put('/optionalrelation/1/',
-# data=json.dumps(self.data),
-# content_type='application/json')
-# self.assertEqual(response.status_code, status.HTTP_200_OK)
-
-
-# class TestOverriddenURLField(TestCase):
-# def setUp(self):
-# class OverriddenURLSerializer(serializers.HyperlinkedModelSerializer):
-# url = serializers.SerializerMethodField('get_url')
-
-# class Meta:
-# model = BlogPost
-# fields = ('title', 'url')
-
-# def get_url(self, obj):
-# return 'foo bar'
-
-# self.Serializer = OverriddenURLSerializer
-# self.obj = BlogPost.objects.create(title='New blog post')
-
-# def test_overridden_url_field(self):
-# """
-# The 'url' field should respect overriding.
-# Regression test for #936.
-# """
-# serializer = self.Serializer(self.obj)
-# self.assertEqual(
-# serializer.data,
-# {'title': 'New blog post', 'url': 'foo bar'}
-# )
-
-
-# class TestURLFieldNameBySettings(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# self.saved_url_field_name = api_settings.URL_FIELD_NAME
-# api_settings.URL_FIELD_NAME = 'global_url_field'
-
-# class Serializer(serializers.HyperlinkedModelSerializer):
-
-# class Meta:
-# model = BlogPost
-# fields = ('title', api_settings.URL_FIELD_NAME)
-
-# self.Serializer = Serializer
-# self.obj = BlogPost.objects.create(title="New blog post")
-
-# def tearDown(self):
-# api_settings.URL_FIELD_NAME = self.saved_url_field_name
-
-# def test_overridden_url_field_name(self):
-# request = factory.get('/posts/')
-# serializer = self.Serializer(self.obj, context={'request': request})
-# self.assertIn(api_settings.URL_FIELD_NAME, serializer.data)
-
-
-# class TestURLFieldNameByOptions(TestCase):
-# urls = 'tests.test_hyperlinkedserializers'
-
-# def setUp(self):
-# class Serializer(serializers.HyperlinkedModelSerializer):
-
-# class Meta:
-# model = BlogPost
-# fields = ('title', 'serializer_url_field')
-# url_field_name = 'serializer_url_field'
-
-# self.Serializer = Serializer
-# self.obj = BlogPost.objects.create(title="New blog post")
-
-# def test_overridden_url_field_name(self):
-# request = factory.get('/posts/')
-# serializer = self.Serializer(self.obj, context={'request': request})
-# self.assertIn(self.Serializer.Meta.url_field_name, serializer.data)
diff --git a/tests/test_metadata.py b/tests/test_metadata.py
new file mode 100644
index 00000000..5ff59c72
--- /dev/null
+++ b/tests/test_metadata.py
@@ -0,0 +1,166 @@
+from __future__ import unicode_literals
+
+from rest_framework import exceptions, serializers, views
+from rest_framework.request import Request
+from rest_framework.test import APIRequestFactory
+import pytest
+
+request = Request(APIRequestFactory().options('/'))
+
+
+class TestMetadata:
+ def test_metadata(self):
+ """
+ OPTIONS requests to views should return a valid 200 response.
+ """
+ class ExampleView(views.APIView):
+ """Example view."""
+ pass
+
+ response = ExampleView().options(request=request)
+ expected = {
+ 'name': 'Example',
+ 'description': 'Example view.',
+ 'renders': [
+ 'application/json',
+ 'text/html'
+ ],
+ 'parses': [
+ 'application/json',
+ 'application/x-www-form-urlencoded',
+ 'multipart/form-data'
+ ]
+ }
+ assert response.status_code == 200
+ assert response.data == expected
+
+ def test_none_metadata(self):
+ """
+ OPTIONS requests to views where `metadata_class = None` should raise
+ a MethodNotAllowed exception, which will result in an HTTP 405 response.
+ """
+ class ExampleView(views.APIView):
+ metadata_class = None
+
+ with pytest.raises(exceptions.MethodNotAllowed):
+ ExampleView().options(request=request)
+
+ def test_actions(self):
+ """
+ On generic views OPTIONS should return an 'actions' key with metadata
+ on the fields that may be supplied to PUT and POST requests.
+ """
+ class ExampleSerializer(serializers.Serializer):
+ choice_field = serializers.ChoiceField(['red', 'green', 'blue'])
+ integer_field = serializers.IntegerField(max_value=10)
+ char_field = serializers.CharField(required=False)
+
+ class ExampleView(views.APIView):
+ """Example view."""
+ def post(self, request):
+ pass
+
+ def get_serializer(self):
+ return ExampleSerializer()
+
+ response = ExampleView().options(request=request)
+ expected = {
+ 'name': 'Example',
+ 'description': 'Example view.',
+ 'renders': [
+ 'application/json',
+ 'text/html'
+ ],
+ 'parses': [
+ 'application/json',
+ 'application/x-www-form-urlencoded',
+ 'multipart/form-data'
+ ],
+ 'actions': {
+ 'POST': {
+ 'choice_field': {
+ 'type': 'choice',
+ 'required': True,
+ 'read_only': False,
+ 'label': 'Choice field',
+ 'choices': [
+ {'display_name': 'red', 'value': 'red'},
+ {'display_name': 'green', 'value': 'green'},
+ {'display_name': 'blue', 'value': 'blue'}
+ ]
+ },
+ 'integer_field': {
+ 'type': 'integer',
+ 'required': True,
+ 'read_only': False,
+ 'label': 'Integer field'
+ },
+ 'char_field': {
+ 'type': 'string',
+ 'required': False,
+ 'read_only': False,
+ 'label': 'Char field'
+ }
+ }
+ }
+ }
+ assert response.status_code == 200
+ assert response.data == expected
+
+ def test_global_permissions(self):
+ """
+ If a user does not have global permissions on an action, then any
+ metadata associated with it should not be included in OPTION responses.
+ """
+ class ExampleSerializer(serializers.Serializer):
+ choice_field = serializers.ChoiceField(['red', 'green', 'blue'])
+ integer_field = serializers.IntegerField(max_value=10)
+ char_field = serializers.CharField(required=False)
+
+ class ExampleView(views.APIView):
+ """Example view."""
+ def post(self, request):
+ pass
+
+ def put(self, request):
+ pass
+
+ def get_serializer(self):
+ return ExampleSerializer()
+
+ def check_permissions(self, request):
+ if request.method == 'POST':
+ raise exceptions.PermissionDenied()
+
+ response = ExampleView().options(request=request)
+ assert response.status_code == 200
+ assert list(response.data['actions'].keys()) == ['PUT']
+
+ def test_object_permissions(self):
+ """
+ If a user does not have object permissions on an action, then any
+ metadata associated with it should not be included in OPTION responses.
+ """
+ class ExampleSerializer(serializers.Serializer):
+ choice_field = serializers.ChoiceField(['red', 'green', 'blue'])
+ integer_field = serializers.IntegerField(max_value=10)
+ char_field = serializers.CharField(required=False)
+
+ class ExampleView(views.APIView):
+ """Example view."""
+ def post(self, request):
+ pass
+
+ def put(self, request):
+ pass
+
+ def get_serializer(self):
+ return ExampleSerializer()
+
+ def get_object(self):
+ if self.request.method == 'PUT':
+ raise exceptions.PermissionDenied()
+
+ response = ExampleView().options(request=request)
+ assert response.status_code == 200
+ assert list(response.data['actions'].keys()) == ['POST']
diff --git a/tests/test_model_serializer.py b/tests/test_model_serializer.py
index ec922b6d..3aec0da0 100644
--- a/tests/test_model_serializer.py
+++ b/tests/test_model_serializer.py
@@ -6,6 +6,7 @@ These tests deal with ensuring that we correctly map the model fields onto
an appropriate set of serializer fields for each case.
"""
from django.core.exceptions import ImproperlyConfigured
+from django.core.validators import MaxValueValidator, MinValueValidator, MinLengthValidator
from django.db import models
from django.test import TestCase
from rest_framework import serializers
@@ -15,7 +16,8 @@ def dedent(blocktext):
return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]])
-# Testing regular field mappings
+# Tests for regular field mappings.
+# ---------------------------------
class CustomField(models.Field):
"""
@@ -32,7 +34,7 @@ class RegularFieldsModel(models.Model):
big_integer_field = models.BigIntegerField()
boolean_field = models.BooleanField(default=False)
char_field = models.CharField(max_length=100)
- comma_seperated_integer_field = models.CommaSeparatedIntegerField(max_length=100)
+ comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=100)
date_field = models.DateField()
datetime_field = models.DateTimeField()
decimal_field = models.DecimalField(max_digits=3, decimal_places=1)
@@ -53,6 +55,19 @@ class RegularFieldsModel(models.Model):
return 'method'
+COLOR_CHOICES = (('red', 'Red'), ('blue', 'Blue'), ('green', 'Green'))
+
+
+class FieldOptionsModel(models.Model):
+ value_limit_field = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(10)])
+ length_limit_field = models.CharField(validators=[MinLengthValidator(3)], max_length=12)
+ blank_field = models.CharField(blank=True, max_length=10)
+ null_field = models.IntegerField(null=True)
+ default_field = models.IntegerField(default=0)
+ descriptive_field = models.IntegerField(help_text='Some help text', verbose_name='A label')
+ choices_field = models.CharField(max_length=100, choices=COLOR_CHOICES)
+
+
class TestRegularFieldMappings(TestCase):
def test_regular_fields(self):
"""
@@ -66,27 +81,45 @@ class TestRegularFieldMappings(TestCase):
TestSerializer():
auto_field = IntegerField(read_only=True)
big_integer_field = IntegerField()
- boolean_field = BooleanField(default=False)
+ boolean_field = BooleanField(required=False)
char_field = CharField(max_length=100)
- comma_seperated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>])
+ comma_separated_integer_field = CharField(max_length=100, validators=[<django.core.validators.RegexValidator object>])
date_field = DateField()
datetime_field = DateTimeField()
decimal_field = DecimalField(decimal_places=1, max_digits=3)
email_field = EmailField(max_length=100)
float_field = FloatField()
integer_field = IntegerField()
- null_boolean_field = BooleanField(required=False)
+ null_boolean_field = NullBooleanField(required=False)
positive_integer_field = IntegerField()
positive_small_integer_field = IntegerField()
slug_field = SlugField(max_length=100)
small_integer_field = IntegerField()
- text_field = CharField()
+ text_field = CharField(style={'type': 'textarea'})
time_field = TimeField()
url_field = URLField(max_length=100)
custom_field = ModelField(model_field=<tests.test_model_serializer.CustomField: custom_field>)
""")
self.assertEqual(repr(TestSerializer()), expected)
+ def test_field_options(self):
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = FieldOptionsModel
+
+ expected = dedent("""
+ TestSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ value_limit_field = IntegerField(max_value=10, min_value=1)
+ length_limit_field = CharField(max_length=12, min_length=3)
+ blank_field = CharField(allow_blank=True, max_length=10, required=False)
+ null_field = IntegerField(allow_null=True, required=False)
+ default_field = IntegerField(required=False)
+ descriptive_field = IntegerField(help_text='Some help text', label='A label')
+ choices_field = ChoiceField(choices=[('red', 'Red'), ('blue', 'Blue'), ('green', 'Green')])
+ """)
+ self.assertEqual(repr(TestSerializer()), expected)
+
def test_method_field(self):
"""
Properties and methods on the model should be allowed as `Meta.fields`
@@ -148,7 +181,7 @@ class TestRegularFieldMappings(TestCase):
fields = ('auto_field', 'invalid')
with self.assertRaises(ImproperlyConfigured) as excinfo:
- TestSerializer()
+ TestSerializer().fields
expected = 'Field name `invalid` is not valid for model `ModelBase`.'
assert str(excinfo.exception) == expected
@@ -165,7 +198,7 @@ class TestRegularFieldMappings(TestCase):
fields = ('auto_field',)
with self.assertRaises(ImproperlyConfigured) as excinfo:
- TestSerializer()
+ TestSerializer().fields
expected = (
'Field `missing` has been declared on serializer '
'`TestSerializer`, but is missing from `Meta.fields`.'
@@ -173,7 +206,8 @@ class TestRegularFieldMappings(TestCase):
assert str(excinfo.exception) == expected
-# Testing relational field mappings
+# Tests for relational field mappings.
+# ------------------------------------
class ForeignKeyTargetModel(models.Model):
name = models.CharField(max_length=100)
@@ -214,7 +248,7 @@ class TestRelationalFieldMappings(TestCase):
TestSerializer():
id = IntegerField(label='ID', read_only=True)
foreign_key = PrimaryKeyRelatedField(queryset=ForeignKeyTargetModel.objects.all())
- one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all())
+ one_to_one = PrimaryKeyRelatedField(queryset=OneToOneTargetModel.objects.all(), validators=[<UniqueValidator(queryset=RelationalModel.objects.all())>])
many_to_many = PrimaryKeyRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all())
through = PrimaryKeyRelatedField(many=True, read_only=True)
""")
@@ -253,7 +287,7 @@ class TestRelationalFieldMappings(TestCase):
TestSerializer():
url = HyperlinkedIdentityField(view_name='relationalmodel-detail')
foreign_key = HyperlinkedRelatedField(queryset=ForeignKeyTargetModel.objects.all(), view_name='foreignkeytargetmodel-detail')
- one_to_one = HyperlinkedRelatedField(queryset=OneToOneTargetModel.objects.all(), view_name='onetoonetargetmodel-detail')
+ one_to_one = HyperlinkedRelatedField(queryset=OneToOneTargetModel.objects.all(), validators=[<UniqueValidator(queryset=RelationalModel.objects.all())>], view_name='onetoonetargetmodel-detail')
many_to_many = HyperlinkedRelatedField(many=True, queryset=ManyToManyTargetModel.objects.all(), view_name='manytomanytargetmodel-detail')
through = HyperlinkedRelatedField(many=True, read_only=True, view_name='throughtargetmodel-detail')
""")
@@ -468,3 +502,36 @@ class TestIntegration(TestCase):
'through': []
}
self.assertEqual(serializer.data, expected)
+
+
+# Tests for bulk create using `ListSerializer`.
+
+class BulkCreateModel(models.Model):
+ name = models.CharField(max_length=10)
+
+
+class TestBulkCreate(TestCase):
+ def test_bulk_create(self):
+ class BasicModelSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = BulkCreateModel
+ fields = ('name',)
+
+ class BulkCreateSerializer(serializers.ListSerializer):
+ child = BasicModelSerializer()
+
+ data = [{'name': 'a'}, {'name': 'b'}, {'name': 'c'}]
+ serializer = BulkCreateSerializer(data=data)
+ assert serializer.is_valid()
+
+ # Objects are returned by save().
+ instances = serializer.save()
+ assert len(instances) == 3
+ assert [item.name for item in instances] == ['a', 'b', 'c']
+
+ # Objects have been created in the database.
+ assert BulkCreateModel.objects.count() == 3
+ assert list(BulkCreateModel.objects.values_list('name', flat=True)) == ['a', 'b', 'c']
+
+ # Serializer returns correct data.
+ assert serializer.data == data
diff --git a/tests/test_modelinfo.py b/tests/test_modelinfo.py
deleted file mode 100644
index 04b67f04..00000000
--- a/tests/test_modelinfo.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from django.test import TestCase
-from django.utils import six
-from rest_framework.utils.model_meta import _resolve_model
-from tests.models import BasicModel
-
-
-class ResolveModelTests(TestCase):
- """
- `_resolve_model` should return a Django model class given the
- provided argument is a Django model class itself, or a properly
- formatted string representation of one.
- """
- def test_resolve_django_model(self):
- resolved_model = _resolve_model(BasicModel)
- self.assertEqual(resolved_model, BasicModel)
-
- def test_resolve_string_representation(self):
- resolved_model = _resolve_model('tests.BasicModel')
- self.assertEqual(resolved_model, BasicModel)
-
- def test_resolve_unicode_representation(self):
- resolved_model = _resolve_model(six.text_type('tests.BasicModel'))
- self.assertEqual(resolved_model, BasicModel)
-
- def test_resolve_non_django_model(self):
- with self.assertRaises(ValueError):
- _resolve_model(TestCase)
-
- def test_resolve_improper_string_representation(self):
- with self.assertRaises(ValueError):
- _resolve_model('BasicModel')
diff --git a/tests/test_nullable_fields.py b/tests/test_nullable_fields.py
deleted file mode 100644
index 9843182a..00000000
--- a/tests/test_nullable_fields.py
+++ /dev/null
@@ -1,39 +0,0 @@
-# from django.core.urlresolvers import reverse
-
-# from django.conf.urls import patterns, url
-# from rest_framework import serializers, generics
-# from rest_framework.test import APITestCase
-# from tests.models import NullableForeignKeySource
-
-
-# class NullableFKSourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = NullableForeignKeySource
-
-
-# class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView):
-# queryset = NullableForeignKeySource.objects.all()
-# serializer_class = NullableFKSourceSerializer
-
-
-# urlpatterns = patterns(
-# '',
-# url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'),
-# )
-
-
-# class NullableForeignKeyTests(APITestCase):
-# """
-# DRF should be able to handle nullable foreign keys when a test
-# Client POST/PUT request is made with its own serialized object.
-# """
-# urls = 'tests.test_nullable_fields'
-
-# def test_updating_object_with_null_fk(self):
-# obj = NullableForeignKeySource(name='example', target=None)
-# obj.save()
-# serialized_data = NullableFKSourceSerializer(obj).data
-
-# response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data)
-
-# self.assertEqual(response.data, serialized_data)
diff --git a/tests/test_permissions.py b/tests/test_permissions.py
index ac398f80..97bac33d 100644
--- a/tests/test_permissions.py
+++ b/tests/test_permissions.py
@@ -95,59 +95,59 @@ class ModelPermissionsIntegrationTests(TestCase):
response = instance_view(request, pk=1)
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- # def test_options_permitted(self):
- # request = factory.options(
- # '/',
- # HTTP_AUTHORIZATION=self.permitted_credentials
- # )
- # response = root_view(request, pk='1')
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertIn('actions', response.data)
- # self.assertEqual(list(response.data['actions'].keys()), ['POST'])
-
- # request = factory.options(
- # '/1',
- # HTTP_AUTHORIZATION=self.permitted_credentials
- # )
- # response = instance_view(request, pk='1')
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertIn('actions', response.data)
- # self.assertEqual(list(response.data['actions'].keys()), ['PUT'])
-
- # def test_options_disallowed(self):
- # request = factory.options(
- # '/',
- # HTTP_AUTHORIZATION=self.disallowed_credentials
- # )
- # response = root_view(request, pk='1')
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertNotIn('actions', response.data)
-
- # request = factory.options(
- # '/1',
- # HTTP_AUTHORIZATION=self.disallowed_credentials
- # )
- # response = instance_view(request, pk='1')
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertNotIn('actions', response.data)
-
- # def test_options_updateonly(self):
- # request = factory.options(
- # '/',
- # HTTP_AUTHORIZATION=self.updateonly_credentials
- # )
- # response = root_view(request, pk='1')
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertNotIn('actions', response.data)
-
- # request = factory.options(
- # '/1',
- # HTTP_AUTHORIZATION=self.updateonly_credentials
- # )
- # response = instance_view(request, pk='1')
- # self.assertEqual(response.status_code, status.HTTP_200_OK)
- # self.assertIn('actions', response.data)
- # self.assertEqual(list(response.data['actions'].keys()), ['PUT'])
+ def test_options_permitted(self):
+ request = factory.options(
+ '/',
+ HTTP_AUTHORIZATION=self.permitted_credentials
+ )
+ response = root_view(request, pk='1')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn('actions', response.data)
+ self.assertEqual(list(response.data['actions'].keys()), ['POST'])
+
+ request = factory.options(
+ '/1',
+ HTTP_AUTHORIZATION=self.permitted_credentials
+ )
+ response = instance_view(request, pk='1')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn('actions', response.data)
+ self.assertEqual(list(response.data['actions'].keys()), ['PUT'])
+
+ def test_options_disallowed(self):
+ request = factory.options(
+ '/',
+ HTTP_AUTHORIZATION=self.disallowed_credentials
+ )
+ response = root_view(request, pk='1')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn('actions', response.data)
+
+ request = factory.options(
+ '/1',
+ HTTP_AUTHORIZATION=self.disallowed_credentials
+ )
+ response = instance_view(request, pk='1')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn('actions', response.data)
+
+ def test_options_updateonly(self):
+ request = factory.options(
+ '/',
+ HTTP_AUTHORIZATION=self.updateonly_credentials
+ )
+ response = root_view(request, pk='1')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertNotIn('actions', response.data)
+
+ request = factory.options(
+ '/1',
+ HTTP_AUTHORIZATION=self.updateonly_credentials
+ )
+ response = instance_view(request, pk='1')
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertIn('actions', response.data)
+ self.assertEqual(list(response.data['actions'].keys()), ['PUT'])
class BasicPermModel(models.Model):
diff --git a/tests/test_relations.py b/tests/test_relations.py
index c29618ce..62353dc2 100644
--- a/tests/test_relations.py
+++ b/tests/test_relations.py
@@ -1,5 +1,5 @@
from .utils import mock_reverse, fail_reverse, BadType, MockObject, MockQueryset
-from django.core.exceptions import ImproperlyConfigured, ValidationError
+from django.core.exceptions import ImproperlyConfigured
from rest_framework import serializers
from rest_framework.test import APISimpleTestCase
import pytest
@@ -30,15 +30,15 @@ class TestPrimaryKeyRelatedField(APISimpleTestCase):
assert instance is self.instance
def test_pk_related_lookup_does_not_exist(self):
- with pytest.raises(ValidationError) as excinfo:
+ with pytest.raises(serializers.ValidationError) as excinfo:
self.field.to_internal_value(4)
- msg = excinfo.value.messages[0]
+ msg = excinfo.value.detail[0]
assert msg == "Invalid pk '4' - object does not exist."
def test_pk_related_lookup_invalid_type(self):
- with pytest.raises(ValidationError) as excinfo:
+ with pytest.raises(serializers.ValidationError) as excinfo:
self.field.to_internal_value(BadType())
- msg = excinfo.value.messages[0]
+ msg = excinfo.value.detail[0]
assert msg == 'Incorrect type. Expected pk value, received BadType.'
def test_pk_representation(self):
@@ -51,7 +51,7 @@ class TestHyperlinkedIdentityField(APISimpleTestCase):
self.instance = MockObject(pk=1, name='foo')
self.field = serializers.HyperlinkedIdentityField(view_name='example')
self.field.reverse = mock_reverse
- self.field.context = {'request': True}
+ self.field._context = {'request': True}
def test_representation(self):
representation = self.field.to_representation(self.instance)
@@ -62,7 +62,7 @@ class TestHyperlinkedIdentityField(APISimpleTestCase):
assert representation is None
def test_representation_with_format(self):
- self.field.context['format'] = 'xml'
+ self.field._context['format'] = 'xml'
representation = self.field.to_representation(self.instance)
assert representation == 'http://example.org/example/1.xml/'
@@ -91,14 +91,14 @@ class TestHyperlinkedIdentityFieldWithFormat(APISimpleTestCase):
self.instance = MockObject(pk=1, name='foo')
self.field = serializers.HyperlinkedIdentityField(view_name='example', format='json')
self.field.reverse = mock_reverse
- self.field.context = {'request': True}
+ self.field._context = {'request': True}
def test_representation(self):
representation = self.field.to_representation(self.instance)
assert representation == 'http://example.org/example/1/'
def test_representation_with_format(self):
- self.field.context['format'] = 'xml'
+ self.field._context['format'] = 'xml'
representation = self.field.to_representation(self.instance)
assert representation == 'http://example.org/example/1.json/'
@@ -120,169 +120,17 @@ class TestSlugRelatedField(APISimpleTestCase):
assert instance is self.instance
def test_slug_related_lookup_does_not_exist(self):
- with pytest.raises(ValidationError) as excinfo:
+ with pytest.raises(serializers.ValidationError) as excinfo:
self.field.to_internal_value('doesnotexist')
- msg = excinfo.value.messages[0]
+ msg = excinfo.value.detail[0]
assert msg == 'Object with name=doesnotexist does not exist.'
def test_slug_related_lookup_invalid_type(self):
- with pytest.raises(ValidationError) as excinfo:
+ with pytest.raises(serializers.ValidationError) as excinfo:
self.field.to_internal_value(BadType())
- msg = excinfo.value.messages[0]
+ msg = excinfo.value.detail[0]
assert msg == 'Invalid value.'
def test_representation(self):
representation = self.field.to_representation(self.instance)
assert representation == self.instance.name
-
-# Older tests, for review...
-
-# """
-# General tests for relational fields.
-# """
-# from __future__ import unicode_literals
-# from django import get_version
-# from django.db import models
-# from django.test import TestCase
-# from django.utils import unittest
-# from rest_framework import serializers
-# from tests.models import BlogPost
-
-
-# class NullModel(models.Model):
-# pass
-
-
-# class FieldTests(TestCase):
-# def test_pk_related_field_with_empty_string(self):
-# """
-# Regression test for #446
-
-# https://github.com/tomchristie/django-rest-framework/issues/446
-# """
-# field = serializers.PrimaryKeyRelatedField(queryset=NullModel.objects.all())
-# self.assertRaises(serializers.ValidationError, field.to_primative, '')
-# self.assertRaises(serializers.ValidationError, field.to_primative, [])
-
-# def test_hyperlinked_related_field_with_empty_string(self):
-# field = serializers.HyperlinkedRelatedField(queryset=NullModel.objects.all(), view_name='')
-# self.assertRaises(serializers.ValidationError, field.to_primative, '')
-# self.assertRaises(serializers.ValidationError, field.to_primative, [])
-
-# def test_slug_related_field_with_empty_string(self):
-# field = serializers.SlugRelatedField(queryset=NullModel.objects.all(), slug_field='pk')
-# self.assertRaises(serializers.ValidationError, field.to_primative, '')
-# self.assertRaises(serializers.ValidationError, field.to_primative, [])
-
-
-# class TestManyRelatedMixin(TestCase):
-# def test_missing_many_to_many_related_field(self):
-# '''
-# Regression test for #632
-
-# https://github.com/tomchristie/django-rest-framework/pull/632
-# '''
-# field = serializers.RelatedField(many=True, read_only=False)
-
-# into = {}
-# field.field_from_native({}, None, 'field_name', into)
-# self.assertEqual(into['field_name'], [])
-
-
-# # Regression tests for #694 (`source` attribute on related fields)
-
-# class RelatedFieldSourceTests(TestCase):
-# def test_related_manager_source(self):
-# """
-# Relational fields should be able to use manager-returning methods as their source.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.RelatedField(many=True, source='get_blogposts_manager')
-
-# class ClassWithManagerMethod(object):
-# def get_blogposts_manager(self):
-# return BlogPost.objects
-
-# obj = ClassWithManagerMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, ['BlogPost object'])
-
-# def test_related_queryset_source(self):
-# """
-# Relational fields should be able to use queryset-returning methods as their source.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.RelatedField(many=True, source='get_blogposts_queryset')
-
-# class ClassWithQuerysetMethod(object):
-# def get_blogposts_queryset(self):
-# return BlogPost.objects.all()
-
-# obj = ClassWithQuerysetMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, ['BlogPost object'])
-
-# def test_dotted_source(self):
-# """
-# Source argument should support dotted.source notation.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.RelatedField(many=True, source='a.b.c')
-
-# class ClassWithQuerysetMethod(object):
-# a = {
-# 'b': {
-# 'c': BlogPost.objects.all()
-# }
-# }
-
-# obj = ClassWithQuerysetMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, ['BlogPost object'])
-
-# # Regression for #1129
-# def test_exception_for_incorect_fk(self):
-# """
-# Check that the exception message are correct if the source field
-# doesn't exist.
-# """
-# from tests.models import ManyToManySource
-
-# class Meta:
-# model = ManyToManySource
-
-# attrs = {
-# 'name': serializers.SlugRelatedField(
-# slug_field='name', source='banzai'),
-# 'Meta': Meta,
-# }
-
-# TestSerializer = type(
-# str('TestSerializer'),
-# (serializers.ModelSerializer,),
-# attrs
-# )
-# with self.assertRaises(AttributeError):
-# TestSerializer(data={'name': 'foo'})
-
-
-# @unittest.skipIf(get_version() < '1.6.0', 'Upstream behaviour changed in v1.6')
-# class RelatedFieldChoicesTests(TestCase):
-# """
-# Tests for #1408 "Web browseable API doesn't have blank option on drop down list box"
-# https://github.com/tomchristie/django-rest-framework/issues/1408
-# """
-# def test_blank_option_is_added_to_choice_if_required_equals_false(self):
-# """
-
-# """
-# post = BlogPost(title="Checking blank option is added")
-# post.save()
-
-# queryset = BlogPost.objects.all()
-# field = serializers.RelatedField(required=False, queryset=queryset)
-
-# choice_count = BlogPost.objects.count()
-# widget_count = len(field.widget.choices)
-
-# self.assertEqual(widget_count, choice_count + 1, 'BLANK_CHOICE_DASH option should have been added')
diff --git a/tests/test_relations_generic.py b/tests/test_relations_generic.py
new file mode 100644
index 00000000..380ad91d
--- /dev/null
+++ b/tests/test_relations_generic.py
@@ -0,0 +1,104 @@
+from __future__ import unicode_literals
+from django.contrib.contenttypes.models import ContentType
+from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey
+from django.db import models
+from django.test import TestCase
+from rest_framework import serializers
+from rest_framework.compat import python_2_unicode_compatible
+
+
+@python_2_unicode_compatible
+class Tag(models.Model):
+ """
+ Tags have a descriptive slug, and are attached to an arbitrary object.
+ """
+ tag = models.SlugField()
+ content_type = models.ForeignKey(ContentType)
+ object_id = models.PositiveIntegerField()
+ tagged_item = GenericForeignKey('content_type', 'object_id')
+
+ def __str__(self):
+ return self.tag
+
+
+@python_2_unicode_compatible
+class Bookmark(models.Model):
+ """
+ A URL bookmark that may have multiple tags attached.
+ """
+ url = models.URLField()
+ tags = GenericRelation(Tag)
+
+ def __str__(self):
+ return 'Bookmark: %s' % self.url
+
+
+@python_2_unicode_compatible
+class Note(models.Model):
+ """
+ A textual note that may have multiple tags attached.
+ """
+ text = models.TextField()
+ tags = GenericRelation(Tag)
+
+ def __str__(self):
+ return 'Note: %s' % self.text
+
+
+class TestGenericRelations(TestCase):
+ def setUp(self):
+ self.bookmark = Bookmark.objects.create(url='https://www.djangoproject.com/')
+ Tag.objects.create(tagged_item=self.bookmark, tag='django')
+ Tag.objects.create(tagged_item=self.bookmark, tag='python')
+ self.note = Note.objects.create(text='Remember the milk')
+ Tag.objects.create(tagged_item=self.note, tag='reminder')
+
+ def test_generic_relation(self):
+ """
+ Test a relationship that spans a GenericRelation field.
+ IE. A reverse generic relationship.
+ """
+
+ class BookmarkSerializer(serializers.ModelSerializer):
+ tags = serializers.StringRelatedField(many=True)
+
+ class Meta:
+ model = Bookmark
+ fields = ('tags', 'url')
+
+ serializer = BookmarkSerializer(self.bookmark)
+ expected = {
+ 'tags': ['django', 'python'],
+ 'url': 'https://www.djangoproject.com/'
+ }
+ self.assertEqual(serializer.data, expected)
+
+ def test_generic_fk(self):
+ """
+ Test a relationship that spans a GenericForeignKey field.
+ IE. A forward generic relationship.
+ """
+
+ class TagSerializer(serializers.ModelSerializer):
+ tagged_item = serializers.StringRelatedField()
+
+ class Meta:
+ model = Tag
+ fields = ('tag', 'tagged_item')
+
+ serializer = TagSerializer(Tag.objects.all(), many=True)
+ expected = [
+ {
+ 'tag': 'django',
+ 'tagged_item': 'Bookmark: https://www.djangoproject.com/'
+ },
+ {
+ 'tag': 'python',
+ 'tagged_item': 'Bookmark: https://www.djangoproject.com/'
+ },
+ {
+ 'tag': 'reminder',
+ 'tagged_item': 'Note: Remember the milk'
+ }
+ ]
+ self.assertEqual(serializer.data, expected)
diff --git a/tests/test_relations_hyperlink.py b/tests/test_relations_hyperlink.py
index 315d1abf..b938e385 100644
--- a/tests/test_relations_hyperlink.py
+++ b/tests/test_relations_hyperlink.py
@@ -1,525 +1,433 @@
-# from __future__ import unicode_literals
-# from django.conf.urls import patterns, url
-# from django.test import TestCase
-# from rest_framework import serializers
-# from rest_framework.test import APIRequestFactory
-# from tests.models import (
-# BlogPost,
-# ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource,
-# NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
-# )
-
-# factory = APIRequestFactory()
-# request = factory.get('/') # Just to ensure we have a request in the serializer context
-
-
-# def dummy_view(request, pk):
-# pass
-
-# urlpatterns = patterns(
-# '',
-# url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'),
-# url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'),
-# url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'),
-# url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'),
-# url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'),
-# url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'),
-# url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'),
-# url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'),
-# )
-
-
-# # ManyToMany
-# class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = ManyToManyTarget
-# fields = ('url', 'name', 'sources')
-
-
-# class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = ManyToManySource
-# fields = ('url', 'name', 'targets')
-
-
-# # ForeignKey
-# class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = ForeignKeyTarget
-# fields = ('url', 'name', 'sources')
-
-
-# class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = ForeignKeySource
-# fields = ('url', 'name', 'target')
-
-
-# # Nullable ForeignKey
-# class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = NullableForeignKeySource
-# fields = ('url', 'name', 'target')
-
-
-# # Nullable OneToOne
-# class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = OneToOneTarget
-# fields = ('url', 'name', 'nullable_source')
-
-
-# # TODO: Add test that .data cannot be accessed prior to .is_valid
-
-# class HyperlinkedManyToManyTests(TestCase):
-# urls = 'tests.test_relations_hyperlink'
-
-# def setUp(self):
-# for idx in range(1, 4):
-# target = ManyToManyTarget(name='target-%d' % idx)
-# target.save()
-# source = ManyToManySource(name='source-%d' % idx)
-# source.save()
-# for target in ManyToManyTarget.objects.all():
-# source.targets.add(target)
-
-# def test_many_to_many_retrieve(self):
-# queryset = ManyToManySource.objects.all()
-# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
-# {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
-# {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_many_to_many_retrieve(self):
-# queryset = ManyToManyTarget.objects.all()
-# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
-# {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
-# {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_many_to_many_update(self):
-# data = {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
-# instance = ManyToManySource.objects.get(pk=1)
-# serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-# self.assertEqual(serializer.data, data)
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = ManyToManySource.objects.all()
-# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
-# {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
-# {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_many_to_many_update(self):
-# data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}
-# instance = ManyToManyTarget.objects.get(pk=1)
-# serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-# self.assertEqual(serializer.data, data)
-
-# # Ensure target 1 is updated, and everything else is as expected
-# queryset = ManyToManyTarget.objects.all()
-# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']},
-# {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
-# {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
-
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_many_to_many_create(self):
-# data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
-# serializer = ManyToManySourceSerializer(data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is added, and everything else is as expected
-# queryset = ManyToManySource.objects.all()
-# serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
-# {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
-# {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
-# {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_many_to_many_create(self):
-# data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
-# serializer = ManyToManyTargetSerializer(data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-4')
-
-# # Ensure target 4 is added, and everything else is as expected
-# queryset = ManyToManyTarget.objects.all()
-# serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
-# {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
-# {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']},
-# {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-
-# class HyperlinkedForeignKeyTests(TestCase):
-# urls = 'tests.test_relations_hyperlink'
-
-# def setUp(self):
-# target = ForeignKeyTarget(name='target-1')
-# target.save()
-# new_target = ForeignKeyTarget(name='target-2')
-# new_target.save()
-# for idx in range(1, 4):
-# source = ForeignKeySource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_foreign_key_retrieve(self):
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_foreign_key_retrieve(self):
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/2/', 'http://testserver/foreignkeysource/3/']},
-# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update(self):
-# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'},
-# {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_incorrect_type(self):
-# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 2}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected url string, received int.']})
-
-# def test_reverse_foreign_key_update(self):
-# data = {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}
-# instance = ForeignKeyTarget.objects.get(pk=2)
-# serializer = ForeignKeyTargetSerializer(instance, data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# # We shouldn't have saved anything to the db yet since save
-# # hasn't been called.
-# queryset = ForeignKeyTarget.objects.all()
-# new_serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/2/', 'http://testserver/foreignkeysource/3/']},
-# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
-# ]
-# self.assertEqual(new_serializer.data, expected)
-
-# serializer.save()
-# self.assertEqual(serializer.data, data)
-
-# # Ensure target 2 is update, and everything else is as expected
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']},
-# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create(self):
-# data = {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'}
-# serializer = ForeignKeySourceSerializer(data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_foreign_key_create(self):
-# data = {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}
-# serializer = ForeignKeyTargetSerializer(data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-3')
-
-# # Ensure target 4 is added, and everything else is as expected
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']},
-# {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
-# {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_invalid_null(self):
-# data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': None}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'target': ['This field is required.']})
-
-
-# class HyperlinkedNullableForeignKeyTests(TestCase):
-# urls = 'tests.test_relations_hyperlink'
-
-# def setUp(self):
-# target = ForeignKeyTarget(name='target-1')
-# target.save()
-# for idx in range(1, 4):
-# if idx == 3:
-# target = None
-# source = NullableForeignKeySource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_foreign_key_retrieve_with_null(self):
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create_with_valid_null(self):
-# data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
-# serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is created, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
-# {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create_with_valid_emptystring(self):
-# """
-# The emptystring should be interpreted as null in the context
-# of relationships.
-# """
-# data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''}
-# expected_data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
-# serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, expected_data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is created, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
-# {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_valid_null(self):
-# data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}
-# instance = NullableForeignKeySource.objects.get(pk=1)
-# serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None},
-# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_valid_emptystring(self):
-# """
-# The emptystring should be interpreted as null in the context
-# of relationships.
-# """
-# data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''}
-# expected_data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}
-# instance = NullableForeignKeySource.objects.get(pk=1)
-# serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request})
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, expected_data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None},
-# {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
-# {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# # reverse foreign keys MUST be read_only
-# # In the general case they do not provide .remove() or .clear()
-# # and cannot be arbitrarily set.
-
-# # def test_reverse_foreign_key_update(self):
-# # data = {'id': 1, 'name': 'target-1', 'sources': [1]}
-# # instance = ForeignKeyTarget.objects.get(pk=1)
-# # serializer = ForeignKeyTargetSerializer(instance, data=data)
-# # self.assertTrue(serializer.is_valid())
-# # self.assertEqual(serializer.data, data)
-# # serializer.save()
-
-# # # Ensure target 1 is updated, and everything else is as expected
-# # queryset = ForeignKeyTarget.objects.all()
-# # serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# # expected = [
-# # {'id': 1, 'name': 'target-1', 'sources': [1]},
-# # {'id': 2, 'name': 'target-2', 'sources': []},
-# # ]
-# # self.assertEqual(serializer.data, expected)
-
-
-# class HyperlinkedNullableOneToOneTests(TestCase):
-# urls = 'tests.test_relations_hyperlink'
-
-# def setUp(self):
-# target = OneToOneTarget(name='target-1')
-# target.save()
-# new_target = OneToOneTarget(name='target-2')
-# new_target.save()
-# source = NullableOneToOneSource(name='source-1', target=target)
-# source.save()
-
-# def test_reverse_foreign_key_retrieve_with_null(self):
-# queryset = OneToOneTarget.objects.all()
-# serializer = NullableOneToOneTargetSerializer(queryset, many=True, context={'request': request})
-# expected = [
-# {'url': 'http://testserver/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': 'http://testserver/nullableonetoonesource/1/'},
-# {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-
-# # Regression tests for #694 (`source` attribute on related fields)
-
-# class HyperlinkedRelatedFieldSourceTests(TestCase):
-# urls = 'tests.test_relations_hyperlink'
-
-# def test_related_manager_source(self):
-# """
-# Relational fields should be able to use manager-returning methods as their source.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.HyperlinkedRelatedField(
-# many=True,
-# source='get_blogposts_manager',
-# view_name='dummy-url',
-# )
-# field.context = {'request': request}
-
-# class ClassWithManagerMethod(object):
-# def get_blogposts_manager(self):
-# return BlogPost.objects
-
-# obj = ClassWithManagerMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, ['http://testserver/dummyurl/1/'])
-
-# def test_related_queryset_source(self):
-# """
-# Relational fields should be able to use queryset-returning methods as their source.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.HyperlinkedRelatedField(
-# many=True,
-# source='get_blogposts_queryset',
-# view_name='dummy-url',
-# )
-# field.context = {'request': request}
-
-# class ClassWithQuerysetMethod(object):
-# def get_blogposts_queryset(self):
-# return BlogPost.objects.all()
-
-# obj = ClassWithQuerysetMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, ['http://testserver/dummyurl/1/'])
-
-# def test_dotted_source(self):
-# """
-# Source argument should support dotted.source notation.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.HyperlinkedRelatedField(
-# many=True,
-# source='a.b.c',
-# view_name='dummy-url',
-# )
-# field.context = {'request': request}
-
-# class ClassWithQuerysetMethod(object):
-# a = {
-# 'b': {
-# 'c': BlogPost.objects.all()
-# }
-# }
-
-# obj = ClassWithQuerysetMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, ['http://testserver/dummyurl/1/'])
+from __future__ import unicode_literals
+from django.conf.urls import patterns, url
+from django.test import TestCase
+from rest_framework import serializers
+from rest_framework.test import APIRequestFactory
+from tests.models import (
+ ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource,
+ NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource
+)
+
+factory = APIRequestFactory()
+request = factory.get('/') # Just to ensure we have a request in the serializer context
+
+
+dummy_view = lambda request, pk: None
+
+urlpatterns = patterns(
+ '',
+ url(r'^dummyurl/(?P<pk>[0-9]+)/$', dummy_view, name='dummy-url'),
+ url(r'^manytomanysource/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanysource-detail'),
+ url(r'^manytomanytarget/(?P<pk>[0-9]+)/$', dummy_view, name='manytomanytarget-detail'),
+ url(r'^foreignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeysource-detail'),
+ url(r'^foreignkeytarget/(?P<pk>[0-9]+)/$', dummy_view, name='foreignkeytarget-detail'),
+ url(r'^nullableforeignkeysource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableforeignkeysource-detail'),
+ url(r'^onetoonetarget/(?P<pk>[0-9]+)/$', dummy_view, name='onetoonetarget-detail'),
+ url(r'^nullableonetoonesource/(?P<pk>[0-9]+)/$', dummy_view, name='nullableonetoonesource-detail'),
+)
+
+
+# ManyToMany
+class ManyToManyTargetSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = ManyToManyTarget
+ fields = ('url', 'name', 'sources')
+
+
+class ManyToManySourceSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = ManyToManySource
+ fields = ('url', 'name', 'targets')
+
+
+# ForeignKey
+class ForeignKeyTargetSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = ForeignKeyTarget
+ fields = ('url', 'name', 'sources')
+
+
+class ForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = ForeignKeySource
+ fields = ('url', 'name', 'target')
+
+
+# Nullable ForeignKey
+class NullableForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = NullableForeignKeySource
+ fields = ('url', 'name', 'target')
+
+
+# Nullable OneToOne
+class NullableOneToOneTargetSerializer(serializers.HyperlinkedModelSerializer):
+ class Meta:
+ model = OneToOneTarget
+ fields = ('url', 'name', 'nullable_source')
+
+
+# TODO: Add test that .data cannot be accessed prior to .is_valid
+
+class HyperlinkedManyToManyTests(TestCase):
+ urls = 'tests.test_relations_hyperlink'
+
+ def setUp(self):
+ for idx in range(1, 4):
+ target = ManyToManyTarget(name='target-%d' % idx)
+ target.save()
+ source = ManyToManySource(name='source-%d' % idx)
+ source.save()
+ for target in ManyToManyTarget.objects.all():
+ source.targets.add(target)
+
+ def test_many_to_many_retrieve(self):
+ queryset = ManyToManySource.objects.all()
+ serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
+ {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
+ {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_many_to_many_retrieve(self):
+ queryset = ManyToManyTarget.objects.all()
+ serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
+ {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
+ {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_many_to_many_update(self):
+ data = {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
+ instance = ManyToManySource.objects.get(pk=1)
+ serializer = ManyToManySourceSerializer(instance, data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = ManyToManySource.objects.all()
+ serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
+ {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
+ {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_many_to_many_update(self):
+ data = {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']}
+ instance = ManyToManyTarget.objects.get(pk=1)
+ serializer = ManyToManyTargetSerializer(instance, data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure target 1 is updated, and everything else is as expected
+ queryset = ManyToManyTarget.objects.all()
+ serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/']},
+ {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
+ {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']}
+
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_many_to_many_create(self):
+ data = {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
+ serializer = ManyToManySourceSerializer(data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is added, and everything else is as expected
+ queryset = ManyToManySource.objects.all()
+ serializer = ManyToManySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/manytomanysource/1/', 'name': 'source-1', 'targets': ['http://testserver/manytomanytarget/1/']},
+ {'url': 'http://testserver/manytomanysource/2/', 'name': 'source-2', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/']},
+ {'url': 'http://testserver/manytomanysource/3/', 'name': 'source-3', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/2/', 'http://testserver/manytomanytarget/3/']},
+ {'url': 'http://testserver/manytomanysource/4/', 'name': 'source-4', 'targets': ['http://testserver/manytomanytarget/1/', 'http://testserver/manytomanytarget/3/']}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_many_to_many_create(self):
+ data = {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
+ serializer = ManyToManyTargetSerializer(data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'target-4')
+
+ # Ensure target 4 is added, and everything else is as expected
+ queryset = ManyToManyTarget.objects.all()
+ serializer = ManyToManyTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/manytomanytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
+ {'url': 'http://testserver/manytomanytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/manytomanysource/2/', 'http://testserver/manytomanysource/3/']},
+ {'url': 'http://testserver/manytomanytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/manytomanysource/3/']},
+ {'url': 'http://testserver/manytomanytarget/4/', 'name': 'target-4', 'sources': ['http://testserver/manytomanysource/1/', 'http://testserver/manytomanysource/3/']}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+
+class HyperlinkedForeignKeyTests(TestCase):
+ urls = 'tests.test_relations_hyperlink'
+
+ def setUp(self):
+ target = ForeignKeyTarget(name='target-1')
+ target.save()
+ new_target = ForeignKeyTarget(name='target-2')
+ new_target.save()
+ for idx in range(1, 4):
+ source = ForeignKeySource(name='source-%d' % idx, target=target)
+ source.save()
+
+ def test_foreign_key_retrieve(self):
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_foreign_key_retrieve(self):
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/2/', 'http://testserver/foreignkeysource/3/']},
+ {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update(self):
+ data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/2/'},
+ {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_incorrect_type(self):
+ data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 2}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected URL string, received int.']})
+
+ def test_reverse_foreign_key_update(self):
+ data = {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}
+ instance = ForeignKeyTarget.objects.get(pk=2)
+ serializer = ForeignKeyTargetSerializer(instance, data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ # We shouldn't have saved anything to the db yet since save
+ # hasn't been called.
+ queryset = ForeignKeyTarget.objects.all()
+ new_serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/2/', 'http://testserver/foreignkeysource/3/']},
+ {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
+ ]
+ self.assertEqual(new_serializer.data, expected)
+
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure target 2 is update, and everything else is as expected
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']},
+ {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create(self):
+ data = {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'}
+ serializer = ForeignKeySourceSerializer(data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/foreignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/foreignkeysource/3/', 'name': 'source-3', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/foreignkeysource/4/', 'name': 'source-4', 'target': 'http://testserver/foreignkeytarget/2/'},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_foreign_key_create(self):
+ data = {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']}
+ serializer = ForeignKeyTargetSerializer(data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'target-3')
+
+ # Ensure target 4 is added, and everything else is as expected
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/foreignkeytarget/1/', 'name': 'target-1', 'sources': ['http://testserver/foreignkeysource/2/']},
+ {'url': 'http://testserver/foreignkeytarget/2/', 'name': 'target-2', 'sources': []},
+ {'url': 'http://testserver/foreignkeytarget/3/', 'name': 'target-3', 'sources': ['http://testserver/foreignkeysource/1/', 'http://testserver/foreignkeysource/3/']},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_invalid_null(self):
+ data = {'url': 'http://testserver/foreignkeysource/1/', 'name': 'source-1', 'target': None}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data, context={'request': request})
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(serializer.errors, {'target': ['This field may not be null.']})
+
+
+class HyperlinkedNullableForeignKeyTests(TestCase):
+ urls = 'tests.test_relations_hyperlink'
+
+ def setUp(self):
+ target = ForeignKeyTarget(name='target-1')
+ target.save()
+ for idx in range(1, 4):
+ if idx == 3:
+ target = None
+ source = NullableForeignKeySource(name='source-%d' % idx, target=target)
+ source.save()
+
+ def test_foreign_key_retrieve_with_null(self):
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create_with_valid_null(self):
+ data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
+ serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is created, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
+ {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create_with_valid_emptystring(self):
+ """
+ The emptystring should be interpreted as null in the context
+ of relationships.
+ """
+ data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': ''}
+ expected_data = {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
+ serializer = NullableForeignKeySourceSerializer(data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, expected_data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is created, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
+ {'url': 'http://testserver/nullableforeignkeysource/4/', 'name': 'source-4', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_valid_null(self):
+ data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}
+ instance = NullableForeignKeySource.objects.get(pk=1)
+ serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None},
+ {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_valid_emptystring(self):
+ """
+ The emptystring should be interpreted as null in the context
+ of relationships.
+ """
+ data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': ''}
+ expected_data = {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None}
+ instance = NullableForeignKeySource.objects.get(pk=1)
+ serializer = NullableForeignKeySourceSerializer(instance, data=data, context={'request': request})
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, expected_data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/nullableforeignkeysource/1/', 'name': 'source-1', 'target': None},
+ {'url': 'http://testserver/nullableforeignkeysource/2/', 'name': 'source-2', 'target': 'http://testserver/foreignkeytarget/1/'},
+ {'url': 'http://testserver/nullableforeignkeysource/3/', 'name': 'source-3', 'target': None},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+
+class HyperlinkedNullableOneToOneTests(TestCase):
+ urls = 'tests.test_relations_hyperlink'
+
+ def setUp(self):
+ target = OneToOneTarget(name='target-1')
+ target.save()
+ new_target = OneToOneTarget(name='target-2')
+ new_target.save()
+ source = NullableOneToOneSource(name='source-1', target=target)
+ source.save()
+
+ def test_reverse_foreign_key_retrieve_with_null(self):
+ queryset = OneToOneTarget.objects.all()
+ serializer = NullableOneToOneTargetSerializer(queryset, many=True, context={'request': request})
+ expected = [
+ {'url': 'http://testserver/onetoonetarget/1/', 'name': 'target-1', 'nullable_source': 'http://testserver/nullableonetoonesource/1/'},
+ {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None},
+ ]
+ self.assertEqual(serializer.data, expected)
diff --git a/tests/test_relations_nested.py b/tests/test_relations_nested.py
deleted file mode 100644
index 4a99fee9..00000000
--- a/tests/test_relations_nested.py
+++ /dev/null
@@ -1,326 +0,0 @@
-# from __future__ import unicode_literals
-# from django.db import models
-# from django.test import TestCase
-# from rest_framework import serializers
-
-# from .models import OneToOneTarget
-
-
-# class OneToOneSource(models.Model):
-# name = models.CharField(max_length=100)
-# target = models.OneToOneField(OneToOneTarget, related_name='source',
-# null=True, blank=True)
-
-
-# class OneToManyTarget(models.Model):
-# name = models.CharField(max_length=100)
-
-
-# class OneToManySource(models.Model):
-# name = models.CharField(max_length=100)
-# target = models.ForeignKey(OneToManyTarget, related_name='sources')
-
-
-# class ReverseNestedOneToOneTests(TestCase):
-# def setUp(self):
-# class OneToOneSourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = OneToOneSource
-# fields = ('id', 'name')
-
-# class OneToOneTargetSerializer(serializers.ModelSerializer):
-# source = OneToOneSourceSerializer()
-
-# class Meta:
-# model = OneToOneTarget
-# fields = ('id', 'name', 'source')
-
-# self.Serializer = OneToOneTargetSerializer
-
-# for idx in range(1, 4):
-# target = OneToOneTarget(name='target-%d' % idx)
-# target.save()
-# source = OneToOneSource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_one_to_one_retrieve(self):
-# queryset = OneToOneTarget.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
-# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
-# {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_one_create(self):
-# data = {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}}
-# serializer = self.Serializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-4')
-
-# # Ensure (target 4, target_source 4, source 4) are added, and
-# # everything else is as expected.
-# queryset = OneToOneTarget.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
-# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
-# {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}},
-# {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_one_create_with_invalid_data(self):
-# data = {'id': 4, 'name': 'target-4', 'source': {'id': 4}}
-# serializer = self.Serializer(data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'source': [{'name': ['This field is required.']}]})
-
-# def test_one_to_one_update(self):
-# data = {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}}
-# instance = OneToOneTarget.objects.get(pk=3)
-# serializer = self.Serializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-3-updated')
-
-# # Ensure (target 3, target_source 3, source 3) are updated,
-# # and everything else is as expected.
-# queryset = OneToOneTarget.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
-# {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
-# {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-
-# class ForwardNestedOneToOneTests(TestCase):
-# def setUp(self):
-# class OneToOneTargetSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = OneToOneTarget
-# fields = ('id', 'name')
-
-# class OneToOneSourceSerializer(serializers.ModelSerializer):
-# target = OneToOneTargetSerializer()
-
-# class Meta:
-# model = OneToOneSource
-# fields = ('id', 'name', 'target')
-
-# self.Serializer = OneToOneSourceSerializer
-
-# for idx in range(1, 4):
-# target = OneToOneTarget(name='target-%d' % idx)
-# target.save()
-# source = OneToOneSource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_one_to_one_retrieve(self):
-# queryset = OneToOneSource.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
-# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
-# {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_one_create(self):
-# data = {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}}
-# serializer = self.Serializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure (target 4, target_source 4, source 4) are added, and
-# # everything else is as expected.
-# queryset = OneToOneSource.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
-# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
-# {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}},
-# {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_one_create_with_invalid_data(self):
-# data = {'id': 4, 'name': 'source-4', 'target': {'id': 4}}
-# serializer = self.Serializer(data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'target': [{'name': ['This field is required.']}]})
-
-# def test_one_to_one_update(self):
-# data = {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}}
-# instance = OneToOneSource.objects.get(pk=3)
-# serializer = self.Serializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-3-updated')
-
-# # Ensure (target 3, target_source 3, source 3) are updated,
-# # and everything else is as expected.
-# queryset = OneToOneSource.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
-# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
-# {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_one_update_to_null(self):
-# data = {'id': 3, 'name': 'source-3-updated', 'target': None}
-# instance = OneToOneSource.objects.get(pk=3)
-# serializer = self.Serializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-3-updated')
-# self.assertEqual(obj.target, None)
-
-# queryset = OneToOneSource.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}},
-# {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}},
-# {'id': 3, 'name': 'source-3-updated', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# # TODO: Nullable 1-1 tests
-# # def test_one_to_one_delete(self):
-# # data = {'id': 3, 'name': 'target-3', 'target_source': None}
-# # instance = OneToOneTarget.objects.get(pk=3)
-# # serializer = self.Serializer(instance, data=data)
-# # self.assertTrue(serializer.is_valid())
-# # serializer.save()
-
-# # # Ensure (target_source 3, source 3) are deleted,
-# # # and everything else is as expected.
-# # queryset = OneToOneTarget.objects.all()
-# # serializer = self.Serializer(queryset)
-# # expected = [
-# # {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}},
-# # {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}},
-# # {'id': 3, 'name': 'target-3', 'source': None}
-# # ]
-# # self.assertEqual(serializer.data, expected)
-
-
-# class ReverseNestedOneToManyTests(TestCase):
-# def setUp(self):
-# class OneToManySourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = OneToManySource
-# fields = ('id', 'name')
-
-# class OneToManyTargetSerializer(serializers.ModelSerializer):
-# sources = OneToManySourceSerializer(many=True, allow_add_remove=True)
-
-# class Meta:
-# model = OneToManyTarget
-# fields = ('id', 'name', 'sources')
-
-# self.Serializer = OneToManyTargetSerializer
-
-# target = OneToManyTarget(name='target-1')
-# target.save()
-# for idx in range(1, 4):
-# source = OneToManySource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_one_to_many_retrieve(self):
-# queryset = OneToManyTarget.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
-# {'id': 2, 'name': 'source-2'},
-# {'id': 3, 'name': 'source-3'}]},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_many_create(self):
-# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
-# {'id': 2, 'name': 'source-2'},
-# {'id': 3, 'name': 'source-3'},
-# {'id': 4, 'name': 'source-4'}]}
-# instance = OneToManyTarget.objects.get(pk=1)
-# serializer = self.Serializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-1')
-
-# # Ensure source 4 is added, and everything else is as
-# # expected.
-# queryset = OneToManyTarget.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
-# {'id': 2, 'name': 'source-2'},
-# {'id': 3, 'name': 'source-3'},
-# {'id': 4, 'name': 'source-4'}]}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_many_create_with_invalid_data(self):
-# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
-# {'id': 2, 'name': 'source-2'},
-# {'id': 3, 'name': 'source-3'},
-# {'id': 4}]}
-# serializer = self.Serializer(data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'sources': [{}, {}, {}, {'name': ['This field is required.']}]})
-
-# def test_one_to_many_update(self):
-# data = {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'},
-# {'id': 2, 'name': 'source-2'},
-# {'id': 3, 'name': 'source-3'}]}
-# instance = OneToManyTarget.objects.get(pk=1)
-# serializer = self.Serializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-1-updated')
-
-# # Ensure (target 1, source 1) are updated,
-# # and everything else is as expected.
-# queryset = OneToManyTarget.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'},
-# {'id': 2, 'name': 'source-2'},
-# {'id': 3, 'name': 'source-3'}]}
-
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_one_to_many_delete(self):
-# data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
-# {'id': 3, 'name': 'source-3'}]}
-# instance = OneToManyTarget.objects.get(pk=1)
-# serializer = self.Serializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-
-# # Ensure source 2 is deleted, and everything else is as
-# # expected.
-# queryset = OneToManyTarget.objects.all()
-# serializer = self.Serializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'},
-# {'id': 3, 'name': 'source-3'}]}
-
-# ]
-# self.assertEqual(serializer.data, expected)
diff --git a/tests/test_relations_pk.py b/tests/test_relations_pk.py
index 031a79b3..e95a877e 100644
--- a/tests/test_relations_pk.py
+++ b/tests/test_relations_pk.py
@@ -1,551 +1,418 @@
-# from __future__ import unicode_literals
-# from django.db import models
-# from django.test import TestCase
-# from django.utils import six
-# from rest_framework import serializers
-# from tests.models import (
-# BlogPost, ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource,
-# NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource,
-# )
-
-
-# # ManyToMany
-# class ManyToManyTargetSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ManyToManyTarget
-# fields = ('id', 'name', 'sources')
-
-
-# class ManyToManySourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ManyToManySource
-# fields = ('id', 'name', 'targets')
-
-
-# # ForeignKey
-# class ForeignKeyTargetSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ForeignKeyTarget
-# fields = ('id', 'name', 'sources')
-
-
-# class ForeignKeySourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ForeignKeySource
-# fields = ('id', 'name', 'target')
-
-
-# # Nullable ForeignKey
-# class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = NullableForeignKeySource
-# fields = ('id', 'name', 'target')
-
-
-# # Nullable OneToOne
-# class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = OneToOneTarget
-# fields = ('id', 'name', 'nullable_source')
-
-
-# # TODO: Add test that .data cannot be accessed prior to .is_valid
-
-# class PKManyToManyTests(TestCase):
-# def setUp(self):
-# for idx in range(1, 4):
-# target = ManyToManyTarget(name='target-%d' % idx)
-# target.save()
-# source = ManyToManySource(name='source-%d' % idx)
-# source.save()
-# for target in ManyToManyTarget.objects.all():
-# source.targets.add(target)
-
-# def test_many_to_many_retrieve(self):
-# queryset = ManyToManySource.objects.all()
-# serializer = ManyToManySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'targets': [1]},
-# {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
-# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_many_to_many_retrieve(self):
-# queryset = ManyToManyTarget.objects.all()
-# serializer = ManyToManyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
-# {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
-# {'id': 3, 'name': 'target-3', 'sources': [3]}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_many_to_many_update(self):
-# data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}
-# instance = ManyToManySource.objects.get(pk=1)
-# serializer = ManyToManySourceSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-# self.assertEqual(serializer.data, data)
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = ManyToManySource.objects.all()
-# serializer = ManyToManySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]},
-# {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
-# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_many_to_many_update(self):
-# data = {'id': 1, 'name': 'target-1', 'sources': [1]}
-# instance = ManyToManyTarget.objects.get(pk=1)
-# serializer = ManyToManyTargetSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-# self.assertEqual(serializer.data, data)
-
-# # Ensure target 1 is updated, and everything else is as expected
-# queryset = ManyToManyTarget.objects.all()
-# serializer = ManyToManyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [1]},
-# {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
-# {'id': 3, 'name': 'target-3', 'sources': [3]}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_many_to_many_create(self):
-# data = {'id': 4, 'name': 'source-4', 'targets': [1, 3]}
-# serializer = ManyToManySourceSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is added, and everything else is as expected
-# queryset = ManyToManySource.objects.all()
-# serializer = ManyToManySourceSerializer(queryset, many=True)
-# self.assertFalse(serializer.fields['targets'].read_only)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'targets': [1]},
-# {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
-# {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]},
-# {'id': 4, 'name': 'source-4', 'targets': [1, 3]},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_many_to_many_create(self):
-# data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]}
-# serializer = ManyToManyTargetSerializer(data=data)
-# self.assertFalse(serializer.fields['sources'].read_only)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-4')
-
-# # Ensure target 4 is added, and everything else is as expected
-# queryset = ManyToManyTarget.objects.all()
-# serializer = ManyToManyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
-# {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
-# {'id': 3, 'name': 'target-3', 'sources': [3]},
-# {'id': 4, 'name': 'target-4', 'sources': [1, 3]}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-
-# class PKForeignKeyTests(TestCase):
-# def setUp(self):
-# target = ForeignKeyTarget(name='target-1')
-# target.save()
-# new_target = ForeignKeyTarget(name='target-2')
-# new_target.save()
-# for idx in range(1, 4):
-# source = ForeignKeySource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_foreign_key_retrieve(self):
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 1},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': 1}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_foreign_key_retrieve(self):
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
-# {'id': 2, 'name': 'target-2', 'sources': []},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update(self):
-# data = {'id': 1, 'name': 'source-1', 'target': 2}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 2},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': 1}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_incorrect_type(self):
-# data = {'id': 1, 'name': 'source-1', 'target': 'foo'}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected pk value, received %s.' % six.text_type.__name__]})
-
-# def test_reverse_foreign_key_update(self):
-# data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]}
-# instance = ForeignKeyTarget.objects.get(pk=2)
-# serializer = ForeignKeyTargetSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# # We shouldn't have saved anything to the db yet since save
-# # hasn't been called.
-# queryset = ForeignKeyTarget.objects.all()
-# new_serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
-# {'id': 2, 'name': 'target-2', 'sources': []},
-# ]
-# self.assertEqual(new_serializer.data, expected)
-
-# serializer.save()
-# self.assertEqual(serializer.data, data)
-
-# # Ensure target 2 is update, and everything else is as expected
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [2]},
-# {'id': 2, 'name': 'target-2', 'sources': [1, 3]},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create(self):
-# data = {'id': 4, 'name': 'source-4', 'target': 2}
-# serializer = ForeignKeySourceSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is added, and everything else is as expected
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 1},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': 1},
-# {'id': 4, 'name': 'source-4', 'target': 2},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_foreign_key_create(self):
-# data = {'id': 3, 'name': 'target-3', 'sources': [1, 3]}
-# serializer = ForeignKeyTargetSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-3')
-
-# # Ensure target 3 is added, and everything else is as expected
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': [2]},
-# {'id': 2, 'name': 'target-2', 'sources': []},
-# {'id': 3, 'name': 'target-3', 'sources': [1, 3]},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_invalid_null(self):
-# data = {'id': 1, 'name': 'source-1', 'target': None}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'target': ['This field is required.']})
-
-# def test_foreign_key_with_empty(self):
-# """
-# Regression test for #1072
-
-# https://github.com/tomchristie/django-rest-framework/issues/1072
-# """
-# serializer = NullableForeignKeySourceSerializer()
-# self.assertEqual(serializer.data['target'], None)
-
-
-# class PKNullableForeignKeyTests(TestCase):
-# def setUp(self):
-# target = ForeignKeyTarget(name='target-1')
-# target.save()
-# for idx in range(1, 4):
-# if idx == 3:
-# target = None
-# source = NullableForeignKeySource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_foreign_key_retrieve_with_null(self):
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 1},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': None},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create_with_valid_null(self):
-# data = {'id': 4, 'name': 'source-4', 'target': None}
-# serializer = NullableForeignKeySourceSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is created, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 1},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': None},
-# {'id': 4, 'name': 'source-4', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create_with_valid_emptystring(self):
-# """
-# The emptystring should be interpreted as null in the context
-# of relationships.
-# """
-# data = {'id': 4, 'name': 'source-4', 'target': ''}
-# expected_data = {'id': 4, 'name': 'source-4', 'target': None}
-# serializer = NullableForeignKeySourceSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, expected_data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is created, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 1},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': None},
-# {'id': 4, 'name': 'source-4', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_valid_null(self):
-# data = {'id': 1, 'name': 'source-1', 'target': None}
-# instance = NullableForeignKeySource.objects.get(pk=1)
-# serializer = NullableForeignKeySourceSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': None},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_valid_emptystring(self):
-# """
-# The emptystring should be interpreted as null in the context
-# of relationships.
-# """
-# data = {'id': 1, 'name': 'source-1', 'target': ''}
-# expected_data = {'id': 1, 'name': 'source-1', 'target': None}
-# instance = NullableForeignKeySource.objects.get(pk=1)
-# serializer = NullableForeignKeySourceSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, expected_data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': None},
-# {'id': 2, 'name': 'source-2', 'target': 1},
-# {'id': 3, 'name': 'source-3', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# # reverse foreign keys MUST be read_only
-# # In the general case they do not provide .remove() or .clear()
-# # and cannot be arbitrarily set.
-
-# # def test_reverse_foreign_key_update(self):
-# # data = {'id': 1, 'name': 'target-1', 'sources': [1]}
-# # instance = ForeignKeyTarget.objects.get(pk=1)
-# # serializer = ForeignKeyTargetSerializer(instance, data=data)
-# # self.assertTrue(serializer.is_valid())
-# # self.assertEqual(serializer.data, data)
-# # serializer.save()
-
-# # # Ensure target 1 is updated, and everything else is as expected
-# # queryset = ForeignKeyTarget.objects.all()
-# # serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# # expected = [
-# # {'id': 1, 'name': 'target-1', 'sources': [1]},
-# # {'id': 2, 'name': 'target-2', 'sources': []},
-# # ]
-# # self.assertEqual(serializer.data, expected)
-
-
-# class PKNullableOneToOneTests(TestCase):
-# def setUp(self):
-# target = OneToOneTarget(name='target-1')
-# target.save()
-# new_target = OneToOneTarget(name='target-2')
-# new_target.save()
-# source = NullableOneToOneSource(name='source-1', target=new_target)
-# source.save()
-
-# def test_reverse_foreign_key_retrieve_with_null(self):
-# queryset = OneToOneTarget.objects.all()
-# serializer = NullableOneToOneTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'nullable_source': None},
-# {'id': 2, 'name': 'target-2', 'nullable_source': 1},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-
-# # The below models and tests ensure that serializer fields corresponding
-# # to a ManyToManyField field with a user-specified ``through`` model are
-# # set to read only
-
-
-# class ManyToManyThroughTarget(models.Model):
-# name = models.CharField(max_length=100)
-
-
-# class ManyToManyThrough(models.Model):
-# source = models.ForeignKey('ManyToManyThroughSource')
-# target = models.ForeignKey(ManyToManyThroughTarget)
-
-
-# class ManyToManyThroughSource(models.Model):
-# name = models.CharField(max_length=100)
-# targets = models.ManyToManyField(ManyToManyThroughTarget,
-# related_name='sources',
-# through='ManyToManyThrough')
-
-
-# class ManyToManyThroughTargetSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ManyToManyThroughTarget
-# fields = ('id', 'name', 'sources')
-
-
-# class ManyToManyThroughSourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ManyToManyThroughSource
-# fields = ('id', 'name', 'targets')
-
-
-# class PKManyToManyThroughTests(TestCase):
-# def setUp(self):
-# self.source = ManyToManyThroughSource.objects.create(
-# name='through-source-1')
-# self.target = ManyToManyThroughTarget.objects.create(
-# name='through-target-1')
-
-# def test_many_to_many_create(self):
-# data = {'id': 2, 'name': 'source-2', 'targets': [self.target.pk]}
-# serializer = ManyToManyThroughSourceSerializer(data=data)
-# self.assertTrue(serializer.fields['targets'].read_only)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(obj.name, 'source-2')
-# self.assertEqual(obj.targets.count(), 0)
-
-# def test_many_to_many_reverse_create(self):
-# data = {'id': 2, 'name': 'target-2', 'sources': [self.source.pk]}
-# serializer = ManyToManyThroughTargetSerializer(data=data)
-# self.assertTrue(serializer.fields['sources'].read_only)
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-# obj = serializer.save()
-# self.assertEqual(obj.name, 'target-2')
-# self.assertEqual(obj.sources.count(), 0)
-
-
-# # Regression tests for #694 (`source` attribute on related fields)
-
-
-# class PrimaryKeyRelatedFieldSourceTests(TestCase):
-# def test_related_manager_source(self):
-# """
-# Relational fields should be able to use manager-returning methods as their source.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_manager')
-
-# class ClassWithManagerMethod(object):
-# def get_blogposts_manager(self):
-# return BlogPost.objects
-
-# obj = ClassWithManagerMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, [1])
-
-# def test_related_queryset_source(self):
-# """
-# Relational fields should be able to use queryset-returning methods as their source.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_queryset')
-
-# class ClassWithQuerysetMethod(object):
-# def get_blogposts_queryset(self):
-# return BlogPost.objects.all()
-
-# obj = ClassWithQuerysetMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, [1])
-
-# def test_dotted_source(self):
-# """
-# Source argument should support dotted.source notation.
-# """
-# BlogPost.objects.create(title='blah')
-# field = serializers.PrimaryKeyRelatedField(many=True, source='a.b.c')
-
-# class ClassWithQuerysetMethod(object):
-# a = {
-# 'b': {
-# 'c': BlogPost.objects.all()
-# }
-# }
-
-# obj = ClassWithQuerysetMethod()
-# value = field.field_to_native(obj, 'field_name')
-# self.assertEqual(value, [1])
+from __future__ import unicode_literals
+from django.test import TestCase
+from django.utils import six
+from rest_framework import serializers
+from tests.models import (
+ ManyToManyTarget, ManyToManySource, ForeignKeyTarget, ForeignKeySource,
+ NullableForeignKeySource, OneToOneTarget, NullableOneToOneSource,
+)
+
+
+# ManyToMany
+class ManyToManyTargetSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = ManyToManyTarget
+ fields = ('id', 'name', 'sources')
+
+
+class ManyToManySourceSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = ManyToManySource
+ fields = ('id', 'name', 'targets')
+
+
+# ForeignKey
+class ForeignKeyTargetSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = ForeignKeyTarget
+ fields = ('id', 'name', 'sources')
+
+
+class ForeignKeySourceSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = ForeignKeySource
+ fields = ('id', 'name', 'target')
+
+
+# Nullable ForeignKey
+class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = NullableForeignKeySource
+ fields = ('id', 'name', 'target')
+
+
+# Nullable OneToOne
+class NullableOneToOneTargetSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = OneToOneTarget
+ fields = ('id', 'name', 'nullable_source')
+
+
+# TODO: Add test that .data cannot be accessed prior to .is_valid
+
+class PKManyToManyTests(TestCase):
+ def setUp(self):
+ for idx in range(1, 4):
+ target = ManyToManyTarget(name='target-%d' % idx)
+ target.save()
+ source = ManyToManySource(name='source-%d' % idx)
+ source.save()
+ for target in ManyToManyTarget.objects.all():
+ source.targets.add(target)
+
+ def test_many_to_many_retrieve(self):
+ queryset = ManyToManySource.objects.all()
+ serializer = ManyToManySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'targets': [1]},
+ {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
+ {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}
+ ]
+ with self.assertNumQueries(4):
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_many_to_many_retrieve(self):
+ queryset = ManyToManyTarget.objects.all()
+ serializer = ManyToManyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
+ {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
+ {'id': 3, 'name': 'target-3', 'sources': [3]}
+ ]
+ with self.assertNumQueries(4):
+ self.assertEqual(serializer.data, expected)
+
+ def test_many_to_many_update(self):
+ data = {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]}
+ instance = ManyToManySource.objects.get(pk=1)
+ serializer = ManyToManySourceSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = ManyToManySource.objects.all()
+ serializer = ManyToManySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'targets': [1, 2, 3]},
+ {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
+ {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_many_to_many_update(self):
+ data = {'id': 1, 'name': 'target-1', 'sources': [1]}
+ instance = ManyToManyTarget.objects.get(pk=1)
+ serializer = ManyToManyTargetSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure target 1 is updated, and everything else is as expected
+ queryset = ManyToManyTarget.objects.all()
+ serializer = ManyToManyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': [1]},
+ {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
+ {'id': 3, 'name': 'target-3', 'sources': [3]}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_many_to_many_create(self):
+ data = {'id': 4, 'name': 'source-4', 'targets': [1, 3]}
+ serializer = ManyToManySourceSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is added, and everything else is as expected
+ queryset = ManyToManySource.objects.all()
+ serializer = ManyToManySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'targets': [1]},
+ {'id': 2, 'name': 'source-2', 'targets': [1, 2]},
+ {'id': 3, 'name': 'source-3', 'targets': [1, 2, 3]},
+ {'id': 4, 'name': 'source-4', 'targets': [1, 3]},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_many_to_many_create(self):
+ data = {'id': 4, 'name': 'target-4', 'sources': [1, 3]}
+ serializer = ManyToManyTargetSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'target-4')
+
+ # Ensure target 4 is added, and everything else is as expected
+ queryset = ManyToManyTarget.objects.all()
+ serializer = ManyToManyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
+ {'id': 2, 'name': 'target-2', 'sources': [2, 3]},
+ {'id': 3, 'name': 'target-3', 'sources': [3]},
+ {'id': 4, 'name': 'target-4', 'sources': [1, 3]}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+
+class PKForeignKeyTests(TestCase):
+ def setUp(self):
+ target = ForeignKeyTarget(name='target-1')
+ target.save()
+ new_target = ForeignKeyTarget(name='target-2')
+ new_target.save()
+ for idx in range(1, 4):
+ source = ForeignKeySource(name='source-%d' % idx, target=target)
+ source.save()
+
+ def test_foreign_key_retrieve(self):
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 1},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': 1}
+ ]
+ with self.assertNumQueries(1):
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_foreign_key_retrieve(self):
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
+ {'id': 2, 'name': 'target-2', 'sources': []},
+ ]
+ with self.assertNumQueries(3):
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update(self):
+ data = {'id': 1, 'name': 'source-1', 'target': 2}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 2},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': 1}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_incorrect_type(self):
+ data = {'id': 1, 'name': 'source-1', 'target': 'foo'}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data)
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(serializer.errors, {'target': ['Incorrect type. Expected pk value, received %s.' % six.text_type.__name__]})
+
+ def test_reverse_foreign_key_update(self):
+ data = {'id': 2, 'name': 'target-2', 'sources': [1, 3]}
+ instance = ForeignKeyTarget.objects.get(pk=2)
+ serializer = ForeignKeyTargetSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ # We shouldn't have saved anything to the db yet since save
+ # hasn't been called.
+ queryset = ForeignKeyTarget.objects.all()
+ new_serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': [1, 2, 3]},
+ {'id': 2, 'name': 'target-2', 'sources': []},
+ ]
+ self.assertEqual(new_serializer.data, expected)
+
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure target 2 is update, and everything else is as expected
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': [2]},
+ {'id': 2, 'name': 'target-2', 'sources': [1, 3]},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create(self):
+ data = {'id': 4, 'name': 'source-4', 'target': 2}
+ serializer = ForeignKeySourceSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is added, and everything else is as expected
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 1},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': 1},
+ {'id': 4, 'name': 'source-4', 'target': 2},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_foreign_key_create(self):
+ data = {'id': 3, 'name': 'target-3', 'sources': [1, 3]}
+ serializer = ForeignKeyTargetSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'target-3')
+
+ # Ensure target 3 is added, and everything else is as expected
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': [2]},
+ {'id': 2, 'name': 'target-2', 'sources': []},
+ {'id': 3, 'name': 'target-3', 'sources': [1, 3]},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_invalid_null(self):
+ data = {'id': 1, 'name': 'source-1', 'target': None}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data)
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(serializer.errors, {'target': ['This field may not be null.']})
+
+ def test_foreign_key_with_empty(self):
+ """
+ Regression test for #1072
+
+ https://github.com/tomchristie/django-rest-framework/issues/1072
+ """
+ serializer = NullableForeignKeySourceSerializer()
+ self.assertEqual(serializer.data['target'], None)
+
+
+class PKNullableForeignKeyTests(TestCase):
+ def setUp(self):
+ target = ForeignKeyTarget(name='target-1')
+ target.save()
+ for idx in range(1, 4):
+ if idx == 3:
+ target = None
+ source = NullableForeignKeySource(name='source-%d' % idx, target=target)
+ source.save()
+
+ def test_foreign_key_retrieve_with_null(self):
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 1},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': None},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create_with_valid_null(self):
+ data = {'id': 4, 'name': 'source-4', 'target': None}
+ serializer = NullableForeignKeySourceSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is created, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 1},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': None},
+ {'id': 4, 'name': 'source-4', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create_with_valid_emptystring(self):
+ """
+ The emptystring should be interpreted as null in the context
+ of relationships.
+ """
+ data = {'id': 4, 'name': 'source-4', 'target': ''}
+ expected_data = {'id': 4, 'name': 'source-4', 'target': None}
+ serializer = NullableForeignKeySourceSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, expected_data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is created, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 1},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': None},
+ {'id': 4, 'name': 'source-4', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_valid_null(self):
+ data = {'id': 1, 'name': 'source-1', 'target': None}
+ instance = NullableForeignKeySource.objects.get(pk=1)
+ serializer = NullableForeignKeySourceSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': None},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_valid_emptystring(self):
+ """
+ The emptystring should be interpreted as null in the context
+ of relationships.
+ """
+ data = {'id': 1, 'name': 'source-1', 'target': ''}
+ expected_data = {'id': 1, 'name': 'source-1', 'target': None}
+ instance = NullableForeignKeySource.objects.get(pk=1)
+ serializer = NullableForeignKeySourceSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, expected_data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': None},
+ {'id': 2, 'name': 'source-2', 'target': 1},
+ {'id': 3, 'name': 'source-3', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+
+class PKNullableOneToOneTests(TestCase):
+ def setUp(self):
+ target = OneToOneTarget(name='target-1')
+ target.save()
+ new_target = OneToOneTarget(name='target-2')
+ new_target.save()
+ source = NullableOneToOneSource(name='source-1', target=new_target)
+ source.save()
+
+ def test_reverse_foreign_key_retrieve_with_null(self):
+ queryset = OneToOneTarget.objects.all()
+ serializer = NullableOneToOneTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'nullable_source': None},
+ {'id': 2, 'name': 'target-2', 'nullable_source': 1},
+ ]
+ self.assertEqual(serializer.data, expected)
diff --git a/tests/test_relations_slug.py b/tests/test_relations_slug.py
index f7a59a95..7bac9046 100644
--- a/tests/test_relations_slug.py
+++ b/tests/test_relations_slug.py
@@ -1,257 +1,268 @@
-# from django.test import TestCase
-# from rest_framework import serializers
-# from tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget
-
-
-# class ForeignKeyTargetSerializer(serializers.ModelSerializer):
-# sources = serializers.SlugRelatedField(many=True, slug_field='name')
-
-# class Meta:
-# model = ForeignKeyTarget
-
-
-# class ForeignKeySourceSerializer(serializers.ModelSerializer):
-# target = serializers.SlugRelatedField(slug_field='name')
-
-# class Meta:
-# model = ForeignKeySource
-
-
-# class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
-# target = serializers.SlugRelatedField(slug_field='name', required=False)
-
-# class Meta:
-# model = NullableForeignKeySource
-
-
-# # TODO: M2M Tests, FKTests (Non-nullable), One2One
-# class SlugForeignKeyTests(TestCase):
-# def setUp(self):
-# target = ForeignKeyTarget(name='target-1')
-# target.save()
-# new_target = ForeignKeyTarget(name='target-2')
-# new_target.save()
-# for idx in range(1, 4):
-# source = ForeignKeySource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_foreign_key_retrieve(self):
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 'target-1'},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': 'target-1'}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_foreign_key_retrieve(self):
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
-# {'id': 2, 'name': 'target-2', 'sources': []},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update(self):
-# data = {'id': 1, 'name': 'source-1', 'target': 'target-2'}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 'target-2'},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': 'target-1'}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_incorrect_type(self):
-# data = {'id': 1, 'name': 'source-1', 'target': 123}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'target': ['Object with name=123 does not exist.']})
-
-# def test_reverse_foreign_key_update(self):
-# data = {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']}
-# instance = ForeignKeyTarget.objects.get(pk=2)
-# serializer = ForeignKeyTargetSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# # We shouldn't have saved anything to the db yet since save
-# # hasn't been called.
-# queryset = ForeignKeyTarget.objects.all()
-# new_serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
-# {'id': 2, 'name': 'target-2', 'sources': []},
-# ]
-# self.assertEqual(new_serializer.data, expected)
-
-# serializer.save()
-# self.assertEqual(serializer.data, data)
-
-# # Ensure target 2 is update, and everything else is as expected
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': ['source-2']},
-# {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create(self):
-# data = {'id': 4, 'name': 'source-4', 'target': 'target-2'}
-# serializer = ForeignKeySourceSerializer(data=data)
-# serializer.is_valid()
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is added, and everything else is as expected
-# queryset = ForeignKeySource.objects.all()
-# serializer = ForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 'target-1'},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': 'target-1'},
-# {'id': 4, 'name': 'source-4', 'target': 'target-2'},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_reverse_foreign_key_create(self):
-# data = {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']}
-# serializer = ForeignKeyTargetSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'target-3')
-
-# # Ensure target 3 is added, and everything else is as expected
-# queryset = ForeignKeyTarget.objects.all()
-# serializer = ForeignKeyTargetSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'target-1', 'sources': ['source-2']},
-# {'id': 2, 'name': 'target-2', 'sources': []},
-# {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_invalid_null(self):
-# data = {'id': 1, 'name': 'source-1', 'target': None}
-# instance = ForeignKeySource.objects.get(pk=1)
-# serializer = ForeignKeySourceSerializer(instance, data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'target': ['This field is required.']})
-
-
-# class SlugNullableForeignKeyTests(TestCase):
-# def setUp(self):
-# target = ForeignKeyTarget(name='target-1')
-# target.save()
-# for idx in range(1, 4):
-# if idx == 3:
-# target = None
-# source = NullableForeignKeySource(name='source-%d' % idx, target=target)
-# source.save()
-
-# def test_foreign_key_retrieve_with_null(self):
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 'target-1'},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': None},
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create_with_valid_null(self):
-# data = {'id': 4, 'name': 'source-4', 'target': None}
-# serializer = NullableForeignKeySourceSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is created, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 'target-1'},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': None},
-# {'id': 4, 'name': 'source-4', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_create_with_valid_emptystring(self):
-# """
-# The emptystring should be interpreted as null in the context
-# of relationships.
-# """
-# data = {'id': 4, 'name': 'source-4', 'target': ''}
-# expected_data = {'id': 4, 'name': 'source-4', 'target': None}
-# serializer = NullableForeignKeySourceSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# obj = serializer.save()
-# self.assertEqual(serializer.data, expected_data)
-# self.assertEqual(obj.name, 'source-4')
-
-# # Ensure source 4 is created, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': 'target-1'},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': None},
-# {'id': 4, 'name': 'source-4', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_valid_null(self):
-# data = {'id': 1, 'name': 'source-1', 'target': None}
-# instance = NullableForeignKeySource.objects.get(pk=1)
-# serializer = NullableForeignKeySourceSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': None},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
-
-# def test_foreign_key_update_with_valid_emptystring(self):
-# """
-# The emptystring should be interpreted as null in the context
-# of relationships.
-# """
-# data = {'id': 1, 'name': 'source-1', 'target': ''}
-# expected_data = {'id': 1, 'name': 'source-1', 'target': None}
-# instance = NullableForeignKeySource.objects.get(pk=1)
-# serializer = NullableForeignKeySourceSerializer(instance, data=data)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, expected_data)
-# serializer.save()
-
-# # Ensure source 1 is updated, and everything else is as expected
-# queryset = NullableForeignKeySource.objects.all()
-# serializer = NullableForeignKeySourceSerializer(queryset, many=True)
-# expected = [
-# {'id': 1, 'name': 'source-1', 'target': None},
-# {'id': 2, 'name': 'source-2', 'target': 'target-1'},
-# {'id': 3, 'name': 'source-3', 'target': None}
-# ]
-# self.assertEqual(serializer.data, expected)
+from django.test import TestCase
+from rest_framework import serializers
+from tests.models import NullableForeignKeySource, ForeignKeySource, ForeignKeyTarget
+
+
+class ForeignKeyTargetSerializer(serializers.ModelSerializer):
+ sources = serializers.SlugRelatedField(
+ slug_field='name',
+ queryset=ForeignKeySource.objects.all(),
+ many=True
+ )
+
+ class Meta:
+ model = ForeignKeyTarget
+
+
+class ForeignKeySourceSerializer(serializers.ModelSerializer):
+ target = serializers.SlugRelatedField(
+ slug_field='name',
+ queryset=ForeignKeyTarget.objects.all()
+ )
+
+ class Meta:
+ model = ForeignKeySource
+
+
+class NullableForeignKeySourceSerializer(serializers.ModelSerializer):
+ target = serializers.SlugRelatedField(
+ slug_field='name',
+ queryset=ForeignKeyTarget.objects.all(),
+ allow_null=True
+ )
+
+ class Meta:
+ model = NullableForeignKeySource
+
+
+# TODO: M2M Tests, FKTests (Non-nullable), One2One
+class SlugForeignKeyTests(TestCase):
+ def setUp(self):
+ target = ForeignKeyTarget(name='target-1')
+ target.save()
+ new_target = ForeignKeyTarget(name='target-2')
+ new_target.save()
+ for idx in range(1, 4):
+ source = ForeignKeySource(name='source-%d' % idx, target=target)
+ source.save()
+
+ def test_foreign_key_retrieve(self):
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 'target-1'},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': 'target-1'}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_foreign_key_retrieve(self):
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
+ {'id': 2, 'name': 'target-2', 'sources': []},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update(self):
+ data = {'id': 1, 'name': 'source-1', 'target': 'target-2'}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 'target-2'},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': 'target-1'}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_incorrect_type(self):
+ data = {'id': 1, 'name': 'source-1', 'target': 123}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data)
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(serializer.errors, {'target': ['Object with name=123 does not exist.']})
+
+ def test_reverse_foreign_key_update(self):
+ data = {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']}
+ instance = ForeignKeyTarget.objects.get(pk=2)
+ serializer = ForeignKeyTargetSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ # We shouldn't have saved anything to the db yet since save
+ # hasn't been called.
+ queryset = ForeignKeyTarget.objects.all()
+ new_serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': ['source-1', 'source-2', 'source-3']},
+ {'id': 2, 'name': 'target-2', 'sources': []},
+ ]
+ self.assertEqual(new_serializer.data, expected)
+
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure target 2 is update, and everything else is as expected
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': ['source-2']},
+ {'id': 2, 'name': 'target-2', 'sources': ['source-1', 'source-3']},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create(self):
+ data = {'id': 4, 'name': 'source-4', 'target': 'target-2'}
+ serializer = ForeignKeySourceSerializer(data=data)
+ serializer.is_valid()
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is added, and everything else is as expected
+ queryset = ForeignKeySource.objects.all()
+ serializer = ForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 'target-1'},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': 'target-1'},
+ {'id': 4, 'name': 'source-4', 'target': 'target-2'},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_reverse_foreign_key_create(self):
+ data = {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']}
+ serializer = ForeignKeyTargetSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'target-3')
+
+ # Ensure target 3 is added, and everything else is as expected
+ queryset = ForeignKeyTarget.objects.all()
+ serializer = ForeignKeyTargetSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'target-1', 'sources': ['source-2']},
+ {'id': 2, 'name': 'target-2', 'sources': []},
+ {'id': 3, 'name': 'target-3', 'sources': ['source-1', 'source-3']},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_invalid_null(self):
+ data = {'id': 1, 'name': 'source-1', 'target': None}
+ instance = ForeignKeySource.objects.get(pk=1)
+ serializer = ForeignKeySourceSerializer(instance, data=data)
+ self.assertFalse(serializer.is_valid())
+ self.assertEqual(serializer.errors, {'target': ['This field may not be null.']})
+
+
+class SlugNullableForeignKeyTests(TestCase):
+ def setUp(self):
+ target = ForeignKeyTarget(name='target-1')
+ target.save()
+ for idx in range(1, 4):
+ if idx == 3:
+ target = None
+ source = NullableForeignKeySource(name='source-%d' % idx, target=target)
+ source.save()
+
+ def test_foreign_key_retrieve_with_null(self):
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 'target-1'},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': None},
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create_with_valid_null(self):
+ data = {'id': 4, 'name': 'source-4', 'target': None}
+ serializer = NullableForeignKeySourceSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is created, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 'target-1'},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': None},
+ {'id': 4, 'name': 'source-4', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_create_with_valid_emptystring(self):
+ """
+ The emptystring should be interpreted as null in the context
+ of relationships.
+ """
+ data = {'id': 4, 'name': 'source-4', 'target': ''}
+ expected_data = {'id': 4, 'name': 'source-4', 'target': None}
+ serializer = NullableForeignKeySourceSerializer(data=data)
+ self.assertTrue(serializer.is_valid())
+ obj = serializer.save()
+ self.assertEqual(serializer.data, expected_data)
+ self.assertEqual(obj.name, 'source-4')
+
+ # Ensure source 4 is created, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': 'target-1'},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': None},
+ {'id': 4, 'name': 'source-4', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_valid_null(self):
+ data = {'id': 1, 'name': 'source-1', 'target': None}
+ instance = NullableForeignKeySource.objects.get(pk=1)
+ serializer = NullableForeignKeySourceSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': None},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
+
+ def test_foreign_key_update_with_valid_emptystring(self):
+ """
+ The emptystring should be interpreted as null in the context
+ of relationships.
+ """
+ data = {'id': 1, 'name': 'source-1', 'target': ''}
+ expected_data = {'id': 1, 'name': 'source-1', 'target': None}
+ instance = NullableForeignKeySource.objects.get(pk=1)
+ serializer = NullableForeignKeySourceSerializer(instance, data=data)
+ self.assertTrue(serializer.is_valid())
+ serializer.save()
+ self.assertEqual(serializer.data, expected_data)
+
+ # Ensure source 1 is updated, and everything else is as expected
+ queryset = NullableForeignKeySource.objects.all()
+ serializer = NullableForeignKeySourceSerializer(queryset, many=True)
+ expected = [
+ {'id': 1, 'name': 'source-1', 'target': None},
+ {'id': 2, 'name': 'source-2', 'target': 'target-1'},
+ {'id': 3, 'name': 'source-3', 'target': None}
+ ]
+ self.assertEqual(serializer.data, expected)
diff --git a/tests/test_renderers.py b/tests/test_renderers.py
index a8fd5f46..416d7f22 100644
--- a/tests/test_renderers.py
+++ b/tests/test_renderers.py
@@ -9,7 +9,7 @@ from django.test import TestCase
from django.utils import six, unittest
from django.utils.translation import ugettext_lazy as _
from rest_framework import status, permissions
-from rest_framework.compat import yaml, etree, StringIO
+from rest_framework.compat import yaml, etree, StringIO, BytesIO
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.renderers import BaseRenderer, JSONRenderer, YAMLRenderer, \
@@ -467,7 +467,7 @@ if yaml:
obj = {'foo': ['bar', 'baz']}
renderer = YAMLRenderer()
content = renderer.render(obj, 'application/yaml')
- self.assertEqual(content, _yaml_repr)
+ self.assertEqual(content.decode('utf-8'), _yaml_repr)
def test_render_and_parse(self):
"""
@@ -480,7 +480,7 @@ if yaml:
parser = YAMLParser()
content = renderer.render(obj, 'application/yaml')
- data = parser.parse(StringIO(content))
+ data = parser.parse(BytesIO(content))
self.assertEqual(obj, data)
def test_render_decimal(self):
@@ -489,7 +489,7 @@ if yaml:
"""
renderer = YAMLRenderer()
content = renderer.render({'field': Decimal('111.2')}, 'application/yaml')
- self.assertYAMLContains(content, "field: '111.2'")
+ self.assertYAMLContains(content.decode('utf-8'), "field: '111.2'")
def assertYAMLContains(self, content, string):
self.assertTrue(string in content, '%r not in %r' % (string, content))
@@ -646,6 +646,7 @@ class CacheRenderTest(TestCase):
"""
method = getattr(self.client, http_method)
resp = method(url)
+ resp._closable_objects = []
del resp.client, resp.request
try:
del resp.wsgi_request
diff --git a/tests/test_request.py b/tests/test_request.py
index 8ddaf0a7..44afd243 100644
--- a/tests/test_request.py
+++ b/tests/test_request.py
@@ -179,89 +179,6 @@ class TestContentParsing(TestCase):
self.assertEqual(request._data, Empty)
self.assertEqual(request._files, Empty)
- # def test_accessing_post_after_data_form(self):
- # """
- # Ensures request.POST can be accessed after request.DATA in
- # form request.
- # """
- # data = {'qwerty': 'uiop'}
- # request = factory.post('/', data=data)
- # self.assertEqual(request.DATA.items(), data.items())
- # self.assertEqual(request.POST.items(), data.items())
-
- # def test_accessing_post_after_data_for_json(self):
- # """
- # Ensures request.POST can be accessed after request.DATA in
- # json request.
- # """
- # data = {'qwerty': 'uiop'}
- # content = json.dumps(data)
- # content_type = 'application/json'
- # parsers = (JSONParser, )
-
- # request = factory.post('/', content, content_type=content_type,
- # parsers=parsers)
- # self.assertEqual(request.DATA.items(), data.items())
- # self.assertEqual(request.POST.items(), [])
-
- # def test_accessing_post_after_data_for_overloaded_json(self):
- # """
- # Ensures request.POST can be accessed after request.DATA in overloaded
- # json request.
- # """
- # data = {'qwerty': 'uiop'}
- # content = json.dumps(data)
- # content_type = 'application/json'
- # parsers = (JSONParser, )
- # form_data = {Request._CONTENT_PARAM: content,
- # Request._CONTENTTYPE_PARAM: content_type}
-
- # request = factory.post('/', form_data, parsers=parsers)
- # self.assertEqual(request.DATA.items(), data.items())
- # self.assertEqual(request.POST.items(), form_data.items())
-
- # def test_accessing_data_after_post_form(self):
- # """
- # Ensures request.DATA can be accessed after request.POST in
- # form request.
- # """
- # data = {'qwerty': 'uiop'}
- # parsers = (FormParser, MultiPartParser)
- # request = factory.post('/', data, parsers=parsers)
-
- # self.assertEqual(request.POST.items(), data.items())
- # self.assertEqual(request.DATA.items(), data.items())
-
- # def test_accessing_data_after_post_for_json(self):
- # """
- # Ensures request.DATA can be accessed after request.POST in
- # json request.
- # """
- # data = {'qwerty': 'uiop'}
- # content = json.dumps(data)
- # content_type = 'application/json'
- # parsers = (JSONParser, )
- # request = factory.post('/', content, content_type=content_type,
- # parsers=parsers)
- # self.assertEqual(request.POST.items(), [])
- # self.assertEqual(request.DATA.items(), data.items())
-
- # def test_accessing_data_after_post_for_overloaded_json(self):
- # """
- # Ensures request.DATA can be accessed after request.POST in overloaded
- # json request
- # """
- # data = {'qwerty': 'uiop'}
- # content = json.dumps(data)
- # content_type = 'application/json'
- # parsers = (JSONParser, )
- # form_data = {Request._CONTENT_PARAM: content,
- # Request._CONTENTTYPE_PARAM: content_type}
-
- # request = factory.post('/', form_data, parsers=parsers)
- # self.assertEqual(request.POST.items(), form_data.items())
- # self.assertEqual(request.DATA.items(), data.items())
-
class MockView(APIView):
authentication_classes = (SessionAuthentication,)
@@ -301,18 +218,6 @@ class TestContentParsingWithAuthentication(TestCase):
response = self.csrf_client.post('/', content)
self.assertEqual(status.HTTP_200_OK, response.status_code)
- # def test_user_logged_in_authentication_has_post_when_logged_in(self):
- # """Ensures request.POST exists after UserLoggedInAuthentication when user does log in"""
- # self.client.login(username='john', password='password')
- # self.csrf_client.login(username='john', password='password')
- # content = {'example': 'example'}
-
- # response = self.client.post('/', content)
- # self.assertEqual(status.OK, response.status_code, "POST data is malformed")
-
- # response = self.csrf_client.post('/', content)
- # self.assertEqual(status.OK, response.status_code, "POST data is malformed")
-
class TestUserSetter(TestCase):
diff --git a/tests/test_response.py b/tests/test_response.py
index 84c39c1a..f233ae33 100644
--- a/tests/test_response.py
+++ b/tests/test_response.py
@@ -262,9 +262,9 @@ class Issue807Tests(TestCase):
expected = "{0}; charset={1}".format(RendererC.media_type, RendererC.charset)
self.assertEqual(expected, resp['Content-Type'])
- def test_content_type_set_explictly_on_response(self):
+ def test_content_type_set_explicitly_on_response(self):
"""
- The content type may be set explictly on the response.
+ The content type may be set explicitly on the response.
"""
headers = {"HTTP_ACCEPT": RendererC.media_type}
resp = self.client.get('/setbyview', **headers)
diff --git a/tests/test_serializer.py b/tests/test_serializer.py
index b0eb4e27..6dabaf42 100644
--- a/tests/test_serializer.py
+++ b/tests/test_serializer.py
@@ -1,2004 +1,177 @@
-# # -*- coding: utf-8 -*-
-# from __future__ import unicode_literals
-# from django.db import models
-# from django.db.models.fields import BLANK_CHOICE_DASH
-# from django.test import TestCase
-# from django.utils import unittest
-# from django.utils.datastructures import MultiValueDict
-# from django.utils.translation import ugettext_lazy as _
-# from rest_framework import serializers, fields, relations
-# from tests.models import (
-# HasPositiveIntegerAsChoice, Album, ActionItem, Anchor, BasicModel,
-# BlankFieldModel, BlogPost, BlogPostComment, Book, CallableDefaultValueModel,
-# DefaultValueModel, ManyToManyModel, Person, ReadOnlyManyToManyModel, Photo,
-# RESTFrameworkModel, ForeignKeySource
-# )
-# from tests.models import BasicModelSerializer
-# import datetime
-# import pickle
-# try:
-# import PIL
-# except:
-# PIL = None
-
-
-# if PIL is not None:
-# class AMOAFModel(RESTFrameworkModel):
-# char_field = models.CharField(max_length=1024, blank=True)
-# comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=1024, blank=True)
-# decimal_field = models.DecimalField(max_digits=64, decimal_places=32, blank=True)
-# email_field = models.EmailField(max_length=1024, blank=True)
-# file_field = models.FileField(upload_to='test', max_length=1024, blank=True)
-# image_field = models.ImageField(upload_to='test', max_length=1024, blank=True)
-# slug_field = models.SlugField(max_length=1024, blank=True)
-# url_field = models.URLField(max_length=1024, blank=True)
-# nullable_char_field = models.CharField(max_length=1024, blank=True, null=True)
-
-# class DVOAFModel(RESTFrameworkModel):
-# positive_integer_field = models.PositiveIntegerField(blank=True)
-# positive_small_integer_field = models.PositiveSmallIntegerField(blank=True)
-# email_field = models.EmailField(blank=True)
-# file_field = models.FileField(upload_to='test', blank=True)
-# image_field = models.ImageField(upload_to='test', blank=True)
-# slug_field = models.SlugField(blank=True)
-# url_field = models.URLField(blank=True)
-
-
-# class SubComment(object):
-# def __init__(self, sub_comment):
-# self.sub_comment = sub_comment
-
-
-# class Comment(object):
-# def __init__(self, email, content, created):
-# self.email = email
-# self.content = content
-# self.created = created or datetime.datetime.now()
-
-# def __eq__(self, other):
-# return all([getattr(self, attr) == getattr(other, attr)
-# for attr in ('email', 'content', 'created')])
-
-# def get_sub_comment(self):
-# sub_comment = SubComment('And Merry Christmas!')
-# return sub_comment
-
-
-# class CommentSerializer(serializers.Serializer):
-# email = serializers.EmailField()
-# content = serializers.CharField(max_length=1000)
-# created = serializers.DateTimeField()
-# sub_comment = serializers.Field(source='get_sub_comment.sub_comment')
-
-# def restore_object(self, data, instance=None):
-# if instance is None:
-# return Comment(**data)
-# for key, val in data.items():
-# setattr(instance, key, val)
-# return instance
-
-
-# class NamesSerializer(serializers.Serializer):
-# first = serializers.CharField()
-# last = serializers.CharField(required=False, default='')
-# initials = serializers.CharField(required=False, default='')
-
-
-# class PersonIdentifierSerializer(serializers.Serializer):
-# ssn = serializers.CharField()
-# names = NamesSerializer(source='names', required=False)
-
-
-# class BookSerializer(serializers.ModelSerializer):
-# isbn = serializers.RegexField(regex=r'^[0-9]{13}$', error_messages={'invalid': 'isbn has to be exact 13 numbers'})
-
-# class Meta:
-# model = Book
-
-
-# class ActionItemSerializer(serializers.ModelSerializer):
-
-# class Meta:
-# model = ActionItem
-
-
-# class ActionItemSerializerOptionalFields(serializers.ModelSerializer):
-# """
-# Intended to test that fields with `required=False` are excluded from validation.
-# """
-# title = serializers.CharField(required=False)
-
-# class Meta:
-# model = ActionItem
-# fields = ('title',)
-
-
-# class ActionItemSerializerCustomRestore(serializers.ModelSerializer):
-
-# class Meta:
-# model = ActionItem
-
-# def restore_object(self, data, instance=None):
-# if instance is None:
-# return ActionItem(**data)
-# for key, val in data.items():
-# setattr(instance, key, val)
-# return instance
-
-
-# class PersonSerializer(serializers.ModelSerializer):
-# info = serializers.Field(source='info')
-
-# class Meta:
-# model = Person
-# fields = ('name', 'age', 'info')
-# read_only_fields = ('age',)
-
-
-# class NestedSerializer(serializers.Serializer):
-# info = serializers.Field()
-
-
-# class ModelSerializerWithNestedSerializer(serializers.ModelSerializer):
-# nested = NestedSerializer(source='*')
-
-# class Meta:
-# model = Person
-
-
-# class NestedSerializerWithRenamedField(serializers.Serializer):
-# renamed_info = serializers.Field(source='info')
-
-
-# class ModelSerializerWithNestedSerializerWithRenamedField(serializers.ModelSerializer):
-# nested = NestedSerializerWithRenamedField(source='*')
-
-# class Meta:
-# model = Person
-
-
-# class PersonSerializerInvalidReadOnly(serializers.ModelSerializer):
-# """
-# Testing for #652.
-# """
-# info = serializers.Field(source='info')
-
-# class Meta:
-# model = Person
-# fields = ('name', 'age', 'info')
-# read_only_fields = ('age', 'info')
-
-
-# class AlbumsSerializer(serializers.ModelSerializer):
-
-# class Meta:
-# model = Album
-# fields = ['title', 'ref'] # lists are also valid options
-
-
-# class PositiveIntegerAsChoiceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = HasPositiveIntegerAsChoice
-# fields = ['some_integer']
-
-
-# class ForeignKeySourceSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ForeignKeySource
-
-
-# class HyperlinkedForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer):
-# class Meta:
-# model = ForeignKeySource
-
-
-# class BasicTests(TestCase):
-# def setUp(self):
-# self.comment = Comment(
-# 'tom@example.com',
-# 'Happy new year!',
-# datetime.datetime(2012, 1, 1)
-# )
-# self.actionitem = ActionItem(title='Some to do item',)
-# self.data = {
-# 'email': 'tom@example.com',
-# 'content': 'Happy new year!',
-# 'created': datetime.datetime(2012, 1, 1),
-# 'sub_comment': 'This wont change'
-# }
-# self.expected = {
-# 'email': 'tom@example.com',
-# 'content': 'Happy new year!',
-# 'created': datetime.datetime(2012, 1, 1),
-# 'sub_comment': 'And Merry Christmas!'
-# }
-# self.person_data = {'name': 'dwight', 'age': 35}
-# self.person = Person(**self.person_data)
-# self.person.save()
-
-# def test_empty(self):
-# serializer = CommentSerializer()
-# expected = {
-# 'email': '',
-# 'content': '',
-# 'created': None
-# }
-# self.assertEqual(serializer.data, expected)
-
-# def test_retrieve(self):
-# serializer = CommentSerializer(self.comment)
-# self.assertEqual(serializer.data, self.expected)
-
-# def test_create(self):
-# serializer = CommentSerializer(data=self.data)
-# expected = self.comment
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, expected)
-# self.assertFalse(serializer.object is expected)
-# self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!')
-
-# def test_create_nested(self):
-# """Test a serializer with nested data."""
-# names = {'first': 'John', 'last': 'Doe', 'initials': 'jd'}
-# data = {'ssn': '1234567890', 'names': names}
-# serializer = PersonIdentifierSerializer(data=data)
-
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, data)
-# self.assertFalse(serializer.object is data)
-# self.assertEqual(serializer.data['names'], names)
-
-# def test_create_partial_nested(self):
-# """Test a serializer with nested data which has missing fields."""
-# names = {'first': 'John'}
-# data = {'ssn': '1234567890', 'names': names}
-# serializer = PersonIdentifierSerializer(data=data)
-
-# expected_names = {'first': 'John', 'last': '', 'initials': ''}
-# data['names'] = expected_names
-
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, data)
-# self.assertFalse(serializer.object is expected_names)
-# self.assertEqual(serializer.data['names'], expected_names)
-
-# def test_null_nested(self):
-# """Test a serializer with a nonexistent nested field"""
-# data = {'ssn': '1234567890'}
-# serializer = PersonIdentifierSerializer(data=data)
-
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, data)
-# self.assertFalse(serializer.object is data)
-# expected = {'ssn': '1234567890', 'names': None}
-# self.assertEqual(serializer.data, expected)
-
-# def test_update(self):
-# serializer = CommentSerializer(self.comment, data=self.data)
-# expected = self.comment
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, expected)
-# self.assertTrue(serializer.object is expected)
-# self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!')
-
-# def test_partial_update(self):
-# msg = 'Merry New Year!'
-# partial_data = {'content': msg}
-# serializer = CommentSerializer(self.comment, data=partial_data)
-# self.assertEqual(serializer.is_valid(), False)
-# serializer = CommentSerializer(self.comment, data=partial_data, partial=True)
-# expected = self.comment
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, expected)
-# self.assertTrue(serializer.object is expected)
-# self.assertEqual(serializer.data['content'], msg)
-
-# def test_model_fields_as_expected(self):
-# """
-# Make sure that the fields returned are the same as defined
-# in the Meta data
-# """
-# serializer = PersonSerializer(self.person)
-# self.assertEqual(
-# set(serializer.data.keys()),
-# set(['name', 'age', 'info'])
-# )
-
-# def test_field_with_dictionary(self):
-# """
-# Make sure that dictionaries from fields are left intact
-# """
-# serializer = PersonSerializer(self.person)
-# expected = self.person_data
-# self.assertEqual(serializer.data['info'], expected)
-
-# def test_read_only_fields(self):
-# """
-# Attempting to update fields set as read_only should have no effect.
-# """
-# serializer = PersonSerializer(self.person, data={'name': 'dwight', 'age': 99})
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(serializer.errors, {})
-# # Assert age is unchanged (35)
-# self.assertEqual(instance.age, self.person_data['age'])
-
-# def test_invalid_read_only_fields(self):
-# """
-# Regression test for #652.
-# """
-# self.assertRaises(AssertionError, PersonSerializerInvalidReadOnly, [])
-
-# def test_serializer_data_is_cleared_on_save(self):
-# """
-# Check _data attribute is cleared on `save()`
-
-# Regression test for #1116
-# — id field is not populated if `data` is accessed prior to `save()`
-# """
-# serializer = ActionItemSerializer(self.actionitem)
-# self.assertIsNone(serializer.data.get('id', None), 'New instance. `id` should not be set.')
-# serializer.save()
-# self.assertIsNotNone(serializer.data.get('id', None), 'Model is saved. `id` should be set.')
-
-# def test_fields_marked_as_not_required_are_excluded_from_validation(self):
-# """
-# Check that fields with `required=False` are included in list of exclusions.
-# """
-# serializer = ActionItemSerializerOptionalFields(self.actionitem)
-# exclusions = serializer.get_validation_exclusions()
-# self.assertTrue('title' in exclusions, '`title` field was marked `required=False` and should be excluded')
-
-
-# class DictStyleSerializer(serializers.Serializer):
-# """
-# Note that we don't have any `restore_object` method, so the default
-# case of simply returning a dict will apply.
-# """
-# email = serializers.EmailField()
-
-
-# class DictStyleSerializerTests(TestCase):
-# def test_dict_style_deserialize(self):
-# """
-# Ensure serializers can deserialize into a dict.
-# """
-# data = {'email': 'foo@example.com'}
-# serializer = DictStyleSerializer(data=data)
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, data)
-
-# def test_dict_style_serialize(self):
-# """
-# Ensure serializers can serialize dict objects.
-# """
-# data = {'email': 'foo@example.com'}
-# serializer = DictStyleSerializer(data)
-# self.assertEqual(serializer.data, data)
-
-
-# class ValidationTests(TestCase):
-# def setUp(self):
-# self.comment = Comment(
-# 'tom@example.com',
-# 'Happy new year!',
-# datetime.datetime(2012, 1, 1)
-# )
-# self.data = {
-# 'email': 'tom@example.com',
-# 'content': 'x' * 1001,
-# 'created': datetime.datetime(2012, 1, 1)
-# }
-# self.actionitem = ActionItem(title='Some to do item',)
-
-# def test_create(self):
-# serializer = CommentSerializer(data=self.data)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']})
-
-# def test_update(self):
-# serializer = CommentSerializer(self.comment, data=self.data)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']})
-
-# def test_update_missing_field(self):
-# data = {
-# 'content': 'xxx',
-# 'created': datetime.datetime(2012, 1, 1)
-# }
-# serializer = CommentSerializer(self.comment, data=data)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, {'email': ['This field is required.']})
-
-# def test_missing_bool_with_default(self):
-# """Make sure that a boolean value with a 'False' value is not
-# mistaken for not having a default."""
-# data = {
-# 'title': 'Some action item',
-# # No 'done' value.
-# }
-# serializer = ActionItemSerializer(self.actionitem, data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.errors, {})
-
-# def test_cross_field_validation(self):
-
-# class CommentSerializerWithCrossFieldValidator(CommentSerializer):
-
-# def validate(self, attrs):
-# if attrs["email"] not in attrs["content"]:
-# raise serializers.ValidationError("Email address not in content")
-# return attrs
-
-# data = {
-# 'email': 'tom@example.com',
-# 'content': 'A comment from tom@example.com',
-# 'created': datetime.datetime(2012, 1, 1)
-# }
-
-# serializer = CommentSerializerWithCrossFieldValidator(data=data)
-# self.assertTrue(serializer.is_valid())
-
-# data['content'] = 'A comment from foo@bar.com'
-
-# serializer = CommentSerializerWithCrossFieldValidator(data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'non_field_errors': ['Email address not in content']})
-
-# def test_null_is_true_fields(self):
-# """
-# Omitting a value for null-field should validate.
-# """
-# serializer = PersonSerializer(data={'name': 'marko'})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.errors, {})
-
-# def test_modelserializer_max_length_exceeded(self):
-# data = {
-# 'title': 'x' * 201,
-# }
-# serializer = ActionItemSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']})
-
-# def test_modelserializer_max_length_exceeded_with_custom_restore(self):
-# """
-# When overriding ModelSerializer.restore_object, validation tests should still apply.
-# Regression test for #623.
-
-# https://github.com/tomchristie/django-rest-framework/pull/623
-# """
-# data = {
-# 'title': 'x' * 201,
-# }
-# serializer = ActionItemSerializerCustomRestore(data=data)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']})
-
-# def test_default_modelfield_max_length_exceeded(self):
-# data = {
-# 'title': 'Testing "info" field...',
-# 'info': 'x' * 13,
-# }
-# serializer = ActionItemSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, {'info': ['Ensure this value has at most 12 characters (it has 13).']})
-
-# def test_datetime_validation_failure(self):
-# """
-# Test DateTimeField validation errors on non-str values.
-# Regression test for #669.
-
-# https://github.com/tomchristie/django-rest-framework/issues/669
-# """
-# data = self.data
-# data['created'] = 0
-
-# serializer = CommentSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), False)
-
-# self.assertIn('created', serializer.errors)
-
-# def test_missing_model_field_exception_msg(self):
-# """
-# Assert that a meaningful exception message is outputted when the model
-# field is missing (e.g. when mistyping ``model``).
-# """
-# class BrokenModelSerializer(serializers.ModelSerializer):
-# class Meta:
-# fields = ['some_field']
-
-# try:
-# BrokenModelSerializer()
-# except AssertionError as e:
-# self.assertEqual(e.args[0], "Serializer class 'BrokenModelSerializer' is missing 'model' Meta option")
-# except:
-# self.fail('Wrong exception type thrown.')
-
-# def test_writable_star_source_on_nested_serializer(self):
-# """
-# Assert that a nested serializer instantiated with source='*' correctly
-# expands the data into the outer serializer.
-# """
-# serializer = ModelSerializerWithNestedSerializer(data={
-# 'name': 'marko',
-# 'nested': {'info': 'hi'}},
-# )
-# self.assertEqual(serializer.is_valid(), True)
-
-# def test_writable_star_source_on_nested_serializer_with_parent_object(self):
-# class TitleSerializer(serializers.Serializer):
-# title = serializers.WritableField(source='title')
-
-# class AlbumSerializer(serializers.ModelSerializer):
-# nested = TitleSerializer(source='*')
-
-# class Meta:
-# model = Album
-# fields = ('nested',)
-
-# class PhotoSerializer(serializers.ModelSerializer):
-# album = AlbumSerializer(source='album')
-
-# class Meta:
-# model = Photo
-# fields = ('album', )
-
-# photo = Photo(album=Album())
-
-# data = {'album': {'nested': {'title': 'test'}}}
-
-# serializer = PhotoSerializer(photo, data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.data, data)
-
-# def test_writable_star_source_with_inner_source_fields(self):
-# """
-# Tests that a serializer with source="*" correctly expands the
-# it's fields into the outer serializer even if they have their
-# own 'source' parameters.
-# """
-
-# serializer = ModelSerializerWithNestedSerializerWithRenamedField(data={
-# 'name': 'marko',
-# 'nested': {'renamed_info': 'hi'}},
-# )
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.errors, {})
-
-
-# class CustomValidationTests(TestCase):
-# class CommentSerializerWithFieldValidator(CommentSerializer):
-
-# def validate_email(self, attrs, source):
-# attrs[source]
-# return attrs
-
-# def validate_content(self, attrs, source):
-# value = attrs[source]
-# if "test" not in value:
-# raise serializers.ValidationError("Test not in value")
-# return attrs
-
-# def test_field_validation(self):
-# data = {
-# 'email': 'tom@example.com',
-# 'content': 'A test comment',
-# 'created': datetime.datetime(2012, 1, 1)
-# }
-
-# serializer = self.CommentSerializerWithFieldValidator(data=data)
-# self.assertTrue(serializer.is_valid())
-
-# data['content'] = 'This should not validate'
-
-# serializer = self.CommentSerializerWithFieldValidator(data=data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'content': ['Test not in value']})
-
-# def test_missing_data(self):
-# """
-# Make sure that validate_content isn't called if the field is missing
-# """
-# incomplete_data = {
-# 'email': 'tom@example.com',
-# 'created': datetime.datetime(2012, 1, 1)
-# }
-# serializer = self.CommentSerializerWithFieldValidator(data=incomplete_data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'content': ['This field is required.']})
-
-# def test_wrong_data(self):
-# """
-# Make sure that validate_content isn't called if the field input is wrong
-# """
-# wrong_data = {
-# 'email': 'not an email',
-# 'content': 'A test comment',
-# 'created': datetime.datetime(2012, 1, 1)
-# }
-# serializer = self.CommentSerializerWithFieldValidator(data=wrong_data)
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'email': ['Enter a valid email address.']})
-
-# def test_partial_update(self):
-# """
-# Make sure that validate_email isn't called when partial=True and email
-# isn't found in data.
-# """
-# initial_data = {
-# 'email': 'tom@example.com',
-# 'content': 'A test comment',
-# 'created': datetime.datetime(2012, 1, 1)
-# }
-
-# serializer = self.CommentSerializerWithFieldValidator(data=initial_data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.object
-
-# new_content = 'An *updated* test comment'
-# partial_data = {
-# 'content': new_content
-# }
-
-# serializer = self.CommentSerializerWithFieldValidator(instance=instance,
-# data=partial_data,
-# partial=True)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.object
-# self.assertEqual(instance.content, new_content)
-
-
-# class PositiveIntegerAsChoiceTests(TestCase):
-# def test_positive_integer_in_json_is_correctly_parsed(self):
-# data = {'some_integer': 1}
-# serializer = PositiveIntegerAsChoiceSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-
-
-# class ModelValidationTests(TestCase):
-# def test_validate_unique(self):
-# """
-# Just check if serializers.ModelSerializer handles unique checks via .full_clean()
-# """
-# serializer = AlbumsSerializer(data={'title': 'a', 'ref': '1'})
-# serializer.is_valid()
-# serializer.save()
-# second_serializer = AlbumsSerializer(data={'title': 'a'})
-# self.assertFalse(second_serializer.is_valid())
-# self.assertEqual(second_serializer.errors, {'title': ['Album with this Title already exists.']})
-# third_serializer = AlbumsSerializer(data=[{'title': 'b', 'ref': '1'}, {'title': 'c'}], many=True)
-# self.assertFalse(third_serializer.is_valid())
-# self.assertEqual(third_serializer.errors, [{'ref': ['Album with this Ref already exists.']}, {}])
-
-# def test_foreign_key_is_null_with_partial(self):
-# """
-# Test ModelSerializer validation with partial=True
-
-# Specifically test that a null foreign key does not pass validation
-# """
-# album = Album(title='test')
-# album.save()
-
-# class PhotoSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Photo
-
-# photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk})
-# self.assertTrue(photo_serializer.is_valid())
-# photo = photo_serializer.save()
-
-# # Updating only the album (foreign key)
-# photo_serializer = PhotoSerializer(instance=photo, data={'album': ''}, partial=True)
-# self.assertFalse(photo_serializer.is_valid())
-# self.assertTrue('album' in photo_serializer.errors)
-# self.assertEqual(photo_serializer.errors['album'], [photo_serializer.error_messages['required']])
-
-# def test_foreign_key_with_partial(self):
-# """
-# Test ModelSerializer validation with partial=True
-
-# Specifically test foreign key validation.
-# """
-
-# album = Album(title='test')
-# album.save()
-
-# class PhotoSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Photo
-
-# photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk})
-# self.assertTrue(photo_serializer.is_valid())
-# photo = photo_serializer.save()
-
-# # Updating only the album (foreign key)
-# photo_serializer = PhotoSerializer(instance=photo, data={'album': album.pk}, partial=True)
-# self.assertTrue(photo_serializer.is_valid())
-# self.assertTrue(photo_serializer.save())
-
-# # Updating only the description
-# photo_serializer = PhotoSerializer(instance=photo,
-# data={'description': 'new'},
-# partial=True)
-
-# self.assertTrue(photo_serializer.is_valid())
-# self.assertTrue(photo_serializer.save())
-
-
-# class RegexValidationTest(TestCase):
-# def test_create_failed(self):
-# serializer = BookSerializer(data={'isbn': '1234567890'})
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']})
-
-# serializer = BookSerializer(data={'isbn': '12345678901234'})
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']})
-
-# serializer = BookSerializer(data={'isbn': 'abcdefghijklm'})
-# self.assertFalse(serializer.is_valid())
-# self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']})
-
-# def test_create_success(self):
-# serializer = BookSerializer(data={'isbn': '1234567890123'})
-# self.assertTrue(serializer.is_valid())
-
-
-# class MetadataTests(TestCase):
-# def test_empty(self):
-# serializer = CommentSerializer()
-# expected = {
-# 'email': serializers.CharField,
-# 'content': serializers.CharField,
-# 'created': serializers.DateTimeField
-# }
-# for field_name, field in expected.items():
-# self.assertTrue(isinstance(serializer.data.fields[field_name], field))
-
-
-# class ManyToManyTests(TestCase):
-# def setUp(self):
-# class ManyToManySerializer(serializers.ModelSerializer):
-# class Meta:
-# model = ManyToManyModel
-
-# self.serializer_class = ManyToManySerializer
-
-# # An anchor instance to use for the relationship
-# self.anchor = Anchor()
-# self.anchor.save()
-
-# # A model instance with a many to many relationship to the anchor
-# self.instance = ManyToManyModel()
-# self.instance.save()
-# self.instance.rel.add(self.anchor)
-
-# # A serialized representation of the model instance
-# self.data = {'id': 1, 'rel': [self.anchor.id]}
-
-# def test_retrieve(self):
-# """
-# Serialize an instance of a model with a ManyToMany relationship.
-# """
-# serializer = self.serializer_class(instance=self.instance)
-# expected = self.data
-# self.assertEqual(serializer.data, expected)
-
-# def test_create(self):
-# """
-# Create an instance of a model with a ManyToMany relationship.
-# """
-# data = {'rel': [self.anchor.id]}
-# serializer = self.serializer_class(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(ManyToManyModel.objects.all()), 2)
-# self.assertEqual(instance.pk, 2)
-# self.assertEqual(list(instance.rel.all()), [self.anchor])
-
-# def test_update(self):
-# """
-# Update an instance of a model with a ManyToMany relationship.
-# """
-# new_anchor = Anchor()
-# new_anchor.save()
-# data = {'rel': [self.anchor.id, new_anchor.id]}
-# serializer = self.serializer_class(self.instance, data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(ManyToManyModel.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# self.assertEqual(list(instance.rel.all()), [self.anchor, new_anchor])
-
-# def test_create_empty_relationship(self):
-# """
-# Create an instance of a model with a ManyToMany relationship,
-# containing no items.
-# """
-# data = {'rel': []}
-# serializer = self.serializer_class(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(ManyToManyModel.objects.all()), 2)
-# self.assertEqual(instance.pk, 2)
-# self.assertEqual(list(instance.rel.all()), [])
-
-# def test_update_empty_relationship(self):
-# """
-# Update an instance of a model with a ManyToMany relationship,
-# containing no items.
-# """
-# new_anchor = Anchor()
-# new_anchor.save()
-# data = {'rel': []}
-# serializer = self.serializer_class(self.instance, data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(ManyToManyModel.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# self.assertEqual(list(instance.rel.all()), [])
-
-# def test_create_empty_relationship_flat_data(self):
-# """
-# Create an instance of a model with a ManyToMany relationship,
-# containing no items, using a representation that does not support
-# lists (eg form data).
-# """
-# data = MultiValueDict()
-# data.setlist('rel', [''])
-# serializer = self.serializer_class(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(ManyToManyModel.objects.all()), 2)
-# self.assertEqual(instance.pk, 2)
-# self.assertEqual(list(instance.rel.all()), [])
-
-
-# class ReadOnlyManyToManyTests(TestCase):
-# def setUp(self):
-# class ReadOnlyManyToManySerializer(serializers.ModelSerializer):
-# rel = serializers.RelatedField(many=True, read_only=True)
-
-# class Meta:
-# model = ReadOnlyManyToManyModel
-
-# self.serializer_class = ReadOnlyManyToManySerializer
-
-# # An anchor instance to use for the relationship
-# self.anchor = Anchor()
-# self.anchor.save()
-
-# # A model instance with a many to many relationship to the anchor
-# self.instance = ReadOnlyManyToManyModel()
-# self.instance.save()
-# self.instance.rel.add(self.anchor)
-
-# # A serialized representation of the model instance
-# self.data = {'rel': [self.anchor.id], 'id': 1, 'text': 'anchor'}
-
-# def test_update(self):
-# """
-# Attempt to update an instance of a model with a ManyToMany
-# relationship. Not updated due to read_only=True
-# """
-# new_anchor = Anchor()
-# new_anchor.save()
-# data = {'rel': [self.anchor.id, new_anchor.id]}
-# serializer = self.serializer_class(self.instance, data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# # rel is still as original (1 entry)
-# self.assertEqual(list(instance.rel.all()), [self.anchor])
-
-# def test_update_without_relationship(self):
-# """
-# Attempt to update an instance of a model where many to ManyToMany
-# relationship is not supplied. Not updated due to read_only=True
-# """
-# new_anchor = Anchor()
-# new_anchor.save()
-# data = {}
-# serializer = self.serializer_class(self.instance, data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# # rel is still as original (1 entry)
-# self.assertEqual(list(instance.rel.all()), [self.anchor])
-
-
-# class DefaultValueTests(TestCase):
-# def setUp(self):
-# class DefaultValueSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = DefaultValueModel
-
-# self.serializer_class = DefaultValueSerializer
-# self.objects = DefaultValueModel.objects
-
-# def test_create_using_default(self):
-# data = {}
-# serializer = self.serializer_class(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(self.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# self.assertEqual(instance.text, 'foobar')
-
-# def test_create_overriding_default(self):
-# data = {'text': 'overridden'}
-# serializer = self.serializer_class(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(self.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# self.assertEqual(instance.text, 'overridden')
-
-# def test_partial_update_default(self):
-# """ Regression test for issue #532 """
-# data = {'text': 'overridden'}
-# serializer = self.serializer_class(data=data, partial=True)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-
-# data = {'extra': 'extra_value'}
-# serializer = self.serializer_class(instance=instance, data=data, partial=True)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-
-# self.assertEqual(instance.extra, 'extra_value')
-# self.assertEqual(instance.text, 'overridden')
-
-
-# class WritableFieldDefaultValueTests(TestCase):
-
-# def setUp(self):
-# self.expected = {'default': 'value'}
-# self.create_field = fields.WritableField
-
-# def test_get_default_value_with_noncallable(self):
-# field = self.create_field(default=self.expected)
-# got = field.get_default_value()
-# self.assertEqual(got, self.expected)
-
-# def test_get_default_value_with_callable(self):
-# field = self.create_field(default=lambda: self.expected)
-# got = field.get_default_value()
-# self.assertEqual(got, self.expected)
-
-# def test_get_default_value_when_not_required(self):
-# field = self.create_field(default=self.expected, required=False)
-# got = field.get_default_value()
-# self.assertEqual(got, self.expected)
-
-# def test_get_default_value_returns_None(self):
-# field = self.create_field()
-# got = field.get_default_value()
-# self.assertIsNone(got)
-
-# def test_get_default_value_returns_non_True_values(self):
-# values = [None, '', False, 0, [], (), {}] # values that assumed as 'False' in the 'if' clause
-# for expected in values:
-# field = self.create_field(default=expected)
-# got = field.get_default_value()
-# self.assertEqual(got, expected)
-
-
-# class RelatedFieldDefaultValueTests(WritableFieldDefaultValueTests):
-
-# def setUp(self):
-# self.expected = {'foo': 'bar'}
-# self.create_field = relations.RelatedField
-
-# def test_get_default_value_returns_empty_list(self):
-# field = self.create_field(many=True)
-# got = field.get_default_value()
-# self.assertListEqual(got, [])
-
-# def test_get_default_value_returns_expected(self):
-# expected = [1, 2, 3]
-# field = self.create_field(many=True, default=expected)
-# got = field.get_default_value()
-# self.assertListEqual(got, expected)
-
-
-# class CallableDefaultValueTests(TestCase):
-# def setUp(self):
-# class CallableDefaultValueSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = CallableDefaultValueModel
-
-# self.serializer_class = CallableDefaultValueSerializer
-# self.objects = CallableDefaultValueModel.objects
-
-# def test_create_using_default(self):
-# data = {}
-# serializer = self.serializer_class(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(self.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# self.assertEqual(instance.text, 'foobar')
-
-# def test_create_overriding_default(self):
-# data = {'text': 'overridden'}
-# serializer = self.serializer_class(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# instance = serializer.save()
-# self.assertEqual(len(self.objects.all()), 1)
-# self.assertEqual(instance.pk, 1)
-# self.assertEqual(instance.text, 'overridden')
-
-
-# class ManyRelatedTests(TestCase):
-# def test_reverse_relations(self):
-# post = BlogPost.objects.create(title="Test blog post")
-# post.blogpostcomment_set.create(text="I hate this blog post")
-# post.blogpostcomment_set.create(text="I love this blog post")
-
-# class BlogPostCommentSerializer(serializers.Serializer):
-# text = serializers.CharField()
-
-# class BlogPostSerializer(serializers.Serializer):
-# title = serializers.CharField()
-# comments = BlogPostCommentSerializer(source='blogpostcomment_set')
-
-# serializer = BlogPostSerializer(instance=post)
-# expected = {
-# 'title': 'Test blog post',
-# 'comments': [
-# {'text': 'I hate this blog post'},
-# {'text': 'I love this blog post'}
-# ]
-# }
-
-# self.assertEqual(serializer.data, expected)
-
-# def test_include_reverse_relations(self):
-# post = BlogPost.objects.create(title="Test blog post")
-# post.blogpostcomment_set.create(text="I hate this blog post")
-# post.blogpostcomment_set.create(text="I love this blog post")
-
-# class BlogPostSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = BlogPost
-# fields = ('id', 'title', 'blogpostcomment_set')
-
-# serializer = BlogPostSerializer(instance=post)
-# expected = {
-# 'id': 1, 'title': 'Test blog post', 'blogpostcomment_set': [1, 2]
-# }
-# self.assertEqual(serializer.data, expected)
-
-# def test_depth_include_reverse_relations(self):
-# post = BlogPost.objects.create(title="Test blog post")
-# post.blogpostcomment_set.create(text="I hate this blog post")
-# post.blogpostcomment_set.create(text="I love this blog post")
-
-# class BlogPostSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = BlogPost
-# fields = ('id', 'title', 'blogpostcomment_set')
-# depth = 1
-
-# serializer = BlogPostSerializer(instance=post)
-# expected = {
-# 'id': 1, 'title': 'Test blog post',
-# 'blogpostcomment_set': [
-# {'id': 1, 'text': 'I hate this blog post', 'blog_post': 1},
-# {'id': 2, 'text': 'I love this blog post', 'blog_post': 1}
-# ]
-# }
-# self.assertEqual(serializer.data, expected)
-
-# def test_callable_source(self):
-# post = BlogPost.objects.create(title="Test blog post")
-# post.blogpostcomment_set.create(text="I love this blog post")
-
-# class BlogPostCommentSerializer(serializers.Serializer):
-# text = serializers.CharField()
-
-# class BlogPostSerializer(serializers.Serializer):
-# title = serializers.CharField()
-# first_comment = BlogPostCommentSerializer(source='get_first_comment')
-
-# serializer = BlogPostSerializer(post)
-
-# expected = {
-# 'title': 'Test blog post',
-# 'first_comment': {'text': 'I love this blog post'}
-# }
-# self.assertEqual(serializer.data, expected)
-
-
-# class RelatedTraversalTest(TestCase):
-# def test_nested_traversal(self):
-# """
-# Source argument should support dotted.source notation.
-# """
-# user = Person.objects.create(name="django")
-# post = BlogPost.objects.create(title="Test blog post", writer=user)
-# post.blogpostcomment_set.create(text="I love this blog post")
-
-# class PersonSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Person
-# fields = ("name", "age")
-
-# class BlogPostCommentSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = BlogPostComment
-# fields = ("text", "post_owner")
-
-# text = serializers.CharField()
-# post_owner = PersonSerializer(source='blog_post.writer')
-
-# class BlogPostSerializer(serializers.Serializer):
-# title = serializers.CharField()
-# comments = BlogPostCommentSerializer(source='blogpostcomment_set')
-
-# serializer = BlogPostSerializer(instance=post)
-
-# expected = {
-# 'title': 'Test blog post',
-# 'comments': [{
-# 'text': 'I love this blog post',
-# 'post_owner': {
-# "name": "django",
-# "age": None
-# }
-# }]
-# }
-
-# self.assertEqual(serializer.data, expected)
-
-# def test_nested_traversal_with_none(self):
-# """
-# If a component of the dotted.source is None, return None for the field.
-# """
-# from tests.models import NullableForeignKeySource
-# instance = NullableForeignKeySource.objects.create(name='Source with null FK')
-
-# class NullableSourceSerializer(serializers.Serializer):
-# target_name = serializers.Field(source='target.name')
-
-# serializer = NullableSourceSerializer(instance=instance)
-
-# expected = {
-# 'target_name': None,
-# }
-
-# self.assertEqual(serializer.data, expected)
-
-
-# class SerializerMethodFieldTests(TestCase):
-# def setUp(self):
-
-# class BoopSerializer(serializers.Serializer):
-# beep = serializers.SerializerMethodField('get_beep')
-# boop = serializers.Field()
-# boop_count = serializers.SerializerMethodField('get_boop_count')
-
-# def get_beep(self, obj):
-# return 'hello!'
-
-# def get_boop_count(self, obj):
-# return len(obj.boop)
-
-# self.serializer_class = BoopSerializer
-
-# def test_serializer_method_field(self):
-
-# class MyModel(object):
-# boop = ['a', 'b', 'c']
-
-# source_data = MyModel()
-
-# serializer = self.serializer_class(source_data)
-
-# expected = {
-# 'beep': 'hello!',
-# 'boop': ['a', 'b', 'c'],
-# 'boop_count': 3,
-# }
-
-# self.assertEqual(serializer.data, expected)
-
-
-# # Test for issue #324
-# class BlankFieldTests(TestCase):
-# def setUp(self):
-
-# class BlankFieldModelSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = BlankFieldModel
-
-# class BlankFieldSerializer(serializers.Serializer):
-# title = serializers.CharField(required=False)
-
-# class NotBlankFieldModelSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = BasicModel
-
-# class NotBlankFieldSerializer(serializers.Serializer):
-# title = serializers.CharField()
-
-# self.model_serializer_class = BlankFieldModelSerializer
-# self.serializer_class = BlankFieldSerializer
-# self.not_blank_model_serializer_class = NotBlankFieldModelSerializer
-# self.not_blank_serializer_class = NotBlankFieldSerializer
-# self.data = {'title': ''}
-
-# def test_create_blank_field(self):
-# serializer = self.serializer_class(data=self.data)
-# self.assertEqual(serializer.is_valid(), True)
-
-# def test_create_model_blank_field(self):
-# serializer = self.model_serializer_class(data=self.data)
-# self.assertEqual(serializer.is_valid(), True)
-
-# def test_create_model_null_field(self):
-# serializer = self.model_serializer_class(data={'title': None})
-# self.assertEqual(serializer.is_valid(), True)
-# serializer.save()
-# self.assertIsNot(serializer.object.pk, None)
-# self.assertEqual(serializer.object.title, '')
-
-# def test_create_not_blank_field(self):
-# """
-# Test to ensure blank data in a field not marked as blank=True
-# is considered invalid in a non-model serializer
-# """
-# serializer = self.not_blank_serializer_class(data=self.data)
-# self.assertEqual(serializer.is_valid(), False)
-
-# def test_create_model_not_blank_field(self):
-# """
-# Test to ensure blank data in a field not marked as blank=True
-# is considered invalid in a model serializer
-# """
-# serializer = self.not_blank_model_serializer_class(data=self.data)
-# self.assertEqual(serializer.is_valid(), False)
-
-# def test_create_model_empty_field(self):
-# serializer = self.model_serializer_class(data={})
-# self.assertEqual(serializer.is_valid(), True)
-
-# def test_create_model_null_field_save(self):
-# """
-# Regression test for #1330.
-
-# https://github.com/tomchristie/django-rest-framework/pull/1330
-# """
-# serializer = self.model_serializer_class(data={'title': None})
-# self.assertEqual(serializer.is_valid(), True)
-
-# try:
-# serializer.save()
-# except Exception:
-# self.fail('Exception raised on save() after validation passes')
-
-
-# # Test for issue #460
-# class SerializerPickleTests(TestCase):
-# """
-# Test pickleability of the output of Serializers
-# """
-# def test_pickle_simple_model_serializer_data(self):
-# """
-# Test simple serializer
-# """
-# pickle.dumps(PersonSerializer(Person(name="Methusela", age=969)).data)
-
-# def test_pickle_inner_serializer(self):
-# """
-# Test pickling a serializer whose resulting .data (a SortedDictWithMetadata) will
-# have unpickleable meta data--in order to make sure metadata doesn't get pulled into the pickle.
-# See DictWithMetadata.__getstate__
-# """
-# class InnerPersonSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Person
-# fields = ('name', 'age')
-# pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data, 0)
-
-# def test_getstate_method_should_not_return_none(self):
-# """
-# Regression test for #645.
-# """
-# data = serializers.DictWithMetadata({1: 1})
-# self.assertEqual(data.__getstate__(), serializers.SortedDict({1: 1}))
-
-# def test_serializer_data_is_pickleable(self):
-# """
-# Another regression test for #645.
-# """
-# data = serializers.SortedDictWithMetadata({1: 1})
-# repr(pickle.loads(pickle.dumps(data, 0)))
-
-
-# # test for issue #725
-# class SeveralChoicesModel(models.Model):
-# color = models.CharField(
-# max_length=10,
-# choices=[('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')],
-# blank=False
-# )
-# drink = models.CharField(
-# max_length=10,
-# choices=[('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')],
-# blank=False,
-# default='beer'
-# )
-# os = models.CharField(
-# max_length=10,
-# choices=[('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')],
-# blank=True
-# )
-# music_genre = models.CharField(
-# max_length=10,
-# choices=[('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')],
-# blank=True,
-# default='metal'
-# )
-
-
-# class SerializerChoiceFields(TestCase):
-
-# def setUp(self):
-# super(SerializerChoiceFields, self).setUp()
-
-# class SeveralChoicesSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = SeveralChoicesModel
-# fields = ('color', 'drink', 'os', 'music_genre')
-
-# self.several_choices_serializer = SeveralChoicesSerializer
-
-# def test_choices_blank_false_not_default(self):
-# serializer = self.several_choices_serializer()
-# self.assertEqual(
-# serializer.fields['color'].choices,
-# [('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')]
-# )
-
-# def test_choices_blank_false_with_default(self):
-# serializer = self.several_choices_serializer()
-# self.assertEqual(
-# serializer.fields['drink'].choices,
-# [('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')]
-# )
-
-# def test_choices_blank_true_not_default(self):
-# serializer = self.several_choices_serializer()
-# self.assertEqual(
-# serializer.fields['os'].choices,
-# BLANK_CHOICE_DASH + [('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')]
-# )
-
-# def test_choices_blank_true_with_default(self):
-# serializer = self.several_choices_serializer()
-# self.assertEqual(
-# serializer.fields['music_genre'].choices,
-# BLANK_CHOICE_DASH + [('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')]
-# )
-
-
-# # Regression tests for #675
-# class Ticket(models.Model):
-# assigned = models.ForeignKey(
-# Person, related_name='assigned_tickets')
-# reviewer = models.ForeignKey(
-# Person, blank=True, null=True, related_name='reviewed_tickets')
-
-
-# class SerializerRelatedChoicesTest(TestCase):
-
-# def setUp(self):
-# super(SerializerRelatedChoicesTest, self).setUp()
-
-# class RelatedChoicesSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Ticket
-# fields = ('assigned', 'reviewer')
-
-# self.related_fields_serializer = RelatedChoicesSerializer
-
-# def test_empty_queryset_required(self):
-# serializer = self.related_fields_serializer()
-# self.assertEqual(serializer.fields['assigned'].queryset.count(), 0)
-# self.assertEqual(
-# [x for x in serializer.fields['assigned'].widget.choices],
-# []
-# )
-
-# def test_empty_queryset_not_required(self):
-# serializer = self.related_fields_serializer()
-# self.assertEqual(serializer.fields['reviewer'].queryset.count(), 0)
-# self.assertEqual(
-# [x for x in serializer.fields['reviewer'].widget.choices],
-# [('', '---------')]
-# )
-
-# def test_with_some_persons_required(self):
-# Person.objects.create(name="Lionel Messi")
-# Person.objects.create(name="Xavi Hernandez")
-# serializer = self.related_fields_serializer()
-# self.assertEqual(serializer.fields['assigned'].queryset.count(), 2)
-# self.assertEqual(
-# [x for x in serializer.fields['assigned'].widget.choices],
-# [(1, 'Person object - 1'), (2, 'Person object - 2')]
-# )
-
-# def test_with_some_persons_not_required(self):
-# Person.objects.create(name="Lionel Messi")
-# Person.objects.create(name="Xavi Hernandez")
-# serializer = self.related_fields_serializer()
-# self.assertEqual(serializer.fields['reviewer'].queryset.count(), 2)
-# self.assertEqual(
-# [x for x in serializer.fields['reviewer'].widget.choices],
-# [('', '---------'), (1, 'Person object - 1'), (2, 'Person object - 2')]
-# )
-
-
-# class DepthTest(TestCase):
-# def test_implicit_nesting(self):
-
-# writer = Person.objects.create(name="django", age=1)
-# post = BlogPost.objects.create(title="Test blog post", writer=writer)
-# comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post)
-
-# class BlogPostCommentSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = BlogPostComment
-# depth = 2
-
-# serializer = BlogPostCommentSerializer(instance=comment)
-# expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post',
-# 'writer': {'id': 1, 'name': 'django', 'age': 1}}}
-
-# self.assertEqual(serializer.data, expected)
-
-# def test_explicit_nesting(self):
-# writer = Person.objects.create(name="django", age=1)
-# post = BlogPost.objects.create(title="Test blog post", writer=writer)
-# comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post)
-
-# class PersonSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Person
-
-# class BlogPostSerializer(serializers.ModelSerializer):
-# writer = PersonSerializer()
-
-# class Meta:
-# model = BlogPost
-
-# class BlogPostCommentSerializer(serializers.ModelSerializer):
-# blog_post = BlogPostSerializer()
-
-# class Meta:
-# model = BlogPostComment
-
-# serializer = BlogPostCommentSerializer(instance=comment)
-# expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post',
-# 'writer': {'id': 1, 'name': 'django', 'age': 1}}}
-
-# self.assertEqual(serializer.data, expected)
-
-
-# class NestedSerializerContextTests(TestCase):
-
-# def test_nested_serializer_context(self):
-# """
-# Regression for #497
-
-# https://github.com/tomchristie/django-rest-framework/issues/497
-# """
-# class PhotoSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Photo
-# fields = ("description", "callable")
-
-# callable = serializers.SerializerMethodField('_callable')
-
-# def _callable(self, instance):
-# if 'context_item' not in self.context:
-# raise RuntimeError("context isn't getting passed into 2nd level nested serializer")
-# return "success"
-
-# class AlbumSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = Album
-# fields = ("photo_set", "callable")
-
-# photo_set = PhotoSerializer(source="photo_set", many=True)
-# callable = serializers.SerializerMethodField("_callable")
-
-# def _callable(self, instance):
-# if 'context_item' not in self.context:
-# raise RuntimeError("context isn't getting passed into 1st level nested serializer")
-# return "success"
-
-# class AlbumCollection(object):
-# albums = None
-
-# class AlbumCollectionSerializer(serializers.Serializer):
-# albums = AlbumSerializer(source="albums", many=True)
-
-# album1 = Album.objects.create(title="album 1")
-# album2 = Album.objects.create(title="album 2")
-# Photo.objects.create(description="Bigfoot", album=album1)
-# Photo.objects.create(description="Unicorn", album=album1)
-# Photo.objects.create(description="Yeti", album=album2)
-# Photo.objects.create(description="Sasquatch", album=album2)
-# album_collection = AlbumCollection()
-# album_collection.albums = [album1, album2]
-
-# # This will raise RuntimeError if context doesn't get passed correctly to the nested Serializers
-# AlbumCollectionSerializer(album_collection, context={'context_item': 'album context'}).data
-
-
-# class DeserializeListTestCase(TestCase):
-
-# def setUp(self):
-# self.data = {
-# 'email': 'nobody@nowhere.com',
-# 'content': 'This is some test content',
-# 'created': datetime.datetime(2013, 3, 7),
-# }
-
-# def test_no_errors(self):
-# data = [self.data.copy() for x in range(0, 3)]
-# serializer = CommentSerializer(data=data, many=True)
-# self.assertTrue(serializer.is_valid())
-# self.assertTrue(isinstance(serializer.object, list))
-# self.assertTrue(
-# all((isinstance(item, Comment) for item in serializer.object))
-# )
-
-# def test_errors_return_as_list(self):
-# invalid_item = self.data.copy()
-# invalid_item['email'] = ''
-# data = [self.data.copy(), invalid_item, self.data.copy()]
-
-# serializer = CommentSerializer(data=data, many=True)
-# self.assertFalse(serializer.is_valid())
-# expected = [{}, {'email': ['This field is required.']}, {}]
-# self.assertEqual(serializer.errors, expected)
-
-
-# # Test for issue 747
-
-# class LazyStringModel(object):
-# def __init__(self, lazystring):
-# self.lazystring = lazystring
-
-
-# class LazyStringSerializer(serializers.Serializer):
-# lazystring = serializers.Field()
-
-# def restore_object(self, attrs, instance=None):
-# if instance is not None:
-# instance.lazystring = attrs.get('lazystring', instance.lazystring)
-# return instance
-# return LazyStringModel(**attrs)
-
-
-# class LazyStringsTestCase(TestCase):
-# def setUp(self):
-# self.model = LazyStringModel(lazystring=_('lazystring'))
-
-# def test_lazy_strings_are_translated(self):
-# serializer = LazyStringSerializer(self.model)
-# self.assertEqual(type(serializer.data['lazystring']),
-# type('lazystring'))
-
-
-# # Test for issue #467
-
-# class FieldLabelTest(TestCase):
-# def setUp(self):
-# self.serializer_class = BasicModelSerializer
-
-# def test_label_from_model(self):
-# """
-# Validates that label and help_text are correctly copied from the model class.
-# """
-# serializer = self.serializer_class()
-# text_field = serializer.fields['text']
-
-# self.assertEqual('Text comes here', text_field.label)
-# self.assertEqual('Text description.', text_field.help_text)
-
-# def test_field_ctor(self):
-# """
-# This is check that ctor supports both label and help_text.
-# """
-# self.assertEqual('Label', fields.Field(label='Label', help_text='Help').label)
-# self.assertEqual('Help', fields.CharField(label='Label', help_text='Help').help_text)
-# self.assertEqual('Label', relations.HyperlinkedRelatedField(view_name='fake', label='Label', help_text='Help', many=True).label)
-
-
-# # Test for issue #961
-
-# class ManyFieldHelpTextTest(TestCase):
-# def test_help_text_no_hold_down_control_msg(self):
-# """
-# Validate that help_text doesn't contain the 'Hold down "Control" ...'
-# message that Django appends to choice fields.
-# """
-# rel_field = fields.Field(help_text=ManyToManyModel._meta.get_field('rel').help_text)
-# self.assertEqual('Some help text.', rel_field.help_text)
-
-
-# class AttributeMappingOnAutogeneratedRelatedFields(TestCase):
-
-# def test_primary_key_related_field(self):
-# serializer = ForeignKeySourceSerializer()
-# self.assertEqual(serializer.fields['target'].help_text, 'Target')
-# self.assertEqual(serializer.fields['target'].label, 'Target')
-
-# def test_hyperlinked_related_field(self):
-# serializer = HyperlinkedForeignKeySourceSerializer()
-# self.assertEqual(serializer.fields['target'].help_text, 'Target')
-# self.assertEqual(serializer.fields['target'].label, 'Target')
-
-
-# @unittest.skipUnless(PIL is not None, 'PIL is not installed')
-# class AttributeMappingOnAutogeneratedFieldsTests(TestCase):
-
-# def setUp(self):
-
-# class AMOAFSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = AMOAFModel
-
-# self.serializer_class = AMOAFSerializer
-# self.fields_attributes = {
-# 'char_field': [
-# ('max_length', 1024),
-# ],
-# 'comma_separated_integer_field': [
-# ('max_length', 1024),
-# ],
-# 'decimal_field': [
-# ('max_digits', 64),
-# ('decimal_places', 32),
-# ],
-# 'email_field': [
-# ('max_length', 1024),
-# ],
-# 'file_field': [
-# ('max_length', 1024),
-# ],
-# 'image_field': [
-# ('max_length', 1024),
-# ],
-# 'slug_field': [
-# ('max_length', 1024),
-# ],
-# 'url_field': [
-# ('max_length', 1024),
-# ],
-# 'nullable_char_field': [
-# ('max_length', 1024),
-# ('allow_none', True),
-# ],
-# }
-
-# def field_test(self, field):
-# serializer = self.serializer_class(data={})
-# self.assertEqual(serializer.is_valid(), True)
-
-# for attribute in self.fields_attributes[field]:
-# self.assertEqual(
-# getattr(serializer.fields[field], attribute[0]),
-# attribute[1]
-# )
-
-# def test_char_field(self):
-# self.field_test('char_field')
-
-# def test_comma_separated_integer_field(self):
-# self.field_test('comma_separated_integer_field')
-
-# def test_decimal_field(self):
-# self.field_test('decimal_field')
-
-# def test_email_field(self):
-# self.field_test('email_field')
-
-# def test_file_field(self):
-# self.field_test('file_field')
-
-# def test_image_field(self):
-# self.field_test('image_field')
-
-# def test_slug_field(self):
-# self.field_test('slug_field')
-
-# def test_url_field(self):
-# self.field_test('url_field')
-
-# def test_nullable_char_field(self):
-# self.field_test('nullable_char_field')
-
-
-# @unittest.skipUnless(PIL is not None, 'PIL is not installed')
-# class DefaultValuesOnAutogeneratedFieldsTests(TestCase):
-
-# def setUp(self):
-
-# class DVOAFSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = DVOAFModel
-
-# self.serializer_class = DVOAFSerializer
-# self.fields_attributes = {
-# 'positive_integer_field': [
-# ('min_value', 0),
-# ],
-# 'positive_small_integer_field': [
-# ('min_value', 0),
-# ],
-# 'email_field': [
-# ('max_length', 75),
-# ],
-# 'file_field': [
-# ('max_length', 100),
-# ],
-# 'image_field': [
-# ('max_length', 100),
-# ],
-# 'slug_field': [
-# ('max_length', 50),
-# ],
-# 'url_field': [
-# ('max_length', 200),
-# ],
-# }
-
-# def field_test(self, field):
-# serializer = self.serializer_class(data={})
-# self.assertEqual(serializer.is_valid(), True)
-
-# for attribute in self.fields_attributes[field]:
-# self.assertEqual(
-# getattr(serializer.fields[field], attribute[0]),
-# attribute[1]
-# )
-
-# def test_positive_integer_field(self):
-# self.field_test('positive_integer_field')
-
-# def test_positive_small_integer_field(self):
-# self.field_test('positive_small_integer_field')
-
-# def test_email_field(self):
-# self.field_test('email_field')
-
-# def test_file_field(self):
-# self.field_test('file_field')
-
-# def test_image_field(self):
-# self.field_test('image_field')
-
-# def test_slug_field(self):
-# self.field_test('slug_field')
-
-# def test_url_field(self):
-# self.field_test('url_field')
-
-
-# class MetadataSerializer(serializers.Serializer):
-# field1 = serializers.CharField(max_length=3, required=True)
-# field2 = serializers.CharField(max_length=10, required=False)
-
-
-# class MetadataSerializerTestCase(TestCase):
-# def setUp(self):
-# self.serializer = MetadataSerializer()
-
-# def test_serializer_metadata(self):
-# metadata = self.serializer.metadata()
-# expected = {
-# 'field1': {
-# 'required': True,
-# 'max_length': 3,
-# 'type': 'string',
-# 'read_only': False
-# },
-# 'field2': {
-# 'required': False,
-# 'max_length': 10,
-# 'type': 'string',
-# 'read_only': False
-# }
-# }
-# self.assertEqual(expected, metadata)
-
-
-# # Regression test for #840
-
-# class SimpleModel(models.Model):
-# text = models.CharField(max_length=100)
-
-
-# class SimpleModelSerializer(serializers.ModelSerializer):
-# text = serializers.CharField()
-# other = serializers.CharField()
-
-# class Meta:
-# model = SimpleModel
-
-# def validate_other(self, attrs, source):
-# del attrs['other']
-# return attrs
-
-
-# class FieldValidationRemovingAttr(TestCase):
-# def test_removing_non_model_field_in_validation(self):
-# """
-# Removing an attr during field valiation should ensure that it is not
-# passed through when restoring the object.
-
-# This allows additional non-model fields to be supported.
-
-# Regression test for #840.
-# """
-# serializer = SimpleModelSerializer(data={'text': 'foo', 'other': 'bar'})
-# self.assertTrue(serializer.is_valid())
-# serializer.save()
-# self.assertEqual(serializer.object.text, 'foo')
-
-
-# # Regression test for #878
-
-# class SimpleTargetModel(models.Model):
-# text = models.CharField(max_length=100)
-
-
-# class SimplePKSourceModelSerializer(serializers.Serializer):
-# targets = serializers.PrimaryKeyRelatedField(queryset=SimpleTargetModel.objects.all(), many=True)
-# text = serializers.CharField()
-
-
-# class SimpleSlugSourceModelSerializer(serializers.Serializer):
-# targets = serializers.SlugRelatedField(queryset=SimpleTargetModel.objects.all(), many=True, slug_field='pk')
-# text = serializers.CharField()
-
-
-# class SerializerSupportsManyRelationships(TestCase):
-# def setUp(self):
-# SimpleTargetModel.objects.create(text='foo')
-# SimpleTargetModel.objects.create(text='bar')
-
-# def test_serializer_supports_pk_many_relationships(self):
-# """
-# Regression test for #878.
-
-# Note that pk behavior has a different code path to usual cases,
-# for performance reasons.
-# """
-# serializer = SimplePKSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]})
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]})
-
-# def test_serializer_supports_slug_many_relationships(self):
-# """
-# Regression test for #878.
-# """
-# serializer = SimpleSlugSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]})
-# self.assertTrue(serializer.is_valid())
-# self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]})
-
-
-# class TransformMethodsSerializer(serializers.Serializer):
-# a = serializers.CharField()
-# b_renamed = serializers.CharField(source='b')
-
-# def transform_a(self, obj, value):
-# return value.lower()
-
-# def transform_b_renamed(self, obj, value):
-# if value is not None:
-# return 'and ' + value
-
-
-# class TestSerializerTransformMethods(TestCase):
-# def setUp(self):
-# self.s = TransformMethodsSerializer()
-
-# def test_transform_methods(self):
-# self.assertEqual(
-# self.s.to_native({'a': 'GREEN EGGS', 'b': 'HAM'}),
-# {
-# 'a': 'green eggs',
-# 'b_renamed': 'and HAM',
-# }
-# )
-
-# def test_missing_fields(self):
-# self.assertEqual(
-# self.s.to_native({'a': 'GREEN EGGS'}),
-# {
-# 'a': 'green eggs',
-# 'b_renamed': None,
-# }
-# )
-
-
-# class DefaultTrueBooleanModel(models.Model):
-# cat = models.BooleanField(default=True)
-# dog = models.BooleanField(default=False)
-
-
-# class SerializerDefaultTrueBoolean(TestCase):
-
-# def setUp(self):
-# super(SerializerDefaultTrueBoolean, self).setUp()
-
-# class DefaultTrueBooleanSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = DefaultTrueBooleanModel
-# fields = ('cat', 'dog')
-
-# self.default_true_boolean_serializer = DefaultTrueBooleanSerializer
-
-# def test_enabled_as_false(self):
-# serializer = self.default_true_boolean_serializer(data={'cat': False,
-# 'dog': False})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.data['cat'], False)
-# self.assertEqual(serializer.data['dog'], False)
-
-# def test_enabled_as_true(self):
-# serializer = self.default_true_boolean_serializer(data={'cat': True,
-# 'dog': True})
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.data['cat'], True)
-# self.assertEqual(serializer.data['dog'], True)
-
-# def test_enabled_partial(self):
-# serializer = self.default_true_boolean_serializer(data={'cat': False},
-# partial=True)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.data['cat'], False)
-# self.assertEqual(serializer.data['dog'], False)
-
-
-# class BoolenFieldTypeTest(TestCase):
-# '''
-# Ensure the various Boolean based model fields are rendered as the proper
-# field type
-
-# '''
-
-# def setUp(self):
-# '''
-# Setup an ActionItemSerializer for BooleanTesting
-# '''
-# data = {
-# 'title': 'b' * 201,
-# }
-# self.serializer = ActionItemSerializer(data=data)
-
-# def test_booleanfield_type(self):
-# '''
-# Test that BooleanField is infered from models.BooleanField
-# '''
-# bfield = self.serializer.get_fields()['done']
-# self.assertEqual(type(bfield), fields.BooleanField)
-
-# def test_nullbooleanfield_type(self):
-# '''
-# Test that BooleanField is infered from models.NullBooleanField
-
-# https://groups.google.com/forum/#!topic/django-rest-framework/D9mXEftpuQ8
-# '''
-# bfield = self.serializer.get_fields()['started']
-# self.assertEqual(type(bfield), fields.BooleanField)
+from rest_framework import serializers
+import pytest
+
+
+# Tests for core functionality.
+# -----------------------------
+
+class TestSerializer:
+ def setup(self):
+ class ExampleSerializer(serializers.Serializer):
+ char = serializers.CharField()
+ integer = serializers.IntegerField()
+ self.Serializer = ExampleSerializer
+
+ def test_valid_serializer(self):
+ serializer = self.Serializer(data={'char': 'abc', 'integer': 123})
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'char': 'abc', 'integer': 123}
+ assert serializer.errors == {}
+
+ def test_invalid_serializer(self):
+ serializer = self.Serializer(data={'char': 'abc'})
+ assert not serializer.is_valid()
+ assert serializer.validated_data == {}
+ assert serializer.errors == {'integer': ['This field is required.']}
+
+ def test_partial_validation(self):
+ serializer = self.Serializer(data={'char': 'abc'}, partial=True)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'char': 'abc'}
+ assert serializer.errors == {}
+
+ def test_empty_serializer(self):
+ serializer = self.Serializer()
+ assert serializer.data == {'char': '', 'integer': None}
+
+ def test_missing_attribute_during_serialization(self):
+ class MissingAttributes:
+ pass
+ instance = MissingAttributes()
+ serializer = self.Serializer(instance)
+ with pytest.raises(AttributeError):
+ serializer.data
+
+
+class TestValidateMethod:
+ def test_non_field_error_validate_method(self):
+ class ExampleSerializer(serializers.Serializer):
+ char = serializers.CharField()
+ integer = serializers.IntegerField()
+
+ def validate(self, attrs):
+ raise serializers.ValidationError('Non field error')
+
+ serializer = ExampleSerializer(data={'char': 'abc', 'integer': 123})
+ assert not serializer.is_valid()
+ assert serializer.errors == {'non_field_errors': ['Non field error']}
+
+ def test_field_error_validate_method(self):
+ class ExampleSerializer(serializers.Serializer):
+ char = serializers.CharField()
+ integer = serializers.IntegerField()
+
+ def validate(self, attrs):
+ raise serializers.ValidationError({'char': 'Field error'})
+
+ serializer = ExampleSerializer(data={'char': 'abc', 'integer': 123})
+ assert not serializer.is_valid()
+ assert serializer.errors == {'char': ['Field error']}
+
+
+class TestBaseSerializer:
+ def setup(self):
+ class ExampleSerializer(serializers.BaseSerializer):
+ def to_representation(self, obj):
+ return {
+ 'id': obj['id'],
+ 'email': obj['name'] + '@' + obj['domain']
+ }
+
+ def to_internal_value(self, data):
+ name, domain = str(data['email']).split('@')
+ return {
+ 'id': int(data['id']),
+ 'name': name,
+ 'domain': domain,
+ }
+
+ self.Serializer = ExampleSerializer
+
+ def test_serialize_instance(self):
+ instance = {'id': 1, 'name': 'tom', 'domain': 'example.com'}
+ serializer = self.Serializer(instance)
+ assert serializer.data == {'id': 1, 'email': 'tom@example.com'}
+
+ def test_serialize_list(self):
+ instances = [
+ {'id': 1, 'name': 'tom', 'domain': 'example.com'},
+ {'id': 2, 'name': 'ann', 'domain': 'example.com'},
+ ]
+ serializer = self.Serializer(instances, many=True)
+ assert serializer.data == [
+ {'id': 1, 'email': 'tom@example.com'},
+ {'id': 2, 'email': 'ann@example.com'}
+ ]
+
+ def test_validate_data(self):
+ data = {'id': 1, 'email': 'tom@example.com'}
+ serializer = self.Serializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'id': 1,
+ 'name': 'tom',
+ 'domain': 'example.com'
+ }
+
+ def test_validate_list(self):
+ data = [
+ {'id': 1, 'email': 'tom@example.com'},
+ {'id': 2, 'email': 'ann@example.com'},
+ ]
+ serializer = self.Serializer(data=data, many=True)
+ assert serializer.is_valid()
+ assert serializer.validated_data == [
+ {'id': 1, 'name': 'tom', 'domain': 'example.com'},
+ {'id': 2, 'name': 'ann', 'domain': 'example.com'}
+ ]
+
+
+class TestStarredSource:
+ """
+ Tests for `source='*'` argument, which is used for nested representations.
+
+ For example:
+
+ nested_field = NestedField(source='*')
+ """
+ data = {
+ 'nested1': {'a': 1, 'b': 2},
+ 'nested2': {'c': 3, 'd': 4}
+ }
+
+ def setup(self):
+ class NestedSerializer1(serializers.Serializer):
+ a = serializers.IntegerField()
+ b = serializers.IntegerField()
+
+ class NestedSerializer2(serializers.Serializer):
+ c = serializers.IntegerField()
+ d = serializers.IntegerField()
+
+ class TestSerializer(serializers.Serializer):
+ nested1 = NestedSerializer1(source='*')
+ nested2 = NestedSerializer2(source='*')
+
+ self.Serializer = TestSerializer
+
+ def test_nested_validate(self):
+ """
+ A nested representation is validated into a flat internal object.
+ """
+ serializer = self.Serializer(data=self.data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'a': 1,
+ 'b': 2,
+ 'c': 3,
+ 'd': 4
+ }
+
+ def test_nested_serialize(self):
+ """
+ An object can be serialized into a nested representation.
+ """
+ instance = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
+ serializer = self.Serializer(instance)
+ assert serializer.data == self.data
diff --git a/tests/test_serializer_bulk_update.py b/tests/test_serializer_bulk_update.py
index 3341ce59..fb881a75 100644
--- a/tests/test_serializer_bulk_update.py
+++ b/tests/test_serializer_bulk_update.py
@@ -1,278 +1,123 @@
-# """
-# Tests to cover bulk create and update using serializers.
-# """
-# from __future__ import unicode_literals
-# from django.test import TestCase
-# from rest_framework import serializers
-
-
-# class BulkCreateSerializerTests(TestCase):
-# """
-# Creating multiple instances using serializers.
-# """
-
-# def setUp(self):
-# class BookSerializer(serializers.Serializer):
-# id = serializers.IntegerField()
-# title = serializers.CharField(max_length=100)
-# author = serializers.CharField(max_length=100)
-
-# self.BookSerializer = BookSerializer
-
-# def test_bulk_create_success(self):
-# """
-# Correct bulk update serialization should return the input data.
-# """
-
-# data = [
-# {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }, {
-# 'id': 1,
-# 'title': 'If this is a man',
-# 'author': 'Primo Levi'
-# }, {
-# 'id': 2,
-# 'title': 'The wind-up bird chronicle',
-# 'author': 'Haruki Murakami'
-# }
-# ]
-
-# serializer = self.BookSerializer(data=data, many=True)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, data)
-
-# def test_bulk_create_errors(self):
-# """
-# Correct bulk update serialization should return the input data.
-# """
-
-# data = [
-# {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }, {
-# 'id': 1,
-# 'title': 'If this is a man',
-# 'author': 'Primo Levi'
-# }, {
-# 'id': 'foo',
-# 'title': 'The wind-up bird chronicle',
-# 'author': 'Haruki Murakami'
-# }
-# ]
-# expected_errors = [
-# {},
-# {},
-# {'id': ['Enter a whole number.']}
-# ]
-
-# serializer = self.BookSerializer(data=data, many=True)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, expected_errors)
-
-# def test_invalid_list_datatype(self):
-# """
-# Data containing list of incorrect data type should return errors.
-# """
-# data = ['foo', 'bar', 'baz']
-# serializer = self.BookSerializer(data=data, many=True)
-# self.assertEqual(serializer.is_valid(), False)
-
-# expected_errors = [
-# {'non_field_errors': ['Invalid data']},
-# {'non_field_errors': ['Invalid data']},
-# {'non_field_errors': ['Invalid data']}
-# ]
-
-# self.assertEqual(serializer.errors, expected_errors)
-
-# def test_invalid_single_datatype(self):
-# """
-# Data containing a single incorrect data type should return errors.
-# """
-# data = 123
-# serializer = self.BookSerializer(data=data, many=True)
-# self.assertEqual(serializer.is_valid(), False)
-
-# expected_errors = {'non_field_errors': ['Expected a list of items.']}
-
-# self.assertEqual(serializer.errors, expected_errors)
-
-# def test_invalid_single_object(self):
-# """
-# Data containing only a single object, instead of a list of objects
-# should return errors.
-# """
-# data = {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }
-# serializer = self.BookSerializer(data=data, many=True)
-# self.assertEqual(serializer.is_valid(), False)
-
-# expected_errors = {'non_field_errors': ['Expected a list of items.']}
-
-# self.assertEqual(serializer.errors, expected_errors)
-
-
-# class BulkUpdateSerializerTests(TestCase):
-# """
-# Updating multiple instances using serializers.
-# """
-
-# def setUp(self):
-# class Book(object):
-# """
-# A data type that can be persisted to a mock storage backend
-# with `.save()` and `.delete()`.
-# """
-# object_map = {}
-
-# def __init__(self, id, title, author):
-# self.id = id
-# self.title = title
-# self.author = author
-
-# def save(self):
-# Book.object_map[self.id] = self
-
-# def delete(self):
-# del Book.object_map[self.id]
-
-# class BookSerializer(serializers.Serializer):
-# id = serializers.IntegerField()
-# title = serializers.CharField(max_length=100)
-# author = serializers.CharField(max_length=100)
-
-# def restore_object(self, attrs, instance=None):
-# if instance:
-# instance.id = attrs['id']
-# instance.title = attrs['title']
-# instance.author = attrs['author']
-# return instance
-# return Book(**attrs)
-
-# self.Book = Book
-# self.BookSerializer = BookSerializer
-
-# data = [
-# {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }, {
-# 'id': 1,
-# 'title': 'If this is a man',
-# 'author': 'Primo Levi'
-# }, {
-# 'id': 2,
-# 'title': 'The wind-up bird chronicle',
-# 'author': 'Haruki Murakami'
-# }
-# ]
-
-# for item in data:
-# book = Book(item['id'], item['title'], item['author'])
-# book.save()
-
-# def books(self):
-# """
-# Return all the objects in the mock storage backend.
-# """
-# return self.Book.object_map.values()
-
-# def test_bulk_update_success(self):
-# """
-# Correct bulk update serialization should return the input data.
-# """
-# data = [
-# {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }, {
-# 'id': 2,
-# 'title': 'Kafka on the shore',
-# 'author': 'Haruki Murakami'
-# }
-# ]
-# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-# new_data = self.BookSerializer(self.books(), many=True).data
-
-# self.assertEqual(data, new_data)
-
-# def test_bulk_update_and_create(self):
-# """
-# Bulk update serialization may also include created items.
-# """
-# data = [
-# {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }, {
-# 'id': 3,
-# 'title': 'Kafka on the shore',
-# 'author': 'Haruki Murakami'
-# }
-# ]
-# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.data, data)
-# serializer.save()
-# new_data = self.BookSerializer(self.books(), many=True).data
-# self.assertEqual(data, new_data)
-
-# def test_bulk_update_invalid_create(self):
-# """
-# Bulk update serialization without allow_add_remove may not create items.
-# """
-# data = [
-# {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }, {
-# 'id': 3,
-# 'title': 'Kafka on the shore',
-# 'author': 'Haruki Murakami'
-# }
-# ]
-# expected_errors = [
-# {},
-# {'non_field_errors': ['Cannot create a new item, only existing items may be updated.']}
-# ]
-# serializer = self.BookSerializer(self.books(), data=data, many=True)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, expected_errors)
-
-# def test_bulk_update_error(self):
-# """
-# Incorrect bulk update serialization should return error data.
-# """
-# data = [
-# {
-# 'id': 0,
-# 'title': 'The electric kool-aid acid test',
-# 'author': 'Tom Wolfe'
-# }, {
-# 'id': 'foo',
-# 'title': 'Kafka on the shore',
-# 'author': 'Haruki Murakami'
-# }
-# ]
-# expected_errors = [
-# {},
-# {'id': ['Enter a whole number.']}
-# ]
-# serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, expected_errors)
+"""
+Tests to cover bulk create and update using serializers.
+"""
+from __future__ import unicode_literals
+from django.test import TestCase
+from django.utils import six
+from rest_framework import serializers
+
+
+class BulkCreateSerializerTests(TestCase):
+ """
+ Creating multiple instances using serializers.
+ """
+
+ def setUp(self):
+ class BookSerializer(serializers.Serializer):
+ id = serializers.IntegerField()
+ title = serializers.CharField(max_length=100)
+ author = serializers.CharField(max_length=100)
+
+ self.BookSerializer = BookSerializer
+
+ def test_bulk_create_success(self):
+ """
+ Correct bulk update serialization should return the input data.
+ """
+
+ data = [
+ {
+ 'id': 0,
+ 'title': 'The electric kool-aid acid test',
+ 'author': 'Tom Wolfe'
+ }, {
+ 'id': 1,
+ 'title': 'If this is a man',
+ 'author': 'Primo Levi'
+ }, {
+ 'id': 2,
+ 'title': 'The wind-up bird chronicle',
+ 'author': 'Haruki Murakami'
+ }
+ ]
+
+ serializer = self.BookSerializer(data=data, many=True)
+ self.assertEqual(serializer.is_valid(), True)
+ self.assertEqual(serializer.validated_data, data)
+
+ def test_bulk_create_errors(self):
+ """
+ Incorrect bulk create serialization should return errors.
+ """
+
+ data = [
+ {
+ 'id': 0,
+ 'title': 'The electric kool-aid acid test',
+ 'author': 'Tom Wolfe'
+ }, {
+ 'id': 1,
+ 'title': 'If this is a man',
+ 'author': 'Primo Levi'
+ }, {
+ 'id': 'foo',
+ 'title': 'The wind-up bird chronicle',
+ 'author': 'Haruki Murakami'
+ }
+ ]
+ expected_errors = [
+ {},
+ {},
+ {'id': ['A valid integer is required.']}
+ ]
+
+ serializer = self.BookSerializer(data=data, many=True)
+ self.assertEqual(serializer.is_valid(), False)
+ self.assertEqual(serializer.errors, expected_errors)
+
+ def test_invalid_list_datatype(self):
+ """
+ Data containing list of incorrect data type should return errors.
+ """
+ data = ['foo', 'bar', 'baz']
+ serializer = self.BookSerializer(data=data, many=True)
+ self.assertEqual(serializer.is_valid(), False)
+
+ text_type_string = six.text_type.__name__
+ message = 'Invalid data. Expected a dictionary, but got %s.' % text_type_string
+ expected_errors = [
+ {'non_field_errors': [message]},
+ {'non_field_errors': [message]},
+ {'non_field_errors': [message]}
+ ]
+
+ self.assertEqual(serializer.errors, expected_errors)
+
+ def test_invalid_single_datatype(self):
+ """
+ Data containing a single incorrect data type should return errors.
+ """
+ data = 123
+ serializer = self.BookSerializer(data=data, many=True)
+ self.assertEqual(serializer.is_valid(), False)
+
+ expected_errors = {'non_field_errors': ['Expected a list of items but got type `int`.']}
+
+ self.assertEqual(serializer.errors, expected_errors)
+
+ def test_invalid_single_object(self):
+ """
+ Data containing only a single object, instead of a list of objects
+ should return errors.
+ """
+ data = {
+ 'id': 0,
+ 'title': 'The electric kool-aid acid test',
+ 'author': 'Tom Wolfe'
+ }
+ serializer = self.BookSerializer(data=data, many=True)
+ self.assertEqual(serializer.is_valid(), False)
+
+ expected_errors = {'non_field_errors': ['Expected a list of items but got type `dict`.']}
+
+ self.assertEqual(serializer.errors, expected_errors)
diff --git a/tests/test_serializer_empty.py b/tests/test_serializer_empty.py
deleted file mode 100644
index 805ac7d4..00000000
--- a/tests/test_serializer_empty.py
+++ /dev/null
@@ -1,15 +0,0 @@
-# from django.test import TestCase
-# from rest_framework import serializers
-
-
-# class EmptySerializerTestCase(TestCase):
-# def test_empty_serializer(self):
-# class FooBarSerializer(serializers.Serializer):
-# foo = serializers.IntegerField()
-# bar = serializers.SerializerMethodField()
-
-# def get_bar(self, obj):
-# return 'bar'
-
-# serializer = FooBarSerializer()
-# self.assertEquals(serializer.data, {'foo': 0})
diff --git a/tests/test_serializer_import.py b/tests/test_serializer_import.py
deleted file mode 100644
index d029c3c5..00000000
--- a/tests/test_serializer_import.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# from django.test import TestCase
-
-# from rest_framework import serializers
-# from tests.accounts.serializers import AccountSerializer
-
-
-# class ImportingModelSerializerTests(TestCase):
-# """
-# In some situations like, GH #1225, it is possible, especially in
-# testing, to import a serializer who's related models have not yet
-# been resolved by Django. `AccountSerializer` is an example of such
-# a serializer (imported at the top of this file).
-# """
-# def test_import_model_serializer(self):
-# """
-# The serializer at the top of this file should have been
-# imported successfully, and we should be able to instantiate it.
-# """
-# self.assertIsInstance(AccountSerializer(), serializers.ModelSerializer)
diff --git a/tests/test_serializer_lists.py b/tests/test_serializer_lists.py
new file mode 100644
index 00000000..640067e3
--- /dev/null
+++ b/tests/test_serializer_lists.py
@@ -0,0 +1,274 @@
+from rest_framework import serializers
+from django.utils.datastructures import MultiValueDict
+
+
+class BasicObject:
+ """
+ A mock object for testing serializer save behavior.
+ """
+ def __init__(self, **kwargs):
+ self._data = kwargs
+ for key, value in kwargs.items():
+ setattr(self, key, value)
+
+ def __eq__(self, other):
+ if self._data.keys() != other._data.keys():
+ return False
+ for key in self._data.keys():
+ if self._data[key] != other._data[key]:
+ return False
+ return True
+
+
+class TestListSerializer:
+ """
+ Tests for using a ListSerializer as a top-level serializer.
+ Note that this is in contrast to using ListSerializer as a field.
+ """
+
+ def setup(self):
+ class IntegerListSerializer(serializers.ListSerializer):
+ child = serializers.IntegerField()
+ self.Serializer = IntegerListSerializer
+
+ def test_validate(self):
+ """
+ Validating a list of items should return a list of validated items.
+ """
+ input_data = ["123", "456"]
+ expected_output = [123, 456]
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
+
+ def test_validate_html_input(self):
+ """
+ HTML input should be able to mock list structures using [x] style ids.
+ """
+ input_data = MultiValueDict({"[0]": ["123"], "[1]": ["456"]})
+ expected_output = [123, 456]
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
+
+
+class TestListSerializerContainingNestedSerializer:
+ """
+ Tests for using a ListSerializer containing another serializer.
+ """
+
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ integer = serializers.IntegerField()
+ boolean = serializers.BooleanField()
+
+ def create(self, validated_data):
+ return BasicObject(**validated_data)
+
+ class ObjectListSerializer(serializers.ListSerializer):
+ child = TestSerializer()
+
+ self.Serializer = ObjectListSerializer
+
+ def test_validate(self):
+ """
+ Validating a list of dictionaries should return a list of
+ validated dictionaries.
+ """
+ input_data = [
+ {"integer": "123", "boolean": "true"},
+ {"integer": "456", "boolean": "false"}
+ ]
+ expected_output = [
+ {"integer": 123, "boolean": True},
+ {"integer": 456, "boolean": False}
+ ]
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
+
+ def test_create(self):
+ """
+ Creating from a list of dictionaries should return a list of objects.
+ """
+ input_data = [
+ {"integer": "123", "boolean": "true"},
+ {"integer": "456", "boolean": "false"}
+ ]
+ expected_output = [
+ BasicObject(integer=123, boolean=True),
+ BasicObject(integer=456, boolean=False),
+ ]
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.save() == expected_output
+
+ def test_serialize(self):
+ """
+ Serialization of a list of objects should return a list of dictionaries.
+ """
+ input_objects = [
+ BasicObject(integer=123, boolean=True),
+ BasicObject(integer=456, boolean=False)
+ ]
+ expected_output = [
+ {"integer": 123, "boolean": True},
+ {"integer": 456, "boolean": False}
+ ]
+ serializer = self.Serializer(input_objects)
+ assert serializer.data == expected_output
+
+ def test_validate_html_input(self):
+ """
+ HTML input should be able to mock list structures using [x]
+ style prefixes.
+ """
+ input_data = MultiValueDict({
+ "[0]integer": ["123"],
+ "[0]boolean": ["true"],
+ "[1]integer": ["456"],
+ "[1]boolean": ["false"]
+ })
+ expected_output = [
+ {"integer": 123, "boolean": True},
+ {"integer": 456, "boolean": False}
+ ]
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
+
+
+class TestNestedListSerializer:
+ """
+ Tests for using a ListSerializer as a field.
+ """
+
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ integers = serializers.ListSerializer(child=serializers.IntegerField())
+ booleans = serializers.ListSerializer(child=serializers.BooleanField())
+
+ def create(self, validated_data):
+ return BasicObject(**validated_data)
+
+ self.Serializer = TestSerializer
+
+ def test_validate(self):
+ """
+ Validating a list of items should return a list of validated items.
+ """
+ input_data = {
+ "integers": ["123", "456"],
+ "booleans": ["true", "false"]
+ }
+ expected_output = {
+ "integers": [123, 456],
+ "booleans": [True, False]
+ }
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
+
+ def test_create(self):
+ """
+ Creation with a list of items return an object with an attribute that
+ is a list of items.
+ """
+ input_data = {
+ "integers": ["123", "456"],
+ "booleans": ["true", "false"]
+ }
+ expected_output = BasicObject(
+ integers=[123, 456],
+ booleans=[True, False]
+ )
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.save() == expected_output
+
+ def test_serialize(self):
+ """
+ Serialization of a list of items should return a list of items.
+ """
+ input_object = BasicObject(
+ integers=[123, 456],
+ booleans=[True, False]
+ )
+ expected_output = {
+ "integers": [123, 456],
+ "booleans": [True, False]
+ }
+ serializer = self.Serializer(input_object)
+ assert serializer.data == expected_output
+
+ def test_validate_html_input(self):
+ """
+ HTML input should be able to mock list structures using [x]
+ style prefixes.
+ """
+ input_data = MultiValueDict({
+ "integers[0]": ["123"],
+ "integers[1]": ["456"],
+ "booleans[0]": ["true"],
+ "booleans[1]": ["false"]
+ })
+ expected_output = {
+ "integers": [123, 456],
+ "booleans": [True, False]
+ }
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
+
+
+class TestNestedListOfListsSerializer:
+ def setup(self):
+ class TestSerializer(serializers.Serializer):
+ integers = serializers.ListSerializer(
+ child=serializers.ListSerializer(
+ child=serializers.IntegerField()
+ )
+ )
+ booleans = serializers.ListSerializer(
+ child=serializers.ListSerializer(
+ child=serializers.BooleanField()
+ )
+ )
+
+ self.Serializer = TestSerializer
+
+ def test_validate(self):
+ input_data = {
+ 'integers': [['123', '456'], ['789', '0']],
+ 'booleans': [['true', 'true'], ['false', 'true']]
+ }
+ expected_output = {
+ "integers": [[123, 456], [789, 0]],
+ "booleans": [[True, True], [False, True]]
+ }
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
+
+ def test_validate_html_input(self):
+ """
+ HTML input should be able to mock lists of lists using [x][y]
+ style prefixes.
+ """
+ input_data = MultiValueDict({
+ "integers[0][0]": ["123"],
+ "integers[0][1]": ["456"],
+ "integers[1][0]": ["789"],
+ "integers[1][1]": ["000"],
+ "booleans[0][0]": ["true"],
+ "booleans[0][1]": ["true"],
+ "booleans[1][0]": ["false"],
+ "booleans[1][1]": ["true"]
+ })
+ expected_output = {
+ "integers": [[123, 456], [789, 0]],
+ "booleans": [[True, True], [False, True]]
+ }
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_output
diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py
index b0f64ca7..f5e4b26a 100644
--- a/tests/test_serializer_nested.py
+++ b/tests/test_serializer_nested.py
@@ -1,349 +1,40 @@
-# """
-# Tests to cover nested serializers.
-
-# Doesn't cover model serializers.
-# """
-# from __future__ import unicode_literals
-# from django.test import TestCase
-# from rest_framework import serializers
-# from . import models
-
-
-# class WritableNestedSerializerBasicTests(TestCase):
-# """
-# Tests for deserializing nested entities.
-# Basic tests that use serializers that simply restore to dicts.
-# """
-
-# def setUp(self):
-# class TrackSerializer(serializers.Serializer):
-# order = serializers.IntegerField()
-# title = serializers.CharField(max_length=100)
-# duration = serializers.IntegerField()
-
-# class AlbumSerializer(serializers.Serializer):
-# album_name = serializers.CharField(max_length=100)
-# artist = serializers.CharField(max_length=100)
-# tracks = TrackSerializer(many=True)
-
-# self.AlbumSerializer = AlbumSerializer
-
-# def test_nested_validation_success(self):
-# """
-# Correct nested serialization should return the input data.
-# """
-
-# data = {
-# 'album_name': 'Discovery',
-# 'artist': 'Daft Punk',
-# 'tracks': [
-# {'order': 1, 'title': 'One More Time', 'duration': 235},
-# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
-# {'order': 3, 'title': 'Digital Love', 'duration': 239}
-# ]
-# }
-
-# serializer = self.AlbumSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, data)
-
-# def test_nested_validation_error(self):
-# """
-# Incorrect nested serialization should return appropriate error data.
-# """
-
-# data = {
-# 'album_name': 'Discovery',
-# 'artist': 'Daft Punk',
-# 'tracks': [
-# {'order': 1, 'title': 'One More Time', 'duration': 235},
-# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
-# {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'}
-# ]
-# }
-# expected_errors = {
-# 'tracks': [
-# {},
-# {},
-# {'duration': ['Enter a whole number.']}
-# ]
-# }
-
-# serializer = self.AlbumSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, expected_errors)
-
-# def test_many_nested_validation_error(self):
-# """
-# Incorrect nested serialization should return appropriate error data
-# when multiple entities are being deserialized.
-# """
-
-# data = [
-# {
-# 'album_name': 'Russian Red',
-# 'artist': 'I Love Your Glasses',
-# 'tracks': [
-# {'order': 1, 'title': 'Cigarettes', 'duration': 121},
-# {'order': 2, 'title': 'No Past Land', 'duration': 198},
-# {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191}
-# ]
-# },
-# {
-# 'album_name': 'Discovery',
-# 'artist': 'Daft Punk',
-# 'tracks': [
-# {'order': 1, 'title': 'One More Time', 'duration': 235},
-# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
-# {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'}
-# ]
-# }
-# ]
-# expected_errors = [
-# {},
-# {
-# 'tracks': [
-# {},
-# {},
-# {'duration': ['Enter a whole number.']}
-# ]
-# }
-# ]
-
-# serializer = self.AlbumSerializer(data=data, many=True)
-# self.assertEqual(serializer.is_valid(), False)
-# self.assertEqual(serializer.errors, expected_errors)
-
-
-# class WritableNestedSerializerObjectTests(TestCase):
-# """
-# Tests for deserializing nested entities.
-# These tests use serializers that restore to concrete objects.
-# """
-
-# def setUp(self):
-# # Couple of concrete objects that we're going to deserialize into
-# class Track(object):
-# def __init__(self, order, title, duration):
-# self.order, self.title, self.duration = order, title, duration
-
-# def __eq__(self, other):
-# return (
-# self.order == other.order and
-# self.title == other.title and
-# self.duration == other.duration
-# )
-
-# class Album(object):
-# def __init__(self, album_name, artist, tracks):
-# self.album_name, self.artist, self.tracks = album_name, artist, tracks
-
-# def __eq__(self, other):
-# return (
-# self.album_name == other.album_name and
-# self.artist == other.artist and
-# self.tracks == other.tracks
-# )
-
-# # And their corresponding serializers
-# class TrackSerializer(serializers.Serializer):
-# order = serializers.IntegerField()
-# title = serializers.CharField(max_length=100)
-# duration = serializers.IntegerField()
-
-# def restore_object(self, attrs, instance=None):
-# return Track(attrs['order'], attrs['title'], attrs['duration'])
-
-# class AlbumSerializer(serializers.Serializer):
-# album_name = serializers.CharField(max_length=100)
-# artist = serializers.CharField(max_length=100)
-# tracks = TrackSerializer(many=True)
-
-# def restore_object(self, attrs, instance=None):
-# return Album(attrs['album_name'], attrs['artist'], attrs['tracks'])
-
-# self.Album, self.Track = Album, Track
-# self.AlbumSerializer = AlbumSerializer
-
-# def test_nested_validation_success(self):
-# """
-# Correct nested serialization should return a restored object
-# that corresponds to the input data.
-# """
-
-# data = {
-# 'album_name': 'Discovery',
-# 'artist': 'Daft Punk',
-# 'tracks': [
-# {'order': 1, 'title': 'One More Time', 'duration': 235},
-# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
-# {'order': 3, 'title': 'Digital Love', 'duration': 239}
-# ]
-# }
-# expected_object = self.Album(
-# album_name='Discovery',
-# artist='Daft Punk',
-# tracks=[
-# self.Track(order=1, title='One More Time', duration=235),
-# self.Track(order=2, title='Aerodynamic', duration=184),
-# self.Track(order=3, title='Digital Love', duration=239),
-# ]
-# )
-
-# serializer = self.AlbumSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, expected_object)
-
-# def test_many_nested_validation_success(self):
-# """
-# Correct nested serialization should return multiple restored objects
-# that corresponds to the input data when multiple objects are
-# being deserialized.
-# """
-
-# data = [
-# {
-# 'album_name': 'Russian Red',
-# 'artist': 'I Love Your Glasses',
-# 'tracks': [
-# {'order': 1, 'title': 'Cigarettes', 'duration': 121},
-# {'order': 2, 'title': 'No Past Land', 'duration': 198},
-# {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191}
-# ]
-# },
-# {
-# 'album_name': 'Discovery',
-# 'artist': 'Daft Punk',
-# 'tracks': [
-# {'order': 1, 'title': 'One More Time', 'duration': 235},
-# {'order': 2, 'title': 'Aerodynamic', 'duration': 184},
-# {'order': 3, 'title': 'Digital Love', 'duration': 239}
-# ]
-# }
-# ]
-# expected_object = [
-# self.Album(
-# album_name='Russian Red',
-# artist='I Love Your Glasses',
-# tracks=[
-# self.Track(order=1, title='Cigarettes', duration=121),
-# self.Track(order=2, title='No Past Land', duration=198),
-# self.Track(order=3, title='They Don\'t Believe', duration=191),
-# ]
-# ),
-# self.Album(
-# album_name='Discovery',
-# artist='Daft Punk',
-# tracks=[
-# self.Track(order=1, title='One More Time', duration=235),
-# self.Track(order=2, title='Aerodynamic', duration=184),
-# self.Track(order=3, title='Digital Love', duration=239),
-# ]
-# )
-# ]
-
-# serializer = self.AlbumSerializer(data=data, many=True)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, expected_object)
-
-
-# class ForeignKeyNestedSerializerUpdateTests(TestCase):
-# def setUp(self):
-# class Artist(object):
-# def __init__(self, name):
-# self.name = name
-
-# def __eq__(self, other):
-# return self.name == other.name
-
-# class Album(object):
-# def __init__(self, name, artist):
-# self.name, self.artist = name, artist
-
-# def __eq__(self, other):
-# return self.name == other.name and self.artist == other.artist
-
-# class ArtistSerializer(serializers.Serializer):
-# name = serializers.CharField()
-
-# def restore_object(self, attrs, instance=None):
-# if instance:
-# instance.name = attrs['name']
-# else:
-# instance = Artist(attrs['name'])
-# return instance
-
-# class AlbumSerializer(serializers.Serializer):
-# name = serializers.CharField()
-# by = ArtistSerializer(source='artist')
-
-# def restore_object(self, attrs, instance=None):
-# if instance:
-# instance.name = attrs['name']
-# instance.artist = attrs['artist']
-# else:
-# instance = Album(attrs['name'], attrs['artist'])
-# return instance
-
-# self.Artist = Artist
-# self.Album = Album
-# self.AlbumSerializer = AlbumSerializer
-
-# def test_create_via_foreign_key_with_source(self):
-# """
-# Check that we can both *create* and *update* into objects across
-# ForeignKeys that have a `source` specified.
-# Regression test for #1170
-# """
-# data = {
-# 'name': 'Discovery',
-# 'by': {'name': 'Daft Punk'},
-# }
-
-# expected = self.Album(artist=self.Artist('Daft Punk'), name='Discovery')
-
-# # create
-# serializer = self.AlbumSerializer(data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, expected)
-
-# # update
-# original = self.Album(artist=self.Artist('The Bats'), name='Free All the Monsters')
-# serializer = self.AlbumSerializer(instance=original, data=data)
-# self.assertEqual(serializer.is_valid(), True)
-# self.assertEqual(serializer.object, expected)
-
-
-# class NestedModelSerializerUpdateTests(TestCase):
-# def test_second_nested_level(self):
-# john = models.Person.objects.create(name="john")
-
-# post = john.blogpost_set.create(title="Test blog post")
-# post.blogpostcomment_set.create(text="I hate this blog post")
-# post.blogpostcomment_set.create(text="I love this blog post")
-
-# class BlogPostCommentSerializer(serializers.ModelSerializer):
-# class Meta:
-# model = models.BlogPostComment
-
-# class BlogPostSerializer(serializers.ModelSerializer):
-# comments = BlogPostCommentSerializer(many=True, source='blogpostcomment_set')
-
-# class Meta:
-# model = models.BlogPost
-# fields = ('id', 'title', 'comments')
-
-# class PersonSerializer(serializers.ModelSerializer):
-# posts = BlogPostSerializer(many=True, source='blogpost_set')
-
-# class Meta:
-# model = models.Person
-# fields = ('id', 'name', 'age', 'posts')
-
-# serialize = PersonSerializer(instance=john)
-# deserialize = PersonSerializer(data=serialize.data, instance=john)
-# self.assertTrue(deserialize.is_valid())
-
-# result = deserialize.object
-# result.save()
-# self.assertEqual(result.id, john.id)
+from rest_framework import serializers
+
+
+class TestNestedSerializer:
+ def setup(self):
+ class NestedSerializer(serializers.Serializer):
+ one = serializers.IntegerField(max_value=10)
+ two = serializers.IntegerField(max_value=10)
+
+ class TestSerializer(serializers.Serializer):
+ nested = NestedSerializer()
+
+ self.Serializer = TestSerializer
+
+ def test_nested_validate(self):
+ input_data = {
+ 'nested': {
+ 'one': '1',
+ 'two': '2',
+ }
+ }
+ expected_data = {
+ 'nested': {
+ 'one': 1,
+ 'two': 2,
+ }
+ }
+ serializer = self.Serializer(data=input_data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == expected_data
+
+ def test_nested_serialize_empty(self):
+ expected_data = {
+ 'nested': {
+ 'one': None,
+ 'two': None
+ }
+ }
+ serializer = self.Serializer()
+ assert serializer.data == expected_data
diff --git a/tests/test_templatetags.py b/tests/test_templatetags.py
index 75ee0eaa..b04a937e 100644
--- a/tests/test_templatetags.py
+++ b/tests/test_templatetags.py
@@ -4,6 +4,7 @@ from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.templatetags.rest_framework import add_query_param, urlize_quoted_links
+
factory = APIRequestFactory()
@@ -49,3 +50,37 @@ class Issue1386Tests(TestCase):
# example from issue #1386, this shouldn't raise an exception
urlize_quoted_links("asdf:[/p]zxcv.com")
+
+
+class URLizerTests(TestCase):
+ """
+ Test if both JSON and YAML URLs are transformed into links well
+ """
+ def _urlize_dict_check(self, data):
+ """
+ For all items in dict test assert that the value is urlized key
+ """
+ for original, urlized in data.items():
+ assert urlize_quoted_links(original, nofollow=False) == urlized
+
+ def test_json_with_url(self):
+ """
+ Test if JSON URLs are transformed into links well
+ """
+ data = {}
+ data['"url": "http://api/users/1/", '] = \
+ '&quot;url&quot;: &quot;<a href="http://api/users/1/">http://api/users/1/</a>&quot;, '
+ data['"foo_set": [\n "http://api/foos/1/"\n], '] = \
+ '&quot;foo_set&quot;: [\n &quot;<a href="http://api/foos/1/">http://api/foos/1/</a>&quot;\n], '
+ self._urlize_dict_check(data)
+
+ def test_yaml_with_url(self):
+ """
+ Test if YAML URLs are transformed into links well
+ """
+ data = {}
+ data['''{users: 'http://api/users/'}'''] = \
+ '''{users: &#39;<a href="http://api/users/">http://api/users/</a>&#39;}'''
+ data['''foo_set: ['http://api/foos/1/']'''] = \
+ '''foo_set: [&#39;<a href="http://api/foos/1/">http://api/foos/1/</a>&#39;]'''
+ self._urlize_dict_check(data)
diff --git a/tests/test_testing.py b/tests/test_testing.py
index 9c472026..9fd5966e 100644
--- a/tests/test_testing.py
+++ b/tests/test_testing.py
@@ -5,6 +5,7 @@ from django.conf.urls import patterns, url
from io import BytesIO
from django.contrib.auth.models import User
+from django.shortcuts import redirect
from django.test import TestCase
from rest_framework.decorators import api_view
from rest_framework.response import Response
@@ -28,10 +29,16 @@ def session_view(request):
})
+@api_view(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'])
+def redirect_view(request):
+ return redirect('/view/')
+
+
urlpatterns = patterns(
'',
url(r'^view/$', view),
url(r'^session-view/$', session_view),
+ url(r'^redirect-view/$', redirect_view),
)
@@ -111,6 +118,46 @@ class TestAPITestClient(TestCase):
response = self.client.get('/view/')
self.assertEqual(response.data['auth'], b'')
+ def test_follow_redirect(self):
+ """
+ Follow redirect by setting follow argument.
+ """
+ response = self.client.get('/redirect-view/')
+ self.assertEqual(response.status_code, 302)
+ response = self.client.get('/redirect-view/', follow=True)
+ self.assertIsNotNone(response.redirect_chain)
+ self.assertEqual(response.status_code, 200)
+
+ response = self.client.post('/redirect-view/')
+ self.assertEqual(response.status_code, 302)
+ response = self.client.post('/redirect-view/', follow=True)
+ self.assertIsNotNone(response.redirect_chain)
+ self.assertEqual(response.status_code, 200)
+
+ response = self.client.put('/redirect-view/')
+ self.assertEqual(response.status_code, 302)
+ response = self.client.put('/redirect-view/', follow=True)
+ self.assertIsNotNone(response.redirect_chain)
+ self.assertEqual(response.status_code, 200)
+
+ response = self.client.patch('/redirect-view/')
+ self.assertEqual(response.status_code, 302)
+ response = self.client.patch('/redirect-view/', follow=True)
+ self.assertIsNotNone(response.redirect_chain)
+ self.assertEqual(response.status_code, 200)
+
+ response = self.client.delete('/redirect-view/')
+ self.assertEqual(response.status_code, 302)
+ response = self.client.delete('/redirect-view/', follow=True)
+ self.assertIsNotNone(response.redirect_chain)
+ self.assertEqual(response.status_code, 200)
+
+ response = self.client.options('/redirect-view/')
+ self.assertEqual(response.status_code, 302)
+ response = self.client.options('/redirect-view/', follow=True)
+ self.assertIsNotNone(response.redirect_chain)
+ self.assertEqual(response.status_code, 200)
+
class TestAPIRequestFactory(TestCase):
def test_csrf_exempt_by_default(self):
diff --git a/tests/test_urlizer.py b/tests/test_urlizer.py
deleted file mode 100644
index a77aa22a..00000000
--- a/tests/test_urlizer.py
+++ /dev/null
@@ -1,37 +0,0 @@
-from __future__ import unicode_literals
-from django.test import TestCase
-from rest_framework.templatetags.rest_framework import urlize_quoted_links
-
-
-class URLizerTests(TestCase):
- """
- Test if both JSON and YAML URLs are transformed into links well
- """
- def _urlize_dict_check(self, data):
- """
- For all items in dict test assert that the value is urlized key
- """
- for original, urlized in data.items():
- assert urlize_quoted_links(original, nofollow=False) == urlized
-
- def test_json_with_url(self):
- """
- Test if JSON URLs are transformed into links well
- """
- data = {}
- data['"url": "http://api/users/1/", '] = \
- '&quot;url&quot;: &quot;<a href="http://api/users/1/">http://api/users/1/</a>&quot;, '
- data['"foo_set": [\n "http://api/foos/1/"\n], '] = \
- '&quot;foo_set&quot;: [\n &quot;<a href="http://api/foos/1/">http://api/foos/1/</a>&quot;\n], '
- self._urlize_dict_check(data)
-
- def test_yaml_with_url(self):
- """
- Test if YAML URLs are transformed into links well
- """
- data = {}
- data['''{users: 'http://api/users/'}'''] = \
- '''{users: &#39;<a href="http://api/users/">http://api/users/</a>&#39;}'''
- data['''foo_set: ['http://api/foos/1/']'''] = \
- '''foo_set: [&#39;<a href="http://api/foos/1/">http://api/foos/1/</a>&#39;]'''
- self._urlize_dict_check(data)
diff --git a/tests/test_breadcrumbs.py b/tests/test_utils.py
index 780fd5c4..8c286ea4 100644
--- a/tests/test_breadcrumbs.py
+++ b/tests/test_utils.py
@@ -1,8 +1,14 @@
from __future__ import unicode_literals
+from django.core.exceptions import ImproperlyConfigured
from django.conf.urls import patterns, url
from django.test import TestCase
+from django.utils import six
+from rest_framework.utils.model_meta import _resolve_model
from rest_framework.utils.breadcrumbs import get_breadcrumbs
from rest_framework.views import APIView
+from tests.models import BasicModel
+
+import rest_framework.utils.model_meta
class Root(APIView):
@@ -24,6 +30,7 @@ class NestedResourceRoot(APIView):
class NestedResourceInstance(APIView):
pass
+
urlpatterns = patterns(
'',
url(r'^$', Root.as_view()),
@@ -35,9 +42,10 @@ urlpatterns = patterns(
class BreadcrumbTests(TestCase):
- """Tests the breadcrumb functionality used by the HTML renderer."""
-
- urls = 'tests.test_breadcrumbs'
+ """
+ Tests the breadcrumb functionality used by the HTML renderer.
+ """
+ urls = 'tests.test_utils'
def test_root_breadcrumbs(self):
url = '/'
@@ -98,3 +106,61 @@ class BreadcrumbTests(TestCase):
get_breadcrumbs(url),
[('Root', '/')]
)
+
+
+class ResolveModelTests(TestCase):
+ """
+ `_resolve_model` should return a Django model class given the
+ provided argument is a Django model class itself, or a properly
+ formatted string representation of one.
+ """
+ def test_resolve_django_model(self):
+ resolved_model = _resolve_model(BasicModel)
+ self.assertEqual(resolved_model, BasicModel)
+
+ def test_resolve_string_representation(self):
+ resolved_model = _resolve_model('tests.BasicModel')
+ self.assertEqual(resolved_model, BasicModel)
+
+ def test_resolve_unicode_representation(self):
+ resolved_model = _resolve_model(six.text_type('tests.BasicModel'))
+ self.assertEqual(resolved_model, BasicModel)
+
+ def test_resolve_non_django_model(self):
+ with self.assertRaises(ValueError):
+ _resolve_model(TestCase)
+
+ def test_resolve_improper_string_representation(self):
+ with self.assertRaises(ValueError):
+ _resolve_model('BasicModel')
+
+
+class ResolveModelWithPatchedDjangoTests(TestCase):
+ """
+ Test coverage for when Django's `get_model` returns `None`.
+
+ Under certain circumstances Django may return `None` with `get_model`:
+ http://git.io/get-model-source
+
+ It usually happens with circular imports so it is important that DRF
+ excepts early, otherwise fault happens downstream and is much more
+ difficult to debug.
+
+ """
+
+ def setUp(self):
+ """Monkeypatch get_model."""
+ self.get_model = rest_framework.utils.model_meta.models.get_model
+
+ def get_model(app_label, model_name):
+ return None
+
+ rest_framework.utils.model_meta.models.get_model = get_model
+
+ def tearDown(self):
+ """Revert monkeypatching."""
+ rest_framework.utils.model_meta.models.get_model = self.get_model
+
+ def test_blows_up_if_model_does_not_resolve(self):
+ with self.assertRaises(ImproperlyConfigured):
+ _resolve_model('tests.BasicModel')
diff --git a/tests/test_validation.py b/tests/test_validation.py
index ce39714d..4234efd3 100644
--- a/tests/test_validation.py
+++ b/tests/test_validation.py
@@ -1,10 +1,10 @@
from __future__ import unicode_literals
-from django.core.validators import MaxValueValidator
-from django.core.exceptions import ValidationError
+from django.core.validators import RegexValidator, MaxValueValidator
from django.db import models
from django.test import TestCase
from rest_framework import generics, serializers, status
from rest_framework.test import APIRequestFactory
+import re
factory = APIRequestFactory()
@@ -88,8 +88,11 @@ class TestAvoidValidation(TestCase):
def test_serializer_errors_has_only_invalid_data_error(self):
serializer = ValidationSerializer(data='invalid data')
self.assertFalse(serializer.is_valid())
- self.assertDictEqual(serializer.errors,
- {'non_field_errors': ['Invalid data']})
+ self.assertDictEqual(serializer.errors, {
+ 'non_field_errors': [
+ 'Invalid data. Expected a dictionary, but got %s.' % type('').__name__
+ ]
+ })
# regression tests for issue: 1493
@@ -159,16 +162,22 @@ class TestChoiceFieldChoicesValidate(TestCase):
value = self.CHOICES[0][0]
try:
f.to_internal_value(value)
- except ValidationError:
+ except serializers.ValidationError:
self.fail("Value %s does not validate" % str(value))
- # def test_nested_choices(self):
- # """
- # Make sure a nested value for choices works as expected.
- # """
- # f = serializers.ChoiceField(choices=self.CHOICES_NESTED)
- # value = self.CHOICES_NESTED[0][1][0][0]
- # try:
- # f.to_native(value)
- # except ValidationError:
- # self.fail("Value %s does not validate" % str(value))
+
+class RegexSerializer(serializers.Serializer):
+ pin = serializers.CharField(
+ validators=[RegexValidator(regex=re.compile('^[0-9]{4,6}$'),
+ message='A PIN is 4-6 digits')])
+
+expected_repr = """
+RegexSerializer():
+ pin = CharField(validators=[<django.core.validators.RegexValidator object>])
+""".strip()
+
+
+class TestRegexSerializer(TestCase):
+ def test_regex_repr(self):
+ serializer_repr = repr(RegexSerializer())
+ assert serializer_repr == expected_repr
diff --git a/tests/test_validators.py b/tests/test_validators.py
new file mode 100644
index 00000000..1df0641c
--- /dev/null
+++ b/tests/test_validators.py
@@ -0,0 +1,273 @@
+from django.db import models
+from django.test import TestCase
+from rest_framework import serializers
+import datetime
+
+
+def dedent(blocktext):
+ return '\n'.join([line[12:] for line in blocktext.splitlines()[1:-1]])
+
+
+# Tests for `UniqueValidator`
+# ---------------------------
+
+class UniquenessModel(models.Model):
+ username = models.CharField(unique=True, max_length=100)
+
+
+class UniquenessSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = UniquenessModel
+
+
+class TestUniquenessValidation(TestCase):
+ def setUp(self):
+ self.instance = UniquenessModel.objects.create(username='existing')
+
+ def test_repr(self):
+ serializer = UniquenessSerializer()
+ expected = dedent("""
+ UniquenessSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ username = CharField(max_length=100, validators=[<UniqueValidator(queryset=UniquenessModel.objects.all())>])
+ """)
+ assert repr(serializer) == expected
+
+ def test_is_not_unique(self):
+ data = {'username': 'existing'}
+ serializer = UniquenessSerializer(data=data)
+ assert not serializer.is_valid()
+ assert serializer.errors == {'username': ['This field must be unique.']}
+
+ def test_is_unique(self):
+ data = {'username': 'other'}
+ serializer = UniquenessSerializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'username': 'other'}
+
+ def test_updated_instance_excluded(self):
+ data = {'username': 'existing'}
+ serializer = UniquenessSerializer(self.instance, data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {'username': 'existing'}
+
+
+# Tests for `UniqueTogetherValidator`
+# -----------------------------------
+
+class UniquenessTogetherModel(models.Model):
+ race_name = models.CharField(max_length=100)
+ position = models.IntegerField()
+
+ class Meta:
+ unique_together = ('race_name', 'position')
+
+
+class UniquenessTogetherSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = UniquenessTogetherModel
+
+
+class TestUniquenessTogetherValidation(TestCase):
+ def setUp(self):
+ self.instance = UniquenessTogetherModel.objects.create(
+ race_name='example',
+ position=1
+ )
+ UniquenessTogetherModel.objects.create(
+ race_name='example',
+ position=2
+ )
+ UniquenessTogetherModel.objects.create(
+ race_name='other',
+ position=1
+ )
+
+ def test_repr(self):
+ serializer = UniquenessTogetherSerializer()
+ expected = dedent("""
+ UniquenessTogetherSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ race_name = CharField(max_length=100, required=True)
+ position = IntegerField(required=True)
+ class Meta:
+ validators = [<UniqueTogetherValidator(queryset=UniquenessTogetherModel.objects.all(), fields=('race_name', 'position'))>]
+ """)
+ assert repr(serializer) == expected
+
+ def test_is_not_unique_together(self):
+ """
+ Failing unique together validation should result in non field errors.
+ """
+ data = {'race_name': 'example', 'position': 2}
+ serializer = UniquenessTogetherSerializer(data=data)
+ assert not serializer.is_valid()
+ assert serializer.errors == {
+ 'non_field_errors': [
+ 'The fields race_name, position must make a unique set.'
+ ]
+ }
+
+ def test_is_unique_together(self):
+ """
+ In a unique together validation, one field may be non-unique
+ so long as the set as a whole is unique.
+ """
+ data = {'race_name': 'other', 'position': 2}
+ serializer = UniquenessTogetherSerializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'race_name': 'other',
+ 'position': 2
+ }
+
+ def test_updated_instance_excluded_from_unique_together(self):
+ """
+ When performing an update, the existing instance does not count
+ as a match against uniqueness.
+ """
+ data = {'race_name': 'example', 'position': 1}
+ serializer = UniquenessTogetherSerializer(self.instance, data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'race_name': 'example',
+ 'position': 1
+ }
+
+ def test_unique_together_is_required(self):
+ """
+ In a unique together validation, all fields are required.
+ """
+ data = {'position': 2}
+ serializer = UniquenessTogetherSerializer(data=data, partial=True)
+ assert not serializer.is_valid()
+ assert serializer.errors == {
+ 'race_name': ['This field is required.']
+ }
+
+ def test_ignore_excluded_fields(self):
+ """
+ When model fields are not included in a serializer, then uniqueness
+ validtors should not be added for that field.
+ """
+ class ExcludedFieldSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = UniquenessTogetherModel
+ fields = ('id', 'race_name',)
+ serializer = ExcludedFieldSerializer()
+ expected = dedent("""
+ ExcludedFieldSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ race_name = CharField(max_length=100)
+ """)
+ assert repr(serializer) == expected
+
+
+# Tests for `UniqueForDateValidator`
+# ----------------------------------
+
+class UniqueForDateModel(models.Model):
+ slug = models.CharField(max_length=100, unique_for_date='published')
+ published = models.DateField()
+
+
+class UniqueForDateSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = UniqueForDateModel
+
+
+class TestUniquenessForDateValidation(TestCase):
+ def setUp(self):
+ self.instance = UniqueForDateModel.objects.create(
+ slug='existing',
+ published='2000-01-01'
+ )
+
+ def test_repr(self):
+ serializer = UniqueForDateSerializer()
+ expected = dedent("""
+ UniqueForDateSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ slug = CharField(max_length=100)
+ published = DateField(required=True)
+ class Meta:
+ validators = [<UniqueForDateValidator(queryset=UniqueForDateModel.objects.all(), field='slug', date_field='published')>]
+ """)
+ assert repr(serializer) == expected
+
+ def test_is_not_unique_for_date(self):
+ """
+ Failing unique for date validation should result in field error.
+ """
+ data = {'slug': 'existing', 'published': '2000-01-01'}
+ serializer = UniqueForDateSerializer(data=data)
+ assert not serializer.is_valid()
+ assert serializer.errors == {
+ 'slug': ['This field must be unique for the "published" date.']
+ }
+
+ def test_is_unique_for_date(self):
+ """
+ Passing unique for date validation.
+ """
+ data = {'slug': 'existing', 'published': '2000-01-02'}
+ serializer = UniqueForDateSerializer(data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'slug': 'existing',
+ 'published': datetime.date(2000, 1, 2)
+ }
+
+ def test_updated_instance_excluded_from_unique_for_date(self):
+ """
+ When performing an update, the existing instance does not count
+ as a match against unique_for_date.
+ """
+ data = {'slug': 'existing', 'published': '2000-01-01'}
+ serializer = UniqueForDateSerializer(instance=self.instance, data=data)
+ assert serializer.is_valid()
+ assert serializer.validated_data == {
+ 'slug': 'existing',
+ 'published': datetime.date(2000, 1, 1)
+ }
+
+
+class HiddenFieldUniqueForDateModel(models.Model):
+ slug = models.CharField(max_length=100, unique_for_date='published')
+ published = models.DateTimeField(auto_now_add=True)
+
+
+class TestHiddenFieldUniquenessForDateValidation(TestCase):
+ def test_repr_date_field_not_included(self):
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = HiddenFieldUniqueForDateModel
+ fields = ('id', 'slug')
+
+ serializer = TestSerializer()
+ expected = dedent("""
+ TestSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ slug = CharField(max_length=100)
+ published = HiddenField(default=CreateOnlyDefault(<function now>))
+ class Meta:
+ validators = [<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>]
+ """)
+ assert repr(serializer) == expected
+
+ def test_repr_date_field_included(self):
+ class TestSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = HiddenFieldUniqueForDateModel
+ fields = ('id', 'slug', 'published')
+
+ serializer = TestSerializer()
+ expected = dedent("""
+ TestSerializer():
+ id = IntegerField(label='ID', read_only=True)
+ slug = CharField(max_length=100)
+ published = DateTimeField(default=CreateOnlyDefault(<function now>), read_only=True)
+ class Meta:
+ validators = [<UniqueForDateValidator(queryset=HiddenFieldUniqueForDateModel.objects.all(), field='slug', date_field='published')>]
+ """)
+ assert repr(serializer) == expected
diff --git a/tests/users/__init__.py b/tests/users/__init__.py
deleted file mode 100644
index e69de29b..00000000
--- a/tests/users/__init__.py
+++ /dev/null
diff --git a/tests/users/models.py b/tests/users/models.py
deleted file mode 100644
index 128bac90..00000000
--- a/tests/users/models.py
+++ /dev/null
@@ -1,6 +0,0 @@
-from django.db import models
-
-
-class User(models.Model):
- account = models.ForeignKey('accounts.Account', blank=True, null=True, related_name='users')
- active_record = models.ForeignKey('records.Record', blank=True, null=True)
diff --git a/tests/users/serializers.py b/tests/users/serializers.py
deleted file mode 100644
index 4893ddb3..00000000
--- a/tests/users/serializers.py
+++ /dev/null
@@ -1,8 +0,0 @@
-from rest_framework import serializers
-
-from tests.users.models import User
-
-
-class UserSerializer(serializers.ModelSerializer):
- class Meta:
- model = User
diff --git a/tox.ini b/tox.ini
index a502af97..388eabc5 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,152 +1,34 @@
[tox]
-downloadcache = {toxworkdir}/cache/
envlist =
- flake8,
- py3.4-django1.7,py3.3-django1.7,py3.2-django1.7,py2.7-django1.7,
- py3.4-django1.6,py3.3-django1.6,py3.2-django1.6,py2.7-django1.6,py2.6-django1.6,
- py3.4-django1.5,py3.3-django1.5,py3.2-django1.5,py2.7-django1.5,py2.6-django1.5,
- py2.7-django1.4,py2.6-django1.4
+ py27-flake8,
+ {py26,py27}-django14,
+ {py26,py27,py32,py33,py34}-django{15,16},
+ {py27,py32,py33,py34}-django{17,master}
[testenv]
commands = ./runtests.py --fast
-
-[testenv:flake8]
-basepython = python2.7
-deps = pytest==2.5.2
- flake8==2.2.2
-commands = ./runtests.py --lintonly
-
-[testenv:py3.4-django1.7]
-basepython = python3.4
-deps = Django==1.7
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.3-django1.7]
-basepython = python3.3
-deps = Django==1.7
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.2-django1.7]
-basepython = python3.2
-deps = Django==1.7
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py2.7-django1.7]
-basepython = python2.7
-deps = Django==1.7
- django-filter==0.7
- defusedxml==0.3
- django-guardian==1.2.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.4-django1.6]
-basepython = python3.4
-deps = Django==1.6.3
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.3-django1.6]
-basepython = python3.3
-deps = Django==1.6.3
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.2-django1.6]
-basepython = python3.2
-deps = Django==1.6.3
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py2.7-django1.6]
-basepython = python2.7
-deps = Django==1.6.3
- django-filter==0.7
- defusedxml==0.3
- django-guardian==1.2.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py2.6-django1.6]
-basepython = python2.6
-deps = Django==1.6.3
- django-filter==0.7
- defusedxml==0.3
- django-guardian==1.2.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.4-django1.5]
-basepython = python3.4
-deps = django==1.5.6
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.3-django1.5]
-basepython = python3.3
-deps = django==1.5.6
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py3.2-django1.5]
-basepython = python3.2
-deps = django==1.5.6
- django-filter==0.7
- defusedxml==0.3
- Pillow==2.3.0
- pytest-django==2.6.1
-
-[testenv:py2.7-django1.5]
-basepython = python2.7
-deps = django==1.5.6
- django-filter==0.7
- defusedxml==0.3
- django-guardian==1.2.3
- Pillow==2.3.0
+setenv =
+ PYTHONDONTWRITEBYTECODE=1
+deps =
+ django14: Django==1.4.16
+ django15: Django==1.5.11
+ django16: Django==1.6.8
+ django17: Django==1.7.1
+ djangomaster: https://github.com/django/django/zipball/master
+ {py26,py27}-django{14,15,16,17}: django-guardian==1.2.3
pytest-django==2.6.1
-
-[testenv:py2.6-django1.5]
-basepython = python2.6
-deps = django==1.5.6
django-filter==0.7
defusedxml==0.3
- django-guardian==1.2.3
- Pillow==2.3.0
- pytest-django==2.6.1
+ markdown>=2.1.0
+ PyYAML>=3.10
-[testenv:py2.7-django1.4]
-basepython = python2.7
-deps = django==1.4.11
- django-filter==0.7
- defusedxml==0.3
- django-guardian==1.2.3
- Pillow==2.3.0
- pytest-django==2.6.1
+[testenv:py27-flake8]
+deps =
+ pytest==2.5.2
+ flake8==2.2.2
+commands = ./runtests.py --lintonly
-[testenv:py2.6-django1.4]
-basepython = python2.6
-deps = django==1.4.11
- django-filter==0.7
- defusedxml==0.3
- django-guardian==1.2.3
- Pillow==2.3.0
- pytest-django==2.6.1
+[testenv:py27-docs]
+deps =
+ mkdocs>=0.11.1
+commands = mkdocs build