diff --git a/.github/ISSUE_TEMPLATE/1-issue.md b/.github/ISSUE_TEMPLATE/1-issue.md deleted file mode 100644 index 0da1549534..0000000000 --- a/.github/ISSUE_TEMPLATE/1-issue.md +++ /dev/null @@ -1,10 +0,0 @@ ---- -name: Issue -about: Please only raise an issue if you've been advised to do so after discussion. Thanks! 🙏 ---- - -## Checklist - -- [ ] Raised initially as discussion #... -- [ ] This cannot be dealt with as a third party library. (We prefer new functionality to be [in the form of third party libraries](https://www.django-rest-framework.org/community/third-party-packages/#about-third-party-packages) where possible.) -- [ ] I have reduced the issue to the simplest possible case. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml deleted file mode 100644 index 382fc521aa..0000000000 --- a/.github/ISSUE_TEMPLATE/config.yml +++ /dev/null @@ -1,6 +0,0 @@ -blank_issues_enabled: false -contact_links: -- name: Discussions - url: https://github.com/encode/django-rest-framework/discussions - about: > - The "Discussions" forum is where you want to start. 💖 diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..2d9e2c5ee9 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,13 @@ +# Keep GitHub Actions up to date with GitHub's Dependabot... +# https://docs.github.com/en/code-security/dependabot/working-with-dependabot/keeping-your-actions-up-to-date-with-dependabot +# https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file#package-ecosystem +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + groups: + github-actions: + patterns: + - "*" # Group all Action updates into a single larger pull request + schedule: + interval: weekly diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index c88dc55cd9..bf158311ab 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -9,21 +9,21 @@ on: jobs: tests: name: Python ${{ matrix.python-version }} - runs-on: ubuntu-20.04 + runs-on: ubuntu-24.04 strategy: matrix: python-version: - - '3.6' - - '3.7' - - '3.8' - '3.9' - '3.10' + - '3.11' + - '3.12' + - '3.13' steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - - uses: actions/setup-python@v3 + - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} cache: 'pip' @@ -33,19 +33,41 @@ jobs: run: python -m pip install --upgrade pip setuptools virtualenv wheel - name: Install dependencies - run: python -m pip install --upgrade codecov tox tox-py + run: python -m pip install --upgrade tox - name: Run tox targets for ${{ matrix.python-version }} - run: tox --py current + run: tox run -f py$(echo ${{ matrix.python-version }} | tr -d . | cut -f 1 -d '-') - name: Run extra tox targets if: ${{ matrix.python-version == '3.9' }} run: | - python setup.py bdist_wheel - rm -r djangorestframework.egg-info # see #6139 tox -e base,dist,docs - tox -e dist --installpkg ./dist/djangorestframework-*.whl - name: Upload coverage - run: | - codecov -e TOXENV,DJANGO + uses: codecov/codecov-action@v5 + with: + env_vars: TOXENV,DJANGO + + test-docs: + name: Test documentation links + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-python@v5 + with: + python-version: '3.9' + + - name: Install dependencies + run: pip install -r requirements/requirements-documentation.txt + + # Start mkdocs server and wait for it to be ready + - run: mkdocs serve & + - run: WAIT_TIME=0 && until nc -vzw 2 localhost 8000 || [ $WAIT_TIME -eq 5 ]; do sleep $(( WAIT_TIME++ )); done + - run: if [ $WAIT_TIME == 5 ]; then echo cannot start mkdocs server on http://localhost:8000; exit 1; fi + + - name: Check links + continue-on-error: true + run: pylinkvalidate.py -P http://localhost:8000/ + + - run: echo "Done" diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 9c29ed0564..8922351756 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -8,17 +8,15 @@ on: jobs: pre-commit: - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: actions/setup-python@v2 + - uses: actions/setup-python@v5 with: - python-version: 3.9 + python-version: "3.10" - - uses: pre-commit/action@v2.0.0 - with: - token: ${{ secrets.GITHUB_TOKEN }} + - uses: pre-commit/action@v3.0.1 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5a6e554b98..27bbcb7634 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.4.0 + rev: v4.5.0 hooks: - id: check-added-large-files - id: check-case-conflict @@ -9,12 +9,31 @@ repos: - id: check-symlinks - id: check-toml - repo: https://github.com/pycqa/isort - rev: 5.8.0 + rev: 5.13.2 hooks: - id: isort - repo: https://github.com/PyCQA/flake8 - rev: 3.9.0 + rev: 7.0.0 hooks: - id: flake8 additional_dependencies: - flake8-tidy-imports +- repo: https://github.com/adamchainz/blacken-docs + rev: 1.16.0 + hooks: + - id: blacken-docs + exclude: ^(?!docs).*$ + additional_dependencies: + - black==23.1.0 +- repo: https://github.com/codespell-project/codespell + # Configuration for codespell is in .codespellrc + rev: v2.2.6 + hooks: + - id: codespell + exclude: locale|kickstarter-announcement.md|coreapi-0.1.1.js + +- repo: https://github.com/asottile/pyupgrade + rev: v3.19.1 + hooks: + - id: pyupgrade + args: ["--py39-plus", "--keep-percent-format"] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d567d45a87..644a719c86 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,7 +1,5 @@ # Contributing to REST framework -At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes. - -Apart from minor documentation changes, the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion. +At this point in its lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes. The [Contributing guide in the documentation](https://www.django-rest-framework.org/community/contributing/) gives some more information on our process and code of conduct. diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index e9230d5c99..1c6881858f 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -1,4 +1,4 @@ -*Note*: Before submitting this pull request, please review our [contributing guidelines](https://www.django-rest-framework.org/community/contributing/#pull-requests). +*Note*: Before submitting a code change, please review our [contributing guidelines](https://www.django-rest-framework.org/community/contributing/#pull-requests). ## Description diff --git a/README.md b/README.md index e8375291dc..be6619b4eb 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,10 @@ The initial aim is to provide a single full-time position on REST framework. [![][posthog-img]][posthog-url] [![][cryptapi-img]][cryptapi-url] [![][fezto-img]][fezto-url] +[![][svix-img]][svix-url] +[![][zuplo-img]][zuplo-url] -Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Spacinov][spacinov-url], [Retool][retool-url], [bit.io][bitio-url], [PostHog][posthog-url], [CryptAPI][cryptapi-url], and [FEZTO][fezto-url]. +Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry][sentry-url], [Stream][stream-url], [Spacinov][spacinov-url], [Retool][retool-url], [bit.io][bitio-url], [PostHog][posthog-url], [CryptAPI][cryptapi-url], [FEZTO][fezto-url], [Svix][svix-url], and [Zuplo][zuplo-url]. --- @@ -38,14 +40,12 @@ Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework: -* The [Web browsable API][sandbox] is a huge usability win for your developers. +* The Web browsable API is a huge usability win for your developers. * [Authentication policies][authentication] including optional packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section]. * [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources. * Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers]. * [Extensive documentation][docs], and [great community support][group]. -There is a live example API for testing purposes, [available here][sandbox]. - **Below**: *Screenshot from the browsable API* ![Screenshot][image] @@ -54,8 +54,8 @@ There is a live example API for testing purposes, [available here][sandbox]. # Requirements -* Python 3.6+ -* Django 4.1, 4.0, 3.2, 3.1, 3.0 +* Python 3.9+ +* Django 4.2, 5.0, 5.1, 5.2 We **highly recommend** and only officially support the latest patch release of each Python and Django series. @@ -173,8 +173,6 @@ Full documentation for the project is available at [https://www.django-rest-fram For questions and support, use the [REST framework discussion group][group], or `#restframework` on libera.chat IRC. -You may also want to [follow the author on Twitter][twitter]. - # Security Please see the [security policy][security-policy]. @@ -185,9 +183,7 @@ Please see the [security policy][security-policy]. [codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master [pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg [pypi]: https://pypi.org/project/djangorestframework/ -[twitter]: https://twitter.com/starletdreaming [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework -[sandbox]: https://restframework.herokuapp.com/ [funding]: https://fund.django-rest-framework.org/topics/funding/ [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors @@ -200,6 +196,8 @@ Please see the [security policy][security-policy]. [posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png [cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png [fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png +[svix-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/svix-premium.png +[zuplo-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/zuplo-readme.png [sentry-url]: https://getsentry.com/welcome/ [stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage @@ -209,6 +207,8 @@ Please see the [security policy][security-policy]. [posthog-url]: https://posthog.com?utm_source=drf&utm_medium=sponsorship&utm_campaign=open-source-sponsorship [cryptapi-url]: https://cryptapi.io [fezto-url]: https://www.fezto.xyz/?utm_source=DjangoRESTFramework +[svix-url]: https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship +[zuplo-url]: https://zuplo.link/django-gh [oauth1-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-rest-framework-oauth [oauth2-section]: https://www.django-rest-framework.org/api-guide/authentication/#django-oauth-toolkit diff --git a/SECURITY.md b/SECURITY.md index a92a1b0cf1..88ff092a26 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,8 +2,6 @@ ## Reporting a Vulnerability -Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team). +**Please report security issues by emailing security@encode.io**. - **Please report security issues by emailing security@djangoproject.com**. - - The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure. +The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure. diff --git a/docs/api-guide/authentication.md b/docs/api-guide/authentication.md index d30b6fed8c..84e58bf4b4 100644 --- a/docs/api-guide/authentication.md +++ b/docs/api-guide/authentication.md @@ -90,6 +90,12 @@ The kind of response that will be used depends on the authentication scheme. Al Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme. +## Django 5.1+ `LoginRequiredMiddleware` + +If you're running Django 5.1+ and use the [`LoginRequiredMiddleware`][login-required-middleware], please note that all views from DRF are opted-out of this middleware. This is because the authentication in DRF is based authentication and permissions classes, which may be determined after the middleware has been applied. Additionally, when the request is not authenticated, the middleware redirects the user to the login page, which is not suitable for API requests, where it's preferable to return a 401 status code. + +REST framework offers an equivalent mechanism for DRF views via the global settings, `DEFAULT_AUTHENTICATION_CLASSES` and `DEFAULT_PERMISSION_CLASSES`. They should be changed accordingly if you need to enforce that API requests are logged in. + ## Apache mod_wsgi specific configuration Note that if deploying to [Apache using mod_wsgi][mod_wsgi_official], the authorization header is not passed through to a WSGI application by default, as it is assumed that authentication will be handled by Apache, rather than at an application level. @@ -201,7 +207,7 @@ If you've already created some users, you can generate tokens for all existing u #### By exposing an api endpoint -When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behaviour. To use it, add the `obtain_auth_token` view to your URLconf: +When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf: from rest_framework.authtoken import views urlpatterns += [ @@ -216,7 +222,7 @@ The `obtain_auth_token` view will return a JSON response when valid `username` a Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. -By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply to throttle you'll need to override the view class, +By default, there are no permissions or throttling applied to the `obtain_auth_token` view. If you do wish to apply throttling you'll need to override the view class, and include them using the `throttle_classes` attribute. If you need a customized version of the `obtain_auth_token` view, you can do so by subclassing the `ObtainAuthToken` view class, and using that in your url conf instead. @@ -250,7 +256,7 @@ And in your `urls.py`: #### With Django admin -It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class customize it to your needs, more specifically by declaring the `user` field as `raw_field`. +It is also possible to create Tokens manually through the admin interface. In case you are using a large user base, we recommend that you monkey patch the `TokenAdmin` class to customize it to your needs, more specifically by declaring the `user` field as `raw_field`. `your_app/admin.py`: @@ -289,7 +295,7 @@ If you're using an AJAX-style API with SessionAuthentication, you'll need to mak **Warning**: Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. -CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behaviour is not suitable for login views, which should always have CSRF validation applied. +CSRF validation in REST framework works slightly differently from standard Django due to the need to support both session and non-session based authentication to the same views. This means that only authenticated requests require CSRF tokens, and anonymous requests may be sent without CSRF tokens. This behavior is not suitable for login views, which should always have CSRF validation applied. ## RemoteUserAuthentication @@ -299,7 +305,7 @@ environment variable. To use it, you must have `django.contrib.auth.backends.RemoteUserBackend` (or a subclass) in your `AUTHENTICATION_BACKENDS` setting. By default, `RemoteUserBackend` creates `User` objects for usernames that don't -already exist. To change this and other behaviour, consult the +already exist. To change this and other behavior, consult the [Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/). If successfully authenticated, `RemoteUserAuthentication` provides the following credentials: @@ -307,7 +313,7 @@ If successfully authenticated, `RemoteUserAuthentication` provides the following * `request.user` will be a Django `User` instance. * `request.auth` will be `None`. -Consult your web server's documentation for information about configuring an authentication method, e.g.: +Consult your web server's documentation for information about configuring an authentication method, for example: * [Apache Authentication How-To](https://httpd.apache.org/docs/2.4/howto/auth.html) * [NGINX (Restricting Access)](https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/) @@ -338,7 +344,7 @@ If the `.authenticate_header()` method is not overridden, the authentication sch The following example will authenticate any incoming request as the user given by the username in a custom request header named 'X-USERNAME'. - from django.contrib.auth.models import User + from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions @@ -414,11 +420,11 @@ The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let y ## HTTP Signature Authentication -HTTP Signature (currently a [IETF draft][http-signature-ietf-draft]) provides a way to achieve origin authentication and message integrity for HTTP messages. Similar to [Amazon's HTTP Signature scheme][amazon-http-signature], used by many of its services, it permits stateless, per-request authentication. [Elvio Toccalino][etoccalino] maintains the [djangorestframework-httpsignature][djangorestframework-httpsignature] (outdated) package which provides an easy to use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig]. +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] (outdated) package which provides an easy-to-use HTTP Signature Authentication mechanism. You can use the updated fork version of [djangorestframework-httpsignature][djangorestframework-httpsignature], which is [drf-httpsig][drf-httpsig]. ## 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 uses token-based authentication. This is ready to use REST implementation of the Django authentication system. +[Djoser][djoser] library provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. The package works with a custom user model and uses token-based authentication. This is a ready to use REST implementation of the Django authentication system. ## django-rest-auth / dj-rest-auth @@ -448,13 +454,19 @@ There are currently two forks of this project. More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html). +## django-pyoidc + +[dango-pyoidc][django_pyoidc] adds support for OpenID Connect (OIDC) authentication. This allows you to delegate user management to an Identity Provider, which can be used to implement Single-Sign-On (SSO). It provides support for most uses-cases, such as customizing how token info are mapped to user models, using OIDC audiences for access control, etc. + +More information can be found in the [Documentation](https://django-pyoidc.readthedocs.io/latest/index.html). + [cite]: https://jacobian.org/writing/rest-worst-practices/ [http401]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.2 [http403]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.4 [basicauth]: https://tools.ietf.org/html/rfc2617 [permission]: permissions.md [throttling]: throttling.md -[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax +[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax [mod_wsgi_official]: https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIPassAuthorization.html [django-oauth-toolkit-getting-started]: https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html [django-rest-framework-oauth]: https://jpadilla.github.io/django-rest-framework-oauth/ @@ -484,3 +496,5 @@ More information can be found in the [Documentation](https://django-rest-durin.r [drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless [django-rest-authemail]: https://github.com/celiao/django-rest-authemail [django-rest-durin]: https://github.com/eshaan7/django-rest-durin +[login-required-middleware]: https://docs.djangoproject.com/en/stable/ref/middleware/#django.contrib.auth.middleware.LoginRequiredMiddleware +[django-pyoidc] : https://github.com/makinacorpus/django_pyoidc diff --git a/docs/api-guide/caching.md b/docs/api-guide/caching.md index ab4f82cd2f..4beea30d06 100644 --- a/docs/api-guide/caching.md +++ b/docs/api-guide/caching.md @@ -28,41 +28,64 @@ from rest_framework import viewsets class UserViewSet(viewsets.ViewSet): # With cookie: cache requested url for each user for 2 hours - @method_decorator(cache_page(60*60*2)) + @method_decorator(cache_page(60 * 60 * 2)) @method_decorator(vary_on_cookie) def list(self, request, format=None): content = { - 'user_feed': request.user.get_user_feed() + "user_feed": request.user.get_user_feed(), } return Response(content) class ProfileView(APIView): # With auth: cache requested url for each user for 2 hours - @method_decorator(cache_page(60*60*2)) - @method_decorator(vary_on_headers("Authorization",)) + @method_decorator(cache_page(60 * 60 * 2)) + @method_decorator(vary_on_headers("Authorization")) def get(self, request, format=None): content = { - 'user_feed': request.user.get_user_feed() + "user_feed": request.user.get_user_feed(), } return Response(content) class PostView(APIView): # Cache page for the requested url - @method_decorator(cache_page(60*60*2)) + @method_decorator(cache_page(60 * 60 * 2)) def get(self, request, format=None): content = { - 'title': 'Post title', - 'body': 'Post content' + "title": "Post title", + "body": "Post content", } return Response(content) ``` + +## Using cache with @api_view decorator + +When using @api_view decorator, the Django-provided method-based cache decorators such as [`cache_page`][page], +[`vary_on_cookie`][cookie] and [`vary_on_headers`][headers] can be called directly. + +```python +from django.views.decorators.cache import cache_page +from django.views.decorators.vary import vary_on_cookie + +from rest_framework.decorators import api_view +from rest_framework.response import Response + + +@cache_page(60 * 15) +@vary_on_cookie +@api_view(["GET"]) +def get_user_list(request): + content = {"user_feed": request.user.get_user_feed()} + return Response(content) +``` + + **NOTE:** The [`cache_page`][page] decorator only caches the `GET` and `HEAD` responses with status 200. -[page]: https://docs.djangoproject.com/en/dev/topics/cache/#the-per-view-cache -[cookie]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie -[headers]: https://docs.djangoproject.com/en/dev/topics/http/decorators/#django.views.decorators.vary.vary_on_headers -[decorator]: https://docs.djangoproject.com/en/dev/topics/class-based-views/intro/#decorating-the-class +[page]: https://docs.djangoproject.com/en/stable/topics/cache/#the-per-view-cache +[cookie]: https://docs.djangoproject.com/en/stable/topics/http/decorators/#django.views.decorators.vary.vary_on_cookie +[headers]: https://docs.djangoproject.com/en/stable/topics/http/decorators/#django.views.decorators.vary.vary_on_headers +[decorator]: https://docs.djangoproject.com/en/stable/topics/class-based-views/intro/#decorating-the-class diff --git a/docs/api-guide/content-negotiation.md b/docs/api-guide/content-negotiation.md index 3a4b0357fa..81cff6a89b 100644 --- a/docs/api-guide/content-negotiation.md +++ b/docs/api-guide/content-negotiation.md @@ -82,7 +82,7 @@ The default content negotiation class may be set globally, using the `DEFAULT_CO You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views. - from myapp.negotiation import IgnoreClientContentNegotiation + from myapp.negotiation import IgnoreClientContentNegotiation from rest_framework.response import Response from rest_framework.views import APIView diff --git a/docs/api-guide/exceptions.md b/docs/api-guide/exceptions.md index 347541d56c..4a31828a0e 100644 --- a/docs/api-guide/exceptions.md +++ b/docs/api-guide/exceptions.md @@ -101,7 +101,7 @@ Note that the exception handler will only be called for responses generated by r The **base class** for all exceptions raised inside an `APIView` class or `@api_view`. -To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `default_code` attributes on the class. +To provide a custom exception, subclass `APIException` and set the `.status_code`, `.default_detail`, and `.default_code` attributes on the class. For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so: @@ -179,7 +179,7 @@ By default this exception results in a response with the HTTP status code "403 F **Signature:** `NotFound(detail=None, code=None)` -Raised when a resource does not exists at the given URL. This exception is equivalent to the standard `Http404` Django exception. +Raised when a resource does not exist at the given URL. This exception is equivalent to the standard `Http404` Django exception. By default this exception results in a response with the HTTP status code "404 Not Found". @@ -217,11 +217,10 @@ By default this exception results in a response with the HTTP status code "429 T ## ValidationError -**Signature:** `ValidationError(detail, code=None)` +**Signature:** `ValidationError(detail=None, code=None)` 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 using a dictionary, you can specify field-level errors while performing object-level validation in the `validate()` method of a serializer. For example. `raise serializers.ValidationError({'name': 'Please enter a valid name.'})` * 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.')` @@ -270,5 +269,5 @@ The [drf-standardized-errors][drf-standardized-errors] package provides an excep [cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/ [authentication]: authentication.md -[django-custom-error-views]: https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views +[django-custom-error-views]: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views [drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index ab1847c0c9..d2e6b67e86 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -46,7 +46,7 @@ Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-f ### `default` -If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behaviour is to not populate the attribute at all. +If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. @@ -78,14 +78,14 @@ Defaults to `False` ### `source` -The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. +The name of the attribute that will be used to populate the field. May be a method that only takes a `self` argument, such as `URLField(source='get_absolute_url')`, or may use dotted notation to traverse attributes, such as `EmailField(source='user.email')`. When serializing fields with dotted notation, it may be necessary to provide a `default` value if any object is not present or is empty during attribute traversal. Beware of possible n+1 problems when using source attribute if you are accessing a relational orm model. For example: class CommentSerializer(serializers.Serializer): email = serializers.EmailField(source="user.email") -would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related]. +This case would require user object to be fetched from database when it is not prefetched. If that is not wanted, be sure to be using `prefetch_related` and `select_related` methods appropriately. For more information about the methods refer to [django documentation][django-docs-select-related]. 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. @@ -151,7 +151,7 @@ Prior to Django 2.1 `models.BooleanField` fields were always `blank=True`. Thus since Django 2.1 default `serializers.BooleanField` instances will be generated without the `required` kwarg (i.e. equivalent to `required=True`) whereas with previous versions of Django, default `BooleanField` instances will be generated -with a `required=False` option. If you want to control this behaviour manually, +with a `required=False` option. If you want to control this behavior manually, explicitly declare the `BooleanField` on the serializer class, or use the `extra_kwargs` option to set the `required` flag. @@ -171,10 +171,10 @@ Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.T **Signature:** `CharField(max_length=None, min_length=None, allow_blank=False, trim_whitespace=True)` -- `max_length` - Validates that the input contains no more than this number of characters. -- `min_length` - Validates that the input contains no fewer than this number of characters. -- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. -- `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`. +* `max_length` - Validates that the input contains no more than this number of characters. +* `min_length` - Validates that the input contains no fewer than this number of characters. +* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. +* `trim_whitespace` - If set to `True` then leading and trailing whitespace is trimmed. Defaults to `True`. The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. @@ -222,11 +222,11 @@ A field that ensures the input is a valid UUID string. The `to_internal_value` m **Signature:** `UUIDField(format='hex_verbose')` -- `format`: Determines the representation format of the uuid value - - `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` - - `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"` - - `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"` - - `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` +* `format`: Determines the representation format of the uuid value + * `'hex_verbose'` - The canonical hex representation, including hyphens: `"5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` + * `'hex'` - The compact hex representation of the UUID, not including hyphens: `"5ce0e9a55ffa654bcee01238041fb31a"` + * `'int'` - A 128 bit integer representation of the UUID: `"123456789012312313134124512351145145114"` + * `'urn'` - RFC 4122 URN representation of the UUID: `"urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a"` Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value` ## FilePathField @@ -237,11 +237,11 @@ Corresponds to `django.forms.fields.FilePathField`. **Signature:** `FilePathField(path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs)` -- `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice. -- `match` - A regular expression, as a string, that FilePathField will use to filter filenames. -- `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`. -- `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`. -- `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. +* `path` - The absolute filesystem path to a directory from which this FilePathField should get its choice. +* `match` - A regular expression, as a string, that FilePathField will use to filter filenames. +* `recursive` - Specifies whether all subdirectories of path should be included. Default is `False`. +* `allow_files` - Specifies whether files in the specified location should be included. Default is `True`. Either this or `allow_folders` must be `True`. +* `allow_folders` - Specifies whether folders in the specified location should be included. Default is `False`. Either this or `allow_files` must be `True`. ## IPAddressField @@ -251,8 +251,8 @@ Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.Gen **Signature**: `IPAddressField(protocol='both', unpack_ipv4=False, **options)` -- `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case insensitive. -- `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. +* `protocol` Limits valid inputs to the specified protocol. Accepted values are 'both' (default), 'IPv4' or 'IPv6'. Matching is case-insensitive. +* `unpack_ipv4` Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1. If this option is enabled that address would be unpacked to 192.0.2.1. Default is disabled. Can only be used when protocol is set to 'both'. --- @@ -266,8 +266,8 @@ Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields. **Signature**: `IntegerField(max_value=None, min_value=None)` -- `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. +* `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. ## FloatField @@ -277,8 +277,8 @@ Corresponds to `django.db.models.fields.FloatField`. **Signature**: `FloatField(max_value=None, min_value=None)` -- `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. +* `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 @@ -288,13 +288,14 @@ 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. It must be either `None` or an integer greater than or equal to `decimal_places`. -- `decimal_places` The number of decimal places to store with the number. -- `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`. -- `max_value` Validate that the number provided is no greater than this value. -- `min_value` Validate that the number provided is no less than this value. -- `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file. -- `rounding` Sets the rounding mode used when quantising to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`. +* `max_digits` The maximum number of digits allowed in the number. It must be either `None` or an integer greater than or equal to `decimal_places`. +* `decimal_places` The number of decimal places to store with the number. +* `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `Decimal` objects should be returned. Defaults to the same value as the `COERCE_DECIMAL_TO_STRING` settings key, which will be `True` unless overridden. If `Decimal` objects are returned by the serializer, then the final output format will be determined by the renderer. Note that setting `localize` will force the value to `True`. +* `max_value` Validate that the number provided is no greater than this value. Should be an integer or `Decimal` object. +* `min_value` Validate that the number provided is no less than this value. Should be an integer or `Decimal` object. +* `localize` Set to `True` to enable localization of input and output based on the current locale. This will also force `coerce_to_string` to `True`. Defaults to `False`. Note that data formatting is enabled if you have set `USE_L10N=True` in your settings file. +* `rounding` Sets the rounding mode used when quantizing to the configured precision. Valid values are [`decimal` module rounding modes][python-decimal-rounding-modes]. Defaults to `None`. +* `normalize_output` Will normalize the decimal value when serialized. This will strip all trailing zeroes and change the value's precision to the minimum required precision to be able to represent the value without losing data. Defaults to `False`. #### Example usage @@ -320,13 +321,13 @@ Corresponds to `django.db.models.fields.DateTimeField`. * `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']`. -* `default_timezone` - A `tzinfo` subclass (`zoneinfo` or `pytz`) prepresenting the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive. +* `default_timezone` - A `tzinfo` subclass (`zoneinfo` or `pytz`) representing the timezone. If not specified and the `USE_TZ` setting is enabled, this defaults to the [current timezone][django-current-timezone]. If `USE_TZ` is disabled, then datetime objects will be naive. #### `DateTimeField` format strings. Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style datetimes should be used. (eg `'2013-01-29T12:34:56.000000Z'`) -When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will determined by the renderer class. +When a value of `None` is used for the format `datetime` objects will be returned by `to_representation` and the final output representation will be determined by the renderer class. #### `auto_now` and `auto_now_add` model fields. @@ -380,8 +381,8 @@ The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu **Signature:** `DurationField(max_value=None, min_value=None)` -- `max_value` Validate that the duration provided is no greater than this value. -- `min_value` Validate that the duration provided is no less than this value. +* `max_value` Validate that the duration provided is no greater than this value. +* `min_value` Validate that the duration provided is no less than this value. --- @@ -395,10 +396,10 @@ Used by `ModelSerializer` to automatically generate fields if the corresponding **Signature:** `ChoiceField(choices)` -- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. -- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. -- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. -- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` +* `choices` - A list of valid values, or a list of `(key, display_name)` tuples. +* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. +* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. +* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. @@ -408,10 +409,10 @@ A field that can accept a set of zero, one or many values, chosen from a limited **Signature:** `MultipleChoiceField(choices)` -- `choices` - A list of valid values, or a list of `(key, display_name)` tuples. -- `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. -- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. -- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` +* `choices` - A list of valid values, or a list of `(key, display_name)` tuples. +* `allow_blank` - If set to `True` then the empty string should be considered a valid value. If set to `False` then the empty string is considered invalid and will raise a validation error. Defaults to `False`. +* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Can be used to ensure that automatically generated ChoiceFields with very large possible selections do not prevent a template from rendering. Defaults to `None`. +* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` As with `ChoiceField`, both the `allow_blank` and `allow_null` options are valid, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. @@ -432,9 +433,9 @@ Corresponds to `django.forms.fields.FileField`. **Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` - - `max_length` - Designates the maximum length for the file name. - - `allow_empty_file` - Designates if empty files are allowed. -- `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. +* `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 @@ -444,9 +445,9 @@ 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. +* `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. @@ -460,10 +461,10 @@ A field class that validates a list of objects. **Signature**: `ListField(child=, allow_empty=True, min_length=None, max_length=None)` -- `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. -- `allow_empty` - Designates if empty lists are allowed. -- `min_length` - Validates that the list contains no fewer than this number of elements. -- `max_length` - Validates that the list contains no more than this number of elements. +* `child` - A field instance that should be used for validating the objects in the list. If this argument is not provided then objects in the list will not be validated. +* `allow_empty` - Designates if empty lists are allowed. +* `min_length` - Validates that the list contains no fewer than this number of elements. +* `max_length` - Validates that the list contains no more than this number of elements. For example, to validate a list of integers you might use something like the following: @@ -484,8 +485,8 @@ A field class that validates a dictionary of objects. The keys in `DictField` ar **Signature**: `DictField(child=, allow_empty=True)` -- `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. -- `allow_empty` - Designates if empty dictionaries are allowed. +* `child` - A field instance that should be used for validating the values in the dictionary. If this argument is not provided then values in the mapping will not be validated. +* `allow_empty` - Designates if empty dictionaries are allowed. For example, to create a field that validates a mapping of strings to strings, you would write something like this: @@ -502,8 +503,8 @@ A preconfigured `DictField` that is compatible with Django's postgres `HStoreFie **Signature**: `HStoreField(child=, allow_empty=True)` -- `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values. -- `allow_empty` - Designates if empty dictionaries are allowed. +* `child` - A field instance that is used for validating the values in the dictionary. The default child field accepts both empty strings and null values. +* `allow_empty` - Designates if empty dictionaries are allowed. Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings. @@ -513,8 +514,8 @@ A field class that validates that the incoming data structure consists of valid **Signature**: `JSONField(binary, encoder)` -- `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`. -- `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`. +* `binary` - If set to `True` then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to `False`. +* `encoder` - Use this JSON encoder to serialize input object. Defaults to `None`. --- @@ -549,6 +550,12 @@ The `HiddenField` class is usually only needed if you have some validation that For further examples on `HiddenField` see the [validators](validators.md) documentation. +--- + +**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request). + +--- + ## 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. @@ -565,7 +572,7 @@ This is a read-only field. It gets its value by calling a method on the serializ **Signature**: `SerializerMethodField(method_name=None)` -- `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. +* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: @@ -771,7 +778,7 @@ Here the mapping between the target and source attribute pairs (`x` and `x_coordinate`, `y` and `y_coordinate`) is handled in the `IntegerField` declarations. It's our `NestedCoordinateSerializer` that takes `source='*'`. -Our new `DataPointSerializer` exhibits the same behaviour as the custom field +Our new `DataPointSerializer` exhibits the same behavior as the custom field approach. Serializing: @@ -831,7 +838,7 @@ the [djangorestframework-recursive][djangorestframework-recursive] package provi ## django-rest-framework-gis -The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. +The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. ## django-rest-framework-hstore @@ -850,4 +857,4 @@ The [django-rest-framework-hstore][django-rest-framework-hstore] package provide [django-hstore]: https://github.com/djangonauts/django-hstore [python-decimal-rounding-modes]: https://docs.python.org/3/library/decimal.html#rounding-modes [django-current-timezone]: https://docs.djangoproject.com/en/stable/topics/i18n/timezones/#default-time-zone-and-current-time-zone -[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related +[django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related diff --git a/docs/api-guide/filtering.md b/docs/api-guide/filtering.md index 9a4ae27457..6c80dc7541 100644 --- a/docs/api-guide/filtering.md +++ b/docs/api-guide/filtering.md @@ -213,19 +213,23 @@ This will allow the client to filter the items in the list by making queries suc You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: search_fields = ['username', 'email', 'profile__profession'] - + For [JSONField][JSONField] and [HStoreField][HStoreField] fields you can filter based on nested values within the data structure using the same double-underscore notation: search_fields = ['data__breed', 'data__owner__other_pets__0__name'] -By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. +By default, searches will use case-insensitive partial matches. The search parameter may contain multiple search terms, which should be whitespace and/or comma separated. If multiple search terms are used then objects will be returned in the list only if all the provided terms are matched. Searches may contain _quoted phrases_ with spaces, each phrase is considered as a single search term. + -The search behavior may be restricted by prepending various characters to the `search_fields`. +The search behavior may be specified by prefixing field names in `search_fields` with one of the following characters (which is equivalent to adding `__` to the field): -* '^' Starts-with search. -* '=' Exact matches. -* '@' Full-text search. (Currently only supported Django's [PostgreSQL backend][postgres-search].) -* '$' Regex search. +| Prefix | Lookup | | +| ------ | --------------| ------------------ | +| `^` | `istartswith` | Starts-with search.| +| `=` | `iexact` | Exact matches. | +| `$` | `iregex` | Regex search. | +| `@` | `search` | Full-text search (Currently only supported Django's [PostgreSQL backend][postgres-search]). | +| None | `icontains` | Contains search (Default). | For example: @@ -253,7 +257,7 @@ The `OrderingFilter` class supports simple query parameter controlled ordering o ![Ordering Filter](../img/ordering-filter.png) -By default, the query parameter is named `'ordering'`, but this may by overridden with the `ORDERING_PARAM` setting. +By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting. For example, to order users by username: @@ -269,7 +273,7 @@ Multiple orderings may also be specified: ### Specifying which fields may be ordered against -It's recommended that you explicitly specify which fields the API should allowing in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so: +It's recommended that you explicitly specify which fields the API should allow in the ordering filter. You can do this by setting an `ordering_fields` attribute on the view, like so: class UserListView(generics.ListAPIView): queryset = User.objects.all() @@ -335,15 +339,6 @@ Generic filters may also present an interface in the browsable API. To do so you The method should return a rendered HTML string. -## Filtering & schemas - -You can also make the filter controls available to the schema autogeneration -that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature: - -`get_schema_fields(self, view)` - -The method should return a list of `coreapi.Field` instances. - # Third party packages The following third party packages provide additional filter implementations. @@ -372,6 +367,6 @@ The [djangorestframework-word-filter][django-rest-framework-word-search-filter] [django-rest-framework-word-search-filter]: https://github.com/trollknurr/django-rest-framework-word-search-filter [django-url-filter]: https://github.com/miki725/django-url-filter [drf-url-filter]: https://github.com/manjitkumar/drf-url-filters -[HStoreField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#hstorefield -[JSONField]: https://docs.djangoproject.com/en/3.0/ref/contrib/postgres/fields/#jsonfield +[HStoreField]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/fields/#hstorefield +[JSONField]: https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.JSONField [postgres-search]: https://docs.djangoproject.com/en/stable/ref/contrib/postgres/search/ diff --git a/docs/api-guide/format-suffixes.md b/docs/api-guide/format-suffixes.md index da4a1af78b..9b4e5b9da4 100644 --- a/docs/api-guide/format-suffixes.md +++ b/docs/api-guide/format-suffixes.md @@ -23,8 +23,8 @@ Returns a URL pattern list which includes format suffix patterns appended to eac Arguments: * **urlpatterns**: Required. A URL pattern list. -* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default. -* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. +* **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default. +* **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. Example: diff --git a/docs/api-guide/generic-views.md b/docs/api-guide/generic-views.md index 9467eb6b48..62a27263cc 100644 --- a/docs/api-guide/generic-views.md +++ b/docs/api-guide/generic-views.md @@ -98,7 +98,7 @@ For example: --- -**Note:** If the serializer_class used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related]. +**Note:** If the `serializer_class` used in the generic view spans orm relations, leading to an n+1 problem, you could optimize your queryset in this method using `select_related` and `prefetch_related`. To get more information about n+1 problem and use cases of the mentioned methods refer to related section in [django documentation][django-docs-select-related]. --- @@ -395,4 +395,4 @@ The following third party packages provide additional generic view implementatio [UpdateModelMixin]: #updatemodelmixin [DestroyModelMixin]: #destroymodelmixin [django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels -[django-docs-select-related]: https://docs.djangoproject.com/en/3.1/ref/models/querysets/#django.db.models.query.QuerySet.select_related +[django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related diff --git a/docs/api-guide/pagination.md b/docs/api-guide/pagination.md index aadc1bbc7f..41887ffd8a 100644 --- a/docs/api-guide/pagination.md +++ b/docs/api-guide/pagination.md @@ -227,7 +227,7 @@ Note that the `paginate_queryset` method may set state on the pagination instanc ## Example -Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: +Suppose we want to replace the default pagination output style with a modified format that includes the next and previous links under in a nested 'links' key. We could specify a custom pagination class like so: class CustomPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): @@ -240,7 +240,7 @@ Suppose we want to replace the default pagination output style with a modified f 'results': data }) -We'd then need to setup the custom class in our configuration: +We'd then need to set up the custom class in our configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination', @@ -262,16 +262,7 @@ API responses for list endpoints will now include a `Link` header, instead of in ![Link Header][link-header] -*A custom pagination style, using the 'Link' header'* - -## Pagination & schemas - -You can also make the pagination controls available to the schema autogeneration -that REST framework provides, by implementing a `get_schema_fields()` method. This method should have the following signature: - -`get_schema_fields(self, view)` - -The method should return a list of `coreapi.Field` instances. +*A custom pagination style, using the 'Link' header* --- diff --git a/docs/api-guide/parsers.md b/docs/api-guide/parsers.md index dde77c3e0e..e5d117011c 100644 --- a/docs/api-guide/parsers.md +++ b/docs/api-guide/parsers.md @@ -11,11 +11,11 @@ sending more complex data than simple forms > > — Malcom Tredinnick, [Django developers group][cite] -REST framework includes a number of built in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts. +REST framework includes a number of built-in Parser classes, that allow you to accept requests with various media types. There is also support for defining your own custom parsers, which gives you the flexibility to design the media types that your API accepts. ## How the parser is determined -The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. +The set of valid parsers for a view is always defined as a list of classes. When `request.data` is accessed, REST framework will examine the `Content-Type` header on the incoming request, and determine which parser to use to parse the request content. --- @@ -87,7 +87,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` will be populated with a `QueryDict`. +Parses multipart HTML form content, which supports file uploads. `request.data` and `request.FILES` will be populated with a `QueryDict` and `MultiValueDict` respectively. You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 8d6f47c79b..775888fb66 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -165,7 +165,7 @@ This permission is suitable if you want your API to only be accessible to a subs ## IsAuthenticatedOrReadOnly -The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthorised users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`. +The `IsAuthenticatedOrReadOnly` will allow authenticated users to perform any request. Requests for unauthenticated users will only be permitted if the request method is one of the "safe" methods; `GET`, `HEAD` or `OPTIONS`. This permission is suitable if you want to your API to allow read permissions to anonymous users, and only allow write permissions to authenticated users. @@ -177,7 +177,7 @@ This permission class ties into Django's standard `django.contrib.auth` [model p * `PUT` and `PATCH` requests require the user to have the `change` permission on the model. * `DELETE` requests require the user to have the `delete` permission on the model. -The default behaviour can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests. +The default behavior can also be overridden to support custom model permissions. For example, you might want to include a `view` model permission for `GET` requests. To use custom model permissions, override `DjangoModelPermissions` and set the `.perms_map` property. Refer to the source code for details. @@ -201,7 +201,7 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid --- -**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions. +**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian2` package][django-rest-framework-guardian2]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions. --- @@ -324,6 +324,10 @@ The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users. +## Rest Framework Roles + +The [Rest Framework Roles][rest-framework-roles] makes it super easy to protect views based on roles. Most importantly allows you to decouple accessibility logic from models and views in a clean human-readable way. + ## Django REST Framework API Key The [Django REST Framework API Key][djangorestframework-api-key] package provides permissions classes, models and helpers to add API key authorization to your API. It can be used to authorize internal or third-party backends and services (i.e. _machines_) which do not have a user account. API keys are stored securely using Django's password hashing infrastructure, and they can be viewed, edited and revoked at anytime in the Django admin. @@ -349,8 +353,9 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp [rest-condition]: https://github.com/caxap/rest_condition [dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions [django-rest-framework-roles]: https://github.com/computer-lab/django-rest-framework-roles +[rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles [djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/ [django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters -[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian +[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2 [drf-access-policy]: https://github.com/rsinger86/drf-access-policy [drf-psq]: https://github.com/drf-psq/drf-psq diff --git a/docs/api-guide/relations.md b/docs/api-guide/relations.md index 9c8295b853..7c4eece4bf 100644 --- a/docs/api-guide/relations.md +++ b/docs/api-guide/relations.md @@ -33,7 +33,7 @@ For example, the following serializer would lead to a database hit each time eva class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] - + # For each album object, tracks should be fetched from database qs = Album.objects.all() print(AlbumSerializer(qs, many=True).data) @@ -246,7 +246,7 @@ When using `SlugRelatedField` as a read-write field, you will normally want to e ## HyperlinkedIdentityField -This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: +This field can be applied as an identity relationship, such as the `'url'` field on a HyperlinkedModelSerializer. It can also be used for an attribute on the object. For example, the following serializer: class AlbumSerializer(serializers.HyperlinkedModelSerializer): track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') @@ -278,7 +278,7 @@ This field is always read-only. As opposed to previously discussed _references_ to another entity, the referred entity can instead also be embedded or _nested_ in the representation of the object that refers to it. -Such nested relationships can be expressed by using serializers as fields. +Such nested relationships can be expressed by using serializers as fields. If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. @@ -494,8 +494,8 @@ This behavior is intended to prevent a template from being unable to render in a There are two keyword arguments you can use to control this behavior: -- `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`. -- `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` +* `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`. +* `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`. @@ -628,12 +628,16 @@ The [drf-nested-routers package][drf-nested-routers] provides routers and relati The [rest-framework-generic-relations][drf-nested-relations] library provides read/write serialization for generic foreign keys. +The [rest-framework-gm2m-relations][drf-gm2m-relations] library provides read/write serialization for [django-gm2m][django-gm2m-field]. + [cite]: http://users.ece.utexas.edu/~adnan/pike.html [reverse-relationships]: https://docs.djangoproject.com/en/stable/topics/db/queries/#following-relationships-backward [routers]: https://www.django-rest-framework.org/api-guide/routers#defaultrouter [generic-relations]: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#id1 [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers [drf-nested-relations]: https://github.com/Ian-Foote/rest-framework-generic-relations +[drf-gm2m-relations]: https://github.com/mojtabaakbari221b/rest-framework-gm2m-relations +[django-gm2m-field]: https://github.com/tkhyn/django-gm2m [django-intermediary-manytomany]: https://docs.djangoproject.com/en/stable/topics/db/models/#intermediary-manytomany [dealing-with-nested-objects]: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects [to_internal_value]: https://www.django-rest-framework.org/api-guide/serializers/#to_internal_valueself-data diff --git a/docs/api-guide/renderers.md b/docs/api-guide/renderers.md index 685a98f5e0..7a6bd39f42 100644 --- a/docs/api-guide/renderers.md +++ b/docs/api-guide/renderers.md @@ -105,7 +105,7 @@ The TemplateHTMLRenderer will create a `RequestContext`, using the `response.dat --- -**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the TemplateHTMLRenderer to render it. For example: +**Note:** When used with a view that makes use of a serializer the `Response` sent for rendering may not be a dictionary and will need to be wrapped in a dict before returning to allow the `TemplateHTMLRenderer` to render it. For example: ``` response.data = {'results': response.data} @@ -192,7 +192,7 @@ By default the response content will be rendered with the highest priority rende def get_default_renderer(self, view): return JSONRenderer() -## AdminRenderer +## AdminRenderer Renders data into HTML for an admin-like display: @@ -283,7 +283,7 @@ By default this will include the following keys: `view`, `request`, `response`, The following is an example plaintext renderer that will return a response with the `data` parameter as the content of the response. - from django.utils.encoding import smart_text + from django.utils.encoding import smart_str from rest_framework import renderers @@ -292,7 +292,7 @@ The following is an example plaintext renderer that will return a response with format = 'txt' def render(self, data, accepted_media_type=None, renderer_context=None): - return smart_text(data, encoding=self.charset) + return smart_str(data, encoding=self.charset) ## Setting the character set @@ -332,7 +332,7 @@ You can do some pretty flexible things using REST framework's renderers. Some e * 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. -## Varying behaviour by media type +## Varying behavior by media type In some cases you might want your view to use different serialization styles depending on the accepted media type. If you need to do this you can access `request.accepted_renderer` to determine the negotiated renderer that will be used for the response. @@ -525,7 +525,7 @@ Comma-separated values are a plain-text tabular data format, that can be easily ## LaTeX -[Rest Framework Latex] provides a renderer that outputs PDFs using Laulatex. It is maintained by [Pebble (S/F Software)][mypebble]. +[Rest Framework Latex] provides a renderer that outputs PDFs using Lualatex. It is maintained by [Pebble (S/F Software)][mypebble]. [cite]: https://docs.djangoproject.com/en/stable/ref/template-response/#the-rendering-process diff --git a/docs/api-guide/requests.md b/docs/api-guide/requests.md index e877c868df..d072ac4367 100644 --- a/docs/api-guide/requests.md +++ b/docs/api-guide/requests.md @@ -49,7 +49,7 @@ If a client sends a request with a content-type that cannot be parsed then a `Un # 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 serialization schemes for different media types. +The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types. ## .accepted_renderer diff --git a/docs/api-guide/reverse.md b/docs/api-guide/reverse.md index 70df42b8f0..c3fa52f21f 100644 --- a/docs/api-guide/reverse.md +++ b/docs/api-guide/reverse.md @@ -32,16 +32,16 @@ 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 - data = { - ... - 'year-summary-url': reverse('year-summary', args=[year], request=request) + from django.utils.timezone import now + + class APIRootView(APIView): + def get(self, request): + year = now().year + data = { + ... + 'year-summary-url': reverse('year-summary', args=[year], request=request) } - return Response(data) + return Response(data) ## reverse_lazy @@ -54,5 +54,5 @@ As with the `reverse` function, you should **include the request as a keyword ar api_root = reverse_lazy('api-root', request=request) [cite]: https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5 -[reverse]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse -[reverse-lazy]: https://docs.djangoproject.com/en/stable/topics/http/urls/#reverse-lazy +[reverse]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse +[reverse-lazy]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy diff --git a/docs/api-guide/routers.md b/docs/api-guide/routers.md index 70c05fdde7..d2be3991fb 100644 --- a/docs/api-guide/routers.md +++ b/docs/api-guide/routers.md @@ -142,6 +142,24 @@ The above example would now generate the following URL pattern: * URL path: `^users/{pk}/change-password/$` * URL name: `'user-change_password'` +### Using Django `path()` with routers + +By default, the URLs created by routers use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router, in this case [path converters][path-converters-topic-reference] are used. For example: + + router = SimpleRouter(use_regex_path=False) + +The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset or `lookup_value_converter` if using path converters. For example, you can limit the lookup to valid UUIDs: + + class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): + lookup_field = 'my_model_id' + lookup_value_regex = '[0-9a-f]{32}' + + class MyPathModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): + lookup_field = 'my_model_uuid' + lookup_value_converter = 'uuid' + +Note that path converters will be used on all URLs registered in the router, including viewset actions. + # API Guide ## SimpleRouter @@ -160,19 +178,13 @@ This router includes routes for the standard set of `list`, `create`, `retrieve` {prefix}/{lookup}/{url_path}/GET, or as specified by `methods` argument`@action(detail=True)` decorated method{basename}-{url_name} -By default the URLs created by `SimpleRouter` are appended with a trailing slash. +By default, the URLs created by `SimpleRouter` are appended with a trailing slash. This behavior can be modified by setting the `trailing_slash` argument to `False` when instantiating the router. For example: router = SimpleRouter(trailing_slash=False) Trailing slashes are conventional in Django, but are not used by default in some other frameworks such as Rails. Which style you choose to use is largely a matter of preference, although some javascript frameworks may expect a particular routing style. -The router will match lookup values containing any characters except slashes and period characters. For a more restrictive (or lenient) lookup pattern, set the `lookup_value_regex` attribute on the viewset. For example, you can limit the lookup to valid UUIDs: - - class MyModelViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): - lookup_field = 'my_model_id' - lookup_value_regex = '[0-9a-f]{32}' - ## DefaultRouter This router is similar to `SimpleRouter` as above, but additionally includes a default API root view, that returns a response containing hyperlinks to all the list views. It also generates routes for optional `.json` style format suffixes. @@ -338,5 +350,6 @@ The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions [drf-extensions-nested-viewsets]: https://chibisov.github.io/drf-extensions/docs/#nested-routes [drf-extensions-collection-level-controllers]: https://chibisov.github.io/drf-extensions/docs/#collection-level-controllers [drf-extensions-customizable-endpoint-names]: https://chibisov.github.io/drf-extensions/docs/#controller-endpoint-name -[url-namespace-docs]: https://docs.djangoproject.com/en/4.0/topics/http/urls/#url-namespaces -[include-api-reference]: https://docs.djangoproject.com/en/4.0/ref/urls/#include +[url-namespace-docs]: https://docs.djangoproject.com/en/stable/topics/http/urls/#url-namespaces +[include-api-reference]: https://docs.djangoproject.com/en/stable/ref/urls/#include +[path-converters-topic-reference]: https://docs.djangoproject.com/en/stable/topics/http/urls/#path-converters diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index 004e2d3ce9..0eee3c99f2 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -9,6 +9,23 @@ source: > > — Heroku, [JSON Schema for the Heroku Platform API][cite] +--- + +**Deprecation notice:** + +REST framework's built-in support for generating OpenAPI schemas is +**deprecated** in favor of 3rd party packages that can provide this +functionality instead. The built-in support will be moved into a separate +package and then subsequently retired over the next releases. + +As a full-fledged replacement, we recommend the [drf-spectacular] package. +It has extensive support for generating OpenAPI 3 schemas from +REST framework APIs, with both automatic and customisable options available. +For further information please refer to +[Documenting your API](../topics/documenting-your-api.md#drf-spectacular). + +--- + API schemas are a useful tool that allow for a range of use cases, including generating reference documentation, or driving dynamic client libraries that can interact with your API. @@ -39,10 +56,11 @@ The following sections explain more. ### Install dependencies - pip install pyyaml uritemplate + pip install pyyaml uritemplate inflection * `pyyaml` is used to generate schema into YAML-based OpenAPI format. * `uritemplate` is used internally to get parameters in path. +* `inflection` is used to pluralize operations more appropriately in the list endpoints. ### Generating a static schema with the `generateschema` management command @@ -77,11 +95,13 @@ urlpatterns = [ # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs. # * `title` and `description` parameters are passed to `SchemaGenerator`. # * Provide view name for use with `reverse()`. - path('openapi', get_schema_view( - title="Your Project", - description="API for all things …", - version="1.0.0" - ), name='openapi-schema'), + path( + "openapi", + get_schema_view( + title="Your Project", description="API for all things …", version="1.0.0" + ), + name="openapi-schema", + ), # ... ] ``` @@ -122,6 +142,7 @@ The `get_schema_view()` helper takes the following keyword arguments: url='https://www.example.org/api/', patterns=schema_url_patterns, ) +* `public`: May be used to specify if schema should bypass views permissions. Default to False * `generator_class`: May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`. @@ -241,11 +262,13 @@ class CustomSchema(AutoSchema): """ AutoSchema subclass using schema_extra_info on the view. """ + ... + class CustomView(APIView): schema = CustomSchema() - schema_extra_info = ... some extra info ... + schema_extra_info = ... # some extra info ``` Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the @@ -260,10 +283,13 @@ class BaseSchema(AutoSchema): """ AutoSchema subclass that knows how to use extra_info. """ + ... + class CustomSchema(BaseSchema): - extra_info = ... some extra info ... + extra_info = ... # some extra info + class CustomView(APIView): schema = CustomSchema() @@ -284,15 +310,14 @@ class CustomSchema(BaseSchema): self.extra_info = kwargs.pop("extra_info") super().__init__(**kwargs) + class CustomView(APIView): - schema = CustomSchema( - extra_info=... some extra info ... - ) + schema = CustomSchema(extra_info=...) # some extra info ``` This saves you having to create a custom subclass per-view for a commonly used option. -Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for +Not all `AutoSchema` methods expose related `__init__()` kwargs, but those for the more commonly needed options do. ### `AutoSchema` methods @@ -300,7 +325,7 @@ the more commonly needed options do. #### `get_components()` Generates the OpenAPI components that describe request and response bodies, -deriving their properties from the serializer. +deriving their properties from the serializer. Returns a dictionary mapping the component name to the generated representation. By default this has just a single pair but you may override @@ -426,7 +451,7 @@ If your views have related customizations that are needed frequently, you can create a base `AutoSchema` subclass for your project that takes additional `__init__()` kwargs to save subclassing `AutoSchema` for each view. -[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api +[cite]: https://www.heroku.com/blog/json_schema_for_heroku_platform_api/ [openapi]: https://github.com/OAI/OpenAPI-Specification [openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions [openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject @@ -437,3 +462,4 @@ create a base `AutoSchema` subclass for your project that takes additional [openapi-generator]: https://github.com/OpenAPITools/openapi-generator [swagger-codegen]: https://github.com/swagger-api/swagger-codegen [info-object]: https://swagger.io/specification/#infoObject +[drf-spectacular]: https://drf-spectacular.readthedocs.io/en/latest/readme.html diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 91a9d63f30..8d56d36f5a 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -226,14 +226,14 @@ Individual fields on a serializer can include validators, by declaring them on t raise serializers.ValidationError('Not a multiple of ten') class GameRecord(serializers.Serializer): - score = IntegerField(validators=[multiple_of_ten]) + score = serializers.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: class EventSerializer(serializers.Serializer): name = serializers.CharField() - room_number = serializers.IntegerField(choices=[101, 102, 103, 201]) + room_number = serializers.ChoiceField(choices=[101, 102, 103, 201]) date = serializers.DateField() class Meta: @@ -594,11 +594,11 @@ The ModelSerializer class also exposes an API that you can override in order to Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model. -### `.serializer_field_mapping` +### `serializer_field_mapping` A mapping of Django model fields to REST framework serializer fields. You can override this mapping to alter the default serializer fields that should be used for each model field. -### `.serializer_related_field` +### `serializer_related_field` This property should be the serializer field class, that is used for relational fields by default. @@ -606,13 +606,13 @@ For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`. For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`. -### `.serializer_url_field` +### `serializer_url_field` The serializer field class that should be used for any `url` field on the serializer. Defaults to `serializers.HyperlinkedIdentityField` -### `.serializer_choice_field` +### `serializer_choice_field` The serializer field class that should be used for any choice fields on the serializer. @@ -622,13 +622,13 @@ Defaults to `serializers.ChoiceField` The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`. -### `.build_standard_field(self, field_name, model_field)` +### `build_standard_field(self, field_name, model_field)` Called to generate a serializer field that maps to a standard model field. The default implementation returns a serializer class based on the `serializer_field_mapping` attribute. -### `.build_relational_field(self, field_name, relation_info)` +### `build_relational_field(self, field_name, relation_info)` Called to generate a serializer field that maps to a relational model field. @@ -636,7 +636,7 @@ The default implementation returns a serializer class based on the `serializer_r The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. -### `.build_nested_field(self, field_name, relation_info, nested_depth)` +### `build_nested_field(self, field_name, relation_info, nested_depth)` Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set. @@ -646,17 +646,17 @@ The `nested_depth` will be the value of the `depth` option, minus one. The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. -### `.build_property_field(self, field_name, model_class)` +### `build_property_field(self, field_name, model_class)` Called to generate a serializer field that maps to a property or zero-argument method on the model class. The default implementation returns a `ReadOnlyField` class. -### `.build_url_field(self, field_name, model_class)` +### `build_url_field(self, field_name, model_class)` Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class. -### `.build_unknown_field(self, field_name, model_class)` +### `build_unknown_field(self, field_name, model_class)` Called when the field name did not map to any model field or model property. The default implementation raises an error, although subclasses may customize this behavior. @@ -758,11 +758,11 @@ This is `True` by default, but can be set to `False` if you want to disallow emp ### `max_length` -This is `None` by default, but can be set to a positive integer if you want to validates that the list contains no more than this number of elements. +This is `None` by default, but can be set to a positive integer if you want to validate that the list contains no more than this number of elements. ### `min_length` -This is `None` by default, but can be set to a positive integer if you want to validates that the list contains no fewer than this number of elements. +This is `None` by default, but can be set to a positive integer if you want to validate that the list contains no fewer than this number of elements. ### Customizing `ListSerializer` behavior @@ -845,8 +845,6 @@ Here's an example of how you might choose to implement multiple updates: class Meta: list_serializer_class = BookListSerializer -It is possible that a third party package may be included alongside the 3.1 release that provides some automatic support for multiple update operations, similar to the `allow_add_remove` behavior that was present in REST framework 2. - #### Customizing ListSerializer initialization When a serializer with `many=True` is instantiated, we need to determine which arguments and keyword arguments should be passed to the `.__init__()` method for both the child `Serializer` class, and for the parent `ListSerializer` class. @@ -910,7 +908,7 @@ We can now use this class to serialize single `HighScore` instances: def high_score(request, pk): instance = HighScore.objects.get(pk=pk) serializer = HighScoreSerializer(instance) - return Response(serializer.data) + return Response(serializer.data) Or use it to serialize multiple instances: @@ -918,7 +916,7 @@ Or use it to serialize multiple instances: def all_high_scores(request): queryset = HighScore.objects.order_by('-score') serializer = HighScoreSerializer(queryset, many=True) - return Response(serializer.data) + return Response(serializer.data) #### Read-write `BaseSerializer` classes @@ -949,8 +947,8 @@ Here's a complete example of our previous `HighScoreSerializer`, that's been upd 'player_name': 'May not be more than 10 characters.' }) - # Return the validated values. This will be available as - # the `.validated_data` property. + # Return the validated values. This will be available as + # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name @@ -1021,7 +1019,7 @@ Some reasons this might be useful include... The signatures for these methods are as follows: -#### `.to_representation(self, instance)` +#### `to_representation(self, instance)` 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. @@ -1033,7 +1031,7 @@ May be overridden in order to modify the representation style. For example: ret['username'] = ret['username'].lower() return ret -#### ``.to_internal_value(self, data)`` +#### ``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. @@ -1189,7 +1187,7 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested ## DRF Encrypt Content -The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data. +The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data. [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index d42000260b..7bee3166d0 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -163,6 +163,12 @@ The string that should used for any versioning parameters, such as in the media Default: `'version'` +#### DEFAULT_VERSIONING_CLASS + +The default versioning scheme to use. + +Default: `None` + --- ## Authentication settings @@ -454,4 +460,4 @@ Default: `None` [cite]: https://www.python.org/dev/peps/pep-0020/ [rfc4627]: https://www.ietf.org/rfc/rfc4627.txt [heroku-minified-json]: https://github.com/interagent/http-api-design#keep-json-minified-in-all-responses -[strftime]: https://docs.python.org/3/library/time.html#time.strftime +[strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes diff --git a/docs/api-guide/status-codes.md b/docs/api-guide/status-codes.md index a37ba15d45..fb2f9bf138 100644 --- a/docs/api-guide/status-codes.md +++ b/docs/api-guide/status-codes.md @@ -41,6 +41,8 @@ This class of status code indicates a provisional response. There are no 1xx st HTTP_100_CONTINUE HTTP_101_SWITCHING_PROTOCOLS + HTTP_102_PROCESSING + HTTP_103_EARLY_HINTS ## Successful - 2xx @@ -93,9 +95,11 @@ The 4xx class of status code is intended for cases in which the client seems to HTTP_415_UNSUPPORTED_MEDIA_TYPE HTTP_416_REQUESTED_RANGE_NOT_SATISFIABLE HTTP_417_EXPECTATION_FAILED + HTTP_421_MISDIRECTED_REQUEST HTTP_422_UNPROCESSABLE_ENTITY HTTP_423_LOCKED HTTP_424_FAILED_DEPENDENCY + HTTP_425_TOO_EARLY HTTP_426_UPGRADE_REQUIRED HTTP_428_PRECONDITION_REQUIRED HTTP_429_TOO_MANY_REQUESTS diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index 261df80f27..ed585faf24 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -25,9 +25,12 @@ The `APIRequestFactory` class supports an almost identical API to Django's stand factory = APIRequestFactory() request = factory.post('/notes/', {'title': 'new idea'}) + # Using the standard RequestFactory API to encode JSON data + request = factory.post('/notes/', {'title': 'new idea'}, content_type='application/json') + #### Using the `format` argument -Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a content type other than multipart form data. For example: +Methods which create a request body, such as `post`, `put` and `patch`, include a `format` argument, which make it easy to generate requests using a wide set of request formats. When using this argument, the factory will select an appropriate renderer and its configured `content_type`. For example: # Create a JSON POST request factory = APIRequestFactory() @@ -41,7 +44,7 @@ To support a wider set of request formats, or change the default format, [see th If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example: - request = factory.post('/notes/', json.dumps({'title': 'new idea'}), content_type='application/json') + request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml') #### PUT and PATCH with form data diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index b875221978..e6d7774a62 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -45,14 +45,14 @@ The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_C } } -The rate descriptions used in `DEFAULT_THROTTLE_RATES` may include `second`, `minute`, `hour` or `day` as the throttle period. +The rates used in `DEFAULT_THROTTLE_RATES` can be specified over a period of second, minute, hour or day. The period must be specified after the `/` separator using `s`, `m`, `h` or `d`, respectively. For increased clarity, extended units such as `second`, `minute`, `hour`, `day` or even abbreviations like `sec`, `min`, `hr` are allowed, as only the first character is relevant to identify the rate. You can also set the throttling policy on a per-view or per-viewset basis, using the `APIView` class-based views. - from rest_framework.response import Response + from rest_framework.response import Response from rest_framework.throttling import UserRateThrottle - from rest_framework.views import APIView + from rest_framework.views import APIView class ExampleView(APIView): throttle_classes = [UserRateThrottle] @@ -110,7 +110,7 @@ You'll need to remember to also set your custom throttle class in the `'DEFAULT_ The built-in throttle implementations are open to [race conditions][race], so under high concurrency they may allow a few extra requests through. -If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See [issue #5181][gh5181] for more details. +If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. --- @@ -220,5 +220,4 @@ The following is an example of a rate throttle, that will randomly throttle 1 in [identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster [cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches [cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache -[gh5181]: https://github.com/encode/django-rest-framework/issues/5181 [race]: https://en.wikipedia.org/wiki/Race_condition#Data_race diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 76dcb0d541..57bcb8628c 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -20,7 +20,7 @@ Validation in Django REST framework serializers is handled a little differently 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. +* 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 `Serializer` classes instead, then you need to define the validation rules explicitly. @@ -48,12 +48,12 @@ If we open up the Django shell using `manage.py shell` we can now CustomerReportSerializer(): id = IntegerField(label='ID', read_only=True) time_raised = DateTimeField(read_only=True) - reference = CharField(max_length=20, validators=[]) + 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. +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. REST framework validators, like their Django counterparts, implement the `__eq__` method, allowing you to compare instances for equality. --- @@ -164,14 +164,18 @@ If you want the date field to be entirely hidden from the user, then use `Hidden --- +--- + +**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request). + +--- + # Advanced field defaults Validators that are applied across multiple fields in the serializer can sometimes require a field input that should not be provided by the API client, but that *is* available as input to the validator. +For this purposes use `HiddenField`. This field will be present in `validated_data` but *will not* be used in the serializer output representation. -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. +**Note:** Using a `read_only=True` field is excluded from writable fields so it won't use a `default=…` argument. Look [3.8 announcement](https://www.django-rest-framework.org/community/3.8-announcement/#altered-the-behaviour-of-read_only-plus-default-on-field). REST framework includes a couple of defaults that may be useful in this context. @@ -183,7 +187,7 @@ A default class that can be used to represent the current user. In order to use default=serializers.CurrentUserDefault() ) -#### CreateOnlyDefault +#### CreateOnlyDefault A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted. @@ -208,7 +212,7 @@ by specifying an empty list for the serializer `Meta.validators` attribute. By default "unique together" validation enforces that all fields be `required=True`. In some cases, you might want to explicit apply -`required=False` to one of the fields, in which case the desired behaviour +`required=False` to one of the fields, in which case the desired behavior of the validation is ambiguous. In this case you will typically need to exclude the validator from the @@ -295,13 +299,14 @@ To write a class-based validator, use the `__call__` method. Class-based validat 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 setting -a `requires_context = True` attribute on the validator. The `__call__` method +a `requires_context = True` attribute on the validator class. The `__call__` method will then be called with the `serializer_field` or `serializer` as an additional argument. - requires_context = True + class MultipleOf: + requires_context = True - def __call__(self, value, serializer_field): - ... + def __call__(self, value, serializer_field): + ... [cite]: https://docs.djangoproject.com/en/stable/ref/validators/ diff --git a/docs/api-guide/views.md b/docs/api-guide/views.md index 878a291b22..b293de75ab 100644 --- a/docs/api-guide/views.md +++ b/docs/api-guide/views.md @@ -153,7 +153,7 @@ The core of this functionality is the `api_view` decorator, which takes a list o This view will use the default renderers, parsers, authentication classes etc specified in the [settings]. -By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behaviour, specify which methods the view allows, like so: +By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so: @api_view(['GET', 'POST']) def hello_world(request): diff --git a/docs/api-guide/viewsets.md b/docs/api-guide/viewsets.md index 4179725078..22acfe327a 100644 --- a/docs/api-guide/viewsets.md +++ b/docs/api-guide/viewsets.md @@ -116,7 +116,7 @@ During dispatch, the following attributes are available on the `ViewSet`. * `name` - the display name for the viewset. This argument is mutually exclusive to `suffix`. * `description` - the display description for the individual view of a viewset. -You may inspect these attributes to adjust behaviour based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this: +You may inspect these attributes to adjust behavior based on the current action. For example, you could restrict permissions to everything except the `list` action similar to this: def get_permissions(self): """ @@ -128,6 +128,8 @@ You may inspect these attributes to adjust behaviour based on the current action permission_classes = [IsAdminUser] return [permission() for permission in permission_classes] +**Note**: the `action` attribute is not available in the `get_parsers`, `get_authenticators` and `get_content_negotiator` methods, as it is set _after_ they are called in the framework lifecycle. If you override one of these methods and try to access the `action` attribute in them, you will get an `AttributeError` error. + ## Marking extra actions for routing If you have ad-hoc methods that should be routable, you can mark them as such with the `@action` decorator. Like regular actions, extra actions may be intended for either a single object, or an entire collection. To indicate this, set the `detail` argument to `True` or `False`. The router will configure its URL patterns accordingly. e.g., the `DefaultRouter` will configure detail actions to contain `pk` in their URL patterns. @@ -178,6 +180,13 @@ The `action` decorator will route `GET` requests by default, but may also accept def unset_password(self, request, pk=None): ... +Argument `methods` also supports HTTP methods defined as [HTTPMethod](https://docs.python.org/3/library/http.html#http.HTTPMethod). Example below is identical to the one above: + + from http import HTTPMethod + + @action(detail=True, methods=[HTTPMethod.POST, HTTPMethod.DELETE]) + def unset_password(self, request, pk=None): + ... The decorator allows you to override any viewset-level configuration such as `permission_classes`, `serializer_class`, `filter_backends`...: @@ -194,15 +203,16 @@ To view all extra actions, call the `.get_extra_actions()` method. Extra actions can map additional HTTP methods to separate `ViewSet` methods. For example, the above password set/unset methods could be consolidated into a single route. Note that additional mappings do not accept arguments. ```python - @action(detail=True, methods=['put'], name='Change Password') - def password(self, request, pk=None): - """Update the user's password.""" - ... - - @password.mapping.delete - def delete_password(self, request, pk=None): - """Delete the user's password.""" - ... +@action(detail=True, methods=["put"], name="Change Password") +def password(self, request, pk=None): + """Update the user's password.""" + ... + + +@password.mapping.delete +def delete_password(self, request, pk=None): + """Delete the user's password.""" + ... ``` ## Reversing action URLs @@ -213,14 +223,14 @@ Note that the `basename` is provided by the router during `ViewSet` registration Using the example from the previous section: -```python ->>> view.reverse_action('set-password', args=['1']) +```pycon +>>> view.reverse_action("set-password", args=["1"]) 'http://localhost:8000/api/users/1/set_password' ``` Alternatively, you can use the `url_name` attribute set by the `@action` decorator. -```python +```pycon >>> view.reverse_action(view.set_password.url_name, args=['1']) 'http://localhost:8000/api/users/1/set_password' ``` @@ -247,7 +257,7 @@ In order to use a `GenericViewSet` class you'll override the class and either mi The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes. -The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`. +The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`. #### Example @@ -303,7 +313,7 @@ You may need to provide custom `ViewSet` classes that do not have the full set o To create a base viewset class that provides `create`, `list` and `retrieve` operations, inherit from `GenericViewSet`, and mixin the required actions: - from rest_framework import mixins + from rest_framework import mixins, viewsets class CreateListRetrieveViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, diff --git a/docs/community/3.0-announcement.md b/docs/community/3.0-announcement.md index b9461defe9..0cb79fc2e2 100644 --- a/docs/community/3.0-announcement.md +++ b/docs/community/3.0-announcement.md @@ -24,7 +24,7 @@ Notable features of this new release include: * 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. +* 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. @@ -632,7 +632,7 @@ The `MultipleChoiceField` class has been added. This field acts like `ChoiceFiel The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`. -The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behaviour in a way that did not simply lookup the field value from the object. For example... +The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customise the behavior 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.""" diff --git a/docs/community/3.10-announcement.md b/docs/community/3.10-announcement.md index 19748aa40d..a2135fd20f 100644 --- a/docs/community/3.10-announcement.md +++ b/docs/community/3.10-announcement.md @@ -41,8 +41,8 @@ update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly ```python REST_FRAMEWORK = { - ... - 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema' + ...: ..., + "DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema", } ``` @@ -74,10 +74,11 @@ urlpatterns = [ # Use the `get_schema_view()` helper to add a `SchemaView` to project URLs. # * `title` and `description` parameters are passed to `SchemaGenerator`. # * Provide view name for use with `reverse()`. - path('openapi', get_schema_view( - title="Your Project", - description="API for all things …" - ), name='openapi-schema'), + path( + "openapi", + get_schema_view(title="Your Project", description="API for all things …"), + name="openapi-schema", + ), # ... ] ``` @@ -142,6 +143,6 @@ continued development by **[signing up for a paid plan][funding]**. *Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [ESG](https://software.esg-usa.com/), [Rollbar](https://rollbar.com/?utm_source=django&utm_medium=sponsorship&utm_campaign=freetrial), [Cadre](https://cadre.com), [Kloudless](https://hubs.ly/H0f30Lf0), and [Lights On Software](https://lightsonsoftware.com).* -[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/master/docs/coreapi/index.md +[legacy-core-api-docs]:https://github.com/encode/django-rest-framework/blob/3.14.0/docs/coreapi/index.md [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: funding.md diff --git a/docs/community/3.11-announcement.md b/docs/community/3.11-announcement.md index 83dd636d19..2fc37a7647 100644 --- a/docs/community/3.11-announcement.md +++ b/docs/community/3.11-announcement.md @@ -43,10 +43,11 @@ be extracted from the class docstring: ```python class DocStringExampleListView(APIView): -""" -get: A description of my GET operation. -post: A description of my POST operation. -""" + """ + get: A description of my GET operation. + post: A description of my POST operation. + """ + permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get(self, request, *args, **kwargs): @@ -63,7 +64,7 @@ In some circumstances a Validator class or a Default class may need to access th * Uniqueness validators need to be able to determine the name of the field to which they are applied, in order to run an appropriate database query. * The `CurrentUserDefault` needs to be able to determine the context with which the serializer was instantiated, in order to return the current user instance. -Previous our approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13. +Our previous approach to this was that implementations could include a `set_context` method, which would be called prior to validation. However this approach had issues with potential race conditions. We have now move this approach into a pending deprecation state. It will continue to function, but will be escalated to a deprecated state in 3.12, and removed entirely in 3.13. Instead, validators or defaults which require the serializer context, should include a `requires_context = True` attribute on the class. diff --git a/docs/community/3.12-announcement.md b/docs/community/3.12-announcement.md index 9d2220933c..b192f7290a 100644 --- a/docs/community/3.12-announcement.md +++ b/docs/community/3.12-announcement.md @@ -30,18 +30,18 @@ in the URL path. For example... -Method | Path | Tags +Method | Path | Tags --------------------------------|-----------------|------------- -`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']` -`GET`, `POST` | `/users/` | `['users']` -`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']` -`GET`, `POST` | `/orders/` | `['orders']` +`GET`, `PUT`, `PATCH`, `DELETE` | `/users/{id}/` | `['users']` +`GET`, `POST` | `/users/` | `['users']` +`GET`, `PUT`, `PATCH`, `DELETE` | `/orders/{id}/` | `['orders']` +`GET`, `POST` | `/orders/` | `['orders']` The tags used for a particular view may also be overridden... ```python class MyOrders(APIView): - schema = AutoSchema(tags=['users', 'orders']) + schema = AutoSchema(tags=["users", "orders"]) ... ``` @@ -68,7 +68,7 @@ may be overridden if needed](https://www.django-rest-framework.org/api-guide/sch ```python class MyOrders(APIView): - schema = AutoSchema(component_name="OrderDetails") + schema = AutoSchema(component_name="OrderDetails") ``` ## More Public API @@ -118,10 +118,11 @@ class SitesSearchView(generics.ListAPIView): by a search against the site name or location. (Location searches are matched against the region and country names.) """ + queryset = Sites.objects.all() serializer_class = SitesSerializer filter_backends = [filters.SearchFilter] - search_fields = ['site_name', 'location__region', 'location__country'] + search_fields = ["site_name", "location__region", "location__country"] ``` ### Searches against annotate fields @@ -135,14 +136,25 @@ class PublisherSearchView(generics.ListAPIView): Search for publishers, optionally filtering the search against the average rating of all their books. """ - queryset = Publisher.objects.annotate(avg_rating=Avg('book__rating')) + + queryset = Publisher.objects.annotate(avg_rating=Avg("book__rating")) serializer_class = PublisherSerializer filter_backends = [filters.SearchFilter] - search_fields = ['avg_rating'] + search_fields = ["avg_rating"] ``` --- +## Deprecations + +### `serializers.NullBooleanField` + +`serializers.NullBooleanField` is now pending deprecation, and will be removed in 3.14. + +Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing. + +--- + ## Funding REST framework is a *collaboratively funded project*. If you use diff --git a/docs/community/3.14-announcement.md b/docs/community/3.14-announcement.md index 0543d0d6d6..991c6fc5af 100644 --- a/docs/community/3.14-announcement.md +++ b/docs/community/3.14-announcement.md @@ -28,10 +28,10 @@ Our requirements are now: * Python 3.6+ * Django 4.1, 4.0, 3.2, 3.1, 3.0 -## `raise_exceptions` argument for `is_valid` is now keyword-only. +## `raise_exception` argument for `is_valid` is now keyword-only. Calling `serializer_instance.is_valid(True)` is no longer acceptable syntax. -If you'd like to use the `raise_exceptions` argument, you must use it as a +If you'd like to use the `raise_exception` argument, you must use it as a keyword argument. See Pull Request [#7952](https://github.com/encode/django-rest-framework/pull/7952) for more details. @@ -60,3 +60,13 @@ See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/75 ## Minor fixes and improvements There are a number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing. + +--- + +## Deprecations + +### `serializers.NullBooleanField` + +`serializers.NullBooleanField` was moved to pending deprecation in 3.12, and deprecated in 3.13. It has now been removed from the core framework. + +Instead use `serializers.BooleanField` field and set `allow_null=True` which does the same thing. diff --git a/docs/community/3.15-announcement.md b/docs/community/3.15-announcement.md new file mode 100644 index 0000000000..848d534b24 --- /dev/null +++ b/docs/community/3.15-announcement.md @@ -0,0 +1,50 @@ + + +# Django REST framework 3.15 + +At the Internet, on March 15th, 2024, with 176 commits by 138 authors, we are happy to announce the release of Django REST framework 3.15. + +## Django 5.0 and Python 3.12 support + +The latest release now fully supports Django 5.0 and Python 3.12. + +The current minimum versions of Django still is 3.0 and Python 3.6. + +## Primary Support of UniqueConstraint + +`ModelSerializer` generates validators for [UniqueConstraint](https://docs.djangoproject.com/en/4.0/ref/models/constraints/#uniqueconstraint) (both UniqueValidator and UniqueTogetherValidator) + +## SimpleRouter non-regex matching support + +By default the URLs created by `SimpleRouter` use regular expressions. This behavior can be modified by setting the `use_regex_path` argument to `False` when instantiating the router. + +## ZoneInfo as the primary source of timezone data + +Dependency on pytz has been removed and deprecation warnings have been added, Django will provide ZoneInfo instances as long as USE_DEPRECATED_PYTZ is not enabled. More info on the migration can be found [in this guide](https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html). + +## Align `SearchFilter` behaviour to `django.contrib.admin` search + +Searches now may contain _quoted phrases_ with spaces, each phrase is considered as a single search term, and it will raise a validation error if any null-character is provided in search. See the [Filtering API guide](../api-guide/filtering.md) for more information. + +## Other fixes and improvements + +There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour. + +See the [release notes](release-notes.md) page for a complete listing. diff --git a/docs/community/3.16-announcement.md b/docs/community/3.16-announcement.md new file mode 100644 index 0000000000..b8f460ae76 --- /dev/null +++ b/docs/community/3.16-announcement.md @@ -0,0 +1,42 @@ + + +# Django REST framework 3.16 + +At the Internet, on March 28th, 2025, we are happy to announce the release of Django REST framework 3.16. + +## Updated Django and Python support + +The latest release now fully supports Django 5.1 and the upcoming 5.2 LTS as well as Python 3.13. + +The current minimum versions of Django is now 4.2 and Python 3.9. + +## Django LoginRequiredMiddleware + +The new `LoginRequiredMiddleware` introduced by Django 5.1 can now be used alongside Django REST Framework, however it is not honored for API views as an equivalent behaviour can be configured via `DEFAULT_AUTHENTICATION_CLASSES`. See [our dedicated section](../api-guide/authentication.md#django-51-loginrequiredmiddleware) in the docs for more information. + +## Improved support for UniqueConstraint + +The generation of validators for [UniqueConstraint](https://docs.djangoproject.com/en/stable/ref/models/constraints/#uniqueconstraint) has been improved to support better nullable fields and constraints with conditions. + +## Other fixes and improvements + +There are a number of fixes and minor improvements in this release, ranging from documentation, internal infrastructure (typing, testing, requirements, deprecation, etc.), security and overall behaviour. + +See the [release notes](release-notes.md) page for a complete listing. diff --git a/docs/community/3.2-announcement.md b/docs/community/3.2-announcement.md index a66ad5d292..eda4071b2e 100644 --- a/docs/community/3.2-announcement.md +++ b/docs/community/3.2-announcement.md @@ -64,7 +64,7 @@ These are a little subtle and probably won't affect most users, but are worth un ### ManyToMany fields and blank=True -We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input. +We've now added an `allow_empty` argument, which can be used with `ListSerializer`, or with `many=True` relationships. This is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input. As a follow-up to this we are now able to properly mirror the behavior of Django's `ModelForm` with respect to how many-to-many fields are validated. diff --git a/docs/community/3.3-announcement.md b/docs/community/3.3-announcement.md index 5dcbe3b3b5..24f493dcdc 100644 --- a/docs/community/3.3-announcement.md +++ b/docs/community/3.3-announcement.md @@ -38,7 +38,7 @@ The AJAX based support for the browsable API means that there are a number of in * To support form based `PUT` and `DELETE`, or to support form content types such as JSON, you should now use the [AJAX forms][ajax-form] javascript library. This replaces the previous 'method and content type overloading' that required significant internal complexity to the request class. * The `accept` query parameter is no longer supported by the default content negotiation class. If you require it then you'll need to [use a custom content negotiation class][accept-headers]. -* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override]. +* The custom `HTTP_X_HTTP_METHOD_OVERRIDE` header is no longer supported by default. If you require it then you'll need to [use custom middleware][method-override]. The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly deprecated, and has now been removed entirely, in line with the deprecation policy. diff --git a/docs/community/3.4-announcement.md b/docs/community/3.4-announcement.md index 67192ecbb2..2954b36b81 100644 --- a/docs/community/3.4-announcement.md +++ b/docs/community/3.4-announcement.md @@ -89,7 +89,7 @@ Name | Support | PyPI pa ---------------------------------|-------------------------------------|-------------------------------- [Core JSON][core-json] | Schema generation & client support. | Built-in support in `coreapi`. [Swagger / OpenAPI][swagger] | Schema generation & client support. | The `openapi-codec` package. -[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package. +[JSON Hyper-Schema][hyperschema] | Currently client support only. | The `hyperschema-codec` package. [API Blueprint][api-blueprint] | Not yet available. | Not yet available. --- @@ -187,7 +187,7 @@ The full set of itemized release notes [are available here][release-notes]. [api-blueprint]: https://apiblueprint.org/ [tut-7]: ../tutorial/7-schemas-and-client-libraries/ [schema-generation]: ../api-guide/schemas/ -[api-clients]: ../topics/api-clients.md +[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md [milestone]: https://github.com/encode/django-rest-framework/milestone/35 [release-notes]: release-notes#34 [metadata]: ../api-guide/metadata/#custom-metadata-classes diff --git a/docs/community/3.5-announcement.md b/docs/community/3.5-announcement.md index 91bfce4286..43a628dd4e 100644 --- a/docs/community/3.5-announcement.md +++ b/docs/community/3.5-announcement.md @@ -64,14 +64,10 @@ from rest_framework.schemas import get_schema_view from rest_framework_swagger.renderers import OpenAPIRenderer, SwaggerUIRenderer schema_view = get_schema_view( - title='Example API', - renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer] + title="Example API", renderer_classes=[OpenAPIRenderer, SwaggerUIRenderer] ) -urlpatterns = [ - path('swagger/', schema_view), - ... -] +urlpatterns = [path("swagger/", schema_view), ...] ``` There have been a large number of fixes to the schema generation. These should diff --git a/docs/community/3.6-announcement.md b/docs/community/3.6-announcement.md index 35704eb583..9e45473eee 100644 --- a/docs/community/3.6-announcement.md +++ b/docs/community/3.6-announcement.md @@ -195,5 +195,5 @@ on realtime support, for the 3.7 release. [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: funding.md [api-docs]: ../topics/documenting-your-api.md -[js-docs]: ../topics/api-clients.md#javascript-client-library -[py-docs]: ../topics/api-clients.md#python-client-library +[js-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#javascript-client-library +[py-docs]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md#python-client-library diff --git a/docs/community/3.8-announcement.md b/docs/community/3.8-announcement.md index 507299782d..f33b220fd7 100644 --- a/docs/community/3.8-announcement.md +++ b/docs/community/3.8-announcement.md @@ -89,7 +89,7 @@ for a complete listing. We're currently working towards moving to using [OpenAPI][openapi] as our default schema output. We'll also be revisiting our API documentation generation and client libraries. -We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries. +We're doing some consolidation in order to make this happen. It's planned that 3.9 will drop the `coreapi` and `coreschema` libraries, and instead use `apistar` for the API documentation generation, schema generation, and API client libraries. [funding]: funding.md [gh5886]: https://github.com/encode/django-rest-framework/issues/5886 diff --git a/docs/community/3.9-announcement.md b/docs/community/3.9-announcement.md index d673fdd183..6bc5e3cc39 100644 --- a/docs/community/3.9-announcement.md +++ b/docs/community/3.9-announcement.md @@ -65,15 +65,12 @@ from rest_framework.renderers import JSONOpenAPIRenderer from django.urls import path schema_view = get_schema_view( - title='Server Monitoring API', - url='https://www.example.org/api/', - renderer_classes=[JSONOpenAPIRenderer] + title="Server Monitoring API", + url="https://www.example.org/api/", + renderer_classes=[JSONOpenAPIRenderer], ) -urlpatterns = [ - path('schema.json', schema_view), - ... -] +urlpatterns = [path("schema.json", schema_view), ...] ``` And here's how you can use the `generateschema` management command: diff --git a/docs/community/contributing.md b/docs/community/contributing.md index 2232bd10b9..5a91889433 100644 --- a/docs/community/contributing.md +++ b/docs/community/contributing.md @@ -4,13 +4,9 @@ > > — [Tim Berners-Lee][cite] -There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project. +!!! note ---- - -**Note**: At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. We may accept pull requests that track the continued development of Django versions, but would prefer not to accept new features or code formatting changes. - ---- + At this point in its lifespan we consider Django REST framework to be feature-complete. We focus on pull requests that track the continued development of Django versions, and generally do not accept new features or code formatting changes. ## Community @@ -32,24 +28,8 @@ The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines f # Issues -Our contribution process is that the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Please only raise an issue or pull request if you've been recommended to do so after discussion. - -Some tips on good potential 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 GitHub project page for related items, and make sure you're running the latest version of REST framework before reporting an issue. -* 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. At this point in it's lifespan we consider Django REST framework to be essentially feature-complete. -* Closing an issue doesn't necessarily mean the end of a discussion. If you believe your issue has been closed incorrectly, explain why and we'll consider if it needs to be reopened. - -## Triaging issues - -Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to - -* Read through the ticket - does it make sense, is it missing any context that would help explain it better? -* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group? -* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request? -* If the ticket is a feature request, do you agree with it, and could the feature request instead be implemented as a third party package? -* If a ticket hasn't had much activity and it addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again. +* Django REST framework is considered feature-complete. Please do not file requests to change behavior, unless it is required for security reasons or to maintain compatibility with upcoming Django or Python versions. +* Feature requests will typically be closed with a recommendation that they be implemented outside the core REST framework library (e.g. as third-party libraries). This approach allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability and great documentation. # Development @@ -80,7 +60,7 @@ To run the tests, clone the repository, and then: # Setup the virtual environment python3 -m venv env source env/bin/activate - pip install django + pip install -e . pip install -r requirements.txt # Run the tests @@ -209,7 +189,6 @@ If you want to draw attention to a note or warning, use a pair of enclosing line [code-of-conduct]: https://www.djangoproject.com/conduct/ [google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [so-filter]: https://stackexchange.com/filters/66475/rest-framework -[issues]: https://github.com/encode/django-rest-framework/issues?state=open [pep-8]: https://www.python.org/dev/peps/pep-0008/ [build-status]: ../img/build-status.png [pull-requests]: https://help.github.com/articles/using-pull-requests diff --git a/docs/community/funding.md b/docs/community/funding.md index 2158cd38f3..7bca4bae4c 100644 --- a/docs/community/funding.md +++ b/docs/community/funding.md @@ -1,398 +1,388 @@ - - - - -# Funding - -If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan. - -**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.** - -Signing up for a paid plan will: - -* Directly contribute to faster releases, more features, and higher quality software. -* Allow more time to be invested in documentation, issue triage, and community support. -* Safeguard the future development of REST framework. - -REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development. - ---- - -## What funding has enabled so far - -* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues. -* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples. -* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation. -* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/). -* Tom Christie, the creator of Django REST framework, working on the project full-time. -* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time. -* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship. -* Contracting development time for the work on the JavaScript client library and API documentation tooling. - ---- - -## What future funding will enable - -* Realtime API support, using WebSockets. This will consist of documentation and support for using REST framework together with Django Channels, plus integrating WebSocket support into the client libraries. -* Better authentication defaults, possibly bringing JWT & CORS support into the core package. -* Securing the community & operations manager position long-term. -* Opening up and securing a part-time position to focus on ticket triage and resolution. -* Paying for development time on building API client libraries in a range of programming languages. These would be integrated directly into the upcoming API documentation. - -Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project. - ---- - -## What our sponsors and users say - -> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem. -> -> — José Padilla, Django REST framework contributor - -  - -> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it. -> -> — Filipe Ximenes, Vinta Software - -  - -> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality. -DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large. -> -> — Andrew Conti, Django REST framework user - ---- - -## Individual plan - -This subscription is recommended for individuals with an interest in seeing REST framework continue to improve. - -If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans). - -
-
-
-
- {{ symbol }} - {{ rates.personal1 }} - /month{% if vat %} +VAT{% endif %} -
-
Individual
-
-
- Support ongoing development -
-
- Credited on the site -
-
- -
-
-
-
- -*Billing is monthly and you can cancel at any time.* - ---- - -## Corporate plans - -These subscriptions are recommended for companies and organizations using REST framework either publicly or privately. - -In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**. - -Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day. - -
-
-
-
- {{ symbol }} - {{ rates.corporate1 }} - /month{% if vat %} +VAT{% endif %} -
-
Basic
-
-
- Support ongoing development -
-
- Funding page ad placement -
-
- -
-
-
-
-
- {{ symbol }} - {{ rates.corporate2 }} - /month{% if vat %} +VAT{% endif %} -
-
Professional
-
-
- Support ongoing development -
-
- Sidebar ad placement -
-
- Priority support for your engineers -
-
- -
-
-
-
-
- {{ symbol }} - {{ rates.corporate3 }} - /month{% if vat %} +VAT{% endif %} -
-
Premium
-
-
- Support ongoing development -
-
- Homepage ad placement -
-
- Sidebar ad placement -
-
- Priority support for your engineers -
-
- -
-
-
- -
- -*Billing is monthly and you can cancel at any time.* - -Once you've signed up, we will contact you via email and arrange your ad placements on the site. - -For further enquires please contact funding@django-rest-framework.org. - ---- - -## Accountability - -In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns. - - - - -
-
-
-

Stay up to date, with our monthly progress reports...

-
- - -
-
- - -
- -
-
-
-
- - - ---- - -## Frequently asked questions - -**Q: Can you issue monthly invoices?** -A: Yes, we are happy to issue monthly invoices. Please just email us and let us know who to issue the invoice to (name and address) and which email address to send it to each month. - -**Q: Does sponsorship include VAT?** -A: Sponsorship is VAT exempt. - -**Q: Do I have to sign up for a certain time period?** -A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime. - -**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?** -A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution. - -**Q: Are you only looking for corporate sponsors?** -A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support. - ---- - -## Our sponsors - -
- - + + + + +# Funding + +If you use REST framework commercially we strongly encourage you to invest in its continued development by signing up for a paid plan. + +**We believe that collaboratively funded software can offer outstanding returns on investment, by encouraging our users to collectively share the cost of development.** + +Signing up for a paid plan will: + +* Directly contribute to faster releases, more features, and higher quality software. +* Allow more time to be invested in keeping the package up to date. +* Safeguard the future development of REST framework. + +REST framework continues to be open-source and permissively licensed, but we firmly believe it is in the commercial best-interest for users of the project to invest in its ongoing development. + +--- + +## What funding has enabled so far + +* The [3.4](https://www.django-rest-framework.org/community/3.4-announcement/) and [3.5](https://www.django-rest-framework.org/community/3.5-announcement/) releases, including schema generation for both Swagger and RAML, a Python client library, a Command Line client, and addressing of a large number of outstanding issues. +* The [3.6](https://www.django-rest-framework.org/community/3.6-announcement/) release, including JavaScript client library, and API documentation, complete with auto-generated code samples. +* The [3.7 release](https://www.django-rest-framework.org/community/3.7-announcement/), made possible due to our collaborative funding model, focuses on improvements to schema generation and the interactive API documentation. +* The recent [3.8 release](https://www.django-rest-framework.org/community/3.8-announcement/). +* Tom Christie, the creator of Django REST framework, working on the project full-time. +* Around 80-90 issues and pull requests closed per month since Tom Christie started working on the project full-time. +* A community & operations manager position part-time for 4 months, helping mature the business and grow sponsorship. +* Contracting development time for the work on the JavaScript client library and API documentation tooling. + +--- + +## What our sponsors and users say + +> As a developer, Django REST framework feels like an obvious and natural extension to all the great things that make up Django and it's community. Getting started is easy while providing simple abstractions which makes it flexible and customizable. Contributing and supporting Django REST framework helps ensure its future and one way or another it also helps Django, and the Python ecosystem. +> +> — José Padilla, Django REST framework contributor + +  + +> The number one feature of the Python programming language is its community. Such a community is only possible because of the Open Source nature of the language and all the culture that comes from it. Building great Open Source projects require great minds. Given that, we at Vinta are not only proud to sponsor the team behind DRF but we also recognize the ROI that comes from it. +> +> — Filipe Ximenes, Vinta Software + +  + +> It's really awesome that this project continues to endure. The code base is top notch and the maintainers are committed to the highest level of quality. +DRF is one of the core reasons why Django is top choice among web frameworks today. In my opinion, it sets the standard for rest frameworks for the development community at large. +> +> — Andrew Conti, Django REST framework user + +Sign up for a paid plan today, and help ensure that REST framework becomes a sustainable, full-time funded project. + +--- + +## Individual plan + +This subscription is recommended for individuals with an interest in seeing REST framework continue to improve. + +If you are using REST framework as a full-time employee, consider recommending that your company takes out a [corporate plan](#corporate-plans). + +
+
+
+
+ {{ symbol }} + {{ rates.personal1 }} + /month{% if vat %} +VAT{% endif %} +
+
Individual
+
+
+ Support ongoing development +
+
+ Credited on the site +
+
+ +
+
+
+
+ +*Billing is monthly and you can cancel at any time.* + +--- + +## Corporate plans + +These subscriptions are recommended for companies and organizations using REST framework either publicly or privately. + +In exchange for funding you'll also receive advertising space on our site, allowing you to **promote your company or product to many tens of thousands of developers worldwide**. + +Our professional and premium plans also include **priority support**. At any time your engineers can escalate an issue or discussion group thread, and we'll ensure it gets a guaranteed response within the next working day. + +
+
+
+
+ {{ symbol }} + {{ rates.corporate1 }} + /month{% if vat %} +VAT{% endif %} +
+
Basic
+
+
+ Support ongoing development +
+
+ Funding page ad placement +
+
+ +
+
+
+
+
+ {{ symbol }} + {{ rates.corporate2 }} + /month{% if vat %} +VAT{% endif %} +
+
Professional
+
+
+ Support ongoing development +
+
+ Sidebar ad placement +
+
+ Priority support for your engineers +
+
+ +
+
+
+
+
+ {{ symbol }} + {{ rates.corporate3 }} + /month{% if vat %} +VAT{% endif %} +
+
Premium
+
+
+ Support ongoing development +
+
+ Homepage ad placement +
+
+ Sidebar ad placement +
+
+ Priority support for your engineers +
+
+ +
+
+
+ +
+ +*Billing is monthly and you can cancel at any time.* + +Once you've signed up, we will contact you via email and arrange your ad placements on the site. + +For further enquires please contact funding@django-rest-framework.org. + +--- + +## Accountability + +In an effort to keep the project as transparent as possible, we are releasing [monthly progress reports](https://www.encode.io/reports/march-2018/) and regularly include financial reports and cost breakdowns. + + + + +
+
+
+

Stay up to date, with our monthly progress reports...

+
+ + +
+
+ + +
+ +
+
+
+
+ + + +--- + +## Frequently asked questions + +**Q: Can you issue monthly invoices?** +A: Yes, we are happy to issue monthly invoices. Please just email us and let us know who to issue the invoice to (name and address) and which email address to send it to each month. + +**Q: Does sponsorship include VAT?** +A: Sponsorship is VAT exempt. + +**Q: Do I have to sign up for a certain time period?** +A: No, we appreciate your support for any time period that is convenient for you. Also, you can cancel your sponsorship anytime. + +**Q: Can I pay yearly? Can I pay upfront fox X amount of months at a time?** +A: We are currently only set up to accept monthly payments. However, if you'd like to support Django REST framework and you can only do yearly/upfront payments, we are happy to work with you and figure out a convenient solution. + +**Q: Are you only looking for corporate sponsors?** +A: No, we value individual sponsors just as much as corporate sponsors and appreciate any kind of support. + +--- + +## Our sponsors + +
+ + diff --git a/docs/community/jobs.md b/docs/community/jobs.md index ce85b75707..f3ce37d15f 100644 --- a/docs/community/jobs.md +++ b/docs/community/jobs.md @@ -7,6 +7,7 @@ Looking for a new Django REST Framework related role? On this site we provide a * [https://www.djangoproject.com/community/jobs/][djangoproject-website] * [https://www.python.org/jobs/][python-org-jobs] +* [https://django.on-remote.com][django-on-remote] * [https://djangogigs.com][django-gigs-com] * [https://djangojobs.net/jobs/][django-jobs-net] * [https://findwork.dev/django-rest-framework-jobs][findwork-dev] @@ -14,8 +15,9 @@ Looking for a new Django REST Framework related role? On this site we provide a * [https://stackoverflow.com/jobs/companies?tl=django][stackoverflow-com] * [https://www.upwork.com/o/jobs/browse/skill/django-framework/][upwork-com] * [https://www.technojobs.co.uk/django-jobs][technobjobs-co-uk] -* [https://remoteok.io/remote-django-jobs][remoteok-io] +* [https://remoteok.com/remote-django-jobs][remoteok-com] * [https://www.remotepython.com/jobs/][remotepython-com] +* [https://www.pyjobs.com/][pyjobs-com] Know of any other great resources for Django REST Framework jobs that are missing in our list? Please [submit a pull request][submit-pr] or [email us][anna-email]. @@ -25,6 +27,7 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram [djangoproject-website]: https://www.djangoproject.com/community/jobs/ [python-org-jobs]: https://www.python.org/jobs/ +[django-on-remote]: https://django.on-remote.com/ [django-gigs-com]: https://djangogigs.com [django-jobs-net]: https://djangojobs.net/jobs/ [findwork-dev]: https://findwork.dev/django-rest-framework-jobs @@ -32,8 +35,9 @@ Wonder how else you can help? One of the best ways you can help Django REST Fram [stackoverflow-com]: https://stackoverflow.com/jobs/companies?tl=django [upwork-com]: https://www.upwork.com/o/jobs/browse/skill/django-framework/ [technobjobs-co-uk]: https://www.technojobs.co.uk/django-jobs -[remoteok-io]: https://remoteok.io/remote-django-jobs +[remoteok-com]: https://remoteok.com/remote-django-jobs [remotepython-com]: https://www.remotepython.com/jobs/ +[pyjobs-com]: https://www.pyjobs.com/ [drf-funding]: https://fund.django-rest-framework.org/topics/funding/ [submit-pr]: https://github.com/encode/django-rest-framework [anna-email]: mailto:anna@django-rest-framework.org diff --git a/docs/community/project-management.md b/docs/community/project-management.md index 293c65e246..daf2cda8d8 100644 --- a/docs/community/project-management.md +++ b/docs/community/project-management.md @@ -13,55 +13,13 @@ The aim is to ensure that the project has a high ## Maintenance team -We have a quarterly maintenance cycle where new members may join the maintenance team. We currently cap the size of the team at 5 members, and may encourage folks to step out of the team for a cycle to allow new members to participate. +[Participating actively in the REST framework project](contributing.md) **does not require being part of the maintenance team**. Almost every important part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository. -#### Current team +#### Composition -The [maintenance team for Q4 2015](https://github.com/encode/django-rest-framework/issues/2190): +The composition of the maintenance team is handled by [@tomchristie](https://github.com/encode/). Team members will be added as collaborators to the repository. -* [@tomchristie](https://github.com/encode/) -* [@xordoquy](https://github.com/xordoquy/) (Release manager.) -* [@carltongibson](https://github.com/carltongibson/) -* [@kevin-brown](https://github.com/kevin-brown/) -* [@jpadilla](https://github.com/jpadilla/) - -#### Maintenance cycles - -Each maintenance cycle is initiated by an issue being opened with the `Process` label. - -* To be considered for a maintainer role simply comment against the issue. -* Existing members must explicitly opt-in to the next cycle by check-marking their name. -* The final decision on the incoming team will be made by `@tomchristie`. - -Members of the maintenance team will be added as collaborators to the repository. - -The following template should be used for the description of the issue, and serves as the formal process for selecting the team. - - This issue is for determining the maintenance team for the *** period. - - Please see the [Project management](https://www.django-rest-framework.org/topics/project-management/) section of our documentation for more details. - - --- - - #### Renewing existing members. - - The following people are the current maintenance team. Please checkmark your name if you wish to continue to have write permission on the repository for the *** period. - - - [ ] @*** - - [ ] @*** - - [ ] @*** - - [ ] @*** - - [ ] @*** - - --- - - #### New members. - - If you wish to be considered for this or a future date, please comment against this or subsequent issues. - - To modify this process for future maintenance cycles make a pull request to the [project management](https://www.django-rest-framework.org/topics/project-management/) documentation. - -#### Responsibilities of team members +#### Responsibilities Team members have the following responsibilities. @@ -76,18 +34,13 @@ Further notes for maintainers: * Code changes should come in the form of a pull request - do not push directly to master. * Maintainers should typically not merge their own pull requests. * Each issue/pull request should have exactly one label once triaged. -* Search for un-triaged issues with [is:open no:label][un-triaged]. - -It should be noted that participating actively in the REST framework project clearly **does not require being part of the maintenance team**. Almost every import part of issue triage and project improvement can be actively worked on regardless of your collaborator status on the repository. --- ## Release process -The release manager is selected on every quarterly maintenance cycle. - -* The manager should be selected by `@tomchristie`. -* The manager will then have the maintainer role added to PyPI package. +* The release manager is selected by `@tomchristie`. +* The release manager will then have the maintainer role added to PyPI package. * The previous manager will then have the maintainer role removed from the PyPI package. Our PyPI releases will be handled by either the current release manager, or by `@tomchristie`. Every release should have an open issue tagged with the `Release` label and marked against the appropriate milestone. @@ -112,6 +65,9 @@ The following template should be used for the description of the issue, and serv - [ ] `docs` Python & Django versions - [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations). - [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py). + - [ ] Ensure documentation validates + - Build and serve docs `mkdocs serve` + - Validate links `pylinkvalidate.py -P http://127.0.0.1:8000` - [ ] Confirm with @tomchristie that release is finalized and ready to go. - [ ] Ensure that release date is included in pull request. - [ ] Merge the release pull request. @@ -195,15 +151,12 @@ If `@tomchristie` ceases to participate in the project then `@j4mie` has respons The following issues still need to be addressed: -* Ensure `@jamie` has back-up access to the `django-rest-framework.org` domain setup and admin. -* Document ownership of the [live example][sandbox] API. +* Ensure `@j4mie` has back-up access to the `django-rest-framework.org` domain setup and admin. * Document ownership of the [mailing list][mailing-list] and IRC channel. * Document ownership and management of the security mailing list. [bus-factor]: https://en.wikipedia.org/wiki/Bus_factor -[un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel [transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/ [transifex-client]: https://pypi.org/project/transifex-client/ [translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations -[sandbox]: https://restframework.herokuapp.com/ [mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework diff --git a/docs/community/release-notes.md b/docs/community/release-notes.md index 887cae3b47..c7b82e9851 100644 --- a/docs/community/release-notes.md +++ b/docs/community/release-notes.md @@ -2,11 +2,13 @@ ## Versioning -Minor version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes. +- **Minor** version numbers (0.0.x) are used for changes that are API compatible. You should be able to upgrade between minor point releases without any other code changes. -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. +- **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. +- **Major** version numbers (x.0.0) are reserved for substantial project milestones. + +As REST Framework is considered feature-complete, most releases are expected to be minor releases. ## Deprecation policy @@ -34,6 +36,191 @@ You can determine your currently installed version using `pip show`: --- +## 3.16.x series + +### 3.16.0 + +**Date**: 28th March 2025 + +This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behaviour of existing features and pre-existing behaviour. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation. + +## Features + +* Add official support for Django 5.1 and its new `LoginRequiredMiddleware` in [#9514](https://github.com/encode/django-rest-framework/pull/9514) and [#9657](https://github.com/encode/django-rest-framework/pull/9657) +* Add official Django 5.2a1 support in [#9634](https://github.com/encode/django-rest-framework/pull/9634) +* Add support for Python 3.13 in [#9527](https://github.com/encode/django-rest-framework/pull/9527) and [#9556](https://github.com/encode/django-rest-framework/pull/9556) +* Support Django 2.1+ test client JSON data automatically serialized in [#6511](https://github.com/encode/django-rest-framework/pull/6511) and fix a regression in [#9615](https://github.com/encode/django-rest-framework/pull/9615) + +## Bug fixes + +* Fix unique together validator to respect condition's fields from `UniqueConstraint` in [#9360](https://github.com/encode/django-rest-framework/pull/9360) +* Fix raising on nullable fields part of `UniqueConstraint` in [#9531](https://github.com/encode/django-rest-framework/pull/9531) +* Fix `unique_together` validation with source in [#9482](https://github.com/encode/django-rest-framework/pull/9482) +* Added protections to `AttributeError` raised within properties in [#9455](https://github.com/encode/django-rest-framework/pull/9455) +* Fix `get_template_context` to handle also lists in [#9467](https://github.com/encode/django-rest-framework/pull/9467) +* Fix "Converter is already registered" deprecation warning. in [#9512](https://github.com/encode/django-rest-framework/pull/9512) +* Fix noisy warning and accept integers as min/max values of `DecimalField` in [#9515](https://github.com/encode/django-rest-framework/pull/9515) +* Fix usages of `open()` in `setup.py` in [#9661](https://github.com/encode/django-rest-framework/pull/9661) + +## Translations + +* Add some missing Chinese translations in [#9505](https://github.com/encode/django-rest-framework/pull/9505) +* Fix spelling mistakes in Farsi language were corrected in [#9521](https://github.com/encode/django-rest-framework/pull/9521) +* Fixing and adding missing Brazilian Portuguese translations in [#9535](https://github.com/encode/django-rest-framework/pull/9535) + +## Removals + +* Remove support for Python 3.8 in [#9670](https://github.com/encode/django-rest-framework/pull/9670) +* Remove long deprecated code from request wrapper in [#9441](https://github.com/encode/django-rest-framework/pull/9441) +* Remove deprecated `AutoSchema._get_reference` method in [#9525](https://github.com/encode/django-rest-framework/pull/9525) + +## Documentation and internal changes + +* Provide tests for hashing of `OperandHolder` in [#9437](https://github.com/encode/django-rest-framework/pull/9437) +* Update documentation: Add `adrf` third party package in [#9198](https://github.com/encode/django-rest-framework/pull/9198) +* Update tutorials links in Community contributions docs in [#9476](https://github.com/encode/django-rest-framework/pull/9476) +* Fix usage of deprecated Django function in example from docs in [#9509](https://github.com/encode/django-rest-framework/pull/9509) +* Move path converter docs into a separate section in [#9524](https://github.com/encode/django-rest-framework/pull/9524) +* Add test covering update view without `queryset` attribute in [#9528](https://github.com/encode/django-rest-framework/pull/9528) +* Fix Transifex link in [#9541](https://github.com/encode/django-rest-framework/pull/9541) +* Fix example `httpie` call in docs in [#9543](https://github.com/encode/django-rest-framework/pull/9543) +* Fix example for serializer field with choices in docs in [#9563](https://github.com/encode/django-rest-framework/pull/9563) +* Remove extra `<>` in validators example in [#9590](https://github.com/encode/django-rest-framework/pull/9590) +* Update `strftime` link in the docs in [#9624](https://github.com/encode/django-rest-framework/pull/9624) +* Switch to codecov GHA in [#9618](https://github.com/encode/django-rest-framework/pull/9618) +* Add note regarding availability of the `action` attribute in 'Introspecting ViewSet actions' docs section in [#9633](https://github.com/encode/django-rest-framework/pull/9633) +* Improved description of allowed throttling rates in documentation in [#9640](https://github.com/encode/django-rest-framework/pull/9640) +* Add `rest-framework-gm2m-relations` package to the list of 3rd party libraries in [#9063](https://github.com/encode/django-rest-framework/pull/9063) +* Fix a number of typos in the test suite in the docs in [#9662](https://github.com/encode/django-rest-framework/pull/9662) +* Add `django-pyoidc` as a third party authentication library in [#9667](https://github.com/encode/django-rest-framework/pull/9667) + +## New Contributors + +* [`@maerteijn`](https://github.com/maerteijn) made their first contribution in [#9198](https://github.com/encode/django-rest-framework/pull/9198) +* [`@FraCata00`](https://github.com/FraCata00) made their first contribution in [#9444](https://github.com/encode/django-rest-framework/pull/9444) +* [`@AlvaroVega`](https://github.com/AlvaroVega) made their first contribution in [#9451](https://github.com/encode/django-rest-framework/pull/9451) +* [`@james`](https://github.com/james)-mchugh made their first contribution in [#9455](https://github.com/encode/django-rest-framework/pull/9455) +* [`@ifeanyidavid`](https://github.com/ifeanyidavid) made their first contribution in [#9479](https://github.com/encode/django-rest-framework/pull/9479) +* [`@p`](https://github.com/p)-schlickmann made their first contribution in [#9480](https://github.com/encode/django-rest-framework/pull/9480) +* [`@akkuman`](https://github.com/akkuman) made their first contribution in [#9505](https://github.com/encode/django-rest-framework/pull/9505) +* [`@rafaelgramoschi`](https://github.com/rafaelgramoschi) made their first contribution in [#9509](https://github.com/encode/django-rest-framework/pull/9509) +* [`@Sinaatkd`](https://github.com/Sinaatkd) made their first contribution in [#9521](https://github.com/encode/django-rest-framework/pull/9521) +* [`@gtkacz`](https://github.com/gtkacz) made their first contribution in [#9535](https://github.com/encode/django-rest-framework/pull/9535) +* [`@sliverc`](https://github.com/sliverc) made their first contribution in [#9556](https://github.com/encode/django-rest-framework/pull/9556) +* [`@gabrielromagnoli1987`](https://github.com/gabrielromagnoli1987) made their first contribution in [#9543](https://github.com/encode/django-rest-framework/pull/9543) +* [`@cheehong1030`](https://github.com/cheehong1030) made their first contribution in [#9563](https://github.com/encode/django-rest-framework/pull/9563) +* [`@amansharma612`](https://github.com/amansharma612) made their first contribution in [#9590](https://github.com/encode/django-rest-framework/pull/9590) +* [`@Gluroda`](https://github.com/Gluroda) made their first contribution in [#9616](https://github.com/encode/django-rest-framework/pull/9616) +* [`@deepakangadi`](https://github.com/deepakangadi) made their first contribution in [#9624](https://github.com/encode/django-rest-framework/pull/9624) +* [`@EXG1O`](https://github.com/EXG1O) made their first contribution in [#9633](https://github.com/encode/django-rest-framework/pull/9633) +* [`@decadenza`](https://github.com/decadenza) made their first contribution in [#9640](https://github.com/encode/django-rest-framework/pull/9640) +* [`@mojtabaakbari221b`](https://github.com/mojtabaakbari221b) made their first contribution in [#9063](https://github.com/encode/django-rest-framework/pull/9063) +* [`@mikemanger`](https://github.com/mikemanger) made their first contribution in [#9661](https://github.com/encode/django-rest-framework/pull/9661) +* [`@gbip`](https://github.com/gbip) made their first contribution in [#9667](https://github.com/encode/django-rest-framework/pull/9667) + +**Full Changelog**: https://github.com/encode/django-rest-framework/compare/3.15.2...3.16.0 + +## 3.15.x series + +### 3.15.2 + +**Date**: 14th June 2024 + +* Fix potential XSS vulnerability in browsable API. [#9435](https://github.com/encode/django-rest-framework/pull/9435) +* Revert "Ensure CursorPagination respects nulls in the ordering field". [#9381](https://github.com/encode/django-rest-framework/pull/9381) +* Use warnings rather than logging a warning for DecimalField. [#9367](https://github.com/encode/django-rest-framework/pull/9367) +* Remove unused code. [#9393](https://github.com/encode/django-rest-framework/pull/9393) +* Django < 4.2 and Python < 3.8 no longer supported. [#9393](https://github.com/encode/django-rest-framework/pull/9393) + +### 3.15.1 + +Date: 22nd March 2024 + +* Fix `SearchFilter` handling of quoted and comma separated strings, when `.get_search_terms` is being called into by a custom class. See [[#9338](https://github.com/encode/django-rest-framework/issues/9338)] +* Revert number of 3.15.0 issues which included unintended side-effects. See [[#9331](https://github.com/encode/django-rest-framework/issues/9331)] + +### 3.15.0 + +Date: 15th March 2024 + +* Django 5.0 and Python 3.12 support [[#9157](https://github.com/encode/django-rest-framework/pull/9157)] +* Use POST method instead of GET to perform logout in browsable API [[9208](https://github.com/encode/django-rest-framework/pull/9208)] +* Added jQuery 3.7.1 support & dropped previous version [[#9094](https://github.com/encode/django-rest-framework/pull/9094)] +* Use str as default path converter [[#9066](https://github.com/encode/django-rest-framework/pull/9066)] +* Document support for http.HTTPMethod in the @action decorator added in Python 3.11 [[#9067](https://github.com/encode/django-rest-framework/pull/9067)] +* Update exceptions.md [[#9071](https://github.com/encode/django-rest-framework/pull/9071)] +* Partial serializer should not have required fields [[#7563](https://github.com/encode/django-rest-framework/pull/7563)] +* Propagate 'default' from model field to serializer field. [[#9030](https://github.com/encode/django-rest-framework/pull/9030)] +* Allow to override child.run_validation call in ListSerializer [[#8035](https://github.com/encode/django-rest-framework/pull/8035)] +* Align SearchFilter behaviour to django.contrib.admin search [[#9017](https://github.com/encode/django-rest-framework/pull/9017)] +* Class name added to unknown field error [[#9019](https://github.com/encode/django-rest-framework/pull/9019)] +* Fix: Pagination response schemas. [[#9049](https://github.com/encode/django-rest-framework/pull/9049)] +* Fix choices in ChoiceField to support IntEnum [[#8955](https://github.com/encode/django-rest-framework/pull/8955)] +* Fix `SearchFilter` rendering search field with invalid value [[#9023](https://github.com/encode/django-rest-framework/pull/9023)] +* Fix OpenAPI Schema yaml rendering for `timedelta` [[#9007](https://github.com/encode/django-rest-framework/pull/9007)] +* Fix `NamespaceVersioning` ignoring `DEFAULT_VERSION` on non-None namespaces [[#7278](https://github.com/encode/django-rest-framework/pull/7278)] +* Added Deprecation Warnings for CoreAPI [[#7519](https://github.com/encode/django-rest-framework/pull/7519)] +* Removed usage of `field.choices` that triggered full table load [[#8950](https://github.com/encode/django-rest-framework/pull/8950)] +* Permit mixed casing of string values for `BooleanField` validation [[#8970](https://github.com/encode/django-rest-framework/pull/8970)] +* Fixes `BrowsableAPIRenderer` for usage with `ListSerializer`. [[#7530](https://github.com/encode/django-rest-framework/pull/7530)] +* Change semantic of `OR` of two permission classes [[#7522](https://github.com/encode/django-rest-framework/pull/7522)] +* Remove dependency on `pytz` [[#8984](https://github.com/encode/django-rest-framework/pull/8984)] +* Make set_value a method within `Serializer` [[#8001](https://github.com/encode/django-rest-framework/pull/8001)] +* Fix URLPathVersioning reverse fallback [[#7247](https://github.com/encode/django-rest-framework/pull/7247)] +* Warn about Decimal type in min_value and max_value arguments of DecimalField [[#8972](https://github.com/encode/django-rest-framework/pull/8972)] +* Fix mapping for choice values [[#8968](https://github.com/encode/django-rest-framework/pull/8968)] +* Refactor read function to use context manager for file handling [[#8967](https://github.com/encode/django-rest-framework/pull/8967)] +* Fix: fallback on CursorPagination ordering if unset on the view [[#8954](https://github.com/encode/django-rest-framework/pull/8954)] +* Replaced `OrderedDict` with `dict` [[#8964](https://github.com/encode/django-rest-framework/pull/8964)] +* Refactor get_field_info method to include max_digits and decimal_places attributes in SimpleMetadata class [[#8943](https://github.com/encode/django-rest-framework/pull/8943)] +* Implement `__eq__` for validators [[#8925](https://github.com/encode/django-rest-framework/pull/8925)] +* Ensure CursorPagination respects nulls in the ordering field [[#8912](https://github.com/encode/django-rest-framework/pull/8912)] +* Use ZoneInfo as primary source of timezone data [[#8924](https://github.com/encode/django-rest-framework/pull/8924)] +* Add username search field for TokenAdmin (#8927) [[#8934](https://github.com/encode/django-rest-framework/pull/8934)] +* Handle Nested Relation in SlugRelatedField when many=False [[#8922](https://github.com/encode/django-rest-framework/pull/8922)] +* Bump version of jQuery to 3.6.4 & updated ref links [[#8909](https://github.com/encode/django-rest-framework/pull/8909)] +* Support UniqueConstraint [[#7438](https://github.com/encode/django-rest-framework/pull/7438)] +* Allow Request, Response, Field, and GenericAPIView to be subscriptable. This allows the classes to be made generic for type checking. [[#8825](https://github.com/encode/django-rest-framework/pull/8825)] +* Feat: Add some changes to ValidationError to support django style validation errors [[#8863](https://github.com/encode/django-rest-framework/pull/8863)] +* Fix Respect `can_read_model` permission in DjangoModelPermissions [[#8009](https://github.com/encode/django-rest-framework/pull/8009)] +* Add SimplePathRouter [[#6789](https://github.com/encode/django-rest-framework/pull/6789)] +* Re-prefetch related objects after updating [[#8043](https://github.com/encode/django-rest-framework/pull/8043)] +* Fix FilePathField required argument [[#8805](https://github.com/encode/django-rest-framework/pull/8805)] +* Raise ImproperlyConfigured exception if `basename` is not unique [[#8438](https://github.com/encode/django-rest-framework/pull/8438)] +* Use PrimaryKeyRelatedField pkfield in openapi [[#8315](https://github.com/encode/django-rest-framework/pull/8315)] +* replace partition with split in BasicAuthentication [[#8790](https://github.com/encode/django-rest-framework/pull/8790)] +* Fix BooleanField's allow_null behavior [[#8614](https://github.com/encode/django-rest-framework/pull/8614)] +* Handle Django's ValidationErrors in ListField [[#6423](https://github.com/encode/django-rest-framework/pull/6423)] +* Remove a bit of inline CSS. Add CSP nonce where it might be required and is available [[#8783](https://github.com/encode/django-rest-framework/pull/8783)] +* Use autocomplete widget for user selection in Token admin [[#8534](https://github.com/encode/django-rest-framework/pull/8534)] +* Make browsable API compatible with strong CSP [[#8784](https://github.com/encode/django-rest-framework/pull/8784)] +* Avoid inline script execution for injecting CSRF token [[#7016](https://github.com/encode/django-rest-framework/pull/7016)] +* Mitigate global dependency on inflection [[#8017](https://github.com/encode/django-rest-framework/pull/8017)] [[#8781](https://github.com/encode/django-rest-framework/pull/8781)] +* Register Django urls [[#8778](https://github.com/encode/django-rest-framework/pull/8778)] +* Implemented Verbose Name Translation for TokenProxy [[#8713](https://github.com/encode/django-rest-framework/pull/8713)] +* Properly handle OverflowError in DurationField deserialization [[#8042](https://github.com/encode/django-rest-framework/pull/8042)] +* Fix OpenAPI operation name plural appropriately [[#8017](https://github.com/encode/django-rest-framework/pull/8017)] +* Represent SafeString as plain string on schema rendering [[#8429](https://github.com/encode/django-rest-framework/pull/8429)] +* Fix #8771 - Checking for authentication even if `_ignore_model_permissions = True` [[#8772](https://github.com/encode/django-rest-framework/pull/8772)] +* Fix 404 when page query parameter is empty string [[#8578](https://github.com/encode/django-rest-framework/pull/8578)] +* Fixes instance check in ListSerializer.to_representation [[#8726](https://github.com/encode/django-rest-framework/pull/8726)] [[#8727](https://github.com/encode/django-rest-framework/pull/8727)] +* FloatField will crash if the input is a number that is too big [[#8725](https://github.com/encode/django-rest-framework/pull/8725)] +* Add missing DurationField to SimpleMetadata label_lookup [[#8702](https://github.com/encode/django-rest-framework/pull/8702)] +* Add support for Python 3.11 [[#8752](https://github.com/encode/django-rest-framework/pull/8752)] +* Make request consistently available in pagination classes [[#8764](https://github.com/encode/django-rest-framework/pull/9764)] +* Possibility to remove trailing zeros on DecimalFields representation [[#6514](https://github.com/encode/django-rest-framework/pull/6514)] +* Add a method for getting serializer field name (OpenAPI) [[#7493](https://github.com/encode/django-rest-framework/pull/7493)] +* Add `__eq__` method for `OperandHolder` class [[#8710](https://github.com/encode/django-rest-framework/pull/8710)] +* Avoid importing `django.test` package when not testing [[#8699](https://github.com/encode/django-rest-framework/pull/8699)] +* Preserve exception messages for wrapped Django exceptions [[#8051](https://github.com/encode/django-rest-framework/pull/8051)] +* Include `examples` and `format` to OpenAPI schema of CursorPagination [[#8687](https://github.com/encode/django-rest-framework/pull/8687)] [[#8686](https://github.com/encode/django-rest-framework/pull/8686)] +* Fix infinite recursion with deepcopy on Request [[#8684](https://github.com/encode/django-rest-framework/pull/8684)] +* Refactor: Replace try/except with contextlib.suppress() [[#8676](https://github.com/encode/django-rest-framework/pull/8676)] +* Minor fix to SerializeMethodField docstring [[#8629](https://github.com/encode/django-rest-framework/pull/8629)] +* Minor refactor: Unnecessary use of list() function [[#8672](https://github.com/encode/django-rest-framework/pull/8672)] +* Unnecessary list comprehension [[#8670](https://github.com/encode/django-rest-framework/pull/8670)] +* Use correct class to indicate present deprecation [[#8665](https://github.com/encode/django-rest-framework/pull/8665)] + ## 3.14.x series ### 3.14.0 @@ -47,7 +234,7 @@ Date: 22nd September 2022 * Stop calling `set_context` on Validators. [[#8589](https://github.com/encode/django-rest-framework/pull/8589)] * Return `NotImplemented` from `ErrorDetails.__ne__`. [[#8538](https://github.com/encode/django-rest-framework/pull/8538)] * Don't evaluate `DateTimeField.default_timezone` when a custom timezone is set. [[#8531](https://github.com/encode/django-rest-framework/pull/8531)] -* Make relative URLs clickable in Browseable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)] +* Make relative URLs clickable in Browsable API. [[#8464](https://github.com/encode/django-rest-framework/pull/8464)] * Support `ManyRelatedField` falling back to the default value when the attribute specified by dot notation doesn't exist. Matches `ManyRelatedField.get_attribute` to `Field.get_attribute`. [[#7574](https://github.com/encode/django-rest-framework/pull/7574)] * Make `schemas.openapi.get_reference` public. [[#7515](https://github.com/encode/django-rest-framework/pull/7515)] * Make `ReturnDict` support `dict` union operators on Python 3.9 and later. [[#8302](https://github.com/encode/django-rest-framework/pull/8302)] @@ -65,7 +252,7 @@ Date: 15th December 2021 Date: 13th December 2021 -* Django 4.0 compatability. [#8178] +* Django 4.0 compatibility. [#8178] * Add `max_length` and `min_length` options to `ListSerializer`. [#8165] * Add `get_request_serializer` and `get_response_serializer` hooks to `AutoSchema`. [#7424] * Fix OpenAPI representation of null-able read only fields. [#8116] @@ -157,6 +344,7 @@ Date: 28th September 2020 * Fix `PrimaryKeyRelatedField` and `HyperlinkedRelatedField` when source field is actually a property. [#7142] * `Token.generate_key` is now a class method. [#7502] * `@action` warns if method is wrapped in a decorator that does not preserve information using `@functools.wraps`. [#7098] +* Deprecate `serializers.NullBooleanField` in favour of `serializers.BooleanField` with `allow_null=True` [#7122] --- @@ -305,7 +493,11 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. class NullableCharField(serializers.CharField): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self.validators = [v for v in self.validators if not isinstance(v, ProhibitNullCharactersValidator)] + self.validators = [ + v + for v in self.validators + if not isinstance(v, ProhibitNullCharactersValidator) + ] ``` * Add `OpenAPIRenderer` and `generate_schema` management command. [#6229][gh6229] * Add OpenAPIRenderer by default, and add schema docs. [#6233][gh6233] @@ -320,7 +512,7 @@ Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. * Allow hashing of ErrorDetail. [#5932][gh5932] * Correct schema parsing for JSONField [#5878][gh5878] * Render descriptions (from help_text) using safe [#5869][gh5869] -* Removed input value from deault_error_message [#5881][gh5881] +* Removed input value from default_error_message [#5881][gh5881] * Added min_value/max_value support in DurationField [#5643][gh5643] * Fixed instance being overwritten in pk-only optimization try/except block [#5747][gh5747] * Fixed AttributeError from items filter when value is None [#5981][gh5981] @@ -941,7 +1133,7 @@ See the [release announcement][3.6-release]. * description.py codes and tests removal. ([#4153][gh4153]) * Wrap guardian.VERSION in tuple. ([#4149][gh4149]) * Refine validator for fields with kwargs. ([#4146][gh4146]) -* Fix None values representation in childs of ListField, DictField. ([#4118][gh4118]) +* Fix None values representation in children of ListField, DictField. ([#4118][gh4118]) * Resolve TimeField representation for midnight value. ([#4107][gh4107]) * Set proper status code in AdminRenderer for the redirection after POST/DELETE requests. ([#4106][gh4106]) * TimeField render returns None instead of 00:00:00. ([#4105][gh4105]) @@ -949,7 +1141,7 @@ See the [release announcement][3.6-release]. * Prevent raising exception when limit is 0. ([#4098][gh4098]) * TokenAuthentication: Allow custom keyword in the header. ([#4097][gh4097]) * Handle incorrectly padded HTTP basic auth header. ([#4090][gh4090]) -* LimitOffset pagination crashes Browseable API when limit=0. ([#4079][gh4079]) +* LimitOffset pagination crashes Browsable API when limit=0. ([#4079][gh4079]) * Fixed DecimalField arbitrary precision support. ([#4075][gh4075]) * Added support for custom CSRF cookie names. ([#4049][gh4049]) * Fix regression introduced by #4035. ([#4041][gh4041]) diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index 9513b13d1a..d213cac3d4 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -32,7 +32,7 @@ We suggest adding your package to the [REST Framework][rest-framework-grid] grid #### 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 Packages][third-party-packages] section. +Create a [Pull Request][drf-create-pr] 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 Packages][third-party-packages] section. #### Announce on the discussion group. @@ -44,7 +44,11 @@ Django REST Framework has a growing community of developers, packages, and resou 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]. +To submit new content, [create a pull request][drf-create-pr]. + +## Async Support + +* [adrf](https://github.com/em1208/adrf) - Async support, provides async Views, ViewSets, and Serializers. ### Authentication @@ -58,6 +62,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque * [drf-oidc-auth][drf-oidc-auth] - Implements OpenID Connect token authentication for DRF. * [drfpasswordless][drfpasswordless] - Adds (Medium, Square Cash inspired) passwordless logins and signups via email and mobile numbers. * [django-rest-authemail][django-rest-authemail] - Provides a RESTful API for user signup and authentication using email addresses. +* [dango-pyoidc][django-pyoidc] adds support for OpenID Connect (OIDC) authentication. ### Permissions @@ -121,10 +126,11 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque * [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters. * [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF. * [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values. -* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF. +* [django-rest-framework-guardian2][django-rest-framework-guardian2] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF. ### Misc +* [drf-sendables][drf-sendables] - User messages for Django REST Framework * [cookiecutter-django-rest][cookiecutter-django-rest] - A cookiecutter template that takes care of the setup and configuration so you can focus on making your REST apis awesome. * [djangorestrelationalhyperlink][djangorestrelationalhyperlink] - A hyperlinked serializer that can can be used to alter relationships via hyperlinks, but otherwise like a hyperlink model serializer. * [django-rest-framework-proxy][django-rest-framework-proxy] - Proxy to redirect incoming request to another API server. @@ -150,7 +156,15 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque * [fast-drf] - A model based library for making API development faster and easier. * [django-requestlogs] - Providing middleware and other helpers for audit logging for REST framework. * [drf-standardized-errors][drf-standardized-errors] - DRF exception handler to standardize error responses for all API endpoints. +* [drf-api-action][drf-api-action] - uses the power of DRF also as a library functions + +### Customization + +* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort. +* [drf-redesign][drf-redesign] - A project that gives a fresh look to the browse-able API using Bootstrap 5. +* [drf-material][drf-material] - A project that gives a sleek and elegant look to the browsable API using Material Design. +[drf-sendables]: https://github.com/amikrop/drf-sendables [cite]: http://www.software-ecosystems.com/Software_Ecosystems/Ecosystems.html [cookiecutter]: https://github.com/jpadilla/cookiecutter-django-rest-framework [new-repo]: https://github.com/new @@ -161,7 +175,6 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque [drf-compat]: https://github.com/encode/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/encode/django-rest-framework/compare -[drf-create-issue]: https://github.com/encode/django-rest-framework/issues/new [authentication]: ../api-guide/authentication.md [permissions]: ../api-guide/permissions.md [third-party-packages]: ../topics/third-party-packages/#existing-third-party-packages @@ -205,7 +218,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque [dry-rest-permissions]: https://github.com/FJNR-inc/dry-rest-permissions [django-url-filter]: https://github.com/miki725/django-url-filter [drf-url-filter]: https://github.com/manjitkumar/drf-url-filters -[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest +[cookiecutter-django-rest]: https://github.com/agconti/cookiecutter-django-rest [drf-haystack]: https://drf-haystack.readthedocs.io/en/latest/ [django-rest-framework-version-transforms]: https://github.com/mrhwick/django-rest-framework-version-transforms [djangorestframework-jsonapi]: https://github.com/django-json-api/django-rest-framework-json-api @@ -229,7 +242,7 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque [djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses [django-restql]: https://github.com/yezyilomo/django-restql [djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt -[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian +[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2 [drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler [djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/ [django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf @@ -241,3 +254,8 @@ To submit new content, [open an issue][drf-create-issue] or [create a pull reque [fast-drf]: https://github.com/iashraful/fast-drf [django-requestlogs]: https://github.com/Raekkeri/django-requestlogs [drf-standardized-errors]: https://github.com/ghazi-git/drf-standardized-errors +[drf-api-action]: https://github.com/Ori-Roza/drf-api-action +[drf-restwind]: https://github.com/youzarsiph/drf-restwind +[drf-redesign]: https://github.com/youzarsiph/drf-redesign +[drf-material]: https://github.com/youzarsiph/drf-material +[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc diff --git a/docs/community/tutorials-and-resources.md b/docs/community/tutorials-and-resources.md index 23faf79128..427bdd2d71 100644 --- a/docs/community/tutorials-and-resources.md +++ b/docs/community/tutorials-and-resources.md @@ -12,19 +12,22 @@ There are a wide range of resources available for learning and using Django REST - + +## Courses + +* [Developing RESTful APIs with Django REST Framework][developing-restful-apis-with-django-rest-framework] + ## Tutorials * [Beginner's Guide to the Django REST Framework][beginners-guide-to-the-django-rest-framework] * [Django REST Framework - An Introduction][drf-an-intro] * [Django REST Framework Tutorial][drf-tutorial] -* [Django REST Framework Course][django-rest-framework-course] * [Building a RESTful API with Django REST Framework][building-a-restful-api-with-drf] * [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] @@ -35,8 +38,10 @@ There are a wide range of resources available for learning and using Django REST * [Check Credentials Using Django REST Framework][check-credentials-using-django-rest-framework] * [Creating a Production Ready API with Python and Django REST Framework – Part 1][creating-a-production-ready-api-with-python-and-drf-part1] * [Creating a Production Ready API with Python and Django REST Framework – Part 2][creating-a-production-ready-api-with-python-and-drf-part2] -* [Django REST Framework Tutorial - Build a Blog API][django-rest-framework-tutorial-build-a-blog] -* [Django REST Framework & React Tutorial - Build a Todo List API][django-rest-framework-react-tutorial-build-a-todo-list] +* [Creating a Production Ready API with Python and Django REST Framework – Part 3][creating-a-production-ready-api-with-python-and-drf-part3] +* [Creating a Production Ready API with Python and Django REST Framework – Part 4][creating-a-production-ready-api-with-python-and-drf-part4] +* [Django Polls Tutorial API][django-polls-api] +* [Django REST Framework Tutorial: Todo API][django-rest-framework-todo-api] * [Tutorial: Django REST with React (Django 2.0)][django-rest-react-valentinog] @@ -45,11 +50,11 @@ There are a wide range of resources available for learning and using Django REST ### Talks * [Level Up! Rethinking the Web API Framework][pycon-us-2017] -* [How to Make a Full Fledged REST API with Django OAuth Toolkit][full-fledged-rest-api-with-django-oauth-tookit] +* [How to Make a Full Fledged REST API with Django OAuth Toolkit][full-fledged-rest-api-with-django-oauth-toolkit] * [Django REST API - So Easy You Can Learn It in 25 Minutes][django-rest-api-so-easy] * [Tom Christie about Django Rest Framework at Django: Under The Hood][django-under-hood-2014] * [Django REST Framework: Schemas, Hypermedia & Client Libraries][pycon-uk-2016] - +* [Finally Understand Authentication in Django REST Framework][django-con-2018] ### Tutorials @@ -99,7 +104,6 @@ Want your Django REST Framework talk/tutorial/article to be added to our website [api-development-with-django-and-django-rest-framework]: https://bnotions.com/news-and-insights/api-development-with-django-and-django-rest-framework/ [cdrf.co]:http://www.cdrf.co [medium-django-rest-framework]: https://medium.com/django-rest-framework -[django-rest-framework-course]: https://teamtreehouse.com/library/django-rest-framework [pycon-uk-2016]: https://www.youtube.com/watch?v=FjmiGh7OqVg [django-under-hood-2014]: https://www.youtube.com/watch?v=3cSsbe-tA0E [integrating-pandas-drf-and-bokeh]: https://web.archive.org/web/20180104205117/http://machinalis.com/blog/pandas-django-rest-framework-bokeh/ @@ -111,12 +115,14 @@ Want your Django REST Framework talk/tutorial/article to be added to our website [chatbot-using-drf-part1]: https://chatbotslife.com/chatbot-using-django-rest-framework-api-ai-slack-part-1-3-69c7e38b7b1e#.g2aceuncf [new-django-admin-with-drf-and-emberjs]: https://blog.levit.be/new-django-admin-with-emberjs-what-are-the-news/ [drf-schema]: https://drf-schema-adapter.readthedocs.io/en/latest/ -[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/2016/09/28/creating-production-ready-api-python-django-rest-framework-part-1/ -[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/2016/10/01/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/ -[django-rest-framework-tutorial-build-a-blog]: https://wsvincent.com/django-rest-framework-tutorial/ -[django-rest-framework-react-tutorial-build-a-todo-list]: https://wsvincent.com/django-rest-framework-react-tutorial/ +[creating-a-production-ready-api-with-python-and-drf-part1]: https://www.andreagrandi.it/posts/creating-production-ready-api-python-django-rest-framework-part-1/ +[creating-a-production-ready-api-with-python-and-drf-part2]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-2/ +[creating-a-production-ready-api-with-python-and-drf-part3]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-3/ +[creating-a-production-ready-api-with-python-and-drf-part4]: https://www.andreagrandi.it/posts/creating-a-production-ready-api-with-python-and-django-rest-framework-part-4/ +[django-polls-api]: https://learndjango.com/tutorials/django-polls-tutorial-api +[django-rest-framework-todo-api]: https://learndjango.com/tutorials/django-rest-framework-tutorial-todo-api [django-rest-api-so-easy]: https://www.youtube.com/watch?v=cqP758k1BaQ -[full-fledged-rest-api-with-django-oauth-tookit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk +[full-fledged-rest-api-with-django-oauth-toolkit]: https://www.youtube.com/watch?v=M6Ud3qC2tTk [drf-in-your-pjs]: https://www.youtube.com/watch?v=xMtHsWa72Ww [building-a-rest-api-using-django-and-drf]: https://www.youtube.com/watch?v=PwssEec3IRw [drf-tutorials]: https://www.youtube.com/watch?v=axRCBgbOJp8&list=PLJtp8Jm8EDzjgVg9vVyIUMoGyqtegj7FH @@ -130,3 +136,5 @@ Want your Django REST Framework talk/tutorial/article to be added to our website [pycon-us-2017]: https://www.youtube.com/watch?v=Rk6MHZdust4 [django-rest-react-valentinog]: https://www.valentinog.com/blog/tutorial-api-django-rest-react/ [doordash-implementing-rest-apis]: https://doordash.engineering/2013/10/07/implementing-rest-apis-with-embedded-privacy/ +[developing-restful-apis-with-django-rest-framework]: https://testdriven.io/courses/django-rest-framework/ +[django-con-2018]: https://youtu.be/pY-oje5b5Qk?si=AOU6tLi0IL1_pVzq \ No newline at end of file diff --git a/docs/coreapi/7-schemas-and-client-libraries.md b/docs/coreapi/7-schemas-and-client-libraries.md deleted file mode 100644 index d95019dab6..0000000000 --- a/docs/coreapi/7-schemas-and-client-libraries.md +++ /dev/null @@ -1,242 +0,0 @@ -# Tutorial 7: Schemas & client libraries - ----- - -**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details. - -If you are looking for information regarding schemas, you might want to look at these updated resources: - -1. [Schema](../api-guide/schemas.md) -2. [Documenting your API](../topics/documenting-your-api.md) - ----- - -A schema is a machine-readable document that describes the available API -endpoints, their URLS, and what operations they support. - -Schemas can be a useful tool for auto-generated documentation, and can also -be used to drive dynamic client libraries that can interact with the API. - -## Core API - -In order to provide schema support REST framework uses [Core API][coreapi]. - -Core API is a document specification for describing APIs. It is used to provide -an internal representation format of the available endpoints and possible -interactions that an API exposes. It can either be used server-side, or -client-side. - -When used server-side, Core API allows an API to support rendering to a wide -range of schema or hypermedia formats. - -When used client-side, Core API allows for dynamically driven client libraries -that can interact with any API that exposes a supported schema or hypermedia -format. - -## Adding a schema - -REST framework supports either explicitly defined schema views, or -automatically generated schemas. Since we're using viewsets and routers, -we can simply use the automatic schema generation. - -You'll need to install the `coreapi` python package in order to include an -API schema, and `pyyaml` to render the schema into the commonly used -YAML-based OpenAPI format. - - $ pip install coreapi pyyaml - -We can now include a schema for our API, by including an autogenerated schema -view in our URL configuration. - -```python -from rest_framework.schemas import get_schema_view - -schema_view = get_schema_view(title='Pastebin API') - -urlpatterns = [ -    path('schema/', schema_view), - ... -] -``` - -If you visit the `/schema/` endpoint in a browser you should now see `corejson` -representation become available as an option. - -![Schema format](../img/corejson-format.png) - -We can also request the schema from the command line, by specifying the desired -content type in the `Accept` header. - - $ http http://127.0.0.1:8000/schema/ Accept:application/coreapi+json - HTTP/1.0 200 OK - Allow: GET, HEAD, OPTIONS - Content-Type: application/coreapi+json - - { - "_meta": { - "title": "Pastebin API" - }, - "_type": "document", - ... - -The default output style is to use the [Core JSON][corejson] encoding. - -Other schema formats, such as [Open API][openapi] (formerly Swagger) are -also supported. - -## Using a command line client - -Now that our API is exposing a schema endpoint, we can use a dynamic client -library to interact with the API. To demonstrate this, let's use the -Core API command line client. - -The command line client is available as the `coreapi-cli` package: - - $ pip install coreapi-cli - -Now check that it is available on the command line... - - $ coreapi - Usage: coreapi [OPTIONS] COMMAND [ARGS]... - - Command line client for interacting with CoreAPI services. - - Visit https://www.coreapi.org/ for more information. - - Options: - --version Display the package version number. - --help Show this message and exit. - - Commands: - ... - -First we'll load the API schema using the command line client. - - $ coreapi get http://127.0.0.1:8000/schema/ - - snippets: { - highlight(id) - list() - read(id) - } - users: { - list() - read(id) - } - -We haven't authenticated yet, so right now we're only able to see the read only -endpoints, in line with how we've set up the permissions on the API. - -Let's try listing the existing snippets, using the command line client: - - $ coreapi action snippets list - [ - { - "url": "http://127.0.0.1:8000/snippets/1/", - "id": 1, - "highlight": "http://127.0.0.1:8000/snippets/1/highlight/", - "owner": "lucy", - "title": "Example", - "code": "print('hello, world!')", - "linenos": true, - "language": "python", - "style": "friendly" - }, - ... - -Some of the API endpoints require named parameters. For example, to get back -the highlight HTML for a particular snippet we need to provide an id. - - $ coreapi action snippets highlight --param id=1 - - - - - Example - ... - -## Authenticating our client - -If we want to be able to create, edit and delete snippets, we'll need to -authenticate as a valid user. In this case we'll just use basic auth. - -Make sure to replace the `` and `` below with your -actual username and password. - - $ coreapi credentials add 127.0.0.1 : --auth basic - Added credentials - 127.0.0.1 "Basic <...>" - -Now if we fetch the schema again, we should be able to see the full -set of available interactions. - - $ coreapi reload - Pastebin API "http://127.0.0.1:8000/schema/"> - snippets: { - create(code, [title], [linenos], [language], [style]) - delete(id) - highlight(id) - list() - partial_update(id, [title], [code], [linenos], [language], [style]) - read(id) - update(id, code, [title], [linenos], [language], [style]) - } - users: { - list() - read(id) - } - -We're now able to interact with these endpoints. For example, to create a new -snippet: - - $ coreapi action snippets create --param title="Example" --param code="print('hello, world')" - { - "url": "http://127.0.0.1:8000/snippets/7/", - "id": 7, - "highlight": "http://127.0.0.1:8000/snippets/7/highlight/", - "owner": "lucy", - "title": "Example", - "code": "print('hello, world')", - "linenos": false, - "language": "python", - "style": "friendly" - } - -And to delete a snippet: - - $ coreapi action snippets delete --param id=7 - -As well as the command line client, developers can also interact with your -API using client libraries. The Python client library is the first of these -to be available, and a Javascript client library is planned to be released -soon. - -For more details on customizing schema generation and using Core API -client libraries you'll need to refer to the full documentation. - -## Reviewing our work - -With an incredibly small amount of code, we've now got a complete pastebin Web API, which is fully web browsable, includes a schema-driven client library, and comes complete with authentication, per-object permissions, and multiple renderer formats. - -We've walked through each step of the design process, and seen how if we need to customize anything we can gradually work our way down to simply using regular Django views. - -You can review the final [tutorial code][repo] on GitHub, or try out a live example in [the sandbox][sandbox]. - -## Onwards and upwards - -We've reached the end of our tutorial. If you want to get more involved in the REST framework project, here are a few places you can start: - -* Contribute on [GitHub][github] by reviewing and submitting issues, and making pull requests. -* Join the [REST framework discussion group][group], and help build the community. -* Follow [the author][twitter] on Twitter and say hi. - -**Now go build awesome things.** - -[coreapi]: https://www.coreapi.org/ -[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding -[openapi]: https://openapis.org/ -[repo]: https://github.com/encode/rest-framework-tutorial -[sandbox]: https://restframework.herokuapp.com/ -[github]: https://github.com/encode/django-rest-framework -[group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework -[twitter]: https://twitter.com/_tomchristie diff --git a/docs/coreapi/from-documenting-your-api.md b/docs/coreapi/from-documenting-your-api.md deleted file mode 100644 index 65ad71c7a7..0000000000 --- a/docs/coreapi/from-documenting-your-api.md +++ /dev/null @@ -1,182 +0,0 @@ - -## Built-in API documentation - ----- - -**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details. - -If you are looking for information regarding schemas, you might want to look at these updated resources: - -1. [Schema](../api-guide/schemas.md) -2. [Documenting your API](../topics/documenting-your-api.md) - ----- - -The built-in API documentation includes: - -* Documentation of API endpoints. -* Automatically generated code samples for each of the available API client libraries. -* Support for API interaction. - -### Installation - -The `coreapi` library is required as a dependency for the API docs. Make sure -to install the latest version. The `Pygments` and `Markdown` libraries -are optional but recommended. - -To install the API documentation, you'll need to include it in your project's URLconf: - - from rest_framework.documentation import include_docs_urls - - urlpatterns = [ - ... - path('docs/', include_docs_urls(title='My API title')) - ] - -This will include two different views: - - * `/docs/` - The documentation page itself. - * `/docs/schema.js` - A JavaScript resource that exposes the API schema. - ---- - -**Note**: By default `include_docs_urls` configures the underlying `SchemaView` to generate _public_ schemas. -This means that views will not be instantiated with a `request` instance. i.e. Inside the view `self.request` will be `None`. - -To be compatible with this behaviour, methods (such as `get_serializer` or `get_serializer_class` etc.) which inspect `self.request` or, particularly, `self.request.user` may need to be adjusted to handle this case. - -You may ensure views are given a `request` instance by calling `include_docs_urls` with `public=False`: - - from rest_framework.documentation import include_docs_urls - - urlpatterns = [ - ... - # Generate schema with valid `request` instance: - path('docs/', include_docs_urls(title='My API title', public=False)) - ] - - ---- - - -### Documenting your views - -You can document your views by including docstrings that describe each of the available actions. -For example: - - class UserList(generics.ListAPIView): - """ - Return a list of all the existing users. - """ - -If a view supports multiple methods, you should split your documentation using `method:` style delimiters. - - class UserList(generics.ListCreateAPIView): - """ - get: - Return a list of all the existing users. - - post: - Create a new user instance. - """ - -When using viewsets, you should use the relevant action names as delimiters. - - class UserViewSet(viewsets.ModelViewSet): - """ - retrieve: - Return the given user. - - list: - Return a list of all the existing users. - - create: - Create a new user instance. - """ - -Custom actions on viewsets can also be documented in a similar way using the method names -as delimiters or by attaching the documentation to action mapping methods. - - class UserViewSet(viewsets.ModelViewset): - ... - - @action(detail=False, methods=['get', 'post']) - def some_action(self, request, *args, **kwargs): - """ - get: - A description of the get method on the custom action. - - post: - A description of the post method on the custom action. - """ - - @some_action.mapping.put - def put_some_action(): - """ - A description of the put method on the custom action. - """ - - -### `documentation` API Reference - -The `rest_framework.documentation` module provides three helper functions to help configure the interactive API documentation, `include_docs_urls` (usage shown above), `get_docs_view` and `get_schemajs_view`. - - `include_docs_urls` employs `get_docs_view` and `get_schemajs_view` to generate the url patterns for the documentation page and JavaScript resource that exposes the API schema respectively. They expose the following options for customisation. (`get_docs_view` and `get_schemajs_view` ultimately call `rest_frameworks.schemas.get_schema_view()`, see the Schemas docs for more options there.) - -#### `include_docs_urls` - -* `title`: Default `None`. May be used to provide a descriptive title for the schema definition. -* `description`: Default `None`. May be used to provide a description for the schema definition. -* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema. -* `public`: Default `True`. Should the schema be considered _public_? If `True` schema is generated without a `request` instance being passed to views. -* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used. -* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`. -* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`. -* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`. -* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`. - -#### `get_docs_view` - -* `title`: Default `None`. May be used to provide a descriptive title for the schema definition. -* `description`: Default `None`. May be used to provide a description for the schema definition. -* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema. -* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views. -* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used. -* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`. -* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`. -* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES`. May be used to pass custom permission classes to the `SchemaView`. -* `renderer_classes`: Default `None`. May be used to pass custom renderer classes to the `SchemaView`. If `None` the `SchemaView` will be configured with `DocumentationRenderer` and `CoreJSONRenderer` renderers, corresponding to the (default) `html` and `corejson` formats. - -#### `get_schemajs_view` - -* `title`: Default `None`. May be used to provide a descriptive title for the schema definition. -* `description`: Default `None`. May be used to provide a description for the schema definition. -* `schema_url`: Default `None`. May be used to pass a canonical base URL for the schema. -* `public`: Default `True`. If `True` schema is generated without a `request` instance being passed to views. -* `patterns`: Default `None`. A list of URLs to inspect when generating the schema. If `None` project's URL conf will be used. -* `generator_class`: Default `rest_framework.schemas.SchemaGenerator`. May be used to specify a `SchemaGenerator` subclass to be passed to the `SchemaView`. -* `authentication_classes`: Default `api_settings.DEFAULT_AUTHENTICATION_CLASSES`. May be used to pass custom authentication classes to the `SchemaView`. -* `permission_classes`: Default `api_settings.DEFAULT_PERMISSION_CLASSES` May be used to pass custom permission classes to the `SchemaView`. - - -### Customising code samples - -The built-in API documentation includes automatically generated code samples for -each of the available API client libraries. - -You may customise these samples by subclassing `DocumentationRenderer`, setting -`languages` to the list of languages you wish to support: - - from rest_framework.renderers import DocumentationRenderer - - - class CustomRenderer(DocumentationRenderer): - languages = ['ruby', 'go'] - -For each language you need to provide an `intro` template, detailing installation instructions and such, -plus a generic template for making API requests, that can be filled with individual request details. -See the [templates for the bundled languages][client-library-templates] for examples. - ---- - -[client-library-templates]: https://github.com/encode/django-rest-framework/tree/master/rest_framework/templates/rest_framework/docs/langs \ No newline at end of file diff --git a/docs/coreapi/index.md b/docs/coreapi/index.md deleted file mode 100644 index dbcb115840..0000000000 --- a/docs/coreapi/index.md +++ /dev/null @@ -1,29 +0,0 @@ -# Legacy CoreAPI Schemas Docs - -Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. - -See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details. - ----- - -You can continue to use CoreAPI schemas by setting the appropriate default schema class: - -```python -# In settings.py -REST_FRAMEWORK = { - 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema', -} -``` - -Under-the-hood, any subclass of `coreapi.AutoSchema` here will trigger use of the old CoreAPI schemas. -**Otherwise** you will automatically be opted-in to the new OpenAPI schemas. - -All CoreAPI related code will be removed in Django REST Framework v3.12. Switch to OpenAPI schemas by then. - ----- - -For reference this folder contains the old CoreAPI related documentation: - -* [Tutorial 7: Schemas & client libraries](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//7-schemas-and-client-libraries.md). -* [Excerpts from _Documenting your API_ topic page](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//from-documenting-your-api.md). -* [`rest_framework.schemas` API Reference](https://github.com/encode/django-rest-framework/blob/master/docs/coreapi//schemas.md). diff --git a/docs/coreapi/schemas.md b/docs/coreapi/schemas.md deleted file mode 100644 index 9f1482d2d8..0000000000 --- a/docs/coreapi/schemas.md +++ /dev/null @@ -1,854 +0,0 @@ -source: schemas.py - -# Schemas - ----- - -**DEPRECATION NOTICE:** Use of CoreAPI-based schemas were deprecated with the introduction of native OpenAPI-based schema generation as of Django REST Framework v3.10. See the [Version 3.10 Release Announcement](../community/3.10-announcement.md) for more details. - -You are probably looking for [this page](../api-guide/schemas.md) if you want latest information regarding schemas. - ----- - -> A machine-readable [schema] describes what resources are available via the API, what their URLs are, how they are represented and what operations they support. -> -> — Heroku, [JSON Schema for the Heroku Platform API][cite] - -API schemas are a useful tool that allow for a range of use cases, including -generating reference documentation, or driving dynamic client libraries that -can interact with your API. - -## Install Core API & PyYAML - -You'll need to install the `coreapi` package in order to add schema support -for REST framework. You probably also want to install `pyyaml`, so that you -can render the schema into the commonly used YAML-based OpenAPI format. - - pip install coreapi pyyaml - -## Quickstart - -There are two different ways you can serve a schema description for your API. - -### Generating a schema with the `generateschema` management command - -To generate a static API schema, use the `generateschema` management command. - -```shell -$ python manage.py generateschema > schema.yml -``` - -Once you've generated a schema in this way you can annotate it with any -additional information that cannot be automatically inferred by the schema -generator. - -You might want to check your API schema into version control and update it -with each new release, or serve the API schema from your site's static media. - -### Adding a view with `get_schema_view` - -To add a dynamically generated schema view to your API, use `get_schema_view`. - -```python -from rest_framework.schemas import get_schema_view -from django.urls import path - -schema_view = get_schema_view(title="Example API") - -urlpatterns = [ - path('schema', schema_view), - ... -] -``` - -See below [for more details](#the-get_schema_view-shortcut) on customizing a -dynamically generated schema view. - -## Internal schema representation - -REST framework uses [Core API][coreapi] in order to model schema information in -a format-independent representation. This information can then be rendered -into various different schema formats, or used to generate API documentation. - -When using Core API, a schema is represented as a `Document` which is the -top-level container object for information about the API. Available API -interactions are represented using `Link` objects. Each link includes a URL, -HTTP method, and may include a list of `Field` instances, which describe any -parameters that may be accepted by the API endpoint. The `Link` and `Field` -instances may also include descriptions, that allow an API schema to be -rendered into user documentation. - -Here's an example of an API description that includes a single `search` -endpoint: - - coreapi.Document( - title='Flight Search API', - url='https://api.example.org/', - content={ - 'search': coreapi.Link( - url='/search/', - action='get', - fields=[ - coreapi.Field( - name='from', - required=True, - location='query', - description='City name or airport code.' - ), - coreapi.Field( - name='to', - required=True, - location='query', - description='City name or airport code.' - ), - coreapi.Field( - name='date', - required=True, - location='query', - description='Flight date in "YYYY-MM-DD" format.' - ) - ], - description='Return flight availability and prices.' - ) - } - ) - -## Schema output formats - -In order to be presented in an HTTP response, the internal representation -has to be rendered into the actual bytes that are used in the response. - -REST framework includes a few different renderers that you can use for -encoding the API schema. - -* `renderers.OpenAPIRenderer` - Renders into YAML-based [OpenAPI][open-api], the most widely used API schema format. -* `renderers.JSONOpenAPIRenderer` - Renders into JSON-based [OpenAPI][open-api]. -* `renderers.CoreJSONRenderer` - Renders into [Core JSON][corejson], a format designed for -use with the `coreapi` client library. - - -[Core JSON][corejson] is designed as a canonical format for use with Core API. -REST framework includes a renderer class for handling this media type, which -is available as `renderers.CoreJSONRenderer`. - - -## Schemas vs Hypermedia - -It's worth pointing out here that Core API can also be used to model hypermedia -responses, which present an alternative interaction style to API schemas. - -With an API schema, the entire available interface is presented up-front -as a single endpoint. Responses to individual API endpoints are then typically -presented as plain data, without any further interactions contained in each -response. - -With Hypermedia, the client is instead presented with a document containing -both data and available interactions. Each interaction results in a new -document, detailing both the current state and the available interactions. - -Further information and support on building Hypermedia APIs with REST framework -is planned for a future version. - - ---- - -# Creating a schema - -REST framework includes functionality for auto-generating a schema, -or allows you to specify one explicitly. - -## Manual Schema Specification - -To manually specify a schema you create a Core API `Document`, similar to the -example above. - - schema = coreapi.Document( - title='Flight Search API', - content={ - ... - } - ) - - -## Automatic Schema Generation - -Automatic schema generation is provided by the `SchemaGenerator` class. - -`SchemaGenerator` processes a list of routed URL patterns and compiles the -appropriately structured Core API Document. - -Basic usage is just to provide the title for your schema and call -`get_schema()`: - - generator = schemas.SchemaGenerator(title='Flight Search API') - schema = generator.get_schema() - -## Per-View Schema Customisation - -By default, view introspection is performed by an `AutoSchema` instance -accessible via the `schema` attribute on `APIView`. This provides the -appropriate Core API `Link` object for the view, request method and path: - - auto_schema = view.schema - coreapi_link = auto_schema.get_link(...) - -(In compiling the schema, `SchemaGenerator` calls `view.schema.get_link()` for -each view, allowed method and path.) - ---- - -**Note**: For basic `APIView` subclasses, default introspection is essentially -limited to the URL kwarg path parameters. For `GenericAPIView` -subclasses, which includes all the provided class based views, `AutoSchema` will -attempt to introspect serializer, pagination and filter fields, as well as -provide richer path field descriptions. (The key hooks here are the relevant -`GenericAPIView` attributes and methods: `get_serializer`, `pagination_class`, -`filter_backends` and so on.) - ---- - -To customise the `Link` generation you may: - -* Instantiate `AutoSchema` on your view with the `manual_fields` kwarg: - - from rest_framework.views import APIView - from rest_framework.schemas import AutoSchema - - class CustomView(APIView): - ... - schema = AutoSchema( - manual_fields=[ - coreapi.Field("extra_field", ...), - ] - ) - - This allows extension for the most common case without subclassing. - -* Provide an `AutoSchema` subclass with more complex customisation: - - from rest_framework.views import APIView - from rest_framework.schemas import AutoSchema - - class CustomSchema(AutoSchema): - def get_link(...): - # Implement custom introspection here (or in other sub-methods) - - class CustomView(APIView): - ... - schema = CustomSchema() - - This provides complete control over view introspection. - -* Instantiate `ManualSchema` on your view, providing the Core API `Fields` for - the view explicitly: - - from rest_framework.views import APIView - from rest_framework.schemas import ManualSchema - - class CustomView(APIView): - ... - schema = ManualSchema(fields=[ - coreapi.Field( - "first_field", - required=True, - location="path", - schema=coreschema.String() - ), - coreapi.Field( - "second_field", - required=True, - location="path", - schema=coreschema.String() - ), - ]) - - This allows manually specifying the schema for some views whilst maintaining - automatic generation elsewhere. - -You may disable schema generation for a view by setting `schema` to `None`: - - class CustomView(APIView): - ... - schema = None # Will not appear in schema - -This also applies to extra actions for `ViewSet`s: - - class CustomViewSet(viewsets.ModelViewSet): - - @action(detail=True, schema=None) - def extra_action(self, request, pk=None): - ... - ---- - -**Note**: For full details on `SchemaGenerator` plus the `AutoSchema` and -`ManualSchema` descriptors see the [API Reference below](#api-reference). - ---- - -# Adding a schema view - -There are a few different ways to add a schema view to your API, depending on -exactly what you need. - -## The get_schema_view shortcut - -The simplest way to include a schema in your project is to use the -`get_schema_view()` function. - - from rest_framework.schemas import get_schema_view - - schema_view = get_schema_view(title="Server Monitoring API") - - urlpatterns = [ - path('', schema_view), - ... - ] - -Once the view has been added, you'll be able to make API requests to retrieve -the auto-generated schema definition. - - $ http http://127.0.0.1:8000/ Accept:application/coreapi+json - HTTP/1.0 200 OK - Allow: GET, HEAD, OPTIONS - Content-Type: application/vnd.coreapi+json - - { - "_meta": { - "title": "Server Monitoring API" - }, - "_type": "document", - ... - } - -The arguments to `get_schema_view()` are: - -#### `title` - -May be used to provide a descriptive title for the schema definition. - -#### `url` - -May be used to pass a canonical URL for the schema. - - schema_view = get_schema_view( - title='Server Monitoring API', - url='https://www.example.org/api/' - ) - -#### `urlconf` - -A string representing the import path to the URL conf that you want -to generate an API schema for. This defaults to the value of Django's -ROOT_URLCONF setting. - - schema_view = get_schema_view( - title='Server Monitoring API', - url='https://www.example.org/api/', - urlconf='myproject.urls' - ) - -#### `renderer_classes` - -May be used to pass the set of renderer classes that can be used to render the API root endpoint. - - from rest_framework.schemas import get_schema_view - from rest_framework.renderers import JSONOpenAPIRenderer - - schema_view = get_schema_view( - title='Server Monitoring API', - url='https://www.example.org/api/', - renderer_classes=[JSONOpenAPIRenderer] - ) - -#### `patterns` - -List of url patterns to limit the schema introspection to. If you only want the `myproject.api` urls -to be exposed in the schema: - - schema_url_patterns = [ - path('api/', include('myproject.api.urls')), - ] - - schema_view = get_schema_view( - title='Server Monitoring API', - url='https://www.example.org/api/', - patterns=schema_url_patterns, - ) - -#### `generator_class` - -May be used to specify a `SchemaGenerator` subclass to be passed to the -`SchemaView`. - -#### `authentication_classes` - -May be used to specify the list of authentication classes that will apply to the schema endpoint. -Defaults to `settings.DEFAULT_AUTHENTICATION_CLASSES` - -#### `permission_classes` - -May be used to specify the list of permission classes that will apply to the schema endpoint. -Defaults to `settings.DEFAULT_PERMISSION_CLASSES` - -## Using an explicit schema view - -If you need a little more control than the `get_schema_view()` shortcut gives you, -then you can use the `SchemaGenerator` class directly to auto-generate the -`Document` instance, and to return that from a view. - -This option gives you the flexibility of setting up the schema endpoint -with whatever behaviour you want. For example, you can apply different -permission, throttling, or authentication policies to the schema endpoint. - -Here's an example of using `SchemaGenerator` together with a view to -return the schema. - -**views.py:** - - from rest_framework.decorators import api_view, renderer_classes - from rest_framework import renderers, response, schemas - - generator = schemas.SchemaGenerator(title='Bookings API') - - @api_view() - @renderer_classes([renderers.OpenAPIRenderer]) - def schema_view(request): - schema = generator.get_schema(request) - return response.Response(schema) - -**urls.py:** - - urlpatterns = [ - path('', schema_view), - ... - ] - -You can also serve different schemas to different users, depending on the -permissions they have available. This approach can be used to ensure that -unauthenticated requests are presented with a different schema to -authenticated requests, or to ensure that different parts of the API are -made visible to different users depending on their role. - -In order to present a schema with endpoints filtered by user permissions, -you need to pass the `request` argument to the `get_schema()` method, like so: - - @api_view() - @renderer_classes([renderers.OpenAPIRenderer]) - def schema_view(request): - generator = schemas.SchemaGenerator(title='Bookings API') - return response.Response(generator.get_schema(request=request)) - -## Explicit schema definition - -An alternative to the auto-generated approach is to specify the API schema -explicitly, by declaring a `Document` object in your codebase. Doing so is a -little more work, but ensures that you have full control over the schema -representation. - - import coreapi - from rest_framework.decorators import api_view, renderer_classes - from rest_framework import renderers, response - - schema = coreapi.Document( - title='Bookings API', - content={ - ... - } - ) - - @api_view() - @renderer_classes([renderers.OpenAPIRenderer]) - def schema_view(request): - return response.Response(schema) - ---- - -# Schemas as documentation - -One common usage of API schemas is to use them to build documentation pages. - -The schema generation in REST framework uses docstrings to automatically -populate descriptions in the schema document. - -These descriptions will be based on: - -* The corresponding method docstring if one exists. -* A named section within the class docstring, which can be either single line or multi-line. -* The class docstring. - -## Examples - -An `APIView`, with an explicit method docstring. - - class ListUsernames(APIView): - def get(self, request): - """ - Return a list of all user names in the system. - """ - usernames = [user.username for user in User.objects.all()] - return Response(usernames) - -A `ViewSet`, with an explicit action docstring. - - class ListUsernames(ViewSet): - def list(self, request): - """ - Return a list of all user names in the system. - """ - usernames = [user.username for user in User.objects.all()] - return Response(usernames) - -A generic view with sections in the class docstring, using single-line style. - - class UserList(generics.ListCreateAPIView): - """ - get: List all the users. - post: Create a new user. - """ - queryset = User.objects.all() - serializer_class = UserSerializer - permission_classes = [IsAdminUser] - -A generic viewset with sections in the class docstring, using multi-line style. - - class UserViewSet(viewsets.ModelViewSet): - """ - API endpoint that allows users to be viewed or edited. - - retrieve: - Return a user instance. - - list: - Return all users, ordered by most recently joined. - """ - queryset = User.objects.all().order_by('-date_joined') - serializer_class = UserSerializer - ---- - -# API Reference - -## SchemaGenerator - -A class that walks a list of routed URL patterns, requests the schema for each view, -and collates the resulting CoreAPI Document. - -Typically you'll instantiate `SchemaGenerator` with a single argument, like so: - - generator = SchemaGenerator(title='Stock Prices API') - -Arguments: - -* `title` **required** - The name of the API. -* `url` - The root URL of the API schema. This option is not required unless the schema is included under path prefix. -* `patterns` - A list of URLs to inspect when generating the schema. Defaults to the project's URL conf. -* `urlconf` - A URL conf module name to use when generating the schema. Defaults to `settings.ROOT_URLCONF`. - -### get_schema(self, request) - -Returns a `coreapi.Document` instance that represents the API schema. - - @api_view - @renderer_classes([renderers.OpenAPIRenderer]) - def schema_view(request): - generator = schemas.SchemaGenerator(title='Bookings API') - return Response(generator.get_schema()) - -The `request` argument is optional, and may be used if you want to apply per-user -permissions to the resulting schema generation. - -### get_links(self, request) - -Return a nested dictionary containing all the links that should be included in the API schema. - -This is a good point to override if you want to modify the resulting structure of the generated schema, -as you can build a new dictionary with a different layout. - - -## AutoSchema - -A class that deals with introspection of individual views for schema generation. - -`AutoSchema` is attached to `APIView` via the `schema` attribute. - -The `AutoSchema` constructor takes a single keyword argument `manual_fields`. - -**`manual_fields`**: a `list` of `coreapi.Field` instances that will be added to -the generated fields. Generated fields with a matching `name` will be overwritten. - - class CustomView(APIView): - schema = AutoSchema(manual_fields=[ - coreapi.Field( - "my_extra_field", - required=True, - location="path", - schema=coreschema.String() - ), - ]) - -For more advanced customisation subclass `AutoSchema` to customise schema generation. - - class CustomViewSchema(AutoSchema): - """ - Overrides `get_link()` to provide Custom Behavior X - """ - - def get_link(self, path, method, base_url): - link = super().get_link(path, method, base_url) - # Do something to customize link here... - return link - - class MyView(APIView): - schema = CustomViewSchema() - -The following methods are available to override. - -### get_link(self, path, method, base_url) - -Returns a `coreapi.Link` instance corresponding to the given view. - -This is the main entry point. -You can override this if you need to provide custom behaviors for particular views. - -### get_description(self, path, method) - -Returns a string to use as the link description. By default this is based on the -view docstring as described in the "Schemas as Documentation" section above. - -### get_encoding(self, path, method) - -Returns a string to indicate the encoding for any request body, when interacting -with the given view. Eg. `'application/json'`. May return a blank string for views -that do not expect a request body. - -### get_path_fields(self, path, method): - -Return a list of `coreapi.Field()` instances. One for each path parameter in the URL. - -### get_serializer_fields(self, path, method) - -Return a list of `coreapi.Field()` instances. One for each field in the serializer class used by the view. - -### get_pagination_fields(self, path, method) - -Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method on any pagination class used by the view. - -### get_filter_fields(self, path, method) - -Return a list of `coreapi.Field()` instances, as returned by the `get_schema_fields()` method of any filter classes used by the view. - -### get_manual_fields(self, path, method) - -Return a list of `coreapi.Field()` instances to be added to or replace generated fields. Defaults to (optional) `manual_fields` passed to `AutoSchema` constructor. - -May be overridden to customise manual fields by `path` or `method`. For example, a per-method adjustment may look like this: - -```python -def get_manual_fields(self, path, method): - """Example adding per-method fields.""" - - extra_fields = [] - if method=='GET': - extra_fields = # ... list of extra fields for GET ... - if method=='POST': - extra_fields = # ... list of extra fields for POST ... - - manual_fields = super().get_manual_fields(path, method) - return manual_fields + extra_fields -``` - -### update_fields(fields, update_with) - -Utility `staticmethod`. Encapsulates logic to add or replace fields from a list -by `Field.name`. May be overridden to adjust replacement criteria. - - -## ManualSchema - -Allows manually providing a list of `coreapi.Field` instances for the schema, -plus an optional description. - - class MyView(APIView): - schema = ManualSchema(fields=[ - coreapi.Field( - "first_field", - required=True, - location="path", - schema=coreschema.String() - ), - coreapi.Field( - "second_field", - required=True, - location="path", - schema=coreschema.String() - ), - ] - ) - -The `ManualSchema` constructor takes two arguments: - -**`fields`**: A list of `coreapi.Field` instances. Required. - -**`description`**: A string description. Optional. - -**`encoding`**: Default `None`. A string encoding, e.g `application/json`. Optional. - ---- - -## Core API - -This documentation gives a brief overview of the components within the `coreapi` -package that are used to represent an API schema. - -Note that these classes are imported from the `coreapi` package, rather than -from the `rest_framework` package. - -### Document - -Represents a container for the API schema. - -#### `title` - -A name for the API. - -#### `url` - -A canonical URL for the API. - -#### `content` - -A dictionary, containing the `Link` objects that the schema contains. - -In order to provide more structure to the schema, the `content` dictionary -may be nested, typically to a second level. For example: - - content={ - "bookings": { - "list": Link(...), - "create": Link(...), - ... - }, - "venues": { - "list": Link(...), - ... - }, - ... - } - -### Link - -Represents an individual API endpoint. - -#### `url` - -The URL of the endpoint. May be a URI template, such as `/users/{username}/`. - -#### `action` - -The HTTP method associated with the endpoint. Note that URLs that support -more than one HTTP method, should correspond to a single `Link` for each. - -#### `fields` - -A list of `Field` instances, describing the available parameters on the input. - -#### `description` - -A short description of the meaning and intended usage of the endpoint. - -### Field - -Represents a single input parameter on a given API endpoint. - -#### `name` - -A descriptive name for the input. - -#### `required` - -A boolean, indicated if the client is required to included a value, or if -the parameter can be omitted. - -#### `location` - -Determines how the information is encoded into the request. Should be one of -the following strings: - -**"path"** - -Included in a templated URI. For example a `url` value of `/products/{product_code}/` could be used together with a `"path"` field, to handle API inputs in a URL path such as `/products/slim-fit-jeans/`. - -These fields will normally correspond with [named arguments in the project URL conf][named-arguments]. - -**"query"** - -Included as a URL query parameter. For example `?search=sale`. Typically for `GET` requests. - -These fields will normally correspond with pagination and filtering controls on a view. - -**"form"** - -Included in the request body, as a single item of a JSON object or HTML form. For example `{"colour": "blue", ...}`. Typically for `POST`, `PUT` and `PATCH` requests. Multiple `"form"` fields may be included on a single link. - -These fields will normally correspond with serializer fields on a view. - -**"body"** - -Included as the complete request body. Typically for `POST`, `PUT` and `PATCH` requests. No more than one `"body"` field may exist on a link. May not be used together with `"form"` fields. - -These fields will normally correspond with views that use `ListSerializer` to validate the request input, or with file upload views. - -#### `encoding` - -**"application/json"** - -JSON encoded request content. Corresponds to views using `JSONParser`. -Valid only if either one or more `location="form"` fields, or a single -`location="body"` field is included on the `Link`. - -**"multipart/form-data"** - -Multipart encoded request content. Corresponds to views using `MultiPartParser`. -Valid only if one or more `location="form"` fields is included on the `Link`. - -**"application/x-www-form-urlencoded"** - -URL encoded request content. Corresponds to views using `FormParser`. Valid -only if one or more `location="form"` fields is included on the `Link`. - -**"application/octet-stream"** - -Binary upload request content. Corresponds to views using `FileUploadParser`. -Valid only if a `location="body"` field is included on the `Link`. - -#### `description` - -A short description of the meaning and intended usage of the input field. - - ---- - -# Third party packages - -## drf-yasg - Yet Another Swagger Generator - -[drf-yasg][drf-yasg] generates [OpenAPI][open-api] documents suitable for code generation - nested schemas, -named models, response bodies, enum/pattern/min/max validators, form parameters, etc. - - -## drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework - -[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility, -customizability and client generation. It's usage patterns are very similar to [drf-yasg][drf-yasg]. - -[cite]: https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api -[coreapi]: https://www.coreapi.org/ -[corejson]: https://www.coreapi.org/specification/encoding/#core-json-encoding -[drf-yasg]: https://github.com/axnsan12/drf-yasg/ -[drf-spectacular]: https://github.com/tfranzel/drf-spectacular/ -[open-api]: https://openapis.org/ -[json-hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html -[api-blueprint]: https://apiblueprint.org/ -[static-files]: https://docs.djangoproject.com/en/stable/howto/static-files/ -[named-arguments]: https://docs.djangoproject.com/en/stable/topics/http/urls/#named-groups diff --git a/docs/img/books/dfa-40-cover.jpg b/docs/img/books/dfa-40-cover.jpg new file mode 100644 index 0000000000..cc47312c70 Binary files /dev/null and b/docs/img/books/dfa-40-cover.jpg differ diff --git a/docs/img/drf-m-api-root.png b/docs/img/drf-m-api-root.png new file mode 100644 index 0000000000..02a7562872 Binary files /dev/null and b/docs/img/drf-m-api-root.png differ diff --git a/docs/img/drf-m-detail-view.png b/docs/img/drf-m-detail-view.png new file mode 100644 index 0000000000..33e3515d84 Binary files /dev/null and b/docs/img/drf-m-detail-view.png differ diff --git a/docs/img/drf-m-list-view.png b/docs/img/drf-m-list-view.png new file mode 100644 index 0000000000..a7771957d1 Binary files /dev/null and b/docs/img/drf-m-list-view.png differ diff --git a/docs/img/drf-r-api-root.png b/docs/img/drf-r-api-root.png new file mode 100644 index 0000000000..5704cc3502 Binary files /dev/null and b/docs/img/drf-r-api-root.png differ diff --git a/docs/img/drf-r-detail-view.png b/docs/img/drf-r-detail-view.png new file mode 100644 index 0000000000..2959c7201a Binary files /dev/null and b/docs/img/drf-r-detail-view.png differ diff --git a/docs/img/drf-r-list-view.png b/docs/img/drf-r-list-view.png new file mode 100644 index 0000000000..1930b5dc0d Binary files /dev/null and b/docs/img/drf-r-list-view.png differ diff --git a/docs/img/drf-rw-api-root.png b/docs/img/drf-rw-api-root.png new file mode 100644 index 0000000000..15b498b9b2 Binary files /dev/null and b/docs/img/drf-rw-api-root.png differ diff --git a/docs/img/drf-rw-detail-view.png b/docs/img/drf-rw-detail-view.png new file mode 100644 index 0000000000..6e821acdab Binary files /dev/null and b/docs/img/drf-rw-detail-view.png differ diff --git a/docs/img/drf-rw-list-view.png b/docs/img/drf-rw-list-view.png new file mode 100644 index 0000000000..625b5c7c94 Binary files /dev/null and b/docs/img/drf-rw-list-view.png differ diff --git a/docs/img/premium/svix-premium.png b/docs/img/premium/svix-premium.png new file mode 100644 index 0000000000..68ff063879 Binary files /dev/null and b/docs/img/premium/svix-premium.png differ diff --git a/docs/img/premium/zuplo-readme.png b/docs/img/premium/zuplo-readme.png new file mode 100644 index 0000000000..245ded35e6 Binary files /dev/null and b/docs/img/premium/zuplo-readme.png differ diff --git a/docs/index.md b/docs/index.md index 2f44fae9a0..d590d2c049 100644 --- a/docs/index.md +++ b/docs/index.md @@ -48,7 +48,7 @@ Django REST framework is a powerful and flexible toolkit for building Web APIs. Some reasons you might want to use REST framework: -* The [Web browsable API][sandbox] is a huge usability win for your developers. +* The Web browsable API is a huge usability win for your developers. * [Authentication policies][authentication] including packages for [OAuth1a][oauth1-section] and [OAuth2][oauth2-section]. * [Serialization][serializers] that supports both [ORM][modelserializer-section] and [non-ORM][serializer-section] data sources. * Customizable all the way down - just use [regular function-based views][functionview-section] if you don't need the [more][generic-views] [powerful][viewsets] [features][routers]. @@ -74,10 +74,12 @@ continued development by **[signing up for a paid plan][funding]**.
  • PostHog
  • CryptAPI
  • FEZTO
  • +
  • Svix
  • +
  • Zuplo
  • -*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Spacinov](https://www.spacinov.com/), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), and [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework).* +*Many thanks to all our [wonderful sponsors][sponsors], and in particular to our premium backers, [Sentry](https://getsentry.com/welcome/), [Stream](https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage), [Spacinov](https://www.spacinov.com/), [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship), [bit.io](https://bit.io/jobs?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [PostHog](https://posthog.com?utm_source=DRF&utm_medium=sponsor&utm_campaign=DRF_sponsorship), [CryptAPI](https://cryptapi.io), [FEZTO](https://www.fezto.xyz/?utm_source=DjangoRESTFramework), [Svix](https://www.svix.com/?utm_source=django-REST&utm_medium=sponsorship), , and [Zuplo](https://zuplo.link/django-web).* --- @@ -85,8 +87,8 @@ continued development by **[signing up for a paid plan][funding]**. REST framework requires the following: -* Python (3.6, 3.7, 3.8, 3.9, 3.10) -* Django (2.2, 3.0, 3.1, 3.2, 4.0, 4.1) +* Django (4.2, 5.0, 5.1, 5.2) +* Python (3.9, 3.10, 3.11, 3.12, 3.13) We **highly recommend** and only officially support the latest patch release of each Python and Django series. @@ -94,8 +96,8 @@ each Python and Django series. The following packages are optional: * [PyYAML][pyyaml], [uritemplate][uriteemplate] (5.1+, 3.0.0+) - Schema generation support. -* [Markdown][markdown] (3.0.0+) - Markdown support for the browsable API. -* [Pygments][pygments] (2.4.0+) - Add syntax highlighting to Markdown processing. +* [Markdown][markdown] (3.3.0+) - Markdown support for the browsable API. +* [Pygments][pygments] (2.7.0+) - Add syntax highlighting to Markdown processing. * [django-filter][django-filter] (1.0.1+) - Filtering support. * [django-guardian][django-guardian] (1.1.1+) - Object level permissions support. @@ -183,20 +185,18 @@ Can't wait to get started? The [quickstart guide][quickstart] is the fastest way ## Development See the [Contribution guidelines][contributing] for information on how to clone -the repository, run the test suite and contribute changes back to REST +the repository, run the test suite and help maintain the code base of REST Framework. ## Support -For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag. +For support please see the [REST framework discussion group][group], try the `#restframework` channel on `irc.libera.chat`, or raise a question on [Stack Overflow][stack-overflow], making sure to include the ['django-rest-framework'][django-rest-framework-tag] tag. For priority support please sign up for a [professional or premium sponsorship plan](https://fund.django-rest-framework.org/topics/funding/). ## Security -Security issues are handled under the supervision of the [Django security team](https://www.djangoproject.com/foundation/teams/#security-team). - -**Please report security issues by emailing security@djangoproject.com**. +**Please report security issues by emailing security@encode.io**. The project maintainers will then work with you to resolve any issues where required, prior to any public disclosure. @@ -246,7 +246,6 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [serializer-section]: api-guide/serializers#serializers [modelserializer-section]: api-guide/serializers#modelserializer [functionview-section]: api-guide/views#function-based-views -[sandbox]: https://restframework.herokuapp.com/ [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [quickstart]: tutorial/quickstart.md diff --git a/docs/topics/ajax-csrf-cors.md b/docs/topics/ajax-csrf-cors.md index a65e3fdf8d..678fa00e71 100644 --- a/docs/topics/ajax-csrf-cors.md +++ b/docs/topics/ajax-csrf-cors.md @@ -2,7 +2,7 @@ > "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." > -> — [Jeff Atwood][cite] +> — [Jeff Atwood][cite] ## Javascript clients @@ -35,7 +35,7 @@ The best way to deal with CORS in REST framework is to add the required response [cite]: https://blog.codinghorror.com/preventing-csrf-and-xsrf-attacks/ [csrf]: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) -[csrf-ajax]: https://docs.djangoproject.com/en/stable/ref/csrf/#ajax +[csrf-ajax]: https://docs.djangoproject.com/en/stable/howto/csrf/#using-csrf-protection-with-ajax [cors]: https://www.w3.org/TR/cors/ [adamchainz]: https://github.com/adamchainz [django-cors-headers]: https://github.com/adamchainz/django-cors-headers diff --git a/docs/topics/api-clients.md b/docs/topics/api-clients.md deleted file mode 100644 index b9f5e3ecd8..0000000000 --- a/docs/topics/api-clients.md +++ /dev/null @@ -1,527 +0,0 @@ -# API Clients - -An API client handles the underlying details of how network requests are made -and how responses are decoded. They present the developer with an application -interface to work against, rather than working directly with the network interface. - -The API clients documented here are not restricted to APIs built with Django REST framework. - They can be used with any API that exposes a supported schema format. - -For example, [the Heroku platform API][heroku-api] exposes a schema in the JSON -Hyperschema format. As a result, the Core API command line client and Python -client library can be [used to interact with the Heroku API][heroku-example]. - -## Client-side Core API - -[Core API][core-api] is a document specification that can be used to describe APIs. It can -be used either server-side, as is done with REST framework's [schema generation][schema-generation], -or used client-side, as described here. - -When used client-side, Core API allows for *dynamically driven client libraries* -that can interact with any API that exposes a supported schema or hypermedia -format. - -Using a dynamically driven client has a number of advantages over interacting -with an API by building HTTP requests directly. - -#### More meaningful interaction - -API interactions are presented in a more meaningful way. You're working at -the application interface layer, rather than the network interface layer. - -#### Resilience & evolvability - -The client determines what endpoints are available, what parameters exist -against each particular endpoint, and how HTTP requests are formed. - -This also allows for a degree of API evolvability. URLs can be modified -without breaking existing clients, or more efficient encodings can be used -on-the-wire, with clients transparently upgrading. - -#### Self-descriptive APIs - -A dynamically driven client is able to present documentation on the API to the -end user. This documentation allows the user to discover the available endpoints -and parameters, and better understand the API they are working with. - -Because this documentation is driven by the API schema it will always be fully -up to date with the most recently deployed version of the service. - ---- - -# Command line client - -The command line client allows you to inspect and interact with any API that -exposes a supported schema format. - -## Getting started - -To install the Core API command line client, use `pip`. - -Note that the command-line client is a separate package to the -python client library. Make sure to install `coreapi-cli`. - - $ pip install coreapi-cli - -To start inspecting and interacting with an API the schema must first be loaded -from the network. - - $ coreapi get http://api.example.org/ - - snippets: { - create(code, [title], [linenos], [language], [style]) - destroy(pk) - highlight(pk) - list([page]) - partial_update(pk, [title], [code], [linenos], [language], [style]) - retrieve(pk) - update(pk, code, [title], [linenos], [language], [style]) - } - users: { - list([page]) - retrieve(pk) - } - -This will then load the schema, displaying the resulting `Document`. This -`Document` includes all the available interactions that may be made against the API. - -To interact with the API, use the `action` command. This command requires a list -of keys that are used to index into the link. - - $ coreapi action users list - [ - { - "url": "http://127.0.0.1:8000/users/2/", - "id": 2, - "username": "aziz", - "snippets": [] - }, - ... - ] - -To inspect the underlying HTTP request and response, use the `--debug` flag. - - $ coreapi action users list --debug - > GET /users/ HTTP/1.1 - > Accept: application/vnd.coreapi+json, */* - > Authorization: Basic bWF4Om1heA== - > Host: 127.0.0.1 - > User-Agent: coreapi - < 200 OK - < Allow: GET, HEAD, OPTIONS - < Content-Type: application/json - < Date: Thu, 30 Jun 2016 10:51:46 GMT - < Server: WSGIServer/0.1 Python/2.7.10 - < Vary: Accept, Cookie - < - < [{"url":"http://127.0.0.1/users/2/","id":2,"username":"aziz","snippets":[]},{"url":"http://127.0.0.1/users/3/","id":3,"username":"amy","snippets":["http://127.0.0.1/snippets/3/"]},{"url":"http://127.0.0.1/users/4/","id":4,"username":"max","snippets":["http://127.0.0.1/snippets/4/","http://127.0.0.1/snippets/5/","http://127.0.0.1/snippets/6/","http://127.0.0.1/snippets/7/"]},{"url":"http://127.0.0.1/users/5/","id":5,"username":"jose","snippets":[]},{"url":"http://127.0.0.1/users/6/","id":6,"username":"admin","snippets":["http://127.0.0.1/snippets/1/","http://127.0.0.1/snippets/2/"]}] - - [ - ... - ] - -Some actions may include optional or required parameters. - - $ coreapi action users create --param username=example - -When using `--param`, the type of the input will be determined automatically. - -If you want to be more explicit about the parameter type then use `--data` for -any null, numeric, boolean, list, or object inputs, and use `--string` for string inputs. - - $ coreapi action users edit --string username=tomchristie --data is_admin=true - -## Authentication & headers - -The `credentials` command is used to manage the request `Authentication:` header. -Any credentials added are always linked to a particular domain, so as to ensure -that credentials are not leaked across differing APIs. - -The format for adding a new credential is: - - $ coreapi credentials add - -For instance: - - $ coreapi credentials add api.example.org "Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b" - -The optional `--auth` flag also allows you to add specific types of authentication, -handling the encoding for you. Currently only `"basic"` is supported as an option here. -For example: - - $ coreapi credentials add api.example.org tomchristie:foobar --auth basic - -You can also add specific request headers, using the `headers` command: - - $ coreapi headers add api.example.org x-api-version 2 - -For more information and a listing of the available subcommands use `coreapi -credentials --help` or `coreapi headers --help`. - -## Codecs - -By default the command line client only includes support for reading Core JSON -schemas, however it includes a plugin system for installing additional codecs. - - $ pip install openapi-codec jsonhyperschema-codec hal-codec - $ coreapi codecs show - Codecs - corejson application/vnd.coreapi+json encoding, decoding - hal application/hal+json encoding, decoding - openapi application/openapi+json encoding, decoding - jsonhyperschema application/schema+json decoding - json application/json data - text text/* data - -## Utilities - -The command line client includes functionality for bookmarking API URLs -under a memorable name. For example, you can add a bookmark for the -existing API, like so... - - $ coreapi bookmarks add accountmanagement - -There is also functionality for navigating forward or backward through the -history of which API URLs have been accessed. - - $ coreapi history show - $ coreapi history back - -For more information and a listing of the available subcommands use -`coreapi bookmarks --help` or `coreapi history --help`. - -## Other commands - -To display the current `Document`: - - $ coreapi show - -To reload the current `Document` from the network: - - $ coreapi reload - -To load a schema file from disk: - - $ coreapi load my-api-schema.json --format corejson - -To dump the current document to console in a given format: - - $ coreapi dump --format openapi - -To remove the current document, along with all currently saved history, -credentials, headers and bookmarks: - - $ coreapi clear - ---- - -# Python client library - -The `coreapi` Python package allows you to programmatically interact with any -API that exposes a supported schema format. - -## Getting started - -You'll need to install the `coreapi` package using `pip` before you can get -started. - - $ pip install coreapi - -In order to start working with an API, we first need a `Client` instance. The -client holds any configuration around which codecs and transports are supported -when interacting with an API, which allows you to provide for more advanced -kinds of behaviour. - - import coreapi - client = coreapi.Client() - -Once we have a `Client` instance, we can fetch an API schema from the network. - - schema = client.get('https://api.example.org/') - -The object returned from this call will be a `Document` instance, which is -a representation of the API schema. - -## Authentication - -Typically you'll also want to provide some authentication credentials when -instantiating the client. - -#### Token authentication - -The `TokenAuthentication` class can be used to support REST framework's built-in -`TokenAuthentication`, as well as OAuth and JWT schemes. - - auth = coreapi.auth.TokenAuthentication( - scheme='JWT', - token='' - ) - client = coreapi.Client(auth=auth) - -When using TokenAuthentication you'll probably need to implement a login flow -using the CoreAPI client. - -A suggested pattern for this would be to initially make an unauthenticated client -request to an "obtain token" endpoint - -For example, using the "Django REST framework JWT" package - - client = coreapi.Client() - schema = client.get('https://api.example.org/') - - action = ['api-token-auth', 'create'] - params = {"username": "example", "password": "secret"} - result = client.action(schema, action, params) - - auth = coreapi.auth.TokenAuthentication( - scheme='JWT', - token=result['token'] - ) - client = coreapi.Client(auth=auth) - -#### Basic authentication - -The `BasicAuthentication` class can be used to support HTTP Basic Authentication. - - auth = coreapi.auth.BasicAuthentication( - username='', - password='' - ) - client = coreapi.Client(auth=auth) - -## Interacting with the API - -Now that we have a client and have fetched our schema `Document`, we can now -start to interact with the API: - - users = client.action(schema, ['users', 'list']) - -Some endpoints may include named parameters, which might be either optional or required: - - new_user = client.action(schema, ['users', 'create'], params={"username": "max"}) - -## Codecs - -Codecs are responsible for encoding or decoding Documents. - -The decoding process is used by a client to take a bytestring of an API schema -definition, and returning the Core API `Document` that represents that interface. - -A codec should be associated with a particular media type, such as `'application/coreapi+json'`. - -This media type is used by the server in the response `Content-Type` header, -in order to indicate what kind of data is being returned in the response. - -#### Configuring codecs - -The codecs that are available can be configured when instantiating a client. -The keyword argument used here is `decoders`, because in the context of a -client the codecs are only for *decoding* responses. - -In the following example we'll configure a client to only accept `Core JSON` -and `JSON` responses. This will allow us to receive and decode a Core JSON schema, -and subsequently to receive JSON responses made against the API. - - from coreapi import codecs, Client - - decoders = [codecs.CoreJSONCodec(), codecs.JSONCodec()] - client = Client(decoders=decoders) - -#### Loading and saving schemas - -You can use a codec directly, in order to load an existing schema definition, -and return the resulting `Document`. - - input_file = open('my-api-schema.json', 'rb') - schema_definition = input_file.read() - codec = codecs.CoreJSONCodec() - schema = codec.load(schema_definition) - -You can also use a codec directly to generate a schema definition given a `Document` instance: - - schema_definition = codec.dump(schema) - output_file = open('my-api-schema.json', 'rb') - output_file.write(schema_definition) - -## Transports - -Transports are responsible for making network requests. The set of transports -that a client has installed determines which network protocols it is able to -support. - -Currently the `coreapi` library only includes an HTTP/HTTPS transport, but -other protocols can also be supported. - -#### Configuring transports - -The behavior of the network layer can be customized by configuring the -transports that the client is instantiated with. - - import requests - from coreapi import transports, Client - - credentials = {'api.example.org': 'Token 3bd44a009d16ff'} - transports = transports.HTTPTransport(credentials=credentials) - client = Client(transports=transports) - -More complex customizations can also be achieved, for example modifying the -underlying `requests.Session` instance to [attach transport adaptors][transport-adaptors] -that modify the outgoing requests. - ---- - -# JavaScript Client Library - -The JavaScript client library allows you to interact with your API either from a browser, or using node. - -## Installing the JavaScript client - -There are two separate JavaScript resources that you need to include in your HTML pages in order to use the JavaScript client library. These are a static `coreapi.js` file, which contains the code for the dynamic client library, and a templated `schema.js` resource, which exposes your API schema. - -First, install the API documentation views. These will include the schema resource that'll allow you to load the schema directly from an HTML page, without having to make an asynchronous AJAX call. - - from rest_framework.documentation import include_docs_urls - - urlpatterns = [ - ... - path('docs/', include_docs_urls(title='My API service'), name='api-docs'), - ] - -Once the API documentation URLs are installed, you'll be able to include both the required JavaScript resources. Note that the ordering of these two lines is important, as the schema loading requires CoreAPI to already be installed. - - - {% load static %} - - - -The `coreapi` library, and the `schema` object will now both be available on the `window` instance. - - const coreapi = window.coreapi; - const schema = window.schema; - -## Instantiating a client - -In order to interact with the API you'll need a client instance. - - var client = new coreapi.Client(); - -Typically you'll also want to provide some authentication credentials when -instantiating the client. - -#### Session authentication - -The `SessionAuthentication` class allows session cookies to provide the user -authentication. You'll want to provide a standard HTML login flow, to allow -the user to login, and then instantiate a client using session authentication: - - let auth = new coreapi.auth.SessionAuthentication({ - csrfCookieName: 'csrftoken', - csrfHeaderName: 'X-CSRFToken', - }); - let client = new coreapi.Client({auth: auth}); - -The authentication scheme will handle including a CSRF header in any outgoing -requests for unsafe HTTP methods. - -#### Token authentication - -The `TokenAuthentication` class can be used to support REST framework's built-in -`TokenAuthentication`, as well as OAuth and JWT schemes. - - let auth = new coreapi.auth.TokenAuthentication({ - scheme: 'JWT', - token: '', - }); - let client = new coreapi.Client({auth: auth}); - -When using TokenAuthentication you'll probably need to implement a login flow -using the CoreAPI client. - -A suggested pattern for this would be to initially make an unauthenticated client -request to an "obtain token" endpoint - -For example, using the "Django REST framework JWT" package - - // Setup some globally accessible state - window.client = new coreapi.Client(); - window.loggedIn = false; - - function loginUser(username, password) { - let action = ["api-token-auth", "obtain-token"]; - let params = {username: username, password: password}; - client.action(schema, action, params).then(function(result) { - // On success, instantiate an authenticated client. - let auth = window.coreapi.auth.TokenAuthentication({ - scheme: 'JWT', - token: result['token'], - }) - window.client = coreapi.Client({auth: auth}); - window.loggedIn = true; - }).catch(function (error) { - // Handle error case where eg. user provides incorrect credentials. - }) - } - -#### Basic authentication - -The `BasicAuthentication` class can be used to support HTTP Basic Authentication. - - let auth = new coreapi.auth.BasicAuthentication({ - username: '', - password: '', - }) - let client = new coreapi.Client({auth: auth}); - -## Using the client - -Making requests: - - let action = ["users", "list"]; - client.action(schema, action).then(function(result) { - // Return value is in 'result' - }) - -Including parameters: - - let action = ["users", "create"]; - let params = {username: "example", email: "example@example.com"}; - client.action(schema, action, params).then(function(result) { - // Return value is in 'result' - }) - -Handling errors: - - client.action(schema, action, params).then(function(result) { - // Return value is in 'result' - }).catch(function (error) { - // Error value is in 'error' - }) - -## Installation with node - -The coreapi package is available on NPM. - - $ npm install coreapi - $ node - const coreapi = require('coreapi') - -You'll either want to include the API schema in your codebase directly, by copying it from the `schema.js` resource, or else load the schema asynchronously. For example: - - let client = new coreapi.Client(); - let schema = null; - client.get("https://api.example.org/").then(function(data) { - // Load a CoreJSON API schema. - schema = data; - console.log('schema loaded'); - }) - -[heroku-api]: https://devcenter.heroku.com/categories/platform-api -[heroku-example]: https://www.coreapi.org/tools-and-resources/example-services/#heroku-json-hyper-schema -[core-api]: https://www.coreapi.org/ -[schema-generation]: ../api-guide/schemas.md -[transport-adaptors]: http://docs.python-requests.org/en/master/user/advanced/#transport-adapters diff --git a/docs/topics/browsable-api.md b/docs/topics/browsable-api.md index ed70c49018..8cf530b7af 100644 --- a/docs/topics/browsable-api.md +++ b/docs/topics/browsable-api.md @@ -15,9 +15,23 @@ If you include fully-qualified URLs in your resource output, they will be 'urliz By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview]. +## Authentication + +To quickly add authentication to the browesable api, add a routes named `"login"` and `"logout"` under the namespace `"rest_framework"`. DRF provides default routes for this which you can add to your urlconf: + +```python +from django.urls import include, path + +urlpatterns = [ + # ... + path("api-auth/", include("rest_framework.urls", namespace="rest_framework")) +] +``` + + ## Customizing -The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.3.5), making it easy to customize the look-and-feel. +The browsable API is built with [Twitter's Bootstrap][bootstrap] (v 3.4.1), making it easy to customize the look-and-feel. To customize the default style, create a template called `rest_framework/api.html` that extends from `rest_framework/base.html`. For example: @@ -35,7 +49,7 @@ To replace the default theme, add a `bootstrap_theme` block to your `api.html` a {% endblock %} -Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. +Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. Make sure that the Bootstrap version of the new theme matches that of the default theme. You can also change the navbar variant, which by default is `navbar-inverse`, using the `bootstrap_navbar_variant` block. The empty `{% block bootstrap_navbar_variant %}{% endblock %}` will use the original Bootstrap navbar style. @@ -44,7 +58,7 @@ Full example: {% extends "rest_framework/base.html" %} {% block bootstrap_theme %} - + {% endblock %} {% block bootstrap_navbar_variant %}{% endblock %} @@ -65,6 +79,48 @@ For more specific CSS tweaks than simply overriding the default bootstrap theme --- +### Third party packages for customization + +You can use a third party package for customization, rather than doing it by yourself. Here is 3 packages for customizing the API: + +* [drf-restwind][drf-restwind] - a modern re-imagining of the Django REST Framework utilizes TailwindCSS and DaisyUI to provide flexible and customizable UI solutions with minimal coding effort. +* [drf-redesign][drf-redesign] - A package for customizing the API using Bootstrap 5. Modern and sleek design, it comes with the support for dark mode. +* [drf-material][drf-material] - Material design for Django REST Framework. + +--- + +![API Root][drf-rw-api-root] + +![List View][drf-rw-list-view] + +![Detail View][drf-rw-detail-view] + +*Screenshots of the drf-restwind* + +--- + +--- + +![API Root][drf-r-api-root] + +![List View][drf-r-list-view] + +![Detail View][drf-r-detail-view] + +*Screenshot of the drf-redesign* + +--- + +![API Root][drf-m-api-root] + +![List View][drf-m-api-root] + +![Detail View][drf-m-api-root] + +*Screenshot of the drf-material* + +--- + ### Blocks All of the blocks available in the browsable API base template that can be used in your `api.html`. @@ -162,3 +218,15 @@ There are [a variety of packages for autocomplete widgets][autocomplete-packages [bcomponentsnav]: https://getbootstrap.com/2.3.2/components.html#navbar [autocomplete-packages]: https://www.djangopackages.com/grids/g/auto-complete/ [django-autocomplete-light]: https://github.com/yourlabs/django-autocomplete-light +[drf-restwind]: https://github.com/youzarsiph/drf-restwind +[drf-rw-api-root]: ../img/drf-rw-api-root.png +[drf-rw-list-view]: ../img/drf-rw-list-view.png +[drf-rw-detail-view]: ../img/drf-rw-detail-view.png +[drf-redesign]: https://github.com/youzarsiph/drf-redesign +[drf-r-api-root]: ../img/drf-r-api-root.png +[drf-r-list-view]: ../img/drf-r-list-view.png +[drf-r-detail-view]: ../img/drf-r-detail-view.png +[drf-material]: https://github.com/youzarsiph/drf-material +[drf-m-api-root]: ../img/drf-m-api-root.png +[drf-m-list-view]: ../img/drf-m-list-view.png +[drf-m-detail-view]: ../img/drf-m-detail-view.png diff --git a/docs/topics/documenting-your-api.md b/docs/topics/documenting-your-api.md index 5eabeee7bb..edb989290d 100644 --- a/docs/topics/documenting-your-api.md +++ b/docs/topics/documenting-your-api.md @@ -4,12 +4,42 @@ > > — Roy Fielding, [REST APIs must be hypertext driven][cite] -REST framework provides built-in support for generating OpenAPI schemas, which -can be used with tools that allow you to build API documentation. +REST framework provides a range of different choices for documenting your API. The following +is a non-exhaustive list of the most popular ones. -There are also a number of great third-party documentation packages available. +## Third party packages for OpenAPI support -## Generating documentation from OpenAPI schemas +### drf-spectacular + +[drf-spectacular][drf-spectacular] is an [OpenAPI 3][open-api] schema generation library with explicit +focus on extensibility, customizability and client generation. It is the recommended way for +generating and presenting OpenAPI schemas. + +The library aims to extract as much schema information as possible, while providing decorators and extensions for easy +customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc], +i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters, +documentation and more. Several popular plugins for DRF are supported out-of-the-box as well. + +### drf-yasg + +[drf-yasg][drf-yasg] is a [Swagger / OpenAPI 2][swagger] generation tool implemented without using the schema generation provided +by Django Rest Framework. + +It aims to implement as much of the [OpenAPI 2][open-api] specification as possible - nested schemas, named models, +response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code +generation tools like `swagger-codegen`. + +This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`: + +![Screenshot - drf-yasg][image-drf-yasg] + +--- + +## Built-in OpenAPI schema generation (deprecated) + +**Deprecation notice: REST framework's built-in support for generating OpenAPI schemas is +deprecated in favor of 3rd party packages that can provide this functionality instead. +As replacement, we recommend using the [drf-spectacular](#drf-spectacular) package.** There are a number of packages available that allow you to generate HTML documentation pages from OpenAPI schemas. @@ -66,10 +96,14 @@ urlpatterns = [ # ... # Route TemplateView to serve Swagger UI template. # * Provide `extra_context` with view name of `SchemaView`. - path('swagger-ui/', TemplateView.as_view( - template_name='swagger-ui.html', - extra_context={'schema_url':'openapi-schema'} - ), name='swagger-ui'), + path( + "swagger-ui/", + TemplateView.as_view( + template_name="swagger-ui.html", + extra_context={"schema_url": "openapi-schema"}, + ), + name="swagger-ui", + ), ] ``` @@ -115,44 +149,18 @@ urlpatterns = [ # ... # Route TemplateView to serve the ReDoc template. # * Provide `extra_context` with view name of `SchemaView`. - path('redoc/', TemplateView.as_view( - template_name='redoc.html', - extra_context={'schema_url':'openapi-schema'} - ), name='redoc'), + path( + "redoc/", + TemplateView.as_view( + template_name="redoc.html", extra_context={"schema_url": "openapi-schema"} + ), + name="redoc", + ), ] ``` See the [ReDoc documentation][redoc] for advanced usage. -## Third party packages - -There are a number of mature third-party packages for providing API documentation. - -#### drf-yasg - Yet Another Swagger Generator - -[drf-yasg][drf-yasg] is a [Swagger][swagger] generation tool implemented without using the schema generation provided -by Django Rest Framework. - -It aims to implement as much of the [OpenAPI][open-api] specification as possible - nested schemas, named models, -response bodies, enum/pattern/min/max validators, form parameters, etc. - and to generate documents usable with code -generation tools like `swagger-codegen`. - -This also translates into a very useful interactive documentation viewer in the form of `swagger-ui`: - - -![Screenshot - drf-yasg][image-drf-yasg] - -#### drf-spectacular - Sane and flexible OpenAPI 3.0 schema generation for Django REST framework - -[drf-spectacular][drf-spectacular] is a [OpenAPI 3][open-api] schema generation tool with explicit focus on extensibility, -customizability and client generation. Usage patterns are very similar to [drf-yasg][drf-yasg]. - -It aims to extract as much schema information as possible, while providing decorators and extensions for easy -customization. There is explicit support for [swagger-codegen][swagger], [SwaggerUI][swagger-ui] and [Redoc][redoc], -i18n, versioning, authentication, polymorphism (dynamic requests and responses), query/path/header parameters, -documentation and more. Several popular plugins for DRF are supported out-of-the-box as well. - ---- ## Self describing APIs diff --git a/docs/topics/html-and-forms.md b/docs/topics/html-and-forms.md index 18774926b5..c7e51c1526 100644 --- a/docs/topics/html-and-forms.md +++ b/docs/topics/html-and-forms.md @@ -1,220 +1,220 @@ -# HTML & Forms - -REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates. - -## Rendering HTML - -In order to return HTML responses you'll need to use either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`. - -The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response. - -The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content. - -Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views. - -Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template: - -**views.py**: - - from my_project.example.models import Profile - from rest_framework.renderers import TemplateHTMLRenderer - from rest_framework.response import Response - from rest_framework.views import APIView - - - class ProfileList(APIView): - renderer_classes = [TemplateHTMLRenderer] - template_name = 'profile_list.html' - - def get(self, request): - queryset = Profile.objects.all() - return Response({'profiles': queryset}) - -**profile_list.html**: - - -

    Profiles

    -
      - {% for profile in profiles %} -
    • {{ profile.name }}
    • - {% endfor %} -
    - - -## Rendering Forms - -Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template. - -The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance: - -**views.py**: - - from django.shortcuts import get_object_or_404 - from my_project.example.models import Profile - from rest_framework.renderers import TemplateHTMLRenderer - from rest_framework.views import APIView - - - class ProfileDetail(APIView): - renderer_classes = [TemplateHTMLRenderer] - template_name = 'profile_detail.html' - - def get(self, request, pk): - profile = get_object_or_404(Profile, pk=pk) - serializer = ProfileSerializer(profile) - return Response({'serializer': serializer, 'profile': profile}) - - def post(self, request, pk): - profile = get_object_or_404(Profile, pk=pk) - serializer = ProfileSerializer(profile, data=request.data) - if not serializer.is_valid(): - return Response({'serializer': serializer, 'profile': profile}) - serializer.save() - return redirect('profile-list') - -**profile_detail.html**: - - {% load rest_framework %} - - - -

    Profile - {{ profile.name }}

    - -
    - {% csrf_token %} - {% render_form serializer %} - -
    - - - -### Using template packs - -The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields. - -REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS. - -The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS: - - - … - - - -Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates. - -Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form. - - class LoginSerializer(serializers.Serializer): - email = serializers.EmailField( - max_length=100, - style={'placeholder': 'Email', 'autofocus': True} - ) - password = serializers.CharField( - max_length=100, - style={'input_type': 'password', 'placeholder': 'Password'} - ) - remember_me = serializers.BooleanField() - ---- - -#### `rest_framework/vertical` - -Presents form labels above their corresponding control inputs, using the standard Bootstrap layout. - -*This is the default template pack.* - - {% load rest_framework %} - - ... - -
    - {% csrf_token %} - {% render_form serializer template_pack='rest_framework/vertical' %} - -
    - -![Vertical form example](../img/vertical.png) - ---- - -#### `rest_framework/horizontal` - -Presents labels and controls alongside each other, using a 2/10 column split. - -*This is the form style used in the browsable API and admin renderers.* - - {% load rest_framework %} - - ... - -
    - {% csrf_token %} - {% render_form serializer %} -
    -
    - -
    -
    -
    - -![Horizontal form example](../img/horizontal.png) - ---- - -#### `rest_framework/inline` - -A compact form style that presents all the controls inline. - - {% load rest_framework %} - - ... - -
    - {% csrf_token %} - {% render_form serializer template_pack='rest_framework/inline' %} - -
    - -![Inline form example](../img/inline.png) - -## Field styles - -Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used. - -The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use. - -For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this: - - details = serializers.CharField( - max_length=1000, - style={'base_template': 'textarea.html'} - ) - -If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name: - - details = serializers.CharField( - max_length=1000, - style={'template': 'my-field-templates/custom-input.html'} - ) - -Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control. - - details = serializers.CharField( - max_length=1000, - style={'base_template': 'textarea.html', 'rows': 10} - ) - -The complete list of `base_template` options and their associated style options is listed below. - -base_template | Valid field types | Additional style options -----|----|---- -input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus -textarea.html | `CharField` | rows, placeholder, hide_label -select.html | `ChoiceField` or relational field types | hide_label -radio.html | `ChoiceField` or relational field types | inline, hide_label -select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label -checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label -checkbox.html | `BooleanField` | hide_label -fieldset.html | Nested serializer | hide_label -list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label +# HTML & Forms + +REST framework is suitable for returning both API style responses, and regular HTML pages. Additionally, serializers can be used as HTML forms and rendered in templates. + +## Rendering HTML + +In order to return HTML responses you'll need to use either `TemplateHTMLRenderer`, or `StaticHTMLRenderer`. + +The `TemplateHTMLRenderer` class expects the response to contain a dictionary of context data, and renders an HTML page based on a template that must be specified either in the view or on the response. + +The `StaticHTMLRender` class expects the response to contain a string of the pre-rendered HTML content. + +Because static HTML pages typically have different behavior from API responses you'll probably need to write any HTML views explicitly, rather than relying on the built-in generic views. + +Here's an example of a view that returns a list of "Profile" instances, rendered in an HTML template: + +**views.py**: + + from my_project.example.models import Profile + from rest_framework.renderers import TemplateHTMLRenderer + from rest_framework.response import Response + from rest_framework.views import APIView + + + class ProfileList(APIView): + renderer_classes = [TemplateHTMLRenderer] + template_name = 'profile_list.html' + + def get(self, request): + queryset = Profile.objects.all() + return Response({'profiles': queryset}) + +**profile_list.html**: + + +

    Profiles

    +
      + {% for profile in profiles %} +
    • {{ profile.name }}
    • + {% endfor %} +
    + + +## Rendering Forms + +Serializers may be rendered as forms by using the `render_form` template tag, and including the serializer instance as context to the template. + +The following view demonstrates an example of using a serializer in a template for viewing and updating a model instance: + +**views.py**: + + from django.shortcuts import get_object_or_404 + from my_project.example.models import Profile + from rest_framework.renderers import TemplateHTMLRenderer + from rest_framework.views import APIView + + + class ProfileDetail(APIView): + renderer_classes = [TemplateHTMLRenderer] + template_name = 'profile_detail.html' + + def get(self, request, pk): + profile = get_object_or_404(Profile, pk=pk) + serializer = ProfileSerializer(profile) + return Response({'serializer': serializer, 'profile': profile}) + + def post(self, request, pk): + profile = get_object_or_404(Profile, pk=pk) + serializer = ProfileSerializer(profile, data=request.data) + if not serializer.is_valid(): + return Response({'serializer': serializer, 'profile': profile}) + serializer.save() + return redirect('profile-list') + +**profile_detail.html**: + + {% load rest_framework %} + + + +

    Profile - {{ profile.name }}

    + +
    + {% csrf_token %} + {% render_form serializer %} + +
    + + + +### Using template packs + +The `render_form` tag takes an optional `template_pack` argument, that specifies which template directory should be used for rendering the form and form fields. + +REST framework includes three built-in template packs, all based on Bootstrap 3. The built-in styles are `horizontal`, `vertical`, and `inline`. The default style is `horizontal`. To use any of these template packs you'll want to also include the Bootstrap 3 CSS. + +The following HTML will link to a CDN hosted version of the Bootstrap 3 CSS: + + + … + + + +Third party packages may include alternate template packs, by bundling a template directory containing the necessary form and field templates. + +Let's take a look at how to render each of the three available template packs. For these examples we'll use a single serializer class to present a "Login" form. + + class LoginSerializer(serializers.Serializer): + email = serializers.EmailField( + max_length=100, + style={'placeholder': 'Email', 'autofocus': True} + ) + password = serializers.CharField( + max_length=100, + style={'input_type': 'password', 'placeholder': 'Password'} + ) + remember_me = serializers.BooleanField() + +--- + +#### `rest_framework/vertical` + +Presents form labels above their corresponding control inputs, using the standard Bootstrap layout. + +*This is the default template pack.* + + {% load rest_framework %} + + ... + +
    + {% csrf_token %} + {% render_form serializer template_pack='rest_framework/vertical' %} + +
    + +![Vertical form example](../img/vertical.png) + +--- + +#### `rest_framework/horizontal` + +Presents labels and controls alongside each other, using a 2/10 column split. + +*This is the form style used in the browsable API and admin renderers.* + + {% load rest_framework %} + + ... + +
    + {% csrf_token %} + {% render_form serializer %} +
    +
    + +
    +
    +
    + +![Horizontal form example](../img/horizontal.png) + +--- + +#### `rest_framework/inline` + +A compact form style that presents all the controls inline. + + {% load rest_framework %} + + ... + +
    + {% csrf_token %} + {% render_form serializer template_pack='rest_framework/inline' %} + +
    + +![Inline form example](../img/inline.png) + +## Field styles + +Serializer fields can have their rendering style customized by using the `style` keyword argument. This argument is a dictionary of options that control the template and layout used. + +The most common way to customize the field style is to use the `base_template` style keyword argument to select which template in the template pack should be use. + +For example, to render a `CharField` as an HTML textarea rather than the default HTML input, you would use something like this: + + details = serializers.CharField( + max_length=1000, + style={'base_template': 'textarea.html'} + ) + +If you instead want a field to be rendered using a custom template that is *not part of an included template pack*, you can instead use the `template` style option, to fully specify a template name: + + details = serializers.CharField( + max_length=1000, + style={'template': 'my-field-templates/custom-input.html'} + ) + +Field templates can also use additional style properties, depending on their type. For example, the `textarea.html` template also accepts a `rows` property that can be used to affect the sizing of the control. + + details = serializers.CharField( + max_length=1000, + style={'base_template': 'textarea.html', 'rows': 10} + ) + +The complete list of `base_template` options and their associated style options is listed below. + +base_template | Valid field types | Additional style options +-----------------------|-------------------------------------------------------------|----------------------------------------------- +input.html | Any string, numeric or date/time field | input_type, placeholder, hide_label, autofocus +textarea.html | `CharField` | rows, placeholder, hide_label +select.html | `ChoiceField` or relational field types | hide_label +radio.html | `ChoiceField` or relational field types | inline, hide_label +select_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | hide_label +checkbox_multiple.html | `MultipleChoiceField` or relational fields with `many=True` | inline, hide_label +checkbox.html | `BooleanField` | hide_label +fieldset.html | Nested serializer | hide_label +list_fieldset.html | `ListField` or nested serializer with `many=True` | hide_label diff --git a/docs/topics/internationalization.md b/docs/topics/internationalization.md index 267ccdb377..2f8f2abf09 100644 --- a/docs/topics/internationalization.md +++ b/docs/topics/internationalization.md @@ -105,7 +105,7 @@ For API clients the most appropriate of these will typically be to use the `Acce [cite]: https://youtu.be/Wa0VfS2q94Y [django-translation]: https://docs.djangoproject.com/en/stable/topics/i18n/translation [custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling -[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/ +[transifex-project]: https://explore.transifex.com/django-rest-framework-1/django-rest-framework/ [django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po [django-language-preference]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#how-django-discovers-language-preference [django-locale-paths]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LOCALE_PATHS diff --git a/docs/topics/rest-hypermedia-hateoas.md b/docs/topics/rest-hypermedia-hateoas.md index a11bd6cc72..3498bddd1c 100644 --- a/docs/topics/rest-hypermedia-hateoas.md +++ b/docs/topics/rest-hypermedia-hateoas.md @@ -4,7 +4,7 @@ > > — Mike Amundsen, [REST fest 2012 keynote][cite]. -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". +First off, the disclaimer. The name "Django REST framework" was decided back in early 2011 and was chosen simply to ensure 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 API, you should look to resources outside of this documentation to help inform your design choices. diff --git a/docs/tutorial/1-serialization.md b/docs/tutorial/1-serialization.md index 67746c517e..b9bf67acbb 100644 --- a/docs/tutorial/1-serialization.md +++ b/docs/tutorial/1-serialization.md @@ -8,7 +8,7 @@ The tutorial is fairly in-depth, so you should probably get a cookie and a cup o --- -**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. The completed implementation is also online as a sandbox version for testing, [available here][sandbox]. +**Note**: The code for this tutorial is available in the [encode/rest-framework-tutorial][repo] repository on GitHub. Feel free to clone the repository and see the code in action. --- @@ -150,7 +150,7 @@ At this point we've translated the model instance into Python native datatypes. content = JSONRenderer().render(serializer.data) content - # b'{"id": 2, "title": "", "code": "print(\\"hello, world\\")\\n", "linenos": false, "language": "python", "style": "friendly"}' + # b'{"id":2,"title":"","code":"print(\\"hello, world\\")\\n","linenos":false,"language":"python","style":"friendly"}' Deserialization is similar. First we parse a stream into Python native datatypes... @@ -165,7 +165,7 @@ Deserialization is similar. First we parse a stream into Python native datatype serializer.is_valid() # True serializer.validated_data - # OrderedDict([('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]) + # {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'} serializer.save() # @@ -175,11 +175,11 @@ We can also serialize querysets instead of model instances. To do so we simply serializer = SnippetSerializer(Snippet.objects.all(), many=True) serializer.data - # [OrderedDict([('id', 1), ('title', ''), ('code', 'foo = "bar"\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 2), ('title', ''), ('code', 'print("hello, world")\n'), ('linenos', False), ('language', 'python'), ('style', 'friendly')]), OrderedDict([('id', 3), ('title', ''), ('code', 'print("hello, world")'), ('linenos', False), ('language', 'python'), ('style', 'friendly')])] + # [{'id': 1, 'title': '', 'code': 'foo = "bar"\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'}, {'id': 3, 'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'}] ## Using ModelSerializers -Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise. +Our `SnippetSerializer` class is replicating a lot of information that's also contained in the `Snippet` model. It would be nice if we could keep our code a bit more concise. In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes. @@ -307,7 +307,7 @@ Quit out of the shell... Validating models... 0 errors found - Django version 4.0,1 using settings 'tutorial.settings' + Django version 5.0, using settings 'tutorial.settings' Starting Development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. @@ -321,42 +321,50 @@ You can install httpie using pip: Finally, we can get a list of all of the snippets: - http http://127.0.0.1:8000/snippets/ + http GET http://127.0.0.1:8000/snippets/ --unsorted HTTP/1.1 200 OK ... [ - { - "id": 1, - "title": "", - "code": "foo = \"bar\"\n", - "linenos": false, - "language": "python", - "style": "friendly" - }, - { - "id": 2, - "title": "", - "code": "print(\"hello, world\")\n", - "linenos": false, - "language": "python", - "style": "friendly" - } + { + "id": 1, + "title": "", + "code": "foo = \"bar\"\n", + "linenos": false, + "language": "python", + "style": "friendly" + }, + { + "id": 2, + "title": "", + "code": "print(\"hello, world\")\n", + "linenos": false, + "language": "python", + "style": "friendly" + }, + { + "id": 3, + "title": "", + "code": "print(\"hello, world\")", + "linenos": false, + "language": "python", + "style": "friendly" + } ] Or we can get a particular snippet by referencing its id: - http http://127.0.0.1:8000/snippets/2/ + http GET http://127.0.0.1:8000/snippets/2/ --unsorted HTTP/1.1 200 OK ... { - "id": 2, - "title": "", - "code": "print(\"hello, world\")\n", - "linenos": false, - "language": "python", - "style": "friendly" + "id": 2, + "title": "", + "code": "print(\"hello, world\")\n", + "linenos": false, + "language": "python", + "style": "friendly" } Similarly, you can have the same json displayed by visiting these URLs in a web browser. @@ -371,7 +379,6 @@ We'll see how we can start to improve things in [part 2 of the tutorial][tut-2]. [quickstart]: quickstart.md [repo]: https://github.com/encode/rest-framework-tutorial -[sandbox]: https://restframework.herokuapp.com/ [venv]: https://docs.python.org/3/library/venv.html [tut-2]: 2-requests-and-responses.md [httpie]: https://github.com/httpie/httpie#installation diff --git a/docs/tutorial/2-requests-and-responses.md b/docs/tutorial/2-requests-and-responses.md index 1d272f3040..47c7facfc6 100644 --- a/docs/tutorial/2-requests-and-responses.md +++ b/docs/tutorial/2-requests-and-responses.md @@ -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` exceptions that occur when accessing `request.data` with malformed input. +The wrappers also provide behavior such as returning `405 Method Not Allowed` responses when appropriate, and handling any `ParseError` exceptions that occur when accessing `request.data` with malformed input. ## Pulling it all together diff --git a/docs/tutorial/3-class-based-views.md b/docs/tutorial/3-class-based-views.md index e02feaa5ea..ccfcd095da 100644 --- a/docs/tutorial/3-class-based-views.md +++ b/docs/tutorial/3-class-based-views.md @@ -79,9 +79,9 @@ Okay, we're done. If you run the development server everything should be workin ## Using mixins -One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behaviour. +One of the big wins of using class-based views is that it allows us to easily compose reusable bits of behavior. -The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behaviour are implemented in REST framework's mixin classes. +The create/retrieve/update/delete operations that we've been using so far are going to be pretty similar for any model-backed API views we create. Those bits of common behavior are implemented in REST framework's mixin classes. Let's take a look at how we can compose the views by using the mixin classes. Here's our `views.py` module again. diff --git a/docs/tutorial/6-viewsets-and-routers.md b/docs/tutorial/6-viewsets-and-routers.md index e12becbd06..6fa2111e7b 100644 --- a/docs/tutorial/6-viewsets-and-routers.md +++ b/docs/tutorial/6-viewsets-and-routers.md @@ -10,10 +10,11 @@ A `ViewSet` class is only bound to a set of method handlers at the last moment, Let's take our current set of views, and refactor them into view sets. -First of all let's refactor our `UserList` and `UserDetail` views into a single `UserViewSet`. We can remove the two views, and replace them with a single class: +First of all let's refactor our `UserList` and `UserDetail` classes into a single `UserViewSet` class. In the `snippets/views.py` file, we can remove the two view classes and replace them with a single ViewSet class: from rest_framework import viewsets + class UserViewSet(viewsets.ReadOnlyModelViewSet): """ This viewset automatically provides `list` and `retrieve` actions. @@ -25,13 +26,15 @@ Here we've used the `ReadOnlyModelViewSet` class to automatically provide the de Next we're going to replace the `SnippetList`, `SnippetDetail` and `SnippetHighlight` view classes. We can remove the three views, and again replace them with a single class. + from rest_framework import permissions + from rest_framework import renderers from rest_framework.decorators import action from rest_framework.response import Response - from rest_framework import permissions + class SnippetViewSet(viewsets.ModelViewSet): """ - This viewset automatically provides `list`, `create`, `retrieve`, + This ViewSet automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. @@ -64,9 +67,10 @@ To see what's going on under the hood let's first explicitly create a set of vie In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views. - from snippets.views import SnippetViewSet, UserViewSet, api_root from rest_framework import renderers + from snippets.views import api_root, SnippetViewSet, UserViewSet + snippet_list = SnippetViewSet.as_view({ 'get': 'list', 'post': 'create' @@ -87,7 +91,7 @@ In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concr 'get': 'retrieve' }) -Notice how we're creating multiple views from each `ViewSet` class, by binding the http methods to the required action for each view. +Notice how we're creating multiple views from each `ViewSet` class, by binding the HTTP methods to the required action for each view. Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual. @@ -108,24 +112,25 @@ Here's our re-wired `snippets/urls.py` file. from django.urls import path, include from rest_framework.routers import DefaultRouter + from snippets import views - # Create a router and register our viewsets with it. + # Create a router and register our ViewSets with it. router = DefaultRouter() - router.register(r'snippets', views.SnippetViewSet,basename="snippet") - router.register(r'users', views.UserViewSet,basename="user") + router.register(r'snippets', views.SnippetViewSet, basename='snippet') + router.register(r'users', views.UserViewSet, basename='user') # The API URLs are now determined automatically by the router. urlpatterns = [ path('', include(router.urls)), ] -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. +Registering the ViewSets with the router is similar to providing a urlpattern. We include two arguments - the URL prefix for the views, and the view set itself. -The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` method from our `views` module. +The `DefaultRouter` class we're using also automatically creates the API root view for us, so we can now delete the `api_root` function from our `views` module. -## Trade-offs between views vs viewsets +## Trade-offs between views vs ViewSets -Using viewsets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf. +Using ViewSets can be a really useful abstraction. It helps ensure that URL conventions will be consistent across your API, minimizes the amount of code you need to write, and allows you to concentrate on the interactions and representations your API provides rather than the specifics of the URL conf. -That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function based views. Using viewsets is less explicit than building your views individually. +That doesn't mean it's always the right approach to take. There's a similar set of trade-offs to consider as when using class-based views instead of function-based views. Using ViewSets is less explicit than building your API views individually. diff --git a/docs/tutorial/quickstart.md b/docs/tutorial/quickstart.md index 4fa2fbbe52..a140dbce0a 100644 --- a/docs/tutorial/quickstart.md +++ b/docs/tutorial/quickstart.md @@ -15,7 +15,6 @@ Create a new Django project named `tutorial`, then start a new app called `quick source env/bin/activate # On Windows use `env\Scripts\activate` # Install Django and Django REST framework into the virtual environment - pip install django pip install djangorestframework # Set up a new project with a single application @@ -30,22 +29,24 @@ The project layout should look like: /tutorial $ find . . - ./manage.py ./tutorial + ./tutorial/asgi.py ./tutorial/__init__.py ./tutorial/quickstart - ./tutorial/quickstart/__init__.py - ./tutorial/quickstart/admin.py - ./tutorial/quickstart/apps.py ./tutorial/quickstart/migrations ./tutorial/quickstart/migrations/__init__.py ./tutorial/quickstart/models.py + ./tutorial/quickstart/__init__.py + ./tutorial/quickstart/apps.py + ./tutorial/quickstart/admin.py ./tutorial/quickstart/tests.py ./tutorial/quickstart/views.py - ./tutorial/asgi.py ./tutorial/settings.py ./tutorial/urls.py ./tutorial/wsgi.py + ./env + ./env/... + ./manage.py It may look unusual that the application has been created within the project directory. Using the project's namespace avoids name clashes with external modules (a topic that goes outside the scope of the quickstart). @@ -53,9 +54,9 @@ Now sync your database for the first time: python manage.py migrate -We'll also create an initial user named `admin` with a password of `password123`. We'll authenticate as that user later in our example. +We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example. - python manage.py createsuperuser --email admin@example.com --username admin + python manage.py createsuperuser --username admin --email admin@example.com Once you've set up a database and the initial user is created and ready to go, open up the app's directory and we'll get coding... @@ -63,7 +64,7 @@ Once you've set up a database and the initial user is created and ready to go, o First up we're going to define some serializers. Let's create a new module named `tutorial/quickstart/serializers.py` that we'll use for our data representations. - from django.contrib.auth.models import User, Group + from django.contrib.auth.models import Group, User from rest_framework import serializers @@ -84,10 +85,10 @@ Notice that we're using hyperlinked relations in this case with `HyperlinkedMode Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing. - from django.contrib.auth.models import User, Group - from rest_framework import viewsets - from rest_framework import permissions - from tutorial.quickstart.serializers import UserSerializer, GroupSerializer + from django.contrib.auth.models import Group, User + from rest_framework import permissions, viewsets + + from tutorial.quickstart.serializers import GroupSerializer, UserSerializer class UserViewSet(viewsets.ModelViewSet): @@ -103,7 +104,7 @@ Right, we'd better write some views then. Open `tutorial/quickstart/views.py` a """ API endpoint that allows groups to be viewed or edited. """ - queryset = Group.objects.all() + queryset = Group.objects.all().order_by('name') serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] @@ -117,6 +118,7 @@ Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... from django.urls import include, path from rest_framework import routers + from tutorial.quickstart import views router = routers.DefaultRouter() @@ -165,38 +167,39 @@ We're now ready to test the API we've built. Let's fire up the server from the We can now access our API, both from the command-line, using tools like `curl`... - bash: curl -H 'Accept: application/json; indent=4' -u admin:password123 http://127.0.0.1:8000/users/ + bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/ + Enter host password for user 'admin': { - "count": 2, + "count": 1, "next": null, "previous": null, "results": [ { - "email": "admin@example.com", - "groups": [], "url": "http://127.0.0.1:8000/users/1/", - "username": "admin" - }, + "username": "admin", + "email": "admin@example.com", + "groups": [] + } ] } Or using the [httpie][httpie], command line tool... - bash: http -a admin:password123 http://127.0.0.1:8000/users/ - - HTTP/1.1 200 OK + bash: http -a admin http://127.0.0.1:8000/users/ + http: password for admin@127.0.0.1:8000:: + $HTTP/1.1 200 OK ... { - "count": 2, + "count": 1, "next": null, "previous": null, "results": [ { "email": "admin@example.com", "groups": [], - "url": "http://localhost:8000/users/1/", - "username": "paul" - }, + "url": "http://127.0.0.1:8000/users/1/", + "username": "admin" + } ] } diff --git a/docs_theme/css/default.css b/docs_theme/css/default.css index 7006f2a668..dfde262933 100644 --- a/docs_theme/css/default.css +++ b/docs_theme/css/default.css @@ -439,3 +439,17 @@ ul.sponsor { display: inline-block !important; } +/* admonition */ +.admonition { + border: .075rem solid #448aff; + border-radius: .2rem; + margin: 1.5625em 0; + padding: 0 .6rem; +} +.admonition-title { + background: #448aff1a; + font-weight: 700; + margin: 0 -.6rem 1em; + padding: 0.4rem 0.6rem; +} + diff --git a/mkdocs.yml b/mkdocs.yml index c58e083183..010aaefe23 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -9,6 +9,7 @@ theme: custom_dir: docs_theme markdown_extensions: + - admonition - toc: anchorlink: True @@ -53,7 +54,6 @@ nav: - 'Settings': 'api-guide/settings.md' - Topics: - 'Documenting your API': 'topics/documenting-your-api.md' - - 'API Clients': 'topics/api-clients.md' - 'Internationalization': 'topics/internationalization.md' - 'AJAX, CSRF & CORS': 'topics/ajax-csrf-cors.md' - 'HTML & Forms': 'topics/html-and-forms.md' @@ -66,6 +66,8 @@ nav: - 'Contributing to REST framework': 'community/contributing.md' - 'Project management': 'community/project-management.md' - 'Release Notes': 'community/release-notes.md' + - '3.16 Announcement': 'community/3.16-announcement.md' + - '3.15 Announcement': 'community/3.15-announcement.md' - '3.14 Announcement': 'community/3.14-announcement.md' - '3.13 Announcement': 'community/3.13-announcement.md' - '3.12 Announcement': 'community/3.12-announcement.md' diff --git a/requirements.txt b/requirements.txt index 395f3b7a86..c3a1f1187c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ # The base set of requirements for REST framework is actually -# just Django, but for the purposes of development and testing -# there are a number of packages that are useful to install. +# just Django and pytz, but for the purposes of development +# and testing there are a number of packages that are useful +# to install. # Laying these out as separate requirements files, allows us to # only included the relevant sets when running tox, and ensures diff --git a/requirements/requirements-documentation.txt b/requirements/requirements-documentation.txt index cf2dc26e88..2cf936ef38 100644 --- a/requirements/requirements-documentation.txt +++ b/requirements/requirements-documentation.txt @@ -1,3 +1,5 @@ # MkDocs to build our documentation. -mkdocs>=1.1.2,<1.2 -jinja2>=2.10,<3.1.0 # contextfilter has been renamed +mkdocs==1.6.0 + +# pylinkvalidator to check for broken links in documentation. +pylinkvalidator==0.3 diff --git a/requirements/requirements-optionals.txt b/requirements/requirements-optionals.txt index f3bb9b709d..bac597c953 100644 --- a/requirements/requirements-optionals.txt +++ b/requirements/requirements-optionals.txt @@ -1,9 +1,10 @@ # Optional packages which may be used with REST framework. coreapi==2.3.1 coreschema==0.0.4 -django-filter>=2.4.0,<3.0 +django-filter django-guardian>=2.4.0,<2.5 -markdown==3.3 -psycopg2-binary>=2.8.5,<2.9 -pygments==2.12 +inflection==0.5.1 +markdown>=3.3.7 +psycopg2-binary>=2.9.5,<2.10 +pygments~=2.17.0 pyyaml>=5.3.1,<5.4 diff --git a/requirements/requirements-packaging.txt b/requirements/requirements-packaging.txt index fae03baab5..81f22a35a1 100644 --- a/requirements/requirements-packaging.txt +++ b/requirements/requirements-packaging.txt @@ -1,8 +1,8 @@ # Wheel for PyPI installs. -wheel>=0.35.1,<0.36 +wheel>=0.36.2,<0.40.0 # Twine for secured PyPI uploads. -twine>=3.2.0,<3.3 +twine>=3.4.2,<4.0.2 # Transifex client for managing translation resources. -transifex-client>=0.13.12,<0.14 +transifex-client diff --git a/requirements/requirements-testing.txt b/requirements/requirements-testing.txt index 313fdedc9b..2b39316a00 100644 --- a/requirements/requirements-testing.txt +++ b/requirements/requirements-testing.txt @@ -1,4 +1,7 @@ # Pytest for running the tests. -pytest>=6.1,<7.0 -pytest-cov>=2.10.1,<3.0 -pytest-django>=4.1.0,<5.0 +pytest>=7.0.1,<8.0 +pytest-cov>=4.0.0,<5.0 +pytest-django>=4.5.2,<5.0 +importlib-metadata<5.0 +# temporary pin of attrs +attrs==22.1.0 diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index d53b2cb4de..692ce9cb17 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -7,13 +7,11 @@ \_| \_\____/\____/ \_/ |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_| """ -import django - __title__ = 'Django REST framework' -__version__ = '3.14.0' +__version__ = '3.16.0' __author__ = 'Tom Christie' __license__ = 'BSD 3-Clause' -__copyright__ = 'Copyright 2011-2019 Encode OSS Ltd' +__copyright__ = 'Copyright 2011-2023 Encode OSS Ltd' # Version synonym VERSION = __version__ @@ -25,9 +23,5 @@ ISO_8601 = 'iso-8601' -if django.VERSION < (3, 2): - default_app_config = 'rest_framework.apps.RestFrameworkConfig' - - -class RemovedInDRF315Warning(PendingDeprecationWarning): +class RemovedInDRF317Warning(PendingDeprecationWarning): pass diff --git a/rest_framework/authentication.py b/rest_framework/authentication.py index 382abf1580..3f3bd2227c 100644 --- a/rest_framework/authentication.py +++ b/rest_framework/authentication.py @@ -78,12 +78,12 @@ def authenticate(self, request): auth_decoded = base64.b64decode(auth[1]).decode('utf-8') except UnicodeDecodeError: auth_decoded = base64.b64decode(auth[1]).decode('latin-1') - auth_parts = auth_decoded.partition(':') - except (TypeError, UnicodeDecodeError, binascii.Error): + + userid, password = auth_decoded.split(':', 1) + except (TypeError, ValueError, UnicodeDecodeError, binascii.Error): msg = _('Invalid basic header. Credentials not correctly base64 encoded.') raise exceptions.AuthenticationFailed(msg) - userid, password = auth_parts[0], auth_parts[2] return self.authenticate_credentials(userid, password, request) def authenticate_credentials(self, userid, password, request=None): diff --git a/rest_framework/authtoken/__init__.py b/rest_framework/authtoken/__init__.py index 285fe15c6b..e69de29bb2 100644 --- a/rest_framework/authtoken/__init__.py +++ b/rest_framework/authtoken/__init__.py @@ -1,4 +0,0 @@ -import django - -if django.VERSION < (3, 2): - default_app_config = 'rest_framework.authtoken.apps.AuthTokenConfig' diff --git a/rest_framework/authtoken/admin.py b/rest_framework/authtoken/admin.py index b359e4cfe8..eabb8fca8b 100644 --- a/rest_framework/authtoken/admin.py +++ b/rest_framework/authtoken/admin.py @@ -4,6 +4,7 @@ from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.urls import reverse +from django.utils.translation import gettext_lazy as _ from rest_framework.authtoken.models import Token, TokenProxy @@ -23,6 +24,8 @@ def url_for_result(self, result): class TokenAdmin(admin.ModelAdmin): list_display = ('key', 'user', 'created') fields = ('user',) + search_fields = ('user__username',) + search_help_text = _('Username') ordering = ('-created',) actions = None # Actions not compatible with mapped IDs. diff --git a/rest_framework/authtoken/management/commands/drf_create_token.py b/rest_framework/authtoken/management/commands/drf_create_token.py index 3d65392442..3f4521fe42 100644 --- a/rest_framework/authtoken/management/commands/drf_create_token.py +++ b/rest_framework/authtoken/management/commands/drf_create_token.py @@ -42,4 +42,4 @@ def handle(self, *args, **options): username) ) self.stdout.write( - 'Generated token {} for user {}'.format(token.key, username)) + f'Generated token {token.key} for user {username}') diff --git a/rest_framework/authtoken/migrations/0004_alter_tokenproxy_options.py b/rest_framework/authtoken/migrations/0004_alter_tokenproxy_options.py new file mode 100644 index 0000000000..0ca9f5d796 --- /dev/null +++ b/rest_framework/authtoken/migrations/0004_alter_tokenproxy_options.py @@ -0,0 +1,17 @@ +# Generated by Django 4.1.3 on 2022-11-24 21:07 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('authtoken', '0003_tokenproxy'), + ] + + operations = [ + migrations.AlterModelOptions( + name='tokenproxy', + options={'verbose_name': 'Token', 'verbose_name_plural': 'Tokens'}, + ), + ] diff --git a/rest_framework/authtoken/models.py b/rest_framework/authtoken/models.py index 5a143d936c..6a17c24525 100644 --- a/rest_framework/authtoken/models.py +++ b/rest_framework/authtoken/models.py @@ -51,4 +51,5 @@ def pk(self): class Meta: proxy = 'rest_framework.authtoken' in settings.INSTALLED_APPS abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS - verbose_name = "token" + verbose_name = _("Token") + verbose_name_plural = _("Tokens") diff --git a/rest_framework/compat.py b/rest_framework/compat.py index ac5cbc572a..ff21bacff4 100644 --- a/rest_framework/compat.py +++ b/rest_framework/compat.py @@ -3,7 +3,9 @@ versions of Django/Python, and compatibility wrappers around optional packages. """ import django -from django.conf import settings +from django.db import models +from django.db.models.constants import LOOKUP_SEP +from django.db.models.sql.query import Node from django.views.generic import View @@ -14,13 +16,6 @@ def unicode_http_header(value): return value -def distinct(queryset, base): - if settings.DATABASES[queryset.db]["ENGINE"] == "django.db.backends.oracle": - # distinct analogue for Oracle users - return base.filter(pk__in=set(queryset.values_list('pk', flat=True))) - return queryset.distinct() - - # django.contrib.postgres requires psycopg2 try: from django.contrib.postgres import fields as postgres_fields @@ -54,6 +49,12 @@ def distinct(queryset, base): except ImportError: yaml = None +# inflection is optional +try: + import inflection +except ImportError: + inflection = None + # requests is optional try: @@ -153,27 +154,51 @@ def md_filter_add_syntax_highlight(md): return False -if django.VERSION >= (4, 2): - # Django 4.2+: use the stock parse_header_parameters function - # Note: Django 4.1 also has an implementation of parse_header_parameters - # which is slightly different from the one in 4.2, it needs - # the compatibility shim as well. - from django.utils.http import parse_header_parameters +if django.VERSION >= (5, 1): + # Django 5.1+: use the stock ip_address_validators function + # Note: Before Django 5.1, ip_address_validators returns a tuple containing + # 1) the list of validators and 2) the error message. Starting from + # Django 5.1 ip_address_validators only returns the list of validators + from django.core.validators import ip_address_validators + + def get_referenced_base_fields_from_q(q): + return q.referenced_base_fields + else: - # Django <= 4.1: create a compatibility shim for parse_header_parameters - from django.http.multipartparser import parse_header - - def parse_header_parameters(line): - # parse_header works with bytes, but parse_header_parameters - # works with strings. Call encode to convert the line to bytes. - main_value_pair, params = parse_header(line.encode()) - return main_value_pair, { - # parse_header will convert *some* values to string. - # parse_header_parameters converts *all* values to string. - # Make sure all values are converted by calling decode on - # any remaining non-string values. - k: v if isinstance(v, str) else v.decode() - for k, v in params.items() + # Django <= 5.1: create a compatibility shim for ip_address_validators + from django.core.validators import \ + ip_address_validators as _ip_address_validators + + def ip_address_validators(protocol, unpack_ipv4): + return _ip_address_validators(protocol, unpack_ipv4)[0] + + # Django < 5.1: create a compatibility shim for Q.referenced_base_fields + # https://github.com/django/django/blob/5.1a1/django/db/models/query_utils.py#L179 + def _get_paths_from_expression(expr): + if isinstance(expr, models.F): + yield expr.name + elif hasattr(expr, 'flatten'): + for child in expr.flatten(): + if isinstance(child, models.F): + yield child.name + elif isinstance(child, models.Q): + yield from _get_children_from_q(child) + + def _get_children_from_q(q): + for child in q.children: + if isinstance(child, Node): + yield from _get_children_from_q(child) + elif isinstance(child, tuple): + lhs, rhs = child + yield lhs + if hasattr(rhs, 'resolve_expression'): + yield from _get_paths_from_expression(rhs) + elif hasattr(child, 'resolve_expression'): + yield from _get_paths_from_expression(child) + + def get_referenced_base_fields_from_q(q): + return { + child.split(LOOKUP_SEP, 1)[0] for child in _get_children_from_q(q) } diff --git a/rest_framework/decorators.py b/rest_framework/decorators.py index 3b572c09ef..864ff73958 100644 --- a/rest_framework/decorators.py +++ b/rest_framework/decorators.py @@ -36,7 +36,7 @@ def decorator(func): # WrappedAPIView.__doc__ = func.doc <--- Not possible to do this # api_view applied without (method_names) - assert not(isinstance(http_method_names, types.FunctionType)), \ + assert not isinstance(http_method_names, types.FunctionType), \ '@api_view missing list of allowed HTTP methods' # api_view applied with eg. string instead of list of strings diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 6374c1ea98..89c0a714c6 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1,3 +1,4 @@ +import contextlib import copy import datetime import decimal @@ -5,8 +6,9 @@ import inspect import re import uuid -from collections import OrderedDict +import warnings from collections.abc import Mapping +from enum import Enum from django.conf import settings from django.core.exceptions import ObjectDoesNotExist @@ -14,7 +16,7 @@ from django.core.validators import ( EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, ProhibitNullCharactersValidator, RegexValidator, - URLValidator, ip_address_validators + URLValidator ) from django.forms import FilePathField as DjangoFilePathField from django.forms import ImageField as DjangoImageField @@ -27,13 +29,19 @@ from django.utils.formats import localize_input, sanitize_separators from django.utils.ipv6 import clean_ipv6_address from django.utils.translation import gettext_lazy as _ -from pytz.exceptions import InvalidTimeError + +try: + import pytz +except ImportError: + pytz = None from rest_framework import ISO_8601 +from rest_framework.compat import ip_address_validators from rest_framework.exceptions import ErrorDetail, ValidationError from rest_framework.settings import api_settings from rest_framework.utils import html, humanize_datetime, json, representation from rest_framework.utils.formatting import lazy_format +from rest_framework.utils.timezone import valid_datetime from rest_framework.validators import ProhibitSurrogateCharactersValidator @@ -103,32 +111,11 @@ def get_attribute(instance, attrs): # If we raised an Attribute or KeyError here it'd get treated # as an omitted field in `Field.get_attribute()`. Instead we # raise a ValueError to ensure the exception is not masked. - raise ValueError('Exception raised in callable attribute "{}"; original exception was: {}'.format(attr, exc)) + raise ValueError(f'Exception raised in callable attribute "{attr}"; original exception was: {exc}') return instance -def set_value(dictionary, keys, value): - """ - Similar to Python's built in `dictionary[key] = value`, - but takes a list of nested keys instead of a single key. - - set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2} - set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2} - set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}} - """ - if not keys: - dictionary.update(value) - return - - for key in keys[:-1]: - if key not in dictionary: - dictionary[key] = {} - dictionary = dictionary[key] - - dictionary[keys[-1]] = value - - def to_choices_dict(choices): """ Convert choices into key/value dicts. @@ -141,7 +128,7 @@ def to_choices_dict(choices): # choices = [1, 2, 3] # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] # choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')] - ret = OrderedDict() + ret = {} for choice in choices: if not isinstance(choice, (list, tuple)): # single choice @@ -164,7 +151,7 @@ def flatten_choices_dict(choices): flatten_choices_dict({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'} flatten_choices_dict({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'} """ - ret = OrderedDict() + ret = {} for key, value in choices.items(): if isinstance(value, dict): # grouped choices (category, sub choices) @@ -355,6 +342,10 @@ def __init__(self, *, read_only=False, write_only=False, messages.update(error_messages or {}) self.error_messages = messages + # Allow generic typing checking for fields. + def __class_getitem__(cls, *args, **kwargs): + return cls + def bind(self, field_name, parent): """ Initializes the field name and parent for the field instance. @@ -672,41 +663,56 @@ class BooleanField(Field): default_empty_html = False initial = False TRUE_VALUES = { - 't', 'T', - 'y', 'Y', 'yes', 'Yes', 'YES', - 'true', 'True', 'TRUE', - 'on', 'On', 'ON', - '1', 1, - True + 't', + 'y', + 'yes', + 'true', + 'on', + '1', + 1, + True, } FALSE_VALUES = { - 'f', 'F', - 'n', 'N', 'no', 'No', 'NO', - 'false', 'False', 'FALSE', - 'off', 'Off', 'OFF', - '0', 0, 0.0, - False + 'f', + 'n', + 'no', + 'false', + 'off', + '0', + 0, + 0.0, + False, } - NULL_VALUES = {'null', 'Null', 'NULL', '', None} + NULL_VALUES = {'null', '', None} + + def __init__(self, **kwargs): + if kwargs.get('allow_null', False): + self.default_empty_html = None + self.initial = None + super().__init__(**kwargs) + + @staticmethod + def _lower_if_str(value): + if isinstance(value, str): + return value.lower() + return value def to_internal_value(self, data): - try: - if data in self.TRUE_VALUES: + with contextlib.suppress(TypeError): + if self._lower_if_str(data) in self.TRUE_VALUES: return True - elif data in self.FALSE_VALUES: + elif self._lower_if_str(data) in self.FALSE_VALUES: return False - elif data in self.NULL_VALUES and self.allow_null: + elif self._lower_if_str(data) in self.NULL_VALUES and self.allow_null: return None - except TypeError: # Input is an unhashable type - pass - self.fail('invalid', input=data) + self.fail("invalid", input=data) def to_representation(self, value): - if value in self.TRUE_VALUES: + if self._lower_if_str(value) in self.TRUE_VALUES: return True - elif value in self.FALSE_VALUES: + elif self._lower_if_str(value) in self.FALSE_VALUES: return False - if value in self.NULL_VALUES and self.allow_null: + if self._lower_if_str(value) in self.NULL_VALUES and self.allow_null: return None return bool(value) @@ -859,7 +865,7 @@ def __init__(self, protocol='both', **kwargs): self.protocol = protocol.lower() self.unpack_ipv4 = (self.protocol == 'both') super().__init__(**kwargs) - validators, error_message = ip_address_validators(protocol, self.unpack_ipv4) + validators = ip_address_validators(protocol, self.unpack_ipv4) self.validators.extend(validators) def to_internal_value(self, data): @@ -920,7 +926,8 @@ class FloatField(Field): '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': _('String value too large.'), + 'overflow': _('Integer value too large to convert to float') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. @@ -946,6 +953,8 @@ def to_internal_value(self, data): return float(data) except (TypeError, ValueError): self.fail('invalid') + except OverflowError: + self.fail('overflow') def to_representation(self, value): return float(value) @@ -964,10 +973,11 @@ class DecimalField(Field): MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None, - localize=False, rounding=None, **kwargs): + localize=False, rounding=None, normalize_output=False, **kwargs): self.max_digits = max_digits self.decimal_places = decimal_places self.localize = localize + self.normalize_output = normalize_output if coerce_to_string is not None: self.coerce_to_string = coerce_to_string if self.localize: @@ -976,6 +986,11 @@ def __init__(self, max_digits, decimal_places, coerce_to_string=None, max_value= self.max_value = max_value self.min_value = min_value + if self.max_value is not None and not isinstance(self.max_value, (int, decimal.Decimal)): + warnings.warn("max_value should be an integer or Decimal instance.") + if self.min_value is not None and not isinstance(self.min_value, (int, decimal.Decimal)): + warnings.warn("min_value should be an integer or Decimal instance.") + if self.max_digits is not None and self.decimal_places is not None: self.max_whole_digits = self.max_digits - self.decimal_places else: @@ -1080,12 +1095,15 @@ def to_representation(self, value): quantized = self.quantize(value) + if self.normalize_output: + quantized = quantized.normalize() + if not coerce_to_string: return quantized if self.localize: return localize_input(quantized) - return '{:f}'.format(quantized) + return f'{quantized:f}' def quantize(self, value): """ @@ -1138,9 +1156,16 @@ def enforce_timezone(self, value): except OverflowError: self.fail('overflow') try: - return timezone.make_aware(value, field_timezone) - except InvalidTimeError: - self.fail('make_aware', timezone=field_timezone) + dt = timezone.make_aware(value, field_timezone) + # When the resulting datetime is a ZoneInfo instance, it won't necessarily + # throw given an invalid datetime, so we need to specifically check. + if not valid_datetime(dt): + self.fail('make_aware', timezone=field_timezone) + return dt + except Exception as e: + if pytz and isinstance(e, pytz.exceptions.InvalidTimeError): + self.fail('make_aware', timezone=field_timezone) + raise e elif (field_timezone is None) and timezone.is_aware(value): return timezone.make_naive(value, datetime.timezone.utc) return value @@ -1158,19 +1183,14 @@ def to_internal_value(self, value): return self.enforce_timezone(value) for input_format in input_formats: - if input_format.lower() == ISO_8601: - try: + with contextlib.suppress(ValueError, TypeError): + if input_format.lower() == ISO_8601: parsed = parse_datetime(value) if parsed is not None: return self.enforce_timezone(parsed) - except (ValueError, TypeError): - pass - else: - try: - parsed = self.datetime_parser(value, input_format) - return self.enforce_timezone(parsed) - except (ValueError, TypeError): - pass + + parsed = self.datetime_parser(value, input_format) + return self.enforce_timezone(parsed) humanized_format = humanize_datetime.datetime_formats(input_formats) self.fail('invalid', format=humanized_format) @@ -1328,6 +1348,7 @@ class DurationField(Field): 'invalid': _('Duration has wrong format. Use one of these formats instead: {format}.'), '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}.'), + 'overflow': _('The number of days must be between {min_days} and {max_days}.'), } def __init__(self, **kwargs): @@ -1346,7 +1367,10 @@ def __init__(self, **kwargs): def to_internal_value(self, value): if isinstance(value, datetime.timedelta): return value - parsed = parse_duration(str(value)) + try: + parsed = parse_duration(str(value)) + except OverflowError: + self.fail('overflow', min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days) if parsed is not None: return parsed self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]') @@ -1376,7 +1400,8 @@ def __init__(self, choices, **kwargs): def to_internal_value(self, data): if data == '' and self.allow_blank: return '' - + if isinstance(data, Enum) and str(data) != str(data.value): + data = data.value try: return self.choice_strings_to_values[str(data)] except KeyError: @@ -1385,6 +1410,8 @@ def to_internal_value(self, data): def to_representation(self, value): if value in ('', None): return value + if isinstance(value, Enum) and str(value) != str(value.value): + value = value.value return self.choice_strings_to_values.get(str(value), value) def iter_options(self): @@ -1408,7 +1435,7 @@ def _set_choices(self, choices): # 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 = { - str(key): key for key in self.choices + str(key.value) if isinstance(key, Enum) and str(key) != str(key.value) else str(key): key for key in self.choices } choices = property(_get_choices, _set_choices) @@ -1469,6 +1496,7 @@ def __init__(self, path, match=None, recursive=False, allow_files=True, allow_folders=allow_folders, required=required ) kwargs['choices'] = field.choices + kwargs['required'] = required super().__init__(**kwargs) @@ -1627,13 +1655,15 @@ def to_representation(self, data): def run_child_validation(self, data): result = [] - errors = OrderedDict() + errors = {} for idx, item in enumerate(data): try: result.append(self.child.run_validation(item)) except ValidationError as e: errors[idx] = e.detail + except DjangoValidationError as e: + errors[idx] = get_error_detail(e) if not errors: return result @@ -1689,7 +1719,7 @@ def to_representation(self, value): def run_child_validation(self, data): result = {} - errors = OrderedDict() + errors = {} for key, value in data.items(): key = str(key) @@ -1791,6 +1821,7 @@ class HiddenField(Field): 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 @@ -1814,12 +1845,13 @@ class SerializerMethodField(Field): For example: - class ExampleSerializer(self): + class ExampleSerializer(Serializer): extra_info = SerializerMethodField() def get_extra_info(self, obj): return ... # Calculate some data to return. """ + def __init__(self, method_name=None, **kwargs): self.method_name = method_name kwargs['source'] = '*' @@ -1829,7 +1861,7 @@ def __init__(self, method_name=None, **kwargs): def bind(self, field_name, parent): # The method name defaults to `get_{field_name}`. if self.method_name is None: - self.method_name = 'get_{field_name}'.format(field_name=field_name) + self.method_name = f'get_{field_name}' super().bind(field_name, parent) diff --git a/rest_framework/filters.py b/rest_framework/filters.py index 1ffd9edc02..3f4730da84 100644 --- a/rest_framework/filters.py +++ b/rest_framework/filters.py @@ -3,19 +3,40 @@ returned by list views. """ import operator +import warnings from functools import reduce -from django.core.exceptions import ImproperlyConfigured +from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured from django.db import models from django.db.models.constants import LOOKUP_SEP from django.template import loader from django.utils.encoding import force_str +from django.utils.text import smart_split, unescape_string_literal from django.utils.translation import gettext_lazy as _ -from rest_framework.compat import coreapi, coreschema, distinct +from rest_framework import RemovedInDRF317Warning +from rest_framework.compat import coreapi, coreschema +from rest_framework.fields import CharField from rest_framework.settings import api_settings +def search_smart_split(search_terms): + """Returns sanitized search terms as a list.""" + split_terms = [] + for term in smart_split(search_terms): + # trim commas to avoid bad matching for quoted phrases + term = term.strip(',') + if term.startswith(('"', "'")) and term[0] == term[-1]: + # quoted phrases are kept together without any other split + split_terms.append(unescape_string_literal(term)) + else: + # non-quoted tokens are split by comma, keeping only non-empty ones + for sub_term in term.split(','): + if sub_term: + split_terms.append(sub_term.strip()) + return split_terms + + class BaseFilterBackend: """ A base class from which all filter backend classes should inherit. @@ -29,6 +50,8 @@ def filter_queryset(self, request, queryset, view): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [] @@ -60,18 +83,38 @@ def get_search_fields(self, view, request): def get_search_terms(self, request): """ Search terms are set by a ?search=... query parameter, - and may be comma and/or whitespace delimited. + and may be whitespace delimited. """ - params = request.query_params.get(self.search_param, '') - params = params.replace('\x00', '') # strip null characters - params = params.replace(',', ' ') - return params.split() + value = request.query_params.get(self.search_param, '') + field = CharField(trim_whitespace=False, allow_blank=True) + cleaned_value = field.run_validation(value) + return search_smart_split(cleaned_value) - def construct_search(self, field_name): + def construct_search(self, field_name, queryset): lookup = self.lookup_prefixes.get(field_name[0]) if lookup: field_name = field_name[1:] else: + # Use field_name if it includes a lookup. + opts = queryset.model._meta + lookup_fields = field_name.split(LOOKUP_SEP) + # Go through the fields, following all relations. + prev_field = None + for path_part in lookup_fields: + if path_part == "pk": + path_part = opts.pk.name + try: + field = opts.get_field(path_part) + except FieldDoesNotExist: + # Use valid query lookups. + if prev_field and prev_field.get_lookup(path_part): + return field_name + else: + prev_field = field + if hasattr(field, "path_infos"): + # Update opts to follow the relation. + opts = field.path_infos[-1].to_opts + # Otherwise, use the field with icontains. lookup = 'icontains' return LOOKUP_SEP.join([field_name, lookup]) @@ -109,43 +152,44 @@ def filter_queryset(self, request, queryset, view): return queryset orm_lookups = [ - self.construct_search(str(search_field)) + self.construct_search(str(search_field), queryset) for search_field in search_fields ] base = queryset - conditions = [] - for search_term in search_terms: - queries = [ - models.Q(**{orm_lookup: search_term}) - for orm_lookup in orm_lookups - ] - conditions.append(reduce(operator.or_, queries)) + # generator which for each term builds the corresponding search + conditions = ( + reduce( + operator.or_, + (models.Q(**{orm_lookup: term}) for orm_lookup in orm_lookups) + ) for term in search_terms + ) queryset = queryset.filter(reduce(operator.and_, conditions)) + # Remove duplicates from results, if necessary if self.must_call_distinct(queryset, search_fields): - # Filtering against a many-to-many field requires us to - # call queryset.distinct() in order to avoid duplicate items - # in the resulting queryset. - # We try to avoid this if possible, for performance reasons. - queryset = distinct(queryset, base) + # inspired by django.contrib.admin + # this is more accurate than .distinct form M2M relationship + # also is cross-database + queryset = queryset.filter(pk=models.OuterRef('pk')) + queryset = base.filter(models.Exists(queryset)) return queryset def to_html(self, request, queryset, view): if not getattr(view, 'search_fields', None): return '' - term = self.get_search_terms(request) - term = term[0] if term else '' context = { 'param': self.search_param, - 'term': term + 'term': request.query_params.get(self.search_param, ''), } template = loader.get_template(self.template) return template.render(context) def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( @@ -306,6 +350,8 @@ def to_html(self, request, queryset, view): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( diff --git a/rest_framework/generics.py b/rest_framework/generics.py index 55cfafda44..1673033214 100644 --- a/rest_framework/generics.py +++ b/rest_framework/generics.py @@ -45,6 +45,10 @@ class GenericAPIView(views.APIView): # The style to use for queryset pagination. pagination_class = api_settings.DEFAULT_PAGINATION_CLASS + # Allow generic typing checking for generic views. + def __class_getitem__(cls, *args, **kwargs): + return cls + def get_queryset(self): """ Get the list of items for this view. diff --git a/rest_framework/locale/ar/LC_MESSAGES/django.mo b/rest_framework/locale/ar/LC_MESSAGES/django.mo index f793d7c73b..a3c7c5ca24 100644 Binary files a/rest_framework/locale/ar/LC_MESSAGES/django.mo and b/rest_framework/locale/ar/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/ar/LC_MESSAGES/django.po b/rest_framework/locale/ar/LC_MESSAGES/django.po index 58f72ec175..be261d8dd4 100644 --- a/rest_framework/locale/ar/LC_MESSAGES/django.po +++ b/rest_framework/locale/ar/LC_MESSAGES/django.po @@ -8,6 +8,7 @@ # Bashar Al-Abdulhadi, 2016-2017 # Eyad Toma , 2015,2017 # zak zak , 2020 +# Salman Saeed Albukhaitan , 2024 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" @@ -24,19 +25,19 @@ msgstr "" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." -msgstr "رأس أساسي غير صالح, لم تقدم اي بيانات." +msgstr "ترويسة أساسية غير صالحة. لم تقدم أي بيانات تفويض." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." -msgstr "رأس أساسي غير صالح, سلسلة البيانات لا يجب أن تحتوي على أي أحرف مسافات" +msgstr "ترويسة أساسية غير صالحة. يجب أن لا تحتوي سلسلة بيانات التفويض على مسافات." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." -msgstr "رأس أساسي غير صالح, البيانات ليست مرمّزة بصحة على أساس64." +msgstr "ترويسة أساسية غير صالحة. بيانات التفويض لم تُشفر بشكل صحيح بنظام أساس64." #: authentication.py:101 msgid "Invalid username/password." -msgstr "اسم المستخدم/كلمة السر غير صحيحين." +msgstr "اسم المستخدم/كلمة المرور غير صحيحة." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." @@ -93,7 +94,7 @@ msgstr "كلمة المرور" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." -msgstr "تعذر تسجيل الدخول بالبيانات التي ادخلتها." +msgstr "تعذر تسجيل الدخول بالبيانات المدخلة." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." @@ -101,11 +102,11 @@ msgstr "يجب أن تتضمن \"اسم المستخدم\" و \"كلمة الم #: exceptions.py:102 msgid "A server error occurred." -msgstr "حدث خطأ في المخدم." +msgstr "حدث خطأ في الخادم." #: exceptions.py:142 msgid "Invalid input." -msgstr "" +msgstr "مدخل غير صالح." #: exceptions.py:161 msgid "Malformed request." @@ -130,11 +131,11 @@ msgstr "غير موجود." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." -msgstr "الطريقة \"{method}\" غير مسموح بها." +msgstr "طريقة \"{method}\" غير مسموح بها." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." -msgstr "لم نتمكن من تلبية الرٱس Accept في الطلب." +msgstr "تعذر تلبية ترويسة Accept في الطلب." #: exceptions.py:212 #, python-brace-format @@ -143,17 +144,17 @@ msgstr "الوسيط \"{media_type}\" الموجود في الطلب غير مع #: exceptions.py:223 msgid "Request was throttled." -msgstr "تم تقييد الطلب." +msgstr "تم حد الطلب." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "متوقع التوفر خلال {wait} ثانية." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "متوقع التوفر خلال {wait} ثواني." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 @@ -166,11 +167,11 @@ msgstr "لا يمكن لهذا الحقل ان يكون فارغاً null." #: fields.py:701 msgid "Must be a valid boolean." -msgstr "" +msgstr "يجب أن يكون قيمة منطقية صالحة." #: fields.py:766 msgid "Not a valid string." -msgstr "" +msgstr "ليس نصاً صالحاً." #: fields.py:767 msgid "This field may not be blank." @@ -179,16 +180,16 @@ msgstr "لا يمكن لهذا الحقل ان يكون فارغاً." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." -msgstr "تأكد ان الحقل لا يزيد عن {max_length} محرف." +msgstr "تأكد ان عدد الحروف في هذا الحقل لا تتجاوز {max_length}." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." -msgstr "تأكد ان الحقل {min_length} محرف على الاقل." +msgstr "تأكد ان عدد الحروف في هذا الحقل لا يقل عن {min_length}." #: fields.py:816 msgid "Enter a valid email address." -msgstr "عليك ان تدخل بريد إلكتروني صالح." +msgstr "يرجى إدخال عنوان بريد إلكتروني صحيح." #: fields.py:827 msgid "This value does not match the required pattern." @@ -204,7 +205,7 @@ msgstr "أدخل \"slug\" صالح يحتوي على حروف، أرقام، ش msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." -msgstr "" +msgstr "أدخل \"slug\" صالح يحتوي على حروف يونيكود، أرقام، شُرط سفلية أو واصلات." #: fields.py:854 msgid "Enter a valid URL." @@ -212,7 +213,7 @@ msgstr "الرجاء إدخال رابط إلكتروني صالح." #: fields.py:867 msgid "Must be a valid UUID." -msgstr "" +msgstr "يجب أن يكون معرف UUID صالح." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." @@ -225,16 +226,16 @@ msgstr "الرجاء إدخال رقم صحيح صالح." #: fields.py:932 fields.py:969 fields.py:1005 fields.py:1366 #, python-brace-format msgid "Ensure this value is less than or equal to {max_value}." -msgstr "تأكد ان القيمة أقل أو تساوي {max_value}." +msgstr "تأكد ان القيمة أقل من أو تساوي {max_value}." #: fields.py:933 fields.py:970 fields.py:1006 fields.py:1367 #, python-brace-format msgid "Ensure this value is greater than or equal to {min_value}." -msgstr "تأكد ان القيمة أكبر أو تساوي {min_value}." +msgstr "تأكد ان القيمة أكبر من أو تساوي {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." -msgstr "السلسلة اطول من القيمة المسموح بها." +msgstr "النص طويل جداً." #: fields.py:968 fields.py:1004 msgid "A valid number is required." @@ -249,7 +250,7 @@ msgstr "تأكد ان القيمة لا تحوي أكثر من {max_digits} رق #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." -msgstr "تأكد انه لا يوجد اكثر من {max_decimal_places} منازل عشرية." +msgstr "تأكد انه لا يوجد اكثر من {max_decimal_places} أرقام عشرية." #: fields.py:1009 #, python-brace-format @@ -261,7 +262,7 @@ msgstr "تأكد انه لا يوجد اكثر من {max_whole_digits} أرقا #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." -msgstr "صيغة التاريخ و الوقت غير صحيحة. عليك أن تستخدم واحدة من هذه الصيغ التالية: {format}." +msgstr "صيغة التاريخ و الوقت غير صحيحة. عليك أن تستخدم احد الصيغ التالية: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." @@ -270,11 +271,11 @@ msgstr "متوقع تاريخ و وقت و وجد تاريخ فقط" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "تاريخ و وقت غير صالح للمنطقة الزمنية \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." -msgstr "" +msgstr "قيمة التاريخ و الوقت خارج النطاق." #: fields.py:1236 #, python-brace-format @@ -293,12 +294,12 @@ msgstr "صيغة الوقت غير صحيحة. عليك أن تستخدم واح #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." -msgstr "صيغة المدة غير صحيحه, يرجى إستخدام إحدى هذه الصيغ: {format}." +msgstr "صيغة المدة غير صحيحة. يرجى استخدام احد الصيغ التالية: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." -msgstr "\"{input}\" ليست واحدة من الخيارات الصالحة." +msgstr "\"{input}\" ليس خياراً صالحاً." #: fields.py:1402 #, python-brace-format @@ -317,7 +318,7 @@ msgstr "هذا التحديد لا يجب أن يكون فارغا." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." -msgstr "{input} كإختيار مسار غير صالح." +msgstr "{input} ليس خيار مسار صالح." #: fields.py:1514 msgid "No file was submitted." @@ -326,41 +327,41 @@ msgstr "لم يتم إرسال أي ملف." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." -msgstr "المعطيات المرسولة ليست ملف. إفحص نوع الترميز في النموذج." +msgstr "البيانات المرسلة ليست ملف. تأكد من نوع الترميز في النموذج." #: fields.py:1516 msgid "No filename could be determined." -msgstr "ما من إسم ملف أمكن تحديده." +msgstr "تعذر تحديد اسم الملف." #: fields.py:1517 msgid "The submitted file is empty." -msgstr "الملف الذي تم إرساله فارغ." +msgstr "الملف المرسل فارغ." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." -msgstr "تأكد ان اسم الملف لا يحوي أكثر من {max_length} محرف (الإسم المرسل يحوي {length} محرف)." +msgstr "تأكد ان طول إسم الملف لا يتجاوز {max_length} حرف (عدد الحروف الحالي {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." -msgstr "الرجاء تحميل صورة صالحة. الملف الذي تم تحميله إما لم يكن صورة او انه كان صورة تالفة." +msgstr "يرجى رفع صورة صالحة. الملف الذي قمت برفعه ليس صورة أو أنه ملف تالف." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." -msgstr "القائمة يجب أن لا تكون فارغة." +msgstr "يجب أن لا تكون القائمة فارغة." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "تأكد ان عدد العناصر في هذا الحقل لا يقل عن {min_length}." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "تأكد ان عدد العناصر في هذا الحقل لا يتجاوز {max_length}." #: fields.py:1682 #, python-brace-format @@ -369,7 +370,7 @@ msgstr "المتوقع كان قاموس عناصر و لكن النوع الم #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "يجب أن لا يكون القاموس فارغاً." #: fields.py:1755 msgid "Value must be valid JSON." @@ -381,7 +382,7 @@ msgstr "بحث" #: filters.py:50 msgid "A search term." -msgstr "" +msgstr "مصطلح البحث." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" @@ -389,7 +390,7 @@ msgstr "الترتيب" #: filters.py:181 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "أي حقل يجب استخدامه عند ترتيب النتائج." #: filters.py:287 msgid "ascending" @@ -401,11 +402,11 @@ msgstr "تنازلي" #: pagination.py:174 msgid "A page number within the paginated result set." -msgstr "" +msgstr "رقم الصفحة ضمن النتائج المقسمة." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." -msgstr "" +msgstr "عدد النتائج التي يجب إرجاعها في كل صفحة." #: pagination.py:189 msgid "Invalid page." @@ -413,11 +414,11 @@ msgstr "صفحة غير صحيحة." #: pagination.py:374 msgid "The initial index from which to return the results." -msgstr "" +msgstr "الفهرس الأولي الذي يجب البدء منه لإرجاع النتائج." #: pagination.py:581 msgid "The pagination cursor value." -msgstr "" +msgstr "قيمة المؤشر للتقسيم." #: pagination.py:583 msgid "Invalid cursor" @@ -431,24 +432,24 @@ msgstr "معرف العنصر \"{pk_value}\" غير صالح - العنصر غ #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." -msgstr "نوع خاطئ. المتوقع قيمة من pk، لكن المتحصل عليه {data_type}." +msgstr "نوع غير صحيح. يتوقع قيمة معرف العنصر، بينما حصل على {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." -msgstr "إرتباط تشعبي غير صالح - لا مطابقة لURL." +msgstr "رابط تشعبي غير صالح - لا يوجد تطابق URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." -msgstr "إرتباط تشعبي غير صالح - مطابقة خاطئة لURL." +msgstr "رابط تشعبي غير صالح - تطابق URL غير صحيح." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." -msgstr "إرتباط تشعبي غير صالح - عنصر غير موجود." +msgstr "رابط تشعبي غير صالح - العنصر غير موجود." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." -msgstr "نوع خاطئ. المتوقع سلسلة URL، لكن المتحصل عليه {data_type}." +msgstr "نوع غير صحيح. المتوقع هو رابط URL، ولكن تم الحصول على {data_type}." #: relations.py:448 #, python-brace-format @@ -461,20 +462,20 @@ msgstr "قيمة غير صالحة." #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "رقم صحيح فريد" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "نص UUID" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "قيمة فريدة" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "نوع {value_type} يحدد هذا {name}." #: serializers.py:337 #, python-brace-format @@ -484,7 +485,7 @@ msgstr "معطيات غير صالحة. المتوقع هو قاموس، لكن #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "إجراءات إضافية" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 @@ -493,27 +494,27 @@ msgstr "مرشحات" #: templates/rest_framework/base.html:37 msgid "navbar" -msgstr "" +msgstr "شريط التنقل" #: templates/rest_framework/base.html:75 msgid "content" -msgstr "" +msgstr "المحتوى" #: templates/rest_framework/base.html:78 msgid "request form" -msgstr "" +msgstr "نموذج الطلب" #: templates/rest_framework/base.html:157 msgid "main content" -msgstr "" +msgstr "المحتوى الرئيسي" #: templates/rest_framework/base.html:173 msgid "request info" -msgstr "" +msgstr "معلومات الطلب" #: templates/rest_framework/base.html:177 msgid "response info" -msgstr "" +msgstr "معلومات الرد" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 @@ -525,7 +526,7 @@ msgstr "لا شيء" #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." -msgstr "ما من عناصر للتحديد." +msgstr "لا يوجد عناصر لتحديدها." #: validators.py:39 msgid "This field must be unique." @@ -539,7 +540,7 @@ msgstr "الحقول {field_names} يجب أن تشكل مجموعة فريدة. #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." -msgstr "" +msgstr "لا يُسمح بالحروف البديلة: U+{code_point:X}." #: validators.py:243 #, python-brace-format @@ -558,11 +559,11 @@ msgstr "الحقل يجب ان يكون فريد للعام {date_field}." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." -msgstr "إصدار غير صالح في الرٱس \"Accept\"." +msgstr "إصدار غير صالح في ترويسة \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." -msgstr "إصدار غير صالح في المسار URL." +msgstr "نسخة غير صالحة في مسار URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." diff --git a/rest_framework/locale/de/LC_MESSAGES/django.mo b/rest_framework/locale/de/LC_MESSAGES/django.mo index 9868803978..99bdec2c05 100644 Binary files a/rest_framework/locale/de/LC_MESSAGES/django.mo and b/rest_framework/locale/de/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/de/LC_MESSAGES/django.po b/rest_framework/locale/de/LC_MESSAGES/django.po index 12ae5ba183..48e59e8796 100644 --- a/rest_framework/locale/de/LC_MESSAGES/django.po +++ b/rest_framework/locale/de/LC_MESSAGES/django.po @@ -11,6 +11,7 @@ # Thomas Tanner, 2015 # Tom Jaster , 2015 # Xavier Ordoquy , 2015 +# stefan6419846, 2025 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" @@ -27,19 +28,19 @@ msgstr "" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." -msgstr "Ungültiger basic header. Keine Zugangsdaten angegeben." +msgstr "Ungültiger Basic Header. Keine Zugangsdaten angegeben." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." -msgstr "Ungültiger basic header. Zugangsdaten sollen keine Leerzeichen enthalten." +msgstr "Ungültiger Basic Header. Zugangsdaten sollen keine Leerzeichen enthalten." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." -msgstr "Ungültiger basic header. Zugangsdaten sind nicht korrekt mit base64 kodiert." +msgstr "Ungültiger Basic Header. Zugangsdaten sind nicht korrekt mit base64 kodiert." #: authentication.py:101 msgid "Invalid username/password." -msgstr "Ungültiger Benutzername/Passwort" +msgstr "Ungültiger Benutzername/Passwort." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." @@ -47,16 +48,16 @@ msgstr "Benutzer inaktiv oder gelöscht." #: authentication.py:184 msgid "Invalid token header. No credentials provided." -msgstr "Ungültiger token header. Keine Zugangsdaten angegeben." +msgstr "Ungültiger Token Header. Keine Zugangsdaten angegeben." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." -msgstr "Ungültiger token header. Zugangsdaten sollen keine Leerzeichen enthalten." +msgstr "Ungültiger Token Header. Zugangsdaten sollen keine Leerzeichen enthalten." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." -msgstr "Ungültiger Token Header. Tokens dürfen keine ungültigen Zeichen enthalten." +msgstr "Ungültiger Token Header. Zugangsdaten dürfen keine ungültigen Zeichen enthalten." #: authentication.py:203 msgid "Invalid token." @@ -108,7 +109,7 @@ msgstr "Ein Serverfehler ist aufgetreten." #: exceptions.py:142 msgid "Invalid input." -msgstr "" +msgstr "Ungültige Eingabe." #: exceptions.py:161 msgid "Malformed request." @@ -124,7 +125,7 @@ msgstr "Anmeldedaten fehlen." #: exceptions.py:179 msgid "You do not have permission to perform this action." -msgstr "Sie sind nicht berechtigt diese Aktion durchzuführen." +msgstr "Sie sind nicht berechtigt, diese Aktion durchzuführen." #: exceptions.py:185 msgid "Not found." @@ -151,17 +152,17 @@ msgstr "Die Anfrage wurde gedrosselt." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "Erwarte Verfügbarkeit in {wait} Sekunde." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "Erwarte Verfügbarkeit in {wait} Sekunden." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." -msgstr "Dieses Feld ist erforderlich." +msgstr "Dieses Feld ist zwingend erforderlich." #: fields.py:317 msgid "This field may not be null." @@ -169,11 +170,11 @@ msgstr "Dieses Feld darf nicht null sein." #: fields.py:701 msgid "Must be a valid boolean." -msgstr "" +msgstr "Muss ein gültiger Wahrheitswert sein." #: fields.py:766 msgid "Not a valid string." -msgstr "" +msgstr "Kein gültiger String." #: fields.py:767 msgid "This field may not be blank." @@ -207,7 +208,7 @@ msgstr "Gib ein gültiges \"slug\" aus Buchstaben, Ziffern, Unterstrichen und Mi msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." -msgstr "" +msgstr "Gib ein gültiges \"slug\" aus Unicode-Buchstaben, Ziffern, Unterstrichen und Minuszeichen ein." #: fields.py:854 msgid "Enter a valid URL." @@ -215,11 +216,11 @@ msgstr "Gib eine gültige URL ein." #: fields.py:867 msgid "Must be a valid UUID." -msgstr "" +msgstr "Muss eine gültige UUID sein." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." -msgstr "Geben Sie eine gültige IPv4 oder IPv6 Adresse an" +msgstr "Geben Sie eine gültige IPv4 oder IPv6 Adresse an." #: fields.py:931 msgid "A valid integer is required." @@ -273,11 +274,11 @@ msgstr "Erwarte eine Datums- und Zeitangabe, erhielt aber ein Datum." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "Ungültige Datumsangabe für die Zeitzone \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." -msgstr "" +msgstr "Datumsangabe außerhalb des Bereichs." #: fields.py:1236 #, python-brace-format @@ -358,12 +359,12 @@ msgstr "Diese Liste darf nicht leer sein." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "Dieses Feld muss mindestens {min_length} Einträge enthalten." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "Dieses Feld darf nicht mehr als {max_length} Einträge enthalten." #: fields.py:1682 #, python-brace-format @@ -372,7 +373,7 @@ msgstr "Erwartete ein Dictionary mit Elementen, erhielt aber den Typ \"{input_ty #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "Dieses Dictionary darf nicht leer sein." #: fields.py:1755 msgid "Value must be valid JSON." @@ -384,7 +385,7 @@ msgstr "Suche" #: filters.py:50 msgid "A search term." -msgstr "" +msgstr "Ein Suchbegriff." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" @@ -392,7 +393,7 @@ msgstr "Sortierung" #: filters.py:181 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "Feld, das zum Sortieren der Ergebnisse verwendet werden soll." #: filters.py:287 msgid "ascending" @@ -404,11 +405,11 @@ msgstr "Absteigend" #: pagination.py:174 msgid "A page number within the paginated result set." -msgstr "" +msgstr "Eine Seitenzahl in der paginierten Ergebnismenge." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." -msgstr "" +msgstr "Anzahl der pro Seite zurückzugebenden Ergebnisse." #: pagination.py:189 msgid "Invalid page." @@ -416,11 +417,11 @@ msgstr "Ungültige Seite." #: pagination.py:374 msgid "The initial index from which to return the results." -msgstr "" +msgstr "Der initiale Index, von dem die Ergebnisse zurückgegeben werden sollen." #: pagination.py:581 msgid "The pagination cursor value." -msgstr "" +msgstr "Der Zeigerwert für die Paginierung" #: pagination.py:583 msgid "Invalid cursor" @@ -434,7 +435,7 @@ msgstr "Ungültiger pk \"{pk_value}\" - Object existiert nicht." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." -msgstr "Falscher Typ. Erwarte pk Wert, erhielt aber {data_type}." +msgstr "Falscher Typ. Erwarte pk-Wert, erhielt aber {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." @@ -451,7 +452,7 @@ msgstr "Ungültiger Hyperlink - Objekt existiert nicht." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." -msgstr "Falscher Typ. Erwarte URL Zeichenkette, erhielt aber {data_type}." +msgstr "Falscher Typ. Erwarte URL-Zeichenkette, erhielt aber {data_type}." #: relations.py:448 #, python-brace-format @@ -464,20 +465,20 @@ msgstr "Ungültiger Wert." #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "eindeutiger Ganzzahl-Wert" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "UUID-String" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "eindeutiger Wert" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "Ein {value_type}, der {name} identifiziert." #: serializers.py:337 #, python-brace-format @@ -487,7 +488,7 @@ msgstr "Ungültige Daten. Dictionary erwartet, aber {datatype} erhalten." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "Zusätzliche Aktionen" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 @@ -496,27 +497,27 @@ msgstr "Filter" #: templates/rest_framework/base.html:37 msgid "navbar" -msgstr "" +msgstr "Navigation" #: templates/rest_framework/base.html:75 msgid "content" -msgstr "" +msgstr "Inhalt" #: templates/rest_framework/base.html:78 msgid "request form" -msgstr "" +msgstr "Anfrage-Formular" #: templates/rest_framework/base.html:157 msgid "main content" -msgstr "" +msgstr "Hauptteil" #: templates/rest_framework/base.html:173 msgid "request info" -msgstr "" +msgstr "Anfrage-Informationen" #: templates/rest_framework/base.html:177 msgid "response info" -msgstr "" +msgstr "Antwort-Informationen" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 @@ -542,7 +543,7 @@ msgstr "Die Felder {field_names} müssen eine eindeutige Menge bilden." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." -msgstr "" +msgstr "Ersatzzeichen sind nicht erlaubt: U+{code_point:X}." #: validators.py:243 #, python-brace-format @@ -565,7 +566,7 @@ msgstr "Ungültige Version in der \"Accept\" Kopfzeile." #: versioning.py:71 msgid "Invalid version in URL path." -msgstr "Ungültige Version im URL Pfad." +msgstr "Ungültige Version im URL-Pfad." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." diff --git a/rest_framework/locale/es/LC_MESSAGES/django.mo b/rest_framework/locale/es/LC_MESSAGES/django.mo index 16df627fcc..77fe3faec3 100644 Binary files a/rest_framework/locale/es/LC_MESSAGES/django.mo and b/rest_framework/locale/es/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/es/LC_MESSAGES/django.po b/rest_framework/locale/es/LC_MESSAGES/django.po index a2f7f1a433..b56fa80142 100644 --- a/rest_framework/locale/es/LC_MESSAGES/django.po +++ b/rest_framework/locale/es/LC_MESSAGES/django.po @@ -10,12 +10,13 @@ # Miguel Gonzalez , 2016 # Miguel Gonzalez , 2015-2016 # Sergio Infante , 2015 +# Federico Bond , 2025 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2020-10-13 21:45+0200\n" -"PO-Revision-Date: 2020-10-13 19:45+0000\n" +"PO-Revision-Date: 2025-05-19 00:05+1000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Spanish (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/es/)\n" "MIME-Version: 1.0\n" @@ -107,7 +108,7 @@ msgstr "Se ha producido un error en el servidor." #: exceptions.py:142 msgid "Invalid input." -msgstr "" +msgstr "Entrada inválida." #: exceptions.py:161 msgid "Malformed request." @@ -150,12 +151,12 @@ msgstr "Solicitud fue regulada (throttled)." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "Se espera que esté disponible en {wait} segundo." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "Se espera que esté disponible en {wait} segundos." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 @@ -168,11 +169,11 @@ msgstr "Este campo no puede ser nulo." #: fields.py:701 msgid "Must be a valid boolean." -msgstr "" +msgstr "Debe ser un booleano válido." #: fields.py:766 msgid "Not a valid string." -msgstr "" +msgstr "No es una cadena válida." #: fields.py:767 msgid "This field may not be blank." @@ -204,9 +205,8 @@ msgstr "Introduzca un \"slug\" válido consistente en letras, números, guiones #: fields.py:839 msgid "" -"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " -"or hyphens." -msgstr "" +"Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, or hyphens." +msgstr "Introduzca un “slug” válido compuesto por letras Unicode, números, guiones bajos o medios." #: fields.py:854 msgid "Enter a valid URL." @@ -214,7 +214,7 @@ msgstr "Introduzca una URL válida." #: fields.py:867 msgid "Must be a valid UUID." -msgstr "" +msgstr "Debe ser un UUID válido." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." @@ -272,11 +272,11 @@ msgstr "Se esperaba un fecha/hora en vez de una fecha." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "Fecha y hora inválida para la zona horaria \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." -msgstr "" +msgstr "Valor de fecha y hora fuera de rango." #: fields.py:1236 #, python-brace-format @@ -357,12 +357,12 @@ msgstr "Esta lista no puede estar vacía." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "Asegúrese de que este campo tiene al menos {min_length} elementos." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "Asegúrese de que este campo no tiene más de {max_length} elementos." #: fields.py:1682 #, python-brace-format @@ -371,7 +371,7 @@ msgstr "Se esperaba un diccionario de elementos en vez del tipo \"{input_type}\" #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "Este diccionario no debe estar vacío." #: fields.py:1755 msgid "Value must be valid JSON." @@ -383,7 +383,7 @@ msgstr "Buscar" #: filters.py:50 msgid "A search term." -msgstr "" +msgstr "Un término de búsqueda." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" @@ -391,7 +391,7 @@ msgstr "Ordenamiento" #: filters.py:181 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "Qué campo usar para ordenar los resultados." #: filters.py:287 msgid "ascending" @@ -403,11 +403,11 @@ msgstr "descendiente" #: pagination.py:174 msgid "A page number within the paginated result set." -msgstr "" +msgstr "Un número de página dentro del conjunto de resultados paginado." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." -msgstr "" +msgstr "Número de resultados a devolver por página." #: pagination.py:189 msgid "Invalid page." @@ -415,11 +415,11 @@ msgstr "Página inválida." #: pagination.py:374 msgid "The initial index from which to return the results." -msgstr "" +msgstr "El índice inicial a partir del cual devolver los resultados." #: pagination.py:581 msgid "The pagination cursor value." -msgstr "" +msgstr "El valor del cursor de paginación." #: pagination.py:583 msgid "Invalid cursor" @@ -463,20 +463,20 @@ msgstr "Valor inválido." #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "valor de entero único" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "Cadena UUID" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "valor único" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "Un {value_type} que identifique este {name}." #: serializers.py:337 #, python-brace-format @@ -486,7 +486,7 @@ msgstr "Datos inválidos. Se esperaba un diccionario pero es un {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "Acciones extras" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 diff --git a/rest_framework/locale/fa/LC_MESSAGES/django.mo b/rest_framework/locale/fa/LC_MESSAGES/django.mo index 099318e69a..53b8fd98e9 100644 Binary files a/rest_framework/locale/fa/LC_MESSAGES/django.mo and b/rest_framework/locale/fa/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/fa/LC_MESSAGES/django.po b/rest_framework/locale/fa/LC_MESSAGES/django.po index 6a5b99acf6..8d76372fa2 100644 --- a/rest_framework/locale/fa/LC_MESSAGES/django.po +++ b/rest_framework/locale/fa/LC_MESSAGES/django.po @@ -7,6 +7,7 @@ # Aryan Baghi , 2020 # Omid Zarin , 2019 # Xavier Ordoquy , 2020 +# Sina Amini , 2024 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" @@ -104,7 +105,7 @@ msgstr "خطای سمت سرور رخ داده است." #: exceptions.py:142 msgid "Invalid input." -msgstr "" +msgstr "ورودی نامعتبر" #: exceptions.py:161 msgid "Malformed request." @@ -147,12 +148,12 @@ msgstr "تعداد درخواست‌های شما محدود شده است." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "انتظار می‌رود در {wait} ثانیه در دسترس باشد." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "انتظار می‌رود در {wait} ثانیه در دسترس باشد." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 @@ -165,11 +166,11 @@ msgstr "این مقدار نباید توهی باشد." #: fields.py:701 msgid "Must be a valid boolean." -msgstr "" +msgstr "باید یک مقدار منطقی(بولی) معتبر باشد." #: fields.py:766 msgid "Not a valid string." -msgstr "" +msgstr "یک رشته معتبر نیست." #: fields.py:767 msgid "This field may not be blank." @@ -187,7 +188,7 @@ msgstr "مطمعن شوید طول این مقدار حداقل {min_length} ا #: fields.py:816 msgid "Enter a valid email address." -msgstr "پست الکترونیکی صحبح وارد کنید." +msgstr "پست الکترونیکی صحیح وارد کنید." #: fields.py:827 msgid "This value does not match the required pattern." @@ -211,7 +212,7 @@ msgstr "یک URL معتبر وارد کنید" #: fields.py:867 msgid "Must be a valid UUID." -msgstr "" +msgstr "باید یک UUID معتبر باشد." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." @@ -269,11 +270,11 @@ msgstr "باید datetime باشد اما date دریافت شد." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "تاریخ و زمان برای منطقه زمانی \"{timezone}\" نامعتبر است." #: fields.py:1151 msgid "Datetime value out of range." -msgstr "" +msgstr "مقدار تاریخ و زمان خارج از محدوده است." #: fields.py:1236 #, python-brace-format @@ -354,12 +355,12 @@ msgstr "این لیست نمی تواند خالی باشد" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "اطمینان حاصل کنید که این فیلد حداقل {min_length} عنصر دارد." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "اطمینان حاصل کنید که این فیلد بیش از {max_length} عنصر ندارد." #: fields.py:1682 #, python-brace-format @@ -368,7 +369,7 @@ msgstr "باید دیکشنری از آیتم ها ارسال می شد، اما #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "این دیکشنری نمی‌تواند خالی باشد." #: fields.py:1755 msgid "Value must be valid JSON." @@ -380,7 +381,7 @@ msgstr "جستجو" #: filters.py:50 msgid "A search term." -msgstr "" +msgstr "یک عبارت جستجو." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" @@ -388,7 +389,7 @@ msgstr "ترتیب" #: filters.py:181 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "کدام فیلد باید هنگام مرتب‌سازی نتایج استفاده شود." #: filters.py:287 msgid "ascending" @@ -400,11 +401,11 @@ msgstr "نزولی" #: pagination.py:174 msgid "A page number within the paginated result set." -msgstr "" +msgstr "یک شماره صفحه‌ در مجموعه نتایج صفحه‌بندی شده." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." -msgstr "" +msgstr "تعداد نتایج برای نمایش در هر صفحه." #: pagination.py:189 msgid "Invalid page." @@ -412,11 +413,11 @@ msgstr "صفحه نامعتبر" #: pagination.py:374 msgid "The initial index from which to return the results." -msgstr "" +msgstr "ایندکس اولیه‌ای که از آن نتایج بازگردانده می‌شود." #: pagination.py:581 msgid "The pagination cursor value." -msgstr "" +msgstr "مقدار نشانگر صفحه‌بندی." #: pagination.py:583 msgid "Invalid cursor" @@ -460,20 +461,20 @@ msgstr "مقدار نامعتبر." #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "مقداد عدد یکتا" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "رشته UUID" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "مقدار یکتا" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "یک {value_type} که این {name} را شناسایی میکند." #: serializers.py:337 #, python-brace-format @@ -483,7 +484,7 @@ msgstr "داده نامعتبر. باید دیکشنری ارسال می شد، #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "اقدامات اضافی" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 @@ -492,27 +493,27 @@ msgstr "فیلترها" #: templates/rest_framework/base.html:37 msgid "navbar" -msgstr "" +msgstr "نوار ناوبری" #: templates/rest_framework/base.html:75 msgid "content" -msgstr "" +msgstr "محتوا" #: templates/rest_framework/base.html:78 msgid "request form" -msgstr "" +msgstr "فرم درخواست" #: templates/rest_framework/base.html:157 msgid "main content" -msgstr "" +msgstr "محتوای اصلی" #: templates/rest_framework/base.html:173 msgid "request info" -msgstr "" +msgstr "اطلاعات درخواست" #: templates/rest_framework/base.html:177 msgid "response info" -msgstr "" +msgstr "اطلاعات پاسخ" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 @@ -538,7 +539,7 @@ msgstr "فیلدهای {field_names} باید یک مجموعه یکتا باش #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." -msgstr "" +msgstr "کاراکترهای جایگزین مجاز نیستند: U+{code_point:X}." #: validators.py:243 #, python-brace-format diff --git a/rest_framework/locale/fa_IR/LC_MESSAGES/django.mo b/rest_framework/locale/fa_IR/LC_MESSAGES/django.mo index 52d3f3bf84..35775d9f2b 100644 Binary files a/rest_framework/locale/fa_IR/LC_MESSAGES/django.mo and b/rest_framework/locale/fa_IR/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/fa_IR/LC_MESSAGES/django.po b/rest_framework/locale/fa_IR/LC_MESSAGES/django.po index 61361d50e5..280725a73c 100644 --- a/rest_framework/locale/fa_IR/LC_MESSAGES/django.po +++ b/rest_framework/locale/fa_IR/LC_MESSAGES/django.po @@ -7,6 +7,7 @@ # Aryan Baghi , 2020 # Omid Zarin , 2019 # Xavier Ordoquy , 2020 +# Sina Amini , 2024 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" @@ -187,7 +188,7 @@ msgstr "مطمعن شوید طول این مقدار حداقل {min_length} ا #: fields.py:816 msgid "Enter a valid email address." -msgstr "پست الکترونیکی صحبح وارد کنید." +msgstr "پست الکترونیکی صحیح وارد کنید." #: fields.py:827 msgid "This value does not match the required pattern." diff --git a/rest_framework/locale/ko_KR/LC_MESSAGES/django.mo b/rest_framework/locale/ko_KR/LC_MESSAGES/django.mo index c3aeb27a96..2228adcf7f 100644 Binary files a/rest_framework/locale/ko_KR/LC_MESSAGES/django.mo and b/rest_framework/locale/ko_KR/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/ko_KR/LC_MESSAGES/django.po b/rest_framework/locale/ko_KR/LC_MESSAGES/django.po index 722dc2c82e..f98cad67d5 100644 --- a/rest_framework/locale/ko_KR/LC_MESSAGES/django.po +++ b/rest_framework/locale/ko_KR/LC_MESSAGES/django.po @@ -1,37 +1,37 @@ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. -# +# # Translators: -# GarakdongBigBoy , 2017 +# JAEGYUN JUNG , 2024 # Hochul Kwak , 2018 +# GarakdongBigBoy , 2017 # Joon Hwan 김준환 , 2017 # SUN CHOI , 2015 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2020-10-13 21:45+0200\n" +"POT-Creation-Date: 2024-10-22 16:13+0900\n" "PO-Revision-Date: 2020-10-13 19:45+0000\n" -"Last-Translator: Xavier Ordoquy \n" -"Language-Team: Korean (Korea) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ko_KR/)\n" +"Last-Translator: JAEGYUN JUNG \n" +"Language: ko_KR\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Language: ko_KR\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." -msgstr "기본 헤더(basic header)가 유효하지 않습니다. 인증데이터(credentials)가 제공되지 않았습니다." +msgstr "기본 헤더가 유효하지 않습니다. 인증 데이터가 제공되지 않았습니다." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." -msgstr "기본 헤더(basic header)가 유효하지 않습니다. 인증데이터(credentials) 문자열은 빈칸(spaces)을 포함하지 않아야 합니다." +msgstr "기본 헤더가 유효하지 않습니다. 인증 데이터 문자열은 공백을 포함하지 않아야 합니다." -#: authentication.py:83 +#: authentication.py:84 msgid "Invalid basic header. Credentials not correctly base64 encoded." -msgstr "기본 헤더(basic header)가 유효하지 않습니다. 인증데이터(credentials)가 base64로 적절히 부호화(encode)되지 않았습니다." +msgstr "기본 헤더가 유효하지 않습니다. 인증 데이터가 올바르게 base64 인코딩되지 않았습니다." #: authentication.py:101 msgid "Invalid username/password." @@ -43,11 +43,11 @@ msgstr "계정이 중지되었거나 삭제되었습니다." #: authentication.py:184 msgid "Invalid token header. No credentials provided." -msgstr "토큰 헤더가 유효하지 않습니다. 인증데이터(credentials)가 제공되지 않았습니다." +msgstr "토큰 헤더가 유효하지 않습니다. 인증 데이터가 제공되지 않았습니다." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." -msgstr "토큰 헤더가 유효하지 않습니다. 토큰 문자열은 빈칸(spaces)을 포함하지 않아야 합니다." +msgstr "토큰 헤더가 유효하지 않습니다. 토큰 문자열은 공백을 포함하지 않아야 합니다." #: authentication.py:193 msgid "" @@ -58,6 +58,10 @@ msgstr "토큰 헤더가 유효하지 않습니다. 토큰 문자열은 유효 msgid "Invalid token." msgstr "토큰이 유효하지 않습니다." +#: authtoken/admin.py:28 authtoken/serializers.py:9 +msgid "Username" +msgstr "사용자 이름" + #: authtoken/apps.py:7 msgid "Auth Token" msgstr "인증 토큰" @@ -68,23 +72,19 @@ msgstr "키" #: authtoken/models.py:16 msgid "User" -msgstr "유저" +msgstr "사용자" #: authtoken/models.py:18 msgid "Created" -msgstr "생성됨" +msgstr "생성일시" -#: authtoken/models.py:27 authtoken/serializers.py:19 +#: authtoken/models.py:27 authtoken/models.py:54 authtoken/serializers.py:19 msgid "Token" msgstr "토큰" -#: authtoken/models.py:28 +#: authtoken/models.py:28 authtoken/models.py:55 msgid "Tokens" -msgstr "" - -#: authtoken/serializers.py:9 -msgid "Username" -msgstr "유저이름" +msgstr "토큰(들)" #: authtoken/serializers.py:13 msgid "Password" @@ -92,390 +92,398 @@ msgstr "비밀번호" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." -msgstr "제공된 인증데이터(credentials)로는 로그인할 수 없습니다." +msgstr "제공된 인증 데이터로는 로그인할 수 없습니다." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"아이디\"와 \"비밀번호\"를 포함해야 합니다." -#: exceptions.py:102 +#: exceptions.py:105 msgid "A server error occurred." msgstr "서버 장애가 발생했습니다." -#: exceptions.py:142 +#: exceptions.py:145 msgid "Invalid input." -msgstr "" +msgstr "유효하지 않은 입력입니다." -#: exceptions.py:161 +#: exceptions.py:166 msgid "Malformed request." msgstr "잘못된 요청입니다." -#: exceptions.py:167 +#: exceptions.py:172 msgid "Incorrect authentication credentials." -msgstr "자격 인증데이터(authentication credentials)가 정확하지 않습니다." +msgstr "자격 인증 데이터가 올바르지 않습니다." -#: exceptions.py:173 +#: exceptions.py:178 msgid "Authentication credentials were not provided." -msgstr "자격 인증데이터(authentication credentials)가 제공되지 않았습니다." +msgstr "자격 인증 데이터가 제공되지 않았습니다." -#: exceptions.py:179 +#: exceptions.py:184 msgid "You do not have permission to perform this action." -msgstr "이 작업을 수행할 권한(permission)이 없습니다." +msgstr "이 작업을 수행할 권한이 없습니다." -#: exceptions.py:185 +#: exceptions.py:190 msgid "Not found." msgstr "찾을 수 없습니다." -#: exceptions.py:191 +#: exceptions.py:196 #, python-brace-format msgid "Method \"{method}\" not allowed." -msgstr "메소드(Method) \"{method}\"는 허용되지 않습니다." +msgstr "메서드 \"{method}\"는 허용되지 않습니다." -#: exceptions.py:202 +#: exceptions.py:207 msgid "Could not satisfy the request Accept header." -msgstr "Accept header 요청을 만족할 수 없습니다." +msgstr "요청 Accept 헤더를 만족시킬 수 없습니다." -#: exceptions.py:212 +#: exceptions.py:217 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "요청된 \"{media_type}\"가 지원되지 않는 미디어 형태입니다." -#: exceptions.py:223 +#: exceptions.py:228 msgid "Request was throttled." -msgstr "요청이 지연(throttled)되었습니다." +msgstr "요청이 제한되었습니다." -#: exceptions.py:224 +#: exceptions.py:229 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "{wait} 초 후에 사용 가능합니다." -#: exceptions.py:225 +#: exceptions.py:230 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "{wait} 초 후에 사용 가능합니다." -#: fields.py:316 relations.py:245 relations.py:279 validators.py:90 -#: validators.py:183 +#: fields.py:292 relations.py:240 relations.py:276 validators.py:99 +#: validators.py:219 msgid "This field is required." msgstr "이 필드는 필수 항목입니다." -#: fields.py:317 +#: fields.py:293 msgid "This field may not be null." msgstr "이 필드는 null일 수 없습니다." -#: fields.py:701 +#: fields.py:661 msgid "Must be a valid boolean." -msgstr "" +msgstr "유효한 불리언이어야 합니다." -#: fields.py:766 +#: fields.py:724 msgid "Not a valid string." -msgstr "" +msgstr "유효한 문자열이 아닙니다." -#: fields.py:767 +#: fields.py:725 msgid "This field may not be blank." msgstr "이 필드는 blank일 수 없습니다." -#: fields.py:768 fields.py:1881 +#: fields.py:726 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." -msgstr "이 필드의 글자 수가 {max_length} 이하인지 확인하십시오." +msgstr "이 필드의 글자 수가 {max_length} 이하인지 확인하세요." -#: fields.py:769 +#: fields.py:727 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." -msgstr "이 필드의 글자 수가 적어도 {min_length} 이상인지 확인하십시오." +msgstr "이 필드의 글자 수가 적어도 {min_length} 이상인지 확인하세요." -#: fields.py:816 +#: fields.py:774 msgid "Enter a valid email address." -msgstr "유효한 이메일 주소를 입력하십시오." +msgstr "유효한 이메일 주소를 입력하세요." -#: fields.py:827 +#: fields.py:785 msgid "This value does not match the required pattern." -msgstr "형식에 맞지 않는 값입니다." +msgstr "이 값은 요구되는 패턴과 일치하지 않습니다." -#: fields.py:838 +#: fields.py:796 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." -msgstr "문자, 숫자, 밑줄( _ ) 또는 하이픈( - )으로 이루어진 유효한 \"slug\"를 입력하십시오." +msgstr "문자, 숫자, 밑줄( _ ) 또는 하이픈( - )으로 이루어진 유효한 \"slug\"를 입력하세요." -#: fields.py:839 +#: fields.py:797 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." -msgstr "" +msgstr "유니코드 문자, 숫자, 밑줄( _ ) 또는 하이픈( - )으로 이루어진 유효한 \"slug\"를 입력하세요." -#: fields.py:854 +#: fields.py:812 msgid "Enter a valid URL." -msgstr "유효한 URL을 입력하십시오." +msgstr "유효한 URL을 입력하세요." -#: fields.py:867 +#: fields.py:825 msgid "Must be a valid UUID." -msgstr "" +msgstr "유효한 UUID 이어야 합니다." -#: fields.py:903 +#: fields.py:861 msgid "Enter a valid IPv4 or IPv6 address." -msgstr "유효한 IPv4 또는 IPv6 주소를 입력하십시오." +msgstr "유효한 IPv4 또는 IPv6 주소를 입력하세요." -#: fields.py:931 +#: fields.py:889 msgid "A valid integer is required." -msgstr "유효한 정수(integer)를 넣어주세요." +msgstr "유효한 정수를 입력하세요." -#: fields.py:932 fields.py:969 fields.py:1005 fields.py:1366 +#: fields.py:890 fields.py:927 fields.py:966 fields.py:1349 #, python-brace-format msgid "Ensure this value is less than or equal to {max_value}." -msgstr "이 값이 {max_value}보다 작거나 같은지 확인하십시오." +msgstr "이 값이 {max_value}보다 작거나 같은지 확인하세요." -#: fields.py:933 fields.py:970 fields.py:1006 fields.py:1367 +#: fields.py:891 fields.py:928 fields.py:967 fields.py:1350 #, python-brace-format msgid "Ensure this value is greater than or equal to {min_value}." -msgstr "이 값이 {min_value}보다 크거나 같은지 확인하십시오." +msgstr "이 값이 {min_value}보다 크거나 같은지 확인하세요." -#: fields.py:934 fields.py:971 fields.py:1010 +#: fields.py:892 fields.py:929 fields.py:971 msgid "String value too large." -msgstr "문자열 값이 너무 큽니다." +msgstr "문자열 값이 너무 깁니다." -#: fields.py:968 fields.py:1004 +#: fields.py:926 fields.py:965 msgid "A valid number is required." -msgstr "유효한 숫자를 넣어주세요." +msgstr "유효한 숫자를 입력하세요." + +#: fields.py:930 +msgid "Integer value too large to convert to float" +msgstr "정수 값이 너무 커서 부동 소수점으로 변환할 수 없습니다." -#: fields.py:1007 +#: fields.py:968 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." -msgstr "전체 숫자(digits)가 {max_digits} 이하인지 확인하십시오." +msgstr "총 자릿수가 {max_digits}을(를) 초과하지 않는지 확인하세요." -#: fields.py:1008 +#: fields.py:969 #, python-brace-format -msgid "" -"Ensure that there are no more than {max_decimal_places} decimal places." -msgstr "소수점 자릿수가 {max_decimal_places} 이하인지 확인하십시오." +msgid "Ensure that there are no more than {max_decimal_places} decimal places." +msgstr "소수점 이하 자릿수가 {max_decimal_places}을(를) 초과하지 않는지 확인하세요." -#: fields.py:1009 +#: fields.py:970 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." -msgstr "소수점 자리 앞에 숫자(digits)가 {max_whole_digits} 이하인지 확인하십시오." +msgstr "소수점 앞 자릿수가 {max_whole_digits}을(를) 초과하지 않는지 확인하세요." -#: fields.py:1148 +#: fields.py:1129 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." -#: fields.py:1149 +#: fields.py:1130 msgid "Expected a datetime but got a date." -msgstr "예상된 datatime 대신 date를 받았습니다." +msgstr "datatime이 예상되었지만 date를 받았습니다." -#: fields.py:1150 +#: fields.py:1131 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "\"{timezone}\" 시간대에 대한 유효하지 않은 datetime 입니다." -#: fields.py:1151 +#: fields.py:1132 msgid "Datetime value out of range." -msgstr "" +msgstr "Datetime 값이 범위를 벗어났습니다." -#: fields.py:1236 +#: fields.py:1219 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Date의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." -#: fields.py:1237 +#: fields.py:1220 msgid "Expected a date but got a datetime." msgstr "예상된 date 대신 datetime을 받았습니다." -#: fields.py:1303 +#: fields.py:1286 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Time의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." -#: fields.py:1365 +#: fields.py:1348 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Duration의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." -#: fields.py:1399 fields.py:1456 +#: fields.py:1351 +#, python-brace-format +msgid "The number of days must be between {min_days} and {max_days}." +msgstr "일수는 {min_days} 이상 {max_days} 이하이어야 합니다." + +#: fields.py:1386 fields.py:1446 #, python-brace-format msgid "\"{input}\" is not a valid choice." -msgstr "\"{input}\"이 유효하지 않은 선택(choice)입니다." +msgstr "\"{input}\"은 유효하지 않은 선택입니다." -#: fields.py:1402 +#: fields.py:1389 #, python-brace-format msgid "More than {count} items..." -msgstr "" +msgstr "{count}개 이상의 아이템이 있습니다..." -#: fields.py:1457 fields.py:1603 relations.py:485 serializers.py:570 +#: fields.py:1447 fields.py:1596 relations.py:486 serializers.py:593 #, python-brace-format msgid "Expected a list of items but got type \"{input_type}\"." msgstr "아이템 리스트가 예상되었으나 \"{input_type}\"를 받았습니다." -#: fields.py:1458 +#: fields.py:1448 msgid "This selection may not be empty." msgstr "이 선택 항목은 비워 둘 수 없습니다." -#: fields.py:1495 +#: fields.py:1487 #, python-brace-format msgid "\"{input}\" is not a valid path choice." -msgstr "\"{input}\"이 유효하지 않은 경로 선택입니다." +msgstr "\"{input}\"은 유효하지 않은 경로 선택입니다." -#: fields.py:1514 +#: fields.py:1507 msgid "No file was submitted." msgstr "파일이 제출되지 않았습니다." -#: fields.py:1515 -msgid "" -"The submitted data was not a file. Check the encoding type on the form." +#: fields.py:1508 +msgid "The submitted data was not a file. Check the encoding type on the form." msgstr "제출된 데이터는 파일이 아닙니다. 제출된 서식의 인코딩 형식을 확인하세요." -#: fields.py:1516 +#: fields.py:1509 msgid "No filename could be determined." msgstr "파일명을 알 수 없습니다." -#: fields.py:1517 +#: fields.py:1510 msgid "The submitted file is empty." msgstr "제출한 파일이 비어있습니다." -#: fields.py:1518 +#: fields.py:1511 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." -msgstr "이 파일명의 글자수가 최대 {max_length}를 넘지 않는지 확인하십시오. (이것은 {length}가 있습니다)." +msgstr "이 파일명의 글자수가 최대 {max_length}자를 넘지 않는지 확인하세요. (현재 {length}자입니다)." -#: fields.py:1566 +#: fields.py:1559 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." -msgstr "유효한 이미지 파일을 업로드 하십시오. 업로드 하신 파일은 이미지 파일이 아니거나 손상된 이미지 파일입니다." +msgstr "유효한 이미지 파일을 업로드하세요. 업로드하신 파일은 이미지 파일이 아니거나 손상된 이미지 파일입니다." -#: fields.py:1604 relations.py:486 serializers.py:571 +#: fields.py:1597 relations.py:487 serializers.py:594 msgid "This list may not be empty." msgstr "이 리스트는 비워 둘 수 없습니다." -#: fields.py:1605 +#: fields.py:1598 serializers.py:596 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "이 필드가 최소 {min_length} 개의 요소를 가지는지 확인하세요." -#: fields.py:1606 +#: fields.py:1599 serializers.py:595 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "이 필드가 최대 {max_length} 개의 요소를 가지는지 확인하세요." -#: fields.py:1682 +#: fields.py:1677 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "아이템 딕셔너리가 예상되었으나 \"{input_type}\" 타입을 받았습니다." -#: fields.py:1683 +#: fields.py:1678 msgid "This dictionary may not be empty." -msgstr "" +msgstr "이 딕셔너리는 비어있을 수 없습니다." -#: fields.py:1755 +#: fields.py:1750 msgid "Value must be valid JSON." -msgstr "Value 는 유효한 JSON형식이어야 합니다." +msgstr "유효한 JSON 값이어야 합니다." -#: filters.py:49 templates/rest_framework/filters/search.html:2 +#: filters.py:72 templates/rest_framework/filters/search.html:2 +#: templates/rest_framework/filters/search.html:8 msgid "Search" msgstr "검색" -#: filters.py:50 +#: filters.py:73 msgid "A search term." -msgstr "" +msgstr "검색어." -#: filters.py:180 templates/rest_framework/filters/ordering.html:3 +#: filters.py:224 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "순서" -#: filters.py:181 +#: filters.py:225 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "결과 정렬 시 사용할 필드." -#: filters.py:287 +#: filters.py:341 msgid "ascending" msgstr "오름차순" -#: filters.py:288 +#: filters.py:342 msgid "descending" msgstr "내림차순" -#: pagination.py:174 +#: pagination.py:180 msgid "A page number within the paginated result set." -msgstr "" +msgstr "페이지네이션된 결과 집합 내의 페이지 번호." -#: pagination.py:179 pagination.py:372 pagination.py:590 +#: pagination.py:185 pagination.py:382 pagination.py:599 msgid "Number of results to return per page." -msgstr "" +msgstr "페이지당 반환할 결과 수." -#: pagination.py:189 +#: pagination.py:195 msgid "Invalid page." msgstr "페이지가 유효하지 않습니다." -#: pagination.py:374 +#: pagination.py:384 msgid "The initial index from which to return the results." -msgstr "" +msgstr "결과를 반환할 초기 인덱스." -#: pagination.py:581 +#: pagination.py:590 msgid "The pagination cursor value." -msgstr "" +msgstr "페이지네이션 커서 값." -#: pagination.py:583 +#: pagination.py:592 msgid "Invalid cursor" -msgstr "커서(cursor)가 유효하지 않습니다." +msgstr "커서가 유효하지 않습니다." -#: relations.py:246 +#: relations.py:241 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "유효하지 않은 pk \"{pk_value}\" - 객체가 존재하지 않습니다." -#: relations.py:247 +#: relations.py:242 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." -msgstr "잘못된 형식입니다. pk 값 대신 {data_type}를 받았습니다." +msgstr "잘못된 형식입니다. pk 값이 예상되었지만, {data_type}을(를) 받았습니다." -#: relations.py:280 +#: relations.py:277 msgid "Invalid hyperlink - No URL match." msgstr "유효하지 않은 하이퍼링크 - 일치하는 URL이 없습니다." -#: relations.py:281 +#: relations.py:278 msgid "Invalid hyperlink - Incorrect URL match." msgstr "유효하지 않은 하이퍼링크 - URL이 일치하지 않습니다." -#: relations.py:282 +#: relations.py:279 msgid "Invalid hyperlink - Object does not exist." msgstr "유효하지 않은 하이퍼링크 - 객체가 존재하지 않습니다." -#: relations.py:283 +#: relations.py:280 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "잘못된 형식입니다. URL 문자열을 예상했으나 {data_type}을 받았습니다." -#: relations.py:448 +#: relations.py:445 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} 객체가 존재하지 않습니다." -#: relations.py:449 +#: relations.py:446 msgid "Invalid value." msgstr "값이 유효하지 않습니다." #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "고유한 정수 값" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "UUID 문자열" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "고유한 값" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "{name}을 식별하는 {value_type}." -#: serializers.py:337 +#: serializers.py:340 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "유효하지 않은 데이터. 딕셔너리(dictionary)대신 {datatype}를 받았습니다." @@ -483,7 +491,7 @@ msgstr "유효하지 않은 데이터. 딕셔너리(dictionary)대신 {datatype} #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "추가 Action들" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 @@ -492,33 +500,33 @@ msgstr "필터" #: templates/rest_framework/base.html:37 msgid "navbar" -msgstr "" +msgstr "네비게이션 바" #: templates/rest_framework/base.html:75 msgid "content" -msgstr "" +msgstr "콘텐츠" #: templates/rest_framework/base.html:78 msgid "request form" -msgstr "" +msgstr "요청 폼" #: templates/rest_framework/base.html:157 msgid "main content" -msgstr "" +msgstr "메인 콘텐츠" #: templates/rest_framework/base.html:173 msgid "request info" -msgstr "" +msgstr "요청 정보" #: templates/rest_framework/base.html:177 msgid "response info" -msgstr "" +msgstr "응답 정보" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 #: templates/rest_framework/vertical/radio.html:3 msgid "None" -msgstr "" +msgstr "없음" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 @@ -528,49 +536,49 @@ msgstr "선택할 아이템이 없습니다." #: validators.py:39 msgid "This field must be unique." -msgstr "이 필드는 반드시 고유(unique)해야 합니다." +msgstr "이 필드는 반드시 고유해야 합니다." -#: validators.py:89 +#: validators.py:98 #, python-brace-format msgid "The fields {field_names} must make a unique set." -msgstr "필드 {field_names} 는 반드시 고유(unique)해야 합니다." +msgstr "필드 {field_names} 는 반드시 고유해야 합니다." -#: validators.py:171 +#: validators.py:200 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." -msgstr "" +msgstr "대체(surrogate) 문자는 허용되지 않습니다: U+{code_point:X}." -#: validators.py:243 +#: validators.py:290 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." -msgstr "이 필드는 고유(unique)한 \"{date_field}\" 날짜를 갖습니다." +msgstr "이 필드는 \"{date_field}\" 날짜에 대해 고유해야 합니다." -#: validators.py:258 +#: validators.py:305 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." -msgstr "이 필드는 고유(unique)한 \"{date_field}\" 월을 갖습니다. " +msgstr "이 필드는 \"{date_field}\" 월에 대해 고유해야 합니다." -#: validators.py:271 +#: validators.py:318 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." -msgstr "이 필드는 고유(unique)한 \"{date_field}\" 년을 갖습니다. " +msgstr "이 필드는 \"{date_field}\" 연도에 대해 고유해야 합니다." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." -msgstr "\"Accept\" 헤더(header)의 버전이 유효하지 않습니다." +msgstr "\"Accept\" 헤더의 버전이 유효하지 않습니다." #: versioning.py:71 msgid "Invalid version in URL path." -msgstr "URL path의 버전이 유효하지 않습니다." +msgstr "URL 경로의 버전이 유효하지 않습니다." -#: versioning.py:116 +#: versioning.py:118 msgid "Invalid version in URL path. Does not match any version namespace." -msgstr "URL 경로에 유효하지 않은 버전이 있습니다. 버전 네임 스페이스와 일치하지 않습니다." +msgstr "URL 경로에 유효하지 않은 버전이 있습니다. 버전 네임스페이스와 일치하지 않습니다." -#: versioning.py:148 +#: versioning.py:150 msgid "Invalid version in hostname." -msgstr "hostname내 버전이 유효하지 않습니다." +msgstr "hostname 내 버전이 유효하지 않습니다." -#: versioning.py:170 +#: versioning.py:172 msgid "Invalid version in query parameter." -msgstr "쿼리 파라메터내 버전이 유효하지 않습니다." +msgstr "쿼리 파라메터 내 버전이 유효하지 않습니다." diff --git a/rest_framework/locale/pt_BR/LC_MESSAGES/django.mo b/rest_framework/locale/pt_BR/LC_MESSAGES/django.mo index 5a6e3788e6..03a0651fa7 100644 Binary files a/rest_framework/locale/pt_BR/LC_MESSAGES/django.mo and b/rest_framework/locale/pt_BR/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/pt_BR/LC_MESSAGES/django.po b/rest_framework/locale/pt_BR/LC_MESSAGES/django.po index 40651552d7..bfd53ee0f2 100644 --- a/rest_framework/locale/pt_BR/LC_MESSAGES/django.po +++ b/rest_framework/locale/pt_BR/LC_MESSAGES/django.po @@ -1,7 +1,7 @@ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. -# +# # Translators: # Cloves Oliveira , 2020 # Craig Blaszczyk , 2015 @@ -9,6 +9,8 @@ # Filipe Rinaldi , 2015 # Hugo Leonardo Chalhoub Mendonça , 2015 # Jonatas Baldin , 2017 +# Gabriel Mitelman Tkacz , 2024 +# Matheus Oliveira , 2025 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" @@ -106,11 +108,11 @@ msgstr "Ocorreu um erro de servidor." #: exceptions.py:142 msgid "Invalid input." -msgstr "" +msgstr "Entrada inválida" #: exceptions.py:161 msgid "Malformed request." -msgstr "Pedido malformado." +msgstr "Requisição malformada." #: exceptions.py:167 msgid "Incorrect authentication credentials." @@ -140,7 +142,7 @@ msgstr "Não foi possível satisfazer a requisição do cabeçalho Accept." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." -msgstr "Tipo de mídia \"{media_type}\" no pedido não é suportado." +msgstr "Tipo de mídia \"{media_type}\" no pedido não é suportado." #: exceptions.py:223 msgid "Request was throttled." @@ -149,12 +151,12 @@ msgstr "Pedido foi limitado." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "Disponível em {wait} segundo." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "Disponível em {wait} segundos." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 @@ -167,15 +169,15 @@ msgstr "Este campo não pode ser nulo." #: fields.py:701 msgid "Must be a valid boolean." -msgstr "" +msgstr "Deve ser um valor booleano válido." #: fields.py:766 msgid "Not a valid string." -msgstr "" +msgstr "Não é uma string válida." #: fields.py:767 msgid "This field may not be blank." -msgstr "Este campo não pode ser em branco." +msgstr "Este campo não pode estar em branco." #: fields.py:768 fields.py:1881 #, python-brace-format @@ -199,21 +201,21 @@ msgstr "Este valor não corresponde ao padrão exigido." msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." -msgstr "Entrar um \"slug\" válido que consista de letras, números, sublinhados ou hífens." +msgstr "Insira um \"slug\" válido que consista de letras, números, sublinhados ou hífens." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." -msgstr "" +msgstr "Insira um \"slug\" válido que consista de letras Unicode, números, sublinhados ou hífens." #: fields.py:854 msgid "Enter a valid URL." -msgstr "Entrar um URL válido." +msgstr "Insira um URL válido." #: fields.py:867 msgid "Must be a valid UUID." -msgstr "" +msgstr "Deve ser um UUID válido." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." @@ -271,11 +273,11 @@ msgstr "Necessário uma data e hora mas recebeu uma data." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "Data e hora inválidas para o fuso horário \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." -msgstr "" +msgstr "Valor de data e hora fora do intervalo." #: fields.py:1236 #, python-brace-format @@ -289,17 +291,17 @@ msgstr "Necessário uma data mas recebeu uma data e hora." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." -msgstr "Formato inválido para Tempo. Use um dos formatos a seguir: {format}." +msgstr "Formato inválido para tempo. Use um dos formatos a seguir: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." -msgstr "Formato inválido para Duração. Use um dos formatos a seguir: {format}." +msgstr "Formato inválido para duração. Use um dos formatos a seguir: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." -msgstr "\"{input}\" não é um escolha válido." +msgstr "\"{input}\" não é um escolha válida." #: fields.py:1402 #, python-brace-format @@ -309,7 +311,7 @@ msgstr "Mais de {count} itens..." #: fields.py:1457 fields.py:1603 relations.py:485 serializers.py:570 #, python-brace-format msgid "Expected a list of items but got type \"{input_type}\"." -msgstr "Necessário uma lista de itens, mas recebeu tipo \"{input_type}\"." +msgstr "Esperava uma lista de itens, mas recebeu tipo \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." @@ -347,7 +349,7 @@ msgstr "Certifique-se de que o nome do arquivo tem menos de {max_length} caracte msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." -msgstr "Fazer upload de uma imagem válida. O arquivo enviado não é um arquivo de imagem ou está corrompido." +msgstr "Faça upload de uma imagem válida. O arquivo enviado não é um arquivo de imagem ou está corrompido." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." @@ -356,25 +358,25 @@ msgstr "Esta lista não pode estar vazia." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "Certifique-se de que este campo tenha pelo menos {min_length} elementos." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "Certifique-se de que este campo não tenha mais que {max_length} elementos." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." -msgstr "Esperado um dicionário de itens mas recebeu tipo \"{input_type}\"." +msgstr "Esperava um dicionário de itens mas recebeu tipo \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "Este dicionário não pode estar vazio." #: fields.py:1755 msgid "Value must be valid JSON." -msgstr "Valor devo ser JSON válido." +msgstr "Valor deve ser JSON válido." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" @@ -382,7 +384,7 @@ msgstr "Buscar" #: filters.py:50 msgid "A search term." -msgstr "" +msgstr "Um termo de busca." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" @@ -390,23 +392,23 @@ msgstr "Ordenando" #: filters.py:181 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "Qual campo usar ao ordenar os resultados." #: filters.py:287 msgid "ascending" -msgstr "ascendente" +msgstr "crescente" #: filters.py:288 msgid "descending" -msgstr "descendente" +msgstr "decrescente" #: pagination.py:174 msgid "A page number within the paginated result set." -msgstr "" +msgstr "Um número de página dentro do conjunto de resultados paginado." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." -msgstr "" +msgstr "Número de resultados a serem retornados por página." #: pagination.py:189 msgid "Invalid page." @@ -414,11 +416,11 @@ msgstr "Página inválida." #: pagination.py:374 msgid "The initial index from which to return the results." -msgstr "" +msgstr "O índice inicial a partir do qual retornar os resultados." #: pagination.py:581 msgid "The pagination cursor value." -msgstr "" +msgstr "O valor do cursor de paginação." #: pagination.py:583 msgid "Invalid cursor" @@ -432,7 +434,7 @@ msgstr "Pk inválido \"{pk_value}\" - objeto não existe." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." -msgstr "Tipo incorreto. Esperado valor pk, recebeu {data_type}." +msgstr "Tipo incorreto. Esperava valor pk, recebeu {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." @@ -462,20 +464,20 @@ msgstr "Valor inválido." #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "valor inteiro único" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "string UUID" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "valor único" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "Um {value_type} que identifica este {name}." #: serializers.py:337 #, python-brace-format @@ -485,7 +487,7 @@ msgstr "Dado inválido. Necessário um dicionário mas recebeu {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "Ações Extras" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 @@ -530,7 +532,7 @@ msgstr "Nenhum item para escholher." #: validators.py:39 msgid "This field must be unique." -msgstr "Esse campo deve ser único." +msgstr "Esse campo deve ser único." #: validators.py:89 #, python-brace-format @@ -540,7 +542,7 @@ msgstr "Os campos {field_names} devem criar um set único." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." -msgstr "" +msgstr "Caracteres substitutos não são permitidos: U+{code_point:X}." #: validators.py:243 #, python-brace-format diff --git a/rest_framework/locale/zh_CN/LC_MESSAGES/django.po b/rest_framework/locale/zh_CN/LC_MESSAGES/django.po index 7e131db425..719df05a13 100644 --- a/rest_framework/locale/zh_CN/LC_MESSAGES/django.po +++ b/rest_framework/locale/zh_CN/LC_MESSAGES/django.po @@ -353,12 +353,12 @@ msgstr "列表字段不能为空值。" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "请确保这个字段至少包含 {min_length} 个元素。" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "请确保这个字段不能超过 {max_length} 个元素。" #: fields.py:1682 #, python-brace-format @@ -367,7 +367,7 @@ msgstr "期望是包含类目的字典,得到类型为 “{input_type}”。" #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "这个字典可能不是空的。" #: fields.py:1755 msgid "Value must be valid JSON." diff --git a/rest_framework/locale/zh_Hans/LC_MESSAGES/django.mo b/rest_framework/locale/zh_Hans/LC_MESSAGES/django.mo index 670228a834..b30686c1f9 100644 Binary files a/rest_framework/locale/zh_Hans/LC_MESSAGES/django.mo and b/rest_framework/locale/zh_Hans/LC_MESSAGES/django.mo differ diff --git a/rest_framework/locale/zh_Hans/LC_MESSAGES/django.po b/rest_framework/locale/zh_Hans/LC_MESSAGES/django.po index ce85b52c77..f85c7119e6 100644 --- a/rest_framework/locale/zh_Hans/LC_MESSAGES/django.po +++ b/rest_framework/locale/zh_Hans/LC_MESSAGES/django.po @@ -104,7 +104,7 @@ msgstr "服务器出现了错误。" #: exceptions.py:142 msgid "Invalid input." -msgstr "" +msgstr "无效的输入。" #: exceptions.py:161 msgid "Malformed request." @@ -142,17 +142,17 @@ msgstr "不支持请求中的媒体类型 “{media_type}”。" #: exceptions.py:223 msgid "Request was throttled." -msgstr "请求超过了限速。" +msgstr "请求已被限流。" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "预计 {wait} 秒后可用。" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "预计 {wait} 秒后可用。" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 @@ -165,11 +165,11 @@ msgstr "该字段不能为 null。" #: fields.py:701 msgid "Must be a valid boolean." -msgstr "" +msgstr "必须是有效的布尔值。" #: fields.py:766 msgid "Not a valid string." -msgstr "" +msgstr "不是有效的字符串。" #: fields.py:767 msgid "This field may not be blank." @@ -203,7 +203,7 @@ msgstr "请输入合法的“短语“,只能包含字母,数字,下划线 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." -msgstr "" +msgstr "请输入有效的“slug”,由 Unicode 字母、数字、下划线或连字符组成。" #: fields.py:854 msgid "Enter a valid URL." @@ -211,7 +211,7 @@ msgstr "请输入合法的URL。" #: fields.py:867 msgid "Must be a valid UUID." -msgstr "" +msgstr "必须是有效的 UUID。" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." @@ -269,11 +269,11 @@ msgstr "期望为日期时间,获得的是日期。" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "时区“{timezone}”的时间格式无效。" #: fields.py:1151 msgid "Datetime value out of range." -msgstr "" +msgstr "时间数值超出有效范围。" #: fields.py:1236 #, python-brace-format @@ -354,12 +354,12 @@ msgstr "列表不能为空。" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "该字段必须包含至少 {min_length} 个元素。" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "该字段不能超过 {max_length} 个元素。" #: fields.py:1682 #, python-brace-format @@ -368,7 +368,7 @@ msgstr "期望是包含类目的字典,得到类型为 “{input_type}”。" #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "该字典不能为空。" #: fields.py:1755 msgid "Value must be valid JSON." @@ -380,7 +380,7 @@ msgstr " 搜索" #: filters.py:50 msgid "A search term." -msgstr "" +msgstr "搜索关键词。" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" @@ -388,7 +388,7 @@ msgstr "排序" #: filters.py:181 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "用于排序结果的字段。" #: filters.py:287 msgid "ascending" @@ -400,11 +400,11 @@ msgstr "倒排序" #: pagination.py:174 msgid "A page number within the paginated result set." -msgstr "" +msgstr "分页结果集中的页码。" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." -msgstr "" +msgstr "每页返回的结果数量。" #: pagination.py:189 msgid "Invalid page." @@ -412,11 +412,11 @@ msgstr "无效页面。" #: pagination.py:374 msgid "The initial index from which to return the results." -msgstr "" +msgstr "返回结果的起始索引位置。" #: pagination.py:581 msgid "The pagination cursor value." -msgstr "" +msgstr "分页游标值" #: pagination.py:583 msgid "Invalid cursor" @@ -460,20 +460,20 @@ msgstr "无效值。" #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "唯一整数值" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "UUID 字符串" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "唯一值" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "标识此 {name} 的 {value_type}。" #: serializers.py:337 #, python-brace-format @@ -483,7 +483,7 @@ msgstr "无效数据。期待为字典类型,得到的是 {datatype} 。" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "扩展操作" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 @@ -492,27 +492,27 @@ msgstr "过滤器" #: templates/rest_framework/base.html:37 msgid "navbar" -msgstr "" +msgstr "导航栏" #: templates/rest_framework/base.html:75 msgid "content" -msgstr "" +msgstr "内容主体" #: templates/rest_framework/base.html:78 msgid "request form" -msgstr "" +msgstr "请求表单" #: templates/rest_framework/base.html:157 msgid "main content" -msgstr "" +msgstr "主要内容区" #: templates/rest_framework/base.html:173 msgid "request info" -msgstr "" +msgstr "请求信息" #: templates/rest_framework/base.html:177 msgid "response info" -msgstr "" +msgstr "响应信息" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 @@ -538,7 +538,7 @@ msgstr "字段 {field_names} 必须能构成唯一集合。" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." -msgstr "" +msgstr "不允许使用代理字符: U+{code_point:X}。" #: validators.py:243 #, python-brace-format diff --git a/rest_framework/metadata.py b/rest_framework/metadata.py index 7708fe0a21..364ca5b14d 100644 --- a/rest_framework/metadata.py +++ b/rest_framework/metadata.py @@ -6,8 +6,6 @@ Future implementations might use JSON schema or other definitions in order to return this information in a more standardized way. """ -from collections import OrderedDict - from django.core.exceptions import PermissionDenied from django.http import Http404 from django.utils.encoding import force_str @@ -48,6 +46,7 @@ class SimpleMetadata(BaseMetadata): serializers.DateField: 'date', serializers.DateTimeField: 'datetime', serializers.TimeField: 'time', + serializers.DurationField: 'duration', serializers.ChoiceField: 'choice', serializers.MultipleChoiceField: 'multiple choice', serializers.FileField: 'file upload', @@ -58,11 +57,12 @@ class SimpleMetadata(BaseMetadata): }) 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] + metadata = { + "name": view.get_view_name(), + "description": view.get_view_description(), + "renders": [renderer.media_type for renderer in view.renderer_classes], + "parses": [parser.media_type for parser in view.parser_classes], + } if hasattr(view, 'get_serializer'): actions = self.determine_actions(request, view) if actions: @@ -105,25 +105,27 @@ def get_serializer_info(self, serializer): # 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)) + return { + field_name: self.get_field_info(field) for field_name, field in serializer.fields.items() if not isinstance(field, serializers.HiddenField) - ]) + } 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) + field_info = { + "type": self.label_lookup[field], + "required": getattr(field, "required", False), + } attrs = [ 'read_only', 'label', 'help_text', 'min_length', 'max_length', - 'min_value', 'max_value' + 'min_value', 'max_value', + 'max_digits', 'decimal_places' ] for attr in attrs: diff --git a/rest_framework/negotiation.py b/rest_framework/negotiation.py index b4bbfa1f54..23012f71fd 100644 --- a/rest_framework/negotiation.py +++ b/rest_framework/negotiation.py @@ -65,7 +65,7 @@ def select_renderer(self, request, renderers, format_suffix=None): full_media_type = ';'.join( (renderer.media_type,) + tuple( - '{}={}'.format(key, value) + f'{key}={value}' for key, value in media_type_wrapper.params.items() ) ) diff --git a/rest_framework/pagination.py b/rest_framework/pagination.py index e815d8d5cf..a543ceeb50 100644 --- a/rest_framework/pagination.py +++ b/rest_framework/pagination.py @@ -2,8 +2,11 @@ Pagination serializers determine the structure of the output that should be used for paginated responses. """ + +import contextlib +import warnings from base64 import b64decode, b64encode -from collections import OrderedDict, namedtuple +from collections import namedtuple from urllib import parse from django.core.paginator import InvalidPage @@ -12,6 +15,7 @@ from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ +from rest_framework import RemovedInDRF317Warning from rest_framework.compat import coreapi, coreschema from rest_framework.exceptions import NotFound from rest_framework.response import Response @@ -149,6 +153,8 @@ def get_results(self, data): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) return [] def get_schema_operation_parameters(self, view): @@ -193,6 +199,7 @@ def paginate_queryset(self, queryset, request, view=None): Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. """ + self.request = request page_size = self.get_page_size(request) if not page_size: return None @@ -212,26 +219,26 @@ def paginate_queryset(self, queryset, request, view=None): # The browsable API should display pagination controls. self.display_page_controls = True - self.request = request return list(self.page) def get_page_number(self, request, paginator): - page_number = request.query_params.get(self.page_query_param, 1) + page_number = request.query_params.get(self.page_query_param) or 1 if page_number in self.last_page_strings: page_number = paginator.num_pages return page_number def get_paginated_response(self, data): - return Response(OrderedDict([ - ('count', self.page.paginator.count), - ('next', self.get_next_link()), - ('previous', self.get_previous_link()), - ('results', data) - ])) + return Response({ + 'count': self.page.paginator.count, + 'next': self.get_next_link(), + 'previous': self.get_previous_link(), + 'results': data, + }) def get_paginated_response_schema(self, schema): return { 'type': 'object', + 'required': ['count', 'results'], 'properties': { 'count': { 'type': 'integer', @@ -257,15 +264,12 @@ def get_paginated_response_schema(self, schema): def get_page_size(self, request): if self.page_size_query_param: - try: + with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) - except (KeyError, ValueError): - pass - return self.page_size def get_next_link(self): @@ -311,6 +315,8 @@ def to_html(self): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' fields = [ coreapi.Field( @@ -380,13 +386,13 @@ class LimitOffsetPagination(BasePagination): template = 'rest_framework/pagination/numbers.html' def paginate_queryset(self, queryset, request, view=None): + self.request = request self.limit = self.get_limit(request) if self.limit is None: return None self.count = self.get_count(queryset) self.offset = self.get_offset(request) - self.request = request if self.count > self.limit and self.template is not None: self.display_page_controls = True @@ -395,16 +401,17 @@ def paginate_queryset(self, queryset, request, view=None): return list(queryset[self.offset:self.offset + self.limit]) def get_paginated_response(self, data): - return Response(OrderedDict([ - ('count', self.count), - ('next', self.get_next_link()), - ('previous', self.get_previous_link()), - ('results', data) - ])) + return Response({ + 'count': self.count, + 'next': self.get_next_link(), + 'previous': self.get_previous_link(), + 'results': data + }) def get_paginated_response_schema(self, schema): return { 'type': 'object', + 'required': ['count', 'results'], 'properties': { 'count': { 'type': 'integer', @@ -430,15 +437,12 @@ def get_paginated_response_schema(self, schema): def get_limit(self, request): if self.limit_query_param: - try: + with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.limit_query_param], strict=True, cutoff=self.max_limit ) - except (KeyError, ValueError): - pass - return self.default_limit def get_offset(self, request): @@ -528,6 +532,8 @@ def get_count(self, queryset): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' return [ coreapi.Field( @@ -603,6 +609,7 @@ class CursorPagination(BasePagination): offset_cutoff = 1000 def paginate_queryset(self, queryset, request, view=None): + self.request = request self.page_size = self.get_page_size(request) if not self.page_size: return None @@ -680,15 +687,12 @@ def paginate_queryset(self, queryset, request, view=None): def get_page_size(self, request): if self.page_size_query_param: - try: + with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) - except (KeyError, ValueError): - pass - return self.page_size def get_next_link(self): @@ -801,6 +805,10 @@ def get_ordering(self, request, queryset, view): """ Return a tuple of strings, that may be used in an `order_by` method. """ + # The default case is to check for an `ordering` attribute + # on this pagination instance. + ordering = self.ordering + ordering_filters = [ filter_cls for filter_cls in getattr(view, 'filter_backends', []) if hasattr(filter_cls, 'get_ordering') @@ -811,26 +819,19 @@ def get_ordering(self, request, queryset, view): # then we defer to that filter to determine the ordering. filter_cls = ordering_filters[0] filter_instance = filter_cls() - ordering = filter_instance.get_ordering(request, queryset, view) - assert ordering is not None, ( - 'Using cursor pagination, but filter class {filter_cls} ' - 'returned a `None` ordering.'.format( - filter_cls=filter_cls.__name__ - ) - ) - else: - # The default case is to check for an `ordering` attribute - # on this pagination instance. - ordering = self.ordering - assert ordering is not None, ( - 'Using cursor pagination, but no ordering attribute was declared ' - 'on the pagination class.' - ) - assert '__' not in ordering, ( - 'Cursor pagination does not support double underscore lookups ' - 'for orderings. Orderings should be an unchanging, unique or ' - 'nearly-unique field on the model, such as "-created" or "pk".' - ) + ordering_from_filter = filter_instance.get_ordering(request, queryset, view) + if ordering_from_filter: + ordering = ordering_from_filter + + assert ordering is not None, ( + 'Using cursor pagination, but no ordering attribute was declared ' + 'on the pagination class.' + ) + assert '__' not in ordering, ( + 'Cursor pagination does not support double underscore lookups ' + 'for orderings. Orderings should be an unchanging, unique or ' + 'nearly-unique field on the model, such as "-created" or "pk".' + ) assert isinstance(ordering, (str, list, tuple)), ( 'Invalid ordering. Expected string or tuple, but got {type}'.format( @@ -892,23 +893,30 @@ def _get_position_from_instance(self, instance, ordering): return str(attr) def get_paginated_response(self, data): - return Response(OrderedDict([ - ('next', self.get_next_link()), - ('previous', self.get_previous_link()), - ('results', data) - ])) + return Response({ + 'next': self.get_next_link(), + 'previous': self.get_previous_link(), + 'results': data, + }) def get_paginated_response_schema(self, schema): return { 'type': 'object', + 'required': ['results'], 'properties': { 'next': { 'type': 'string', 'nullable': True, + 'format': 'uri', + 'example': 'http://api.example.org/accounts/?{cursor_query_param}=cD00ODY%3D"'.format( + cursor_query_param=self.cursor_query_param) }, 'previous': { 'type': 'string', 'nullable': True, + 'format': 'uri', + 'example': 'http://api.example.org/accounts/?{cursor_query_param}=cj0xJnA9NDg3'.format( + cursor_query_param=self.cursor_query_param) }, 'results': schema, }, @@ -927,6 +935,8 @@ def to_html(self): def get_schema_fields(self, view): assert coreapi is not None, 'coreapi must be installed to use `get_schema_fields()`' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert coreschema is not None, 'coreschema must be installed to use `get_schema_fields()`' fields = [ coreapi.Field( diff --git a/rest_framework/parsers.py b/rest_framework/parsers.py index 4ee8e578b8..0e8e4bcb8d 100644 --- a/rest_framework/parsers.py +++ b/rest_framework/parsers.py @@ -4,7 +4,9 @@ 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. """ + import codecs +import contextlib from django.conf import settings from django.core.files.uploadhandler import StopFutureHandlers @@ -13,9 +15,9 @@ from django.http.multipartparser import \ MultiPartParser as DjangoMultiPartParser from django.http.multipartparser import MultiPartParserError +from django.utils.http import parse_header_parameters from rest_framework import renderers -from rest_framework.compat import parse_header_parameters from rest_framework.exceptions import ParseError from rest_framework.settings import api_settings from rest_framework.utils import json @@ -193,17 +195,12 @@ def get_filename(self, stream, media_type, parser_context): Detects the uploaded file name. First searches a 'filename' url kwarg. Then tries to parse Content-Disposition header. """ - try: + with contextlib.suppress(KeyError): return parser_context['kwargs']['filename'] - except KeyError: - pass - try: + with contextlib.suppress(AttributeError, KeyError, ValueError): meta = parser_context['request'].META disposition, params = parse_header_parameters(meta['HTTP_CONTENT_DISPOSITION']) if 'filename*' in params: return params['filename*'] - else: - return params['filename'] - except (AttributeError, KeyError, ValueError): - pass + return params['filename'] diff --git a/rest_framework/permissions.py b/rest_framework/permissions.py index 16459b251f..768f6cb957 100644 --- a/rest_framework/permissions.py +++ b/rest_framework/permissions.py @@ -46,6 +46,17 @@ def __call__(self, *args, **kwargs): op2 = self.op2_class(*args, **kwargs) return self.operator_class(op1, op2) + def __eq__(self, other): + return ( + isinstance(other, OperandHolder) and + self.operator_class == other.operator_class and + self.op1_class == other.op1_class and + self.op2_class == other.op2_class + ) + + def __hash__(self): + return hash((self.operator_class, self.op1_class, self.op2_class)) + class AND: def __init__(self, op1, op2): @@ -214,21 +225,21 @@ def _queryset(self, view): if hasattr(view, 'get_queryset'): queryset = view.get_queryset() assert queryset is not None, ( - '{}.get_queryset() returned None'.format(view.__class__.__name__) + f'{view.__class__.__name__}.get_queryset() returned None' ) return queryset return view.queryset def has_permission(self, request, view): + if not request.user or ( + not request.user.is_authenticated and self.authenticated_users_only): + return False + # Workaround to ensure DjangoModelPermissions are not applied # to the root view when using DefaultRouter. if getattr(view, '_ignore_model_permissions', False): return True - if not request.user or ( - not request.user.is_authenticated and self.authenticated_users_only): - return False - queryset = self._queryset(view) perms = self.get_required_permissions(request.method, queryset.model) diff --git a/rest_framework/relations.py b/rest_framework/relations.py index bdedd43b86..4409bce77c 100644 --- a/rest_framework/relations.py +++ b/rest_framework/relations.py @@ -1,5 +1,6 @@ +import contextlib import sys -from collections import OrderedDict +from operator import attrgetter from urllib import parse from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist @@ -70,6 +71,7 @@ class PKOnlyObject: 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 @@ -170,7 +172,7 @@ def use_pk_only_optimization(self): def get_attribute(self, instance): if self.use_pk_only_optimization() and self.source_attrs: # Optimized case, return a mock object only containing the pk attribute. - try: + with contextlib.suppress(AttributeError): attribute_instance = get_attribute(instance, self.source_attrs[:-1]) value = attribute_instance.serializable_value(self.source_attrs[-1]) if is_simple_callable(value): @@ -183,9 +185,6 @@ def get_attribute(self, instance): value = getattr(value, 'pk', value) return PKOnlyObject(pk=value) - except AttributeError: - pass - # Standard case, return the object instance. return super().get_attribute(instance) @@ -199,13 +198,9 @@ def get_choices(self, cutoff=None): if cutoff is not None: queryset = queryset[:cutoff] - return OrderedDict([ - ( - self.to_representation(item), - self.display_value(item) - ) - for item in queryset - ]) + return { + self.to_representation(item): self.display_value(item) for item in queryset + } @property def choices(self): @@ -466,7 +461,11 @@ def to_internal_value(self, data): self.fail('invalid') def to_representation(self, obj): - return getattr(obj, self.slug_field) + slug = self.slug_field + if "__" in slug: + # handling nested relationship if defined + slug = slug.replace('__', '.') + return attrgetter(slug)(obj) class ManyRelatedField(Field): diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index b74df9a0bb..b81f9ab46c 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -6,8 +6,10 @@ REST framework also provides an HTML renderer that renders the browsable API. """ + import base64 -from collections import OrderedDict +import contextlib +import datetime from urllib import parse from django import forms @@ -17,11 +19,13 @@ from django.template import engines, loader from django.urls import NoReverseMatch from django.utils.html import mark_safe +from django.utils.http import parse_header_parameters +from django.utils.safestring import SafeString from rest_framework import VERSION, exceptions, serializers, status from rest_framework.compat import ( INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS, coreapi, coreschema, - parse_header_parameters, pygments_css, yaml + pygments_css, yaml ) from rest_framework.exceptions import ParseError from rest_framework.request import is_form_media_type, override_method @@ -72,11 +76,8 @@ def get_indent(self, accepted_media_type, renderer_context): # then pretty print the result. # Note that we coerce `indent=0` into `indent=None`. base_media_type, params = parse_header_parameters(accepted_media_type) - try: + with contextlib.suppress(KeyError, ValueError, TypeError): return zero_as_none(max(min(int(params['indent']), 8), 0)) - except (KeyError, ValueError, TypeError): - pass - # If 'indent' is provided in the context, then pretty print the result. # E.g. If we're being called by the BrowsableAPIRenderer. return renderer_context.get('indent', None) @@ -170,6 +171,10 @@ def resolve_template(self, template_names): def get_template_context(self, data, renderer_context): response = renderer_context['response'] + # in case a ValidationError is caught the data parameter may be a list + # see rest_framework.views.exception_handler + if isinstance(data, list): + return {'details': data, 'status_code': response.status_code} if response.exception: data['status_code'] = response.status_code return data @@ -488,11 +493,8 @@ def get_rendered_html_form(self, data, view, method, request): return if existing_serializer is not None: - try: + with contextlib.suppress(TypeError): return self.render_form_for_serializer(existing_serializer) - except TypeError: - pass - if has_serializer: if method in ('PUT', 'PATCH'): serializer = view.get_serializer(instance=instance, **kwargs) @@ -510,6 +512,9 @@ def get_rendered_html_form(self, data, view, method, request): return self.render_form_for_serializer(serializer) def render_form_for_serializer(self, serializer): + if isinstance(serializer, serializers.ListSerializer): + return None + if hasattr(serializer, 'initial_data'): serializer.is_valid() @@ -559,10 +564,13 @@ def get_raw_data_form(self, data, view, method, request): context['indent'] = 4 # strip HiddenField from output + is_list_serializer = isinstance(serializer, serializers.ListSerializer) + serializer = serializer.child if is_list_serializer else serializer data = serializer.data.copy() for name, field in serializer.fields.items(): if isinstance(field, serializers.HiddenField): data.pop(name, None) + data = [data] if is_list_serializer else data content = renderer.render(data, accepted, context) # Renders returns bytes, but CharField expects a str. content = content.decode() @@ -656,7 +664,7 @@ def get_context(self, data, accepted_media_type, renderer_context): 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 = OrderedDict(sorted(response.items())) + response_headers = dict(sorted(response.items())) renderer_content_type = '' if renderer: renderer_content_type = '%s' % renderer.media_type @@ -1059,6 +1067,8 @@ def render(self, data, media_type=None, renderer_context=None): class Dumper(yaml.Dumper): def ignore_aliases(self, data): return True + Dumper.add_representer(SafeString, Dumper.represent_str) + Dumper.add_representer(datetime.timedelta, encoders.CustomScalar.represent_timedelta) return yaml.dump(data, default_flow_style=False, sort_keys=False, Dumper=Dumper).encode('utf-8') diff --git a/rest_framework/request.py b/rest_framework/request.py index 93634e667d..1527e435b3 100644 --- a/rest_framework/request.py +++ b/rest_framework/request.py @@ -16,9 +16,9 @@ from django.http import HttpRequest, QueryDict from django.http.request import RawPostDataException from django.utils.datastructures import MultiValueDict +from django.utils.http import parse_header_parameters from rest_framework import exceptions -from rest_framework.compat import parse_header_parameters from rest_framework.settings import api_settings @@ -186,6 +186,10 @@ def __repr__(self): self.method, self.get_full_path()) + # Allow generic typing checking for requests. + def __class_getitem__(cls, *args, **kwargs): + return cls + def _default_negotiator(self): return api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS() @@ -213,7 +217,8 @@ def query_params(self): @property def data(self): if not _hasattr(self, '_full_data'): - self._load_data_and_files() + with wrap_attributeerrors(): + self._load_data_and_files() return self._full_data @property @@ -413,22 +418,17 @@ def __getattr__(self, attr): to proxy it to the underlying HttpRequest object. """ try: - return getattr(self._request, attr) + _request = self.__getattribute__("_request") + return getattr(_request, attr) except AttributeError: - return self.__getattribute__(attr) - - @property - def DATA(self): - raise NotImplementedError( - '`request.DATA` has been deprecated in favor of `request.data` ' - 'since version 3.0, and has been fully removed as of version 3.2.' - ) + raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{attr}'") @property def POST(self): # Ensure that request.POST uses our request parsing. if not _hasattr(self, '_data'): - self._load_data_and_files() + with wrap_attributeerrors(): + self._load_data_and_files() if is_form_media_type(self.content_type): return self._data return QueryDict('', encoding=self._request._encoding) @@ -439,16 +439,10 @@ def FILES(self): # Different from the other two cases, which are not valid property # names on the WSGIRequest class. if not _hasattr(self, '_files'): - self._load_data_and_files() + with wrap_attributeerrors(): + self._load_data_and_files() return self._files - @property - def QUERY_PARAMS(self): - raise NotImplementedError( - '`request.QUERY_PARAMS` has been deprecated in favor of `request.query_params` ' - 'since version 3.0, and has been fully removed as of version 3.2.' - ) - def force_plaintext_errors(self, value): # Hack to allow our exception handler to force choice of # plaintext or html error responses. diff --git a/rest_framework/response.py b/rest_framework/response.py index 4954237347..507ea595f6 100644 --- a/rest_framework/response.py +++ b/rest_framework/response.py @@ -46,6 +46,10 @@ def __init__(self, data=None, status=None, for name, value in headers.items(): self[name] = value + # Allow generic typing checking for responses. + def __class_getitem__(cls, *args, **kwargs): + return cls + @property def rendered_content(self): renderer = getattr(self, 'accepted_renderer', None) @@ -62,7 +66,7 @@ def rendered_content(self): content_type = self.content_type if content_type is None and charset is not None: - content_type = "{}; charset={}".format(media_type, charset) + content_type = f"{media_type}; charset={charset}" elif content_type is None: content_type = media_type self['Content-Type'] = content_type diff --git a/rest_framework/routers.py b/rest_framework/routers.py index e0ae24b95c..2b9478e905 100644 --- a/rest_framework/routers.py +++ b/rest_framework/routers.py @@ -14,10 +14,10 @@ urlpatterns = router.urls """ import itertools -from collections import OrderedDict, namedtuple +from collections import namedtuple from django.core.exceptions import ImproperlyConfigured -from django.urls import NoReverseMatch, re_path +from django.urls import NoReverseMatch, path, re_path from rest_framework import views from rest_framework.response import Response @@ -52,12 +52,24 @@ def __init__(self): def register(self, prefix, viewset, basename=None): if basename is None: basename = self.get_default_basename(viewset) + + if self.is_already_registered(basename): + msg = (f'Router with basename "{basename}" is already registered. ' + f'Please provide a unique basename for viewset "{viewset}"') + raise ImproperlyConfigured(msg) + self.registry.append((prefix, viewset, basename)) # invalidate the urls cache if hasattr(self, '_urls'): del self._urls + def is_already_registered(self, new_basename): + """ + Check if `basename` is already registered + """ + return any(basename == new_basename for _prefix, _viewset, basename in self.registry) + def get_default_basename(self, viewset): """ If `basename` is not specified, attempt to automatically determine @@ -123,8 +135,29 @@ class SimpleRouter(BaseRouter): ), ] - def __init__(self, trailing_slash=True): + def __init__(self, trailing_slash=True, use_regex_path=True): self.trailing_slash = '/' if trailing_slash else '' + self._use_regex = use_regex_path + if use_regex_path: + self._base_pattern = '(?P<{lookup_prefix}{lookup_url_kwarg}>{lookup_value})' + self._default_value_pattern = '[^/.]+' + self._url_conf = re_path + else: + self._base_pattern = '<{lookup_value}:{lookup_prefix}{lookup_url_kwarg}>' + self._default_value_pattern = 'str' + self._url_conf = path + # remove regex characters from routes + _routes = [] + for route in self.routes: + url_param = route.url + if url_param[0] == '^': + url_param = url_param[1:] + if url_param[-1] == '$': + url_param = url_param[:-1] + + _routes.append(route._replace(url=url_param)) + self.routes = _routes + super().__init__() def get_default_basename(self, viewset): @@ -213,13 +246,18 @@ def get_lookup_regex(self, viewset, lookup_prefix=''): https://github.com/alanjds/drf-nested-routers """ - base_regex = '(?P<{lookup_prefix}{lookup_url_kwarg}>{lookup_value})' # Use `pk` as default field, unset set. Default regex should not # consume `.json` style suffixes and should break at '/' boundaries. lookup_field = getattr(viewset, 'lookup_field', 'pk') lookup_url_kwarg = getattr(viewset, 'lookup_url_kwarg', None) or lookup_field - lookup_value = getattr(viewset, 'lookup_value_regex', '[^/.]+') - return base_regex.format( + lookup_value = None + if not self._use_regex: + # try to get a more appropriate attribute when not using regex + lookup_value = getattr(viewset, 'lookup_value_converter', None) + if lookup_value is None: + # fallback to legacy + lookup_value = getattr(viewset, 'lookup_value_regex', self._default_value_pattern) + return self._base_pattern.format( lookup_prefix=lookup_prefix, lookup_url_kwarg=lookup_url_kwarg, lookup_value=lookup_value @@ -253,8 +291,12 @@ def get_urls(self): # controlled by project's urls.py and the router is in an app, # so a slash in the beginning will (A) cause Django to give # warnings and (B) generate URLS that will require using '//'. - if not prefix and regex[:2] == '^/': - regex = '^' + regex[2:] + if not prefix: + if self._url_conf is path: + if regex[0] == '/': + regex = regex[1:] + elif regex[:2] == '^/': + regex = '^' + regex[2:] initkwargs = route.initkwargs.copy() initkwargs.update({ @@ -264,7 +306,7 @@ def get_urls(self): view = viewset.as_view(mapping, **initkwargs) name = route.name.format(basename=basename) - ret.append(re_path(regex, view, name=name)) + ret.append(self._url_conf(regex, view, name=name)) return ret @@ -279,7 +321,7 @@ class APIRootView(views.APIView): def get(self, request, *args, **kwargs): # Return a plain {"name": "hyperlink"} response. - ret = OrderedDict() + ret = {} namespace = request.resolver_match.namespace for key, url_name in self.api_root_dict.items(): if namespace: @@ -323,7 +365,7 @@ def get_api_root_view(self, api_urls=None): """ Return a basic root view. """ - api_root_dict = OrderedDict() + api_root_dict = {} list_name = self.routes[0].name for prefix, viewset, basename in self.registry: api_root_dict[prefix] = list_name.format(basename=basename) @@ -339,7 +381,7 @@ def get_urls(self): if self.include_root_view: view = self.get_api_root_view(api_urls=urls) - root_url = re_path(r'^$', view, name=self.root_view_name) + root_url = path('', view, name=self.root_view_name) urls.append(root_url) if self.include_format_suffixes: diff --git a/rest_framework/schemas/coreapi.py b/rest_framework/schemas/coreapi.py index 908518e9d7..657178304a 100644 --- a/rest_framework/schemas/coreapi.py +++ b/rest_framework/schemas/coreapi.py @@ -1,11 +1,11 @@ import warnings -from collections import Counter, OrderedDict +from collections import Counter from urllib import parse from django.db import models from django.utils.encoding import force_str -from rest_framework import exceptions, serializers +from rest_framework import RemovedInDRF317Warning, exceptions, serializers from rest_framework.compat import coreapi, coreschema, uritemplate from rest_framework.settings import api_settings @@ -54,7 +54,7 @@ def distribute_links(obj): """ -class LinkNode(OrderedDict): +class LinkNode(dict): def __init__(self): self.links = [] self.methods_counter = Counter() @@ -68,7 +68,7 @@ def get_available_key(self, preferred_key): current_val = self.methods_counter[preferred_key] self.methods_counter[preferred_key] += 1 - key = '{}_{}'.format(preferred_key, current_val) + key = f'{preferred_key}_{current_val}' if key not in self: return key @@ -118,6 +118,8 @@ class SchemaGenerator(BaseSchemaGenerator): def __init__(self, title=None, url=None, description=None, patterns=None, urlconf=None, version=None): assert coreapi, '`coreapi` must be installed for schema support.' + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) assert coreschema, '`coreschema` must be installed for schema support.' super().__init__(title, url, description, patterns, urlconf) @@ -268,11 +270,11 @@ def field_to_schema(field): ) elif isinstance(field, serializers.Serializer): return coreschema.Object( - properties=OrderedDict([ - (key, field_to_schema(value)) + properties={ + key: field_to_schema(value) for key, value in field.fields.items() - ]), + }, title=title, description=description ) @@ -351,6 +353,9 @@ def __init__(self, manual_fields=None): will be added to auto-generated fields, overwriting on `Field.name` """ super().__init__() + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + if manual_fields is None: manual_fields = [] self._manual_fields = manual_fields @@ -549,7 +554,7 @@ def update_fields(fields, update_with): if not update_with: return fields - by_name = OrderedDict((f.name, f) for f in fields) + by_name = {f.name: f for f in fields} for f in update_with: by_name[f.name] = f fields = list(by_name.values()) @@ -592,6 +597,9 @@ def __init__(self, fields, description='', encoding=None): * `description`: String description for view. Optional. """ super().__init__() + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) + assert all(isinstance(f, coreapi.Field) for f in fields), "`fields` must be a list of coreapi.Field instances" self._fields = fields self._description = description @@ -613,4 +621,6 @@ def get_link(self, path, method, base_url): def is_enabled(): """Is CoreAPI Mode enabled?""" + if coreapi is not None: + warnings.warn('CoreAPI compatibility is deprecated and will be removed in DRF 3.17', RemovedInDRF317Warning) return issubclass(api_settings.DEFAULT_SCHEMA_CLASS, AutoSchema) diff --git a/rest_framework/schemas/generators.py b/rest_framework/schemas/generators.py index d3c6446aa4..f59e25c213 100644 --- a/rest_framework/schemas/generators.py +++ b/rest_framework/schemas/generators.py @@ -102,12 +102,12 @@ def get_path_from_regex(self, path_regex): Given a URL conf regex, return a URI template string. """ # ???: Would it be feasible to adjust this such that we generate the - # path, plus the kwargs, plus the type from the convertor, such that we + # path, plus the kwargs, plus the type from the converter, such that we # could feed that straight into the parameter schema object? path = simplify_regex(path_regex) - # Strip Django 2.0 convertors as they are incompatible with uritemplate format + # Strip Django 2.0 converters as they are incompatible with uritemplate format return re.sub(_PATH_PARAMETER_COMPONENT_RE, r'{\g}', path) def should_include_endpoint(self, path, callback): diff --git a/rest_framework/schemas/inspectors.py b/rest_framework/schemas/inspectors.py index 027472db14..e027b46a70 100644 --- a/rest_framework/schemas/inspectors.py +++ b/rest_framework/schemas/inspectors.py @@ -79,8 +79,9 @@ def get_description(self, path, method): view = self.view method_name = getattr(view, 'action', method.lower()) - method_docstring = getattr(view, method_name, None).__doc__ - if method_docstring: + method_func = getattr(view, method_name, None) + method_docstring = method_func.__doc__ + if method_func and method_docstring: # An explicit docstring on the method or action. return self._get_description_section(view, method.lower(), formatting.dedent(smart_str(method_docstring))) else: @@ -88,7 +89,7 @@ def get_description(self, path, method): view.get_view_description()) def _get_description_section(self, view, header, description): - lines = [line for line in description.splitlines()] + lines = description.splitlines() current_section = '' sections = {'': ''} diff --git a/rest_framework/schemas/openapi.py b/rest_framework/schemas/openapi.py index ee614fdf6e..eb7dc909d9 100644 --- a/rest_framework/schemas/openapi.py +++ b/rest_framework/schemas/openapi.py @@ -1,6 +1,5 @@ import re import warnings -from collections import OrderedDict from decimal import Decimal from operator import attrgetter from urllib.parse import urljoin @@ -12,10 +11,8 @@ from django.db import models from django.utils.encoding import force_str -from rest_framework import ( - RemovedInDRF315Warning, exceptions, renderers, serializers -) -from rest_framework.compat import uritemplate +from rest_framework import exceptions, renderers, serializers +from rest_framework.compat import inflection, uritemplate from rest_framework.fields import _UnvalidatedField, empty from rest_framework.settings import api_settings @@ -85,7 +82,7 @@ def get_schema(self, request=None, public=False): continue if components_schemas[k] == components[k]: continue - warnings.warn('Schema component "{}" has been overriden with a different value.'.format(k)) + warnings.warn(f'Schema component "{k}" has been overridden with a different value.') components_schemas.update(components) @@ -247,8 +244,9 @@ def get_operation_id_base(self, path, method, action): if name.endswith(action.title()): # ListView, UpdateAPIView, ThingDelete ... name = name[:-len(action)] - if action == 'list' and not name.endswith('s'): # listThings instead of listThing - name += 's' + if action == 'list': + assert inflection, '`inflection` must be installed for OpenAPI schema support.' + name = inflection.pluralize(name) return name @@ -338,7 +336,7 @@ def get_pagination_parameters(self, path, method): return paginator.get_schema_operation_parameters(view) def map_choicefield(self, field): - choices = list(OrderedDict.fromkeys(field.choices)) # preserve order and remove duplicates + choices = list(dict.fromkeys(field.choices)) # preserve order and remove duplicates if all(isinstance(choice, bool) for choice in choices): type = 'boolean' elif all(isinstance(choice, int) for choice in choices): @@ -385,6 +383,8 @@ def map_field(self, field): 'items': self.map_field(field.child_relation) } if isinstance(field, serializers.PrimaryKeyRelatedField): + if getattr(field, "pk_field", False): + return self.map_field(field=field.pk_field) model = getattr(field.queryset, 'model', None) if model is not None: model_field = model._meta.pk @@ -522,8 +522,8 @@ def map_serializer(self, serializer): if isinstance(field, serializers.HiddenField): continue - if field.required: - required.append(field.field_name) + if field.required and not serializer.partial: + required.append(self.get_field_name(field)) schema = self.map_field(field) if field.read_only: @@ -538,7 +538,7 @@ def map_serializer(self, serializer): schema['description'] = str(field.help_text) self.map_field_validators(field, schema) - properties[field.field_name] = schema + properties[self.get_field_name(field)] = schema result = { 'type': 'object', @@ -589,6 +589,13 @@ def map_field_validators(self, field, schema): schema['maximum'] = int(digits * '9') + 1 schema['minimum'] = -schema['maximum'] + def get_field_name(self, field): + """ + Override this method if you want to change schema field name. + For example, convert snake_case field name to camelCase. + """ + return field.field_name + def get_paginator(self): pagination_class = getattr(self.view, 'pagination_class', None) if pagination_class: @@ -637,7 +644,7 @@ def get_response_serializer(self, path, method): return self.get_serializer(path, method) def get_reference(self, serializer): - return {'$ref': '#/components/schemas/{}'.format(self.get_component_name(serializer))} + return {'$ref': f'#/components/schemas/{self.get_component_name(serializer)}'} def get_request_body(self, path, method): if method not in ('PUT', 'PATCH', 'POST'): @@ -712,11 +719,3 @@ def get_tags(self, path, method): path = path[1:] return [path.split('/')[0].replace('_', '-')] - - def _get_reference(self, serializer): - warnings.warn( - "Method `_get_reference()` has been renamed to `get_reference()`. " - "The old name will be removed in DRF v3.15.", - RemovedInDRF315Warning, stacklevel=2 - ) - return self.get_reference(serializer) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index 083910174b..0b87aa8fc1 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -10,10 +10,12 @@ 2. The process of marshalling between python primitives and request and response content is handled by parsers and renderers. """ + +import contextlib import copy import inspect import traceback -from collections import OrderedDict, defaultdict +from collections import defaultdict from collections.abc import Mapping from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured @@ -24,9 +26,11 @@ from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ -from rest_framework.compat import postgres_fields +from rest_framework.compat import ( + get_referenced_base_fields_from_q, postgres_fields +) from rest_framework.exceptions import ErrorDetail, ValidationError -from rest_framework.fields import get_error_detail, set_value +from rest_framework.fields import get_error_detail from rest_framework.settings import api_settings from rest_framework.utils import html, model_meta, representation from rest_framework.utils.field_mapping import ( @@ -74,6 +78,7 @@ 'instance', 'data', 'partial', 'context', 'allow_null', 'max_length', 'min_length' ) +LIST_SERIALIZER_KWARGS_REMOVE = ('allow_empty', 'min_length', 'max_length') ALL_FIELDS = '__all__' @@ -143,19 +148,12 @@ def many_init(cls, *args, **kwargs): kwargs['child'] = cls() return CustomListSerializer(*args, **kwargs) """ - allow_empty = kwargs.pop('allow_empty', None) - max_length = kwargs.pop('max_length', None) - min_length = kwargs.pop('min_length', None) - child_serializer = cls(*args, **kwargs) - list_kwargs = { - 'child': child_serializer, - } - if allow_empty is not None: - list_kwargs['allow_empty'] = allow_empty - if max_length is not None: - list_kwargs['max_length'] = max_length - if min_length is not None: - list_kwargs['min_length'] = min_length + list_kwargs = {} + for key in LIST_SERIALIZER_KWARGS_REMOVE: + value = kwargs.pop(key, None) + if value is not None: + list_kwargs[key] = value + list_kwargs['child'] = cls(*args, **kwargs) list_kwargs.update({ key: value for key, value in kwargs.items() if key in LIST_SERIALIZER_KWARGS @@ -306,7 +304,7 @@ def visit(name): for name, f in base._declared_fields.items() if name not in known ] - return OrderedDict(base_fields + fields) + return dict(base_fields + fields) def __new__(cls, name, bases, attrs): attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs) @@ -344,6 +342,26 @@ class Serializer(BaseSerializer, metaclass=SerializerMetaclass): 'invalid': _('Invalid data. Expected a dictionary, but got {datatype}.') } + def set_value(self, dictionary, keys, value): + """ + Similar to Python's built in `dictionary[key] = value`, + but takes a list of nested keys instead of a single key. + + set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2} + set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2} + set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}} + """ + if not keys: + dictionary.update(value) + return + + for key in keys[:-1]: + if key not in dictionary: + dictionary[key] = {} + dictionary = dictionary[key] + + dictionary[keys[-1]] = value + @cached_property def fields(self): """ @@ -391,20 +409,20 @@ def get_initial(self): if hasattr(self, 'initial_data'): # initial_data may not be a valid type if not isinstance(self.initial_data, Mapping): - return OrderedDict() + return {} - return OrderedDict([ - (field_name, field.get_value(self.initial_data)) + return { + 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()) + return { + field.field_name: field.get_initial() for field in self.fields.values() if not field.read_only - ]) + } def get_value(self, dictionary): # We override the default field access in order to support @@ -439,7 +457,7 @@ def _read_only_defaults(self): if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source) ] - defaults = OrderedDict() + defaults = {} for field in fields: try: default = field.get_default() @@ -472,8 +490,8 @@ def to_internal_value(self, data): api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='invalid') - ret = OrderedDict() - errors = OrderedDict() + ret = {} + errors = {} fields = self._writable_fields for field in fields: @@ -490,7 +508,7 @@ def to_internal_value(self, data): except SkipField: pass else: - set_value(ret, field.source_attrs, validated_value) + self.set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) @@ -501,7 +519,7 @@ def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ - ret = OrderedDict() + ret = {} fields = self._readable_fields for field in fields: @@ -625,6 +643,17 @@ def run_validation(self, data=empty): return value + def run_child_validation(self, data): + """ + Run validation on child serializer. + You may need to override this method to support multiple updates. For example: + + self.child.instance = self.instance.get(pk=data['id']) + self.child.initial_data = data + return super().run_child_validation(data) + """ + return self.child.run_validation(data) + def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. @@ -663,7 +692,7 @@ def to_internal_value(self, data): for item in data: try: - validated = self.child.run_validation(item) + validated = self.run_child_validation(item) except ValidationError as exc: errors.append(exc.detail) else: @@ -681,7 +710,7 @@ def to_representation(self, data): """ # Dealing with nested relationships, data can be a Manager, # so, first get a queryset from the Manager if needed - iterable = data.all() if isinstance(data, models.Manager) else data + iterable = data.all() if isinstance(data, models.manager.BaseManager) else data return [ self.child.to_representation(item) for item in iterable @@ -1059,7 +1088,7 @@ def get_fields(self): ) # Determine the fields that should be included on the serializer. - fields = OrderedDict() + fields = {} for field_name in field_names: # If the field is explicitly declared on the class then use that. @@ -1338,8 +1367,8 @@ def build_unknown_field(self, field_name, model_class): Raise an error on any unknown fields. """ raise ImproperlyConfigured( - 'Field name `%s` is not valid for model `%s`.' % - (field_name, model_class.__name__) + 'Field name `%s` is not valid for model `%s` in `%s.%s`.' % + (field_name, model_class.__name__, self.__class__.__module__, self.__class__.__name__) ) def include_extra_kwargs(self, kwargs, extra_kwargs): @@ -1396,6 +1425,23 @@ def get_extra_kwargs(self): return extra_kwargs + def get_unique_together_constraints(self, model): + """ + Returns iterator of (fields, queryset, condition_fields, condition), + each entry describes an unique together constraint on `fields` in `queryset` + with respect of constraint's `condition`. + """ + for parent_class in [model] + list(model._meta.parents): + for unique_together in parent_class._meta.unique_together: + yield unique_together, model._default_manager, [], None + for constraint in parent_class._meta.constraints: + if isinstance(constraint, models.UniqueConstraint) and len(constraint.fields) > 1: + if constraint.condition is None: + condition_fields = [] + else: + condition_fields = list(get_referenced_base_fields_from_q(constraint.condition)) + yield (constraint.fields, model._default_manager, condition_fields, constraint.condition) + def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs): """ Return any additional field options that need to be included as a @@ -1424,12 +1470,12 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs unique_constraint_names -= {None} - # Include each of the `unique_together` field names, + # Include each of the `unique_together` and `UniqueConstraint` field names, # so long as all the field names are included on the serializer. - for parent_class in [model] + list(model._meta.parents): - for unique_together_list in parent_class._meta.unique_together: - if set(field_names).issuperset(unique_together_list): - unique_constraint_names |= set(unique_together_list) + for unique_together_list, queryset, condition_fields, condition in self.get_unique_together_constraints(model): + unique_together_list_and_condition_fields = set(unique_together_list) | set(condition_fields) + if set(field_names).issuperset(unique_together_list_and_condition_fields): + unique_constraint_names |= unique_together_list_and_condition_fields # Now we have all the field names that have uniqueness constraints # applied, we can add the extra 'required=...' or 'default=...' @@ -1447,6 +1493,8 @@ def get_uniqueness_extra_kwargs(self, field_names, declared_fields, extra_kwargs default = timezone.now elif unique_constraint_field.has_default(): default = unique_constraint_field.default + elif unique_constraint_field.null: + default = None else: default = empty @@ -1496,12 +1544,10 @@ def _get_model_fields(self, field_names, declared_fields, extra_kwargs): # they can't be nested attribute lookups. continue - try: + with contextlib.suppress(FieldDoesNotExist): field = model._meta.get_field(source) if isinstance(field, DjangoModelField): model_fields[source] = field - except FieldDoesNotExist: - pass return model_fields @@ -1526,25 +1572,20 @@ def get_unique_together_validators(self): """ Determine a default set of validators for any unique_together constraints. """ - model_class_inheritance_tree = ( - [self.Meta.model] + - list(self.Meta.model._meta.parents) - ) - # The field names we're passing though here only include fields # which may map onto a model field. Any dotted field name lookups # cannot map to a field, and must be a traversal, so we're not # including those. - field_sources = OrderedDict( - (field.field_name, field.source) for field in self._writable_fields + field_sources = { + field.field_name: field.source for field in self._writable_fields if (field.source != '*') and ('.' not in field.source) - ) + } # Special Case: Add read_only fields with defaults. - field_sources.update(OrderedDict( - (field.field_name, field.source) for field in self.fields.values() + field_sources.update({ + field.field_name: field.source for field in self.fields.values() if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source) - )) + }) # Invert so we can find the serializer field names that correspond to # the model field names in the unique_together sets. This also allows @@ -1556,34 +1597,36 @@ def get_unique_together_validators(self): # Note that we make sure to check `unique_together` both on the # base model class, but also on any parent classes. validators = [] - for parent_class in model_class_inheritance_tree: - for unique_together in parent_class._meta.unique_together: - # Skip if serializer does not map to all unique together sources - if not set(source_map).issuperset(unique_together): - continue - - for source in unique_together: - assert len(source_map[source]) == 1, ( - "Unable to create `UniqueTogetherValidator` for " - "`{model}.{field}` as `{serializer}` has multiple " - "fields ({fields}) that map to this model field. " - "Either remove the extra fields, or override " - "`Meta.validators` with a `UniqueTogetherValidator` " - "using the desired field names." - .format( - model=self.Meta.model.__name__, - serializer=self.__class__.__name__, - field=source, - fields=', '.join(source_map[source]), - ) - ) + for unique_together, queryset, condition_fields, condition in self.get_unique_together_constraints(self.Meta.model): + # Skip if serializer does not map to all unique together sources + unique_together_and_condition_fields = set(unique_together) | set(condition_fields) + if not set(source_map).issuperset(unique_together_and_condition_fields): + continue - field_names = tuple(source_map[f][0] for f in unique_together) - validator = UniqueTogetherValidator( - queryset=parent_class._default_manager, - fields=field_names + for source in unique_together_and_condition_fields: + assert len(source_map[source]) == 1, ( + "Unable to create `UniqueTogetherValidator` for " + "`{model}.{field}` as `{serializer}` has multiple " + "fields ({fields}) that map to this model field. " + "Either remove the extra fields, or override " + "`Meta.validators` with a `UniqueTogetherValidator` " + "using the desired field names." + .format( + model=self.Meta.model.__name__, + serializer=self.__class__.__name__, + field=source, + fields=', '.join(source_map[source]), + ) ) - validators.append(validator) + + field_names = tuple(source_map[f][0] for f in unique_together) + validator = UniqueTogetherValidator( + queryset=queryset, + fields=field_names, + condition_fields=tuple(source_map[f][0] for f in condition_fields), + condition=condition, + ) + validators.append(validator) return validators def get_unique_for_date_validators(self): diff --git a/rest_framework/settings.py b/rest_framework/settings.py index 9eb4c5653b..b0d7bacecc 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -19,7 +19,9 @@ back to the defaults. """ from django.conf import settings -from django.test.signals import setting_changed +# Import from `django.core.signals` instead of the official location +# `django.test.signals` to avoid importing the test module unnecessarily. +from django.core.signals import setting_changed from django.utils.module_loading import import_string from rest_framework import ISO_8601 @@ -114,7 +116,7 @@ 'COERCE_DECIMAL_TO_STRING': True, 'UPLOADED_FILES_USE_URL': True, - # Browseable API + # Browsable API 'HTML_SELECT_CUTOFF': 1000, 'HTML_SELECT_CUTOFF_TEXT': "More than {count} items...", diff --git a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css index c2fcb303d9..5c033be376 100644 --- a/rest_framework/static/rest_framework/css/bootstrap-tweaks.css +++ b/rest_framework/static/rest_framework/css/bootstrap-tweaks.css @@ -231,3 +231,7 @@ body a:hover { margin-left: 5px; margin-right: 5px; } + +.pagination { + margin: 5px 0 10px 0; +} diff --git a/rest_framework/static/rest_framework/js/ajax-form.js b/rest_framework/static/rest_framework/js/ajax-form.js index 1483305ff9..dda5454c2c 100644 --- a/rest_framework/static/rest_framework/js/ajax-form.js +++ b/rest_framework/static/rest_framework/js/ajax-form.js @@ -3,6 +3,12 @@ function replaceDocument(docString) { doc.write(docString); doc.close(); + + if (window.djdt) { + // If Django Debug Toolbar is available, reinitialize it so that + // it can show updated panels from new `docString`. + window.addEventListener("load", djdt.init); + } } function doAjaxSubmit(e) { diff --git a/rest_framework/static/rest_framework/js/csrf.js b/rest_framework/static/rest_framework/js/csrf.js index 6e4bf39a79..0d8444f279 100644 --- a/rest_framework/static/rest_framework/js/csrf.js +++ b/rest_framework/static/rest_framework/js/csrf.js @@ -38,6 +38,7 @@ function sameOrigin(url) { !(/^(\/\/|http:|https:).*/.test(url)); } +window.drf = JSON.parse(document.getElementById('drf_csrf').textContent); var csrftoken = window.drf.csrfToken; $.ajaxSetup({ diff --git a/rest_framework/static/rest_framework/js/jquery-3.5.1.min.js b/rest_framework/static/rest_framework/js/jquery-3.5.1.min.js deleted file mode 100644 index b0614034ad..0000000000 --- a/rest_framework/static/rest_framework/js/jquery-3.5.1.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/*! jQuery v3.5.1 | (c) JS Foundation and other contributors | jquery.org/license */ -!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,v=n.hasOwnProperty,a=v.toString,l=a.call(Object),y={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.5.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&y(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!v||!v.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ye(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace($,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ve(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ye(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e.namespaceURI,n=(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],v=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="",e.querySelectorAll("[msallowcapture^='']").length&&v.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||v.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||v.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||v.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||v.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||v.push(".#.+[+~]"),e.querySelectorAll("\\\f"),v.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&v.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&v.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&v.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),v.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),v=v.length&&new RegExp(v.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),y=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},D=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&y(p,e)?-1:t==C||t.ownerDocument==p&&y(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!v||!v.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function D(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||j,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,j=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),y.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="",y.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="",y.option=!!ce.lastChild;var ge={thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function ve(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ye(e,t){for(var n=0,r=e.length;n",""]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function qe(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function Le(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function He(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Oe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),y.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="
    ",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(y.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):("number"==typeof f.top&&(f.top+="px"),"number"==typeof f.left&&(f.left+="px"),c.css(f))}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return $(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=$e(y.pixelPosition,function(e,t){if(t)return t=Be(e,n),Me.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return $(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0+~]|"+ge+")"+ge+"*"),x=new RegExp(ge+"|>"),j=new RegExp(g),A=new RegExp("^"+t+"$"),D={ID:new RegExp("^#("+t+")"),CLASS:new RegExp("^\\.("+t+")"),TAG:new RegExp("^("+t+"|[*])"),ATTR:new RegExp("^"+p),PSEUDO:new RegExp("^"+g),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ge+"*(even|odd|(([+-]|)(\\d*)n|)"+ge+"*(?:([+-]|)"+ge+"*(\\d+)|))"+ge+"*\\)|)","i"),bool:new RegExp("^(?:"+f+")$","i"),needsContext:new RegExp("^"+ge+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ge+"*((?:-\\d)?\\d*)"+ge+"*\\)|)(?=[^-]|$)","i")},N=/^(?:input|select|textarea|button)$/i,q=/^h\d$/i,L=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,H=/[+~]/,O=new RegExp("\\\\[\\da-fA-F]{1,6}"+ge+"?|\\\\([^\\r\\n\\f])","g"),P=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},M=function(){V()},R=J(function(e){return!0===e.disabled&&fe(e,"fieldset")},{dir:"parentNode",next:"legend"});try{k.apply(oe=ae.call(ye.childNodes),ye.childNodes),oe[ye.childNodes.length].nodeType}catch(e){k={apply:function(e,t){me.apply(e,ae.call(t))},call:function(e){me.apply(e,ae.call(arguments,1))}}}function I(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(V(e),e=e||T,C)){if(11!==p&&(u=L.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return k.call(n,a),n}else if(f&&(a=f.getElementById(i))&&I.contains(e,a)&&a.id===i)return k.call(n,a),n}else{if(u[2])return k.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&e.getElementsByClassName)return k.apply(n,e.getElementsByClassName(i)),n}if(!(h[t+" "]||d&&d.test(t))){if(c=t,f=e,1===p&&(x.test(t)||m.test(t))){(f=H.test(t)&&U(e.parentNode)||e)==e&&le.scope||((s=e.getAttribute("id"))?s=ce.escapeSelector(s):e.setAttribute("id",s=S)),o=(l=Y(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+Q(l[o]);c=l.join(",")}try{return k.apply(n,f.querySelectorAll(c)),n}catch(e){h(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return re(t.replace(ve,"$1"),e,n,r)}function W(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function F(e){return e[S]=!0,e}function $(e){var t=T.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function B(t){return function(e){return fe(e,"input")&&e.type===t}}function _(t){return function(e){return(fe(e,"input")||fe(e,"button"))&&e.type===t}}function z(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&R(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function X(a){return F(function(o){return o=+o,F(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function U(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function V(e){var t,n=e?e.ownerDocument||e:ye;return n!=T&&9===n.nodeType&&n.documentElement&&(r=(T=n).documentElement,C=!ce.isXMLDoc(T),i=r.matches||r.webkitMatchesSelector||r.msMatchesSelector,r.msMatchesSelector&&ye!=T&&(t=T.defaultView)&&t.top!==t&&t.addEventListener("unload",M),le.getById=$(function(e){return r.appendChild(e).id=ce.expando,!T.getElementsByName||!T.getElementsByName(ce.expando).length}),le.disconnectedMatch=$(function(e){return i.call(e,"*")}),le.scope=$(function(){return T.querySelectorAll(":scope")}),le.cssHas=$(function(){try{return T.querySelector(":has(*,:jqfake)"),!1}catch(e){return!0}}),le.getById?(b.filter.ID=function(e){var t=e.replace(O,P);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(O,P);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&C){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):t.querySelectorAll(e)},b.find.CLASS=function(e,t){if("undefined"!=typeof t.getElementsByClassName&&C)return t.getElementsByClassName(e)},d=[],$(function(e){var t;r.appendChild(e).innerHTML="",e.querySelectorAll("[selected]").length||d.push("\\["+ge+"*(?:value|"+f+")"),e.querySelectorAll("[id~="+S+"-]").length||d.push("~="),e.querySelectorAll("a#"+S+"+*").length||d.push(".#.+[+~]"),e.querySelectorAll(":checked").length||d.push(":checked"),(t=T.createElement("input")).setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),r.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&d.push(":enabled",":disabled"),(t=T.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||d.push("\\["+ge+"*name"+ge+"*="+ge+"*(?:''|\"\")")}),le.cssHas||d.push(":has"),d=d.length&&new RegExp(d.join("|")),l=function(e,t){if(e===t)return a=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!le.sortDetached&&t.compareDocumentPosition(e)===n?e===T||e.ownerDocument==ye&&I.contains(ye,e)?-1:t===T||t.ownerDocument==ye&&I.contains(ye,t)?1:o?se.call(o,e)-se.call(o,t):0:4&n?-1:1)}),T}for(e in I.matches=function(e,t){return I(e,null,null,t)},I.matchesSelector=function(e,t){if(V(e),C&&!h[t+" "]&&(!d||!d.test(t)))try{var n=i.call(e,t);if(n||le.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){h(t,!0)}return 0":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(O,P),e[3]=(e[3]||e[4]||e[5]||"").replace(O,P),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||I.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&I.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return D.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&j.test(n)&&(t=Y(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(O,P).toLowerCase();return"*"===e?function(){return!0}:function(e){return fe(e,t)}},CLASS:function(e){var t=s[e+" "];return t||(t=new RegExp("(^|"+ge+")"+e+"("+ge+"|$)"))&&s(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=I.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function T(e,n,r){return v(n)?ce.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?ce.grep(e,function(e){return e===n!==r}):"string"!=typeof n?ce.grep(e,function(e){return-1)[^>]*|#([\w-]+))$/;(ce.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||k,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:S.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof ce?t[0]:t,ce.merge(this,ce.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:C,!0)),w.test(r[1])&&ce.isPlainObject(t))for(r in t)v(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=C.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):v(e)?void 0!==n.ready?n.ready(e):e(ce):ce.makeArray(e,this)}).prototype=ce.fn,k=ce(C);var E=/^(?:parents|prev(?:Until|All))/,j={children:!0,contents:!0,next:!0,prev:!0};function A(e,t){while((e=e[t])&&1!==e.nodeType);return e}ce.fn.extend({has:function(e){var t=ce(e,this),n=t.length;return this.filter(function(){for(var e=0;e\x20\t\r\n\f]*)/i,Ce=/^$|^module$|\/(?:java|ecma)script/i;xe=C.createDocumentFragment().appendChild(C.createElement("div")),(be=C.createElement("input")).setAttribute("type","radio"),be.setAttribute("checked","checked"),be.setAttribute("name","t"),xe.appendChild(be),le.checkClone=xe.cloneNode(!0).cloneNode(!0).lastChild.checked,xe.innerHTML="",le.noCloneChecked=!!xe.cloneNode(!0).lastChild.defaultValue,xe.innerHTML="",le.option=!!xe.lastChild;var ke={thead:[1,"","
    "],col:[2,"","
    "],tr:[2,"","
    "],td:[3,"","
    "],_default:[0,"",""]};function Se(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&fe(e,t)?ce.merge([e],n):n}function Ee(e,t){for(var n=0,r=e.length;n",""]);var je=/<|&#?\w+;/;function Ae(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d\s*$/g;function Re(e,t){return fe(e,"table")&&fe(11!==t.nodeType?t:t.firstChild,"tr")&&ce(e).children("tbody")[0]||e}function Ie(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function We(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Fe(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(_.hasData(e)&&(s=_.get(e).events))for(i in _.remove(t,"handle events"),s)for(n=0,r=s[i].length;n").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),C.head.appendChild(r[0])},abort:function(){i&&i()}}});var Jt,Kt=[],Zt=/(=)\?(?=&|$)|\?\?/;ce.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Kt.pop()||ce.expando+"_"+jt.guid++;return this[e]=!0,e}}),ce.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Zt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Zt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=v(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Zt,"$1"+r):!1!==e.jsonp&&(e.url+=(At.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||ce.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=ie[r],ie[r]=function(){o=arguments},n.always(function(){void 0===i?ce(ie).removeProp(r):ie[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Kt.push(r)),o&&v(i)&&i(o[0]),o=i=void 0}),"script"}),le.createHTMLDocument=((Jt=C.implementation.createHTMLDocument("").body).innerHTML="
    ",2===Jt.childNodes.length),ce.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(le.createHTMLDocument?((r=(t=C.implementation.createHTMLDocument("")).createElement("base")).href=C.location.href,t.head.appendChild(r)):t=C),o=!n&&[],(i=w.exec(e))?[t.createElement(i[1])]:(i=Ae([e],t,o),o&&o.length&&ce(o).remove(),ce.merge([],i.childNodes)));var r,i,o},ce.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1").append(ce.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},ce.expr.pseudos.animated=function(t){return ce.grep(ce.timers,function(e){return t===e.elem}).length},ce.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=ce.css(e,"position"),c=ce(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=ce.css(e,"top"),u=ce.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),v(t)&&(t=t.call(e,n,ce.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},ce.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){ce.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===ce.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===ce.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=ce(e).offset()).top+=ce.css(e,"borderTopWidth",!0),i.left+=ce.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-ce.css(r,"marginTop",!0),left:t.left-i.left-ce.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===ce.css(e,"position"))e=e.offsetParent;return e||J})}}),ce.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;ce.fn[t]=function(e){return M(this,function(e,t,n){var r;if(y(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),ce.each(["top","left"],function(e,n){ce.cssHooks[n]=Ye(le.pixelPosition,function(e,t){if(t)return t=Ge(e,n),_e.test(t)?ce(e).position()[n]+"px":t})}),ce.each({Height:"height",Width:"width"},function(a,s){ce.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){ce.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return M(this,function(e,t,n){var r;return y(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?ce.css(e,t,i):ce.style(e,t,n,i)},s,n?e:void 0,n)}})}),ce.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ce.fn[t]=function(e){return this.on(t,e)}}),ce.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)}}),ce.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){ce.fn[n]=function(e,t){return 0 {% block userlinks %} {% if user.is_authenticated %} - {% optional_logout request user %} + {% optional_logout request user csrf_token %} {% else %} {% optional_login request %} {% endif %} @@ -244,23 +244,19 @@ {% endif %} {% block script %} - - + - + {% endblock %} {% endblock %} diff --git a/rest_framework/templates/rest_framework/base.html b/rest_framework/templates/rest_framework/base.html index a88e1591c6..e261d8c9d5 100644 --- a/rest_framework/templates/rest_framework/base.html +++ b/rest_framework/templates/rest_framework/base.html @@ -46,7 +46,7 @@