Repository: encode/django-rest-framework Branch: main Commit: 30d58a75eeef Files: 438 Total size: 3.3 MB Directory structure: gitextract_snnuc0bd/ ├── .gitattributes ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ └── config.yml │ ├── dependabot.yml │ ├── release.yml │ ├── stale.yml │ └── workflows/ │ ├── main.yml │ ├── mkdocs-deploy.yml │ └── release.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .readthedocs.yaml ├── .tx/ │ └── config ├── CONTRIBUTING.md ├── LICENSE.md ├── MANIFEST.in ├── PULL_REQUEST_TEMPLATE.md ├── README.md ├── SECURITY.md ├── codecov.yml ├── codespell-ignore-words.txt ├── docs/ │ ├── CNAME │ ├── api-guide/ │ │ ├── authentication.md │ │ ├── caching.md │ │ ├── content-negotiation.md │ │ ├── exceptions.md │ │ ├── fields.md │ │ ├── filtering.md │ │ ├── format-suffixes.md │ │ ├── generic-views.md │ │ ├── metadata.md │ │ ├── pagination.md │ │ ├── parsers.md │ │ ├── permissions.md │ │ ├── relations.md │ │ ├── renderers.md │ │ ├── requests.md │ │ ├── responses.md │ │ ├── reverse.md │ │ ├── routers.md │ │ ├── schemas.md │ │ ├── serializers.md │ │ ├── settings.md │ │ ├── status-codes.md │ │ ├── testing.md │ │ ├── throttling.md │ │ ├── validators.md │ │ ├── versioning.md │ │ ├── views.md │ │ └── viewsets.md │ ├── community/ │ │ ├── 3.0-announcement.md │ │ ├── 3.1-announcement.md │ │ ├── 3.10-announcement.md │ │ ├── 3.11-announcement.md │ │ ├── 3.12-announcement.md │ │ ├── 3.13-announcement.md │ │ ├── 3.14-announcement.md │ │ ├── 3.15-announcement.md │ │ ├── 3.16-announcement.md │ │ ├── 3.2-announcement.md │ │ ├── 3.3-announcement.md │ │ ├── 3.4-announcement.md │ │ ├── 3.5-announcement.md │ │ ├── 3.6-announcement.md │ │ ├── 3.7-announcement.md │ │ ├── 3.8-announcement.md │ │ ├── 3.9-announcement.md │ │ ├── contributing.md │ │ ├── jobs.md │ │ ├── kickstarter-announcement.md │ │ ├── mozilla-grant.md │ │ ├── project-management.md │ │ ├── release-notes.md │ │ ├── third-party-packages.md │ │ └── tutorials-and-resources.md │ ├── index.md │ ├── theme/ │ │ ├── js/ │ │ │ └── prettify-1.0.js │ │ ├── main.html │ │ ├── src/ │ │ │ ├── README.md │ │ │ └── drf-logos.fig │ │ └── stylesheets/ │ │ ├── extra.css │ │ └── prettify.css │ ├── topics/ │ │ ├── ajax-csrf-cors.md │ │ ├── browsable-api.md │ │ ├── browser-enhancements.md │ │ ├── documenting-your-api.md │ │ ├── html-and-forms.md │ │ ├── internationalization.md │ │ ├── rest-hypermedia-hateoas.md │ │ └── writable-nested-serializers.md │ └── tutorial/ │ ├── 1-serialization.md │ ├── 2-requests-and-responses.md │ ├── 3-class-based-views.md │ ├── 4-authentication-and-permissions.md │ ├── 5-relationships-and-hyperlinked-apis.md │ ├── 6-viewsets-and-routers.md │ └── quickstart.md ├── licenses/ │ ├── bootstrap.md │ └── jquery.json-view.md ├── mkdocs.yml ├── pyproject.toml ├── rest_framework/ │ ├── __init__.py │ ├── apps.py │ ├── authentication.py │ ├── authtoken/ │ │ ├── __init__.py │ │ ├── admin.py │ │ ├── apps.py │ │ ├── management/ │ │ │ ├── __init__.py │ │ │ └── commands/ │ │ │ ├── __init__.py │ │ │ └── drf_create_token.py │ │ ├── migrations/ │ │ │ ├── 0001_initial.py │ │ │ ├── 0002_auto_20160226_1747.py │ │ │ ├── 0003_tokenproxy.py │ │ │ ├── 0004_alter_tokenproxy_options.py │ │ │ └── __init__.py │ │ ├── models.py │ │ ├── serializers.py │ │ └── views.py │ ├── checks.py │ ├── compat.py │ ├── decorators.py │ ├── exceptions.py │ ├── fields.py │ ├── filters.py │ ├── generics.py │ ├── locale/ │ │ ├── ach/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ar/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── az/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── be/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── bg/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ca/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ca_ES/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── cs/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── da/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── de/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── el/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── el_GR/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── en/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── en_AU/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── en_CA/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── en_US/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── es/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── et/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── fa/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── fa_IR/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── fi/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── fr/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── fr_CA/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── gl/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── gl_ES/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── he_IL/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── hu/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── hy/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── id/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── it/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ja/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── kk/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ko_KR/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── lt/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── lv/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── mk/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── nb/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ne_NP/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── nl/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── nn/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── no/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── pl/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── pt/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── pt_BR/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── pt_PT/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ro/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ru/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── ru_RU/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── sk/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── sl/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── sv/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── th/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── tr/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── tr_TR/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── uk/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── vi/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── zh_CN/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── zh_Hans/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ ├── zh_Hant/ │ │ │ └── LC_MESSAGES/ │ │ │ ├── django.mo │ │ │ └── django.po │ │ └── zh_TW/ │ │ └── LC_MESSAGES/ │ │ ├── django.mo │ │ └── django.po │ ├── management/ │ │ ├── __init__.py │ │ └── commands/ │ │ ├── __init__.py │ │ └── generateschema.py │ ├── metadata.py │ ├── mixins.py │ ├── negotiation.py │ ├── pagination.py │ ├── parsers.py │ ├── permissions.py │ ├── relations.py │ ├── renderers.py │ ├── request.py │ ├── response.py │ ├── reverse.py │ ├── routers.py │ ├── schemas/ │ │ ├── __init__.py │ │ ├── generators.py │ │ ├── inspectors.py │ │ ├── openapi.py │ │ ├── utils.py │ │ └── views.py │ ├── serializers.py │ ├── settings.py │ ├── static/ │ │ └── rest_framework/ │ │ ├── css/ │ │ │ ├── bootstrap-tweaks.css │ │ │ ├── default.css │ │ │ ├── font-awesome-4.0.3.css │ │ │ └── prettify.css │ │ └── js/ │ │ ├── ajax-form.js │ │ ├── csrf.js │ │ ├── default.js │ │ ├── load-ajax-form.js │ │ └── prettify-min.js │ ├── status.py │ ├── templates/ │ │ └── rest_framework/ │ │ ├── admin/ │ │ │ ├── detail.html │ │ │ ├── dict_value.html │ │ │ ├── list.html │ │ │ ├── list_value.html │ │ │ └── simple_list_value.html │ │ ├── admin.html │ │ ├── api.html │ │ ├── base.html │ │ ├── filters/ │ │ │ ├── base.html │ │ │ ├── ordering.html │ │ │ └── search.html │ │ ├── horizontal/ │ │ │ ├── checkbox.html │ │ │ ├── checkbox_multiple.html │ │ │ ├── dict_field.html │ │ │ ├── fieldset.html │ │ │ ├── form.html │ │ │ ├── input.html │ │ │ ├── list_field.html │ │ │ ├── list_fieldset.html │ │ │ ├── radio.html │ │ │ ├── select.html │ │ │ ├── select_multiple.html │ │ │ └── textarea.html │ │ ├── inline/ │ │ │ ├── checkbox.html │ │ │ ├── checkbox_multiple.html │ │ │ ├── dict_field.html │ │ │ ├── fieldset.html │ │ │ ├── form.html │ │ │ ├── input.html │ │ │ ├── list_field.html │ │ │ ├── list_fieldset.html │ │ │ ├── radio.html │ │ │ ├── select.html │ │ │ ├── select_multiple.html │ │ │ └── textarea.html │ │ ├── login.html │ │ ├── login_base.html │ │ ├── pagination/ │ │ │ ├── numbers.html │ │ │ └── previous_and_next.html │ │ ├── raw_data_form.html │ │ └── vertical/ │ │ ├── checkbox.html │ │ ├── checkbox_multiple.html │ │ ├── dict_field.html │ │ ├── fieldset.html │ │ ├── form.html │ │ ├── input.html │ │ ├── list_field.html │ │ ├── list_fieldset.html │ │ ├── radio.html │ │ ├── select.html │ │ ├── select_multiple.html │ │ └── textarea.html │ ├── templatetags/ │ │ ├── __init__.py │ │ └── rest_framework.py │ ├── test.py │ ├── throttling.py │ ├── urlpatterns.py │ ├── urls.py │ ├── utils/ │ │ ├── __init__.py │ │ ├── breadcrumbs.py │ │ ├── encoders.py │ │ ├── field_mapping.py │ │ ├── formatting.py │ │ ├── html.py │ │ ├── humanize_datetime.py │ │ ├── json.py │ │ ├── mediatypes.py │ │ ├── model_meta.py │ │ ├── representation.py │ │ ├── serializer_helpers.py │ │ ├── timezone.py │ │ └── urls.py │ ├── validators.py │ ├── versioning.py │ ├── views.py │ └── viewsets.py ├── runtests.py ├── setup.cfg ├── tests/ │ ├── __init__.py │ ├── authentication/ │ │ ├── __init__.py │ │ ├── migrations/ │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ ├── models.py │ │ └── test_authentication.py │ ├── browsable_api/ │ │ ├── __init__.py │ │ ├── auth_urls.py │ │ ├── no_auth_urls.py │ │ ├── serializers.py │ │ ├── test_browsable_api.py │ │ ├── test_browsable_nested_api.py │ │ ├── test_form_rendering.py │ │ └── views.py │ ├── conftest.py │ ├── generic_relations/ │ │ ├── __init__.py │ │ ├── migrations/ │ │ │ ├── 0001_initial.py │ │ │ └── __init__.py │ │ ├── models.py │ │ └── test_generic_relations.py │ ├── importable/ │ │ ├── __init__.py │ │ └── test_installed.py │ ├── models.py │ ├── schemas/ │ │ ├── __init__.py │ │ ├── test_get_schema_view.py │ │ ├── test_managementcommand.py │ │ ├── test_openapi.py │ │ └── views.py │ ├── test_atomic_requests.py │ ├── test_authtoken.py │ ├── test_bound_fields.py │ ├── test_decorators.py │ ├── test_description.py │ ├── test_encoders.py │ ├── test_exceptions.py │ ├── test_fields.py │ ├── test_filters.py │ ├── test_generics.py │ ├── test_htmlrenderer.py │ ├── test_lazy_hyperlinks.py │ ├── test_metadata.py │ ├── test_middleware.py │ ├── test_model_serializer.py │ ├── test_multitable_inheritance.py │ ├── test_negotiation.py │ ├── test_one_to_one_with_inheritance.py │ ├── test_pagination.py │ ├── test_parsers.py │ ├── test_permissions.py │ ├── test_prefetch_related.py │ ├── test_relations.py │ ├── test_relations_hyperlink.py │ ├── test_relations_pk.py │ ├── test_relations_slug.py │ ├── test_renderers.py │ ├── test_request.py │ ├── test_requests_client.py │ ├── test_response.py │ ├── test_reverse.py │ ├── test_routers.py │ ├── test_serializer.py │ ├── test_serializer_bulk_update.py │ ├── test_serializer_lists.py │ ├── test_serializer_nested.py │ ├── test_settings.py │ ├── test_status.py │ ├── test_templates.py │ ├── test_templatetags.py │ ├── test_testing.py │ ├── test_throttling.py │ ├── test_urlpatterns.py │ ├── test_utils.py │ ├── test_validation.py │ ├── test_validation_error.py │ ├── test_validators.py │ ├── test_versioning.py │ ├── test_views.py │ ├── test_viewsets.py │ ├── test_write_only_fields.py │ ├── urls.py │ └── utils.py └── tox.ini ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ docs/theme/src/drf-logos.fig filter=lfs diff=lfs merge=lfs -text ================================================ FILE: .github/FUNDING.yml ================================================ github: [browniebroke] open_collective: django-rest-framework ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ 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. 💖 Please note that at this point in its lifespan, we consider Django REST framework to be feature-complete. ================================================ FILE: .github/dependabot.yml ================================================ # 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 cooldown: default-days: 7 - package-ecosystem: "pip" directory: "/" groups: test: patterns: - "pytest*" - "attrs" - "importlib-metadata" - "pytz" docs: patterns: - "mkdocs" - "pylinkvalidator" optional: patterns: - "django-filter" - "django-guardian" - "inflection" - "legacy-cgi" - "markdown" - "psycopg*" - "pygments" - "pyyaml" schedule: interval: weekly cooldown: default-days: 7 ================================================ FILE: .github/release.yml ================================================ changelog: exclude: labels: - dependencies - Internal - CI - Documentation authors: - dependabot[bot] - pre-commit-ci[bot] categories: - title: Breaking changes labels: - Breaking - title: Features labels: - Feature - title: Bug fixes labels: - Bug - title: Translations labels: - Translations - title: Packaging labels: - Packaging - title: Other changes labels: - '*' ================================================ FILE: .github/stale.yml ================================================ # Documentation: https://github.com/probot/stale # Number of days of inactivity before an issue becomes stale daysUntilStale: 60 # Number of days of inactivity before a stale issue is closed daysUntilClose: 7 # Comment to post when marking an issue as stale. Set to `false` to disable markComment: > This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions. # Comment to post when closing a stale issue. Set to `false` to disable closeComment: false # Limit the number of actions per hour, from 1-30. Default is 30 limitPerRun: 1 # Label to use when marking as stale staleLabel: stale ================================================ FILE: .github/workflows/main.yml ================================================ name: CI on: push: branches: - main pull_request: concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: pre-commit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v6 with: fetch-depth: 0 - uses: actions/setup-python@v6 with: python-version: "3.10" - uses: pre-commit/action@v3.0.1 tests: name: Python ${{ matrix.python-version }} runs-on: ubuntu-24.04 strategy: matrix: python-version: - '3.10' - '3.11' - '3.12' - '3.13' - '3.14' steps: - uses: actions/checkout@v6 - uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} allow-prereleases: true cache: 'pip' - name: Upgrade packaging tools run: python -m pip install --upgrade pip setuptools virtualenv wheel - name: Install dependencies run: python -m pip install --upgrade tox - name: Run tox targets for ${{ matrix.python-version }} 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.13' }} run: | tox -e base,dist,docs - name: Upload coverage 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@v6 - uses: actions/setup-python@v6 with: python-version: '3.13' - name: Install dependencies run: pip install --group docs # 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 run: pylinkvalidate.py -P http://localhost:8000/ - run: echo "Done" ================================================ FILE: .github/workflows/mkdocs-deploy.yml ================================================ name: mkdocs on: push: branches: - main paths: - docs/** - docs_theme/** - pyproject.toml - mkdocs.yml - .github/workflows/mkdocs-deploy.yml jobs: deploy: runs-on: ubuntu-latest environment: github-pages permissions: contents: write concurrency: group: ${{ github.workflow }}-${{ github.ref }} steps: - uses: actions/checkout@v6 - run: git fetch --no-tags --prune --depth=1 origin gh-pages - uses: actions/setup-python@v6 with: python-version: 3.x - run: pip install --group docs - run: mkdocs gh-deploy ================================================ FILE: .github/workflows/release.yml ================================================ name: Publish Release concurrency: # stop previous release runs if tag is recreated group: release-${{ github.ref }} cancel-in-progress: true on: push: tags: # Order matters, the last rule that applies to a tag # is the one that takes effect: # https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#example-including-and-excluding-branches-and-tags - '*.*.*' # There should be no dev tags created, but to be safe, # let's not publish them. - '!*.*.*.dev*' env: PYPI_URL: https://pypi.org/p/djangorestframework PYPI_TEST_URL: https://test.pypi.org/p/djangorestframework jobs: build: name: Build distribution 📦 runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v6 - name: Set up Python uses: actions/setup-python@v6 with: python-version: "3.x" - name: Install pypa/build run: python3 -m pip install build - name: Build a binary wheel and a source tarball run: python3 -m build - name: Store the distribution packages uses: actions/upload-artifact@v7 with: name: python-package-distributions path: dist/ publish-to-testpypi: name: Publish Python 🐍 distribution 📦 to TestPyPI needs: - build runs-on: ubuntu-24.04 environment: name: testpypi url: ${{ env.PYPI_TEST_URL }} permissions: id-token: write # IMPORTANT: mandatory for trusted publishing steps: - name: Download all the dists uses: actions/download-artifact@v8 with: name: python-package-distributions path: dist/ - name: Publish distribution 📦 to TestPyPI uses: pypa/gh-action-pypi-publish@release/v1.13 with: repository-url: https://test.pypi.org/legacy/ skip-existing: true publish-to-pypi: name: Publish Python 🐍 distribution 📦 to PyPI needs: - build - publish-to-testpypi runs-on: ubuntu-24.04 environment: name: pypi url: ${{ env.PYPI_URL }} permissions: id-token: write # IMPORTANT: mandatory for trusted publishing steps: - name: Download all the dists uses: actions/download-artifact@v8 with: name: python-package-distributions path: dist/ - name: Publish distribution 📦 to PyPI uses: pypa/gh-action-pypi-publish@release/v1.13 github-release: name: >- Sign the Python 🐍 distribution 📦 with Sigstore and upload them to GitHub Release needs: - publish-to-pypi runs-on: ubuntu-24.04 permissions: contents: write # IMPORTANT: mandatory for making GitHub Releases id-token: write # IMPORTANT: mandatory for sigstore steps: - name: Download all the dists uses: actions/download-artifact@v8 with: name: python-package-distributions path: dist/ - name: Sign the dists with Sigstore uses: sigstore/gh-action-sigstore-python@v3.2.0 with: inputs: >- ./dist/*.tar.gz ./dist/*.whl - name: Create GitHub Release env: GITHUB_TOKEN: ${{ github.token }} run: >- gh release create '${{ github.ref_name }}' --repo '${{ github.repository }}' --generate-notes - name: Upload artifact signatures to GitHub Release env: GITHUB_TOKEN: ${{ github.token }} # Upload to GitHub Release using the `gh` CLI. # `dist/` contains the built packages, and the # sigstore-produced signatures and certificates. run: >- gh release upload '${{ github.ref_name }}' dist/** --repo '${{ github.repository }}' ================================================ FILE: .gitignore ================================================ *.pyc *.db *~ *.py.bak /site/ /htmlcov/ /coverage/ /build/ /dist/ /*.egg-info/ /env/ MANIFEST coverage.* .coverage .cache/ !.github !.gitignore !.pre-commit-config.yaml ================================================ FILE: .pre-commit-config.yaml ================================================ repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v6.0.0 hooks: - id: check-added-large-files - id: check-case-conflict - id: check-json - id: check-merge-conflict - id: check-symlinks - id: check-toml - repo: https://github.com/PyCQA/isort rev: 7.0.0 hooks: - id: isort - repo: https://github.com/PyCQA/flake8 rev: 7.3.0 hooks: - id: flake8 additional_dependencies: - flake8-tidy-imports - flake8-bugbear - repo: https://github.com/adamchainz/blacken-docs rev: 1.20.0 hooks: - id: blacken-docs additional_dependencies: - black==26.1.0 - repo: https://github.com/codespell-project/codespell # Configuration for codespell is in pyproject.toml rev: v2.4.1 hooks: - id: codespell additional_dependencies: # python doesn't come with a toml parser prior to 3.11 - "tomli; python_version < '3.11'" - repo: https://github.com/asottile/pyupgrade rev: v3.21.2 hooks: - id: pyupgrade args: ["--py310-plus", "--keep-percent-format"] - repo: https://github.com/tox-dev/pyproject-fmt rev: v2.11.1 hooks: - id: pyproject-fmt ================================================ FILE: .readthedocs.yaml ================================================ # Read the Docs configuration file # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details # Required version: 2 # Set the OS, Python version, and other tools you might need build: os: ubuntu-24.04 tools: python: "3.13" jobs: install: - pip install --upgrade pip - pip install -e . --group docs # Build documentation with Mkdocs mkdocs: configuration: mkdocs.yml ================================================ FILE: .tx/config ================================================ [main] host = https://www.transifex.com lang_map = sr@latin:sr_Latn, zh-Hans:zh_Hans, zh-Hant:zh_Hant [django-rest-framework.djangopo] file_filter = rest_framework/locale//LC_MESSAGES/django.po source_file = rest_framework/locale/en_US/LC_MESSAGES/django.po source_lang = en_US type = PO ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to REST framework 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. 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 open a pull request if you've been recommended to do so **after discussion**. 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. ================================================ FILE: LICENSE.md ================================================ # License Copyright © 2011-present, [Encode OSS Ltd](https://www.encode.io/). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: MANIFEST.in ================================================ recursive-include tests/ * global-exclude __pycache__ global-exclude *.py[co] ================================================ FILE: PULL_REQUEST_TEMPLATE.md ================================================ *Note*: Before submitting a code change, please review our [contributing guidelines](https://www.django-rest-framework.org/community/contributing/#pull-requests). ## Description Please describe your pull request. If it fixes a bug or resolves a feature request, be sure to link to that issue. When linking to an issue, please use `refs #...` in the description of the pull request. ================================================ FILE: README.md ================================================ # [Django REST framework][docs] [![build-status-image]][build-status] [![coverage-status-image]][codecov] [![pypi-version]][pypi] **Awesome web-browsable Web APIs.** Full documentation for the project is available at [https://www.django-rest-framework.org/][docs]. --- # Overview 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 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]. **Below**: *Screenshot from the browsable API* ![Screenshot][image] ---- # Requirements * Python 3.10+ * Django 4.2, 5.0, 5.1, 5.2, 6.0 We **highly recommend** and only officially support the latest patch release of each Python and Django series. # Installation Install using `pip`... pip install djangorestframework Add `'rest_framework'` to your `INSTALLED_APPS` setting. ```python INSTALLED_APPS = [ # ... "rest_framework", ] ``` # Example Let's take a look at a quick example of using REST framework to build a simple model-backed API for accessing users and groups. Start up a new project like so... pip install django pip install djangorestframework django-admin startproject example . ./manage.py migrate ./manage.py createsuperuser Now edit the `example/urls.py` module in your project: ```python from django.contrib.auth.models import User from django.urls import include, path from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email", "is_staff"] # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide a way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r"users", UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("", include(router.urls)), path("api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] ``` We'd also like to configure a couple of settings for our API. Add the following to your `settings.py` module: ```python INSTALLED_APPS = [ # ... make sure to include the default installed apps here. "rest_framework", ] REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly", ] } ``` That's it, we're done! ./manage.py runserver You can now open the API in your browser at `http://127.0.0.1:8000/`, and view your new 'users' API. If you use the `Login` control in the top right corner you'll also be able to add, create and delete users from the system. You can also interact with the API using command line tools such as [`curl`](https://curl.haxx.se/). For example, to list the users endpoint: $ curl -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ [ { "url": "http://127.0.0.1:8000/users/1/", "username": "admin", "email": "admin@example.com", "is_staff": true, } ] Or to create a new user: $ curl -X POST -d username=new -d email=new@example.com -d is_staff=false -H 'Accept: application/json; indent=4' -u admin:password http://127.0.0.1:8000/users/ { "url": "http://127.0.0.1:8000/users/2/", "username": "new", "email": "new@example.com", "is_staff": false, } # Documentation & Support Full documentation for the project is available at [https://www.django-rest-framework.org/][docs]. For questions and support, use the [REST framework discussion group][group], or `#restframework` on libera.chat IRC. # Security Please see the [security policy][security-policy]. [build-status-image]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml/badge.svg [build-status]: https://github.com/encode/django-rest-framework/actions/workflows/main.yml [coverage-status-image]: https://img.shields.io/codecov/c/github/encode/django-rest-framework/main.svg [codecov]: https://codecov.io/github/encode/django-rest-framework?branch=main [pypi-version]: https://img.shields.io/pypi/v/djangorestframework.svg [pypi]: https://pypi.org/project/djangorestframework/ [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [funding]: https://fund.django-rest-framework.org/topics/funding/ [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [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 [serializer-section]: https://www.django-rest-framework.org/api-guide/serializers/#serializers [modelserializer-section]: https://www.django-rest-framework.org/api-guide/serializers/#modelserializer [functionview-section]: https://www.django-rest-framework.org/api-guide/views/#function-based-views [generic-views]: https://www.django-rest-framework.org/api-guide/generic-views/ [viewsets]: https://www.django-rest-framework.org/api-guide/viewsets/ [routers]: https://www.django-rest-framework.org/api-guide/routers/ [serializers]: https://www.django-rest-framework.org/api-guide/serializers/ [authentication]: https://www.django-rest-framework.org/api-guide/authentication/ [image]: https://www.django-rest-framework.org/img/quickstart.png [docs]: https://www.django-rest-framework.org/ [security-policy]: https://github.com/encode/django-rest-framework/security/policy ================================================ FILE: SECURITY.md ================================================ # Security Policy ## Reporting a Vulnerability **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. ================================================ FILE: codecov.yml ================================================ coverage: precision: 2 round: down range: "80...100" status: project: yes patch: no changes: no comment: off ================================================ FILE: codespell-ignore-words.txt ================================================ Tim assertIn IAM endcode deque thead lets fo malcom ser ================================================ FILE: docs/CNAME ================================================ www.django-rest-framework.org ================================================ FILE: docs/api-guide/authentication.md ================================================ --- source: - authentication.py --- > Auth needs to be pluggable. > > — Jacob Kaplan-Moss, ["REST worst practices"][cite] Authentication is the mechanism of associating an incoming request with a set of identifying credentials, such as the user the request came from, or the token that it was signed with. The [permission] and [throttling] policies can then use those credentials to determine if the request should be permitted. REST framework provides several authentication schemes out of the box, and also allows you to implement custom schemes. Authentication always runs at the very start of the view, before the permission and throttling checks occur, and before any other code is allowed to proceed. The `request.user` property will typically be set to an instance of the `contrib.auth` package's `User` class. The `request.auth` property is used for any additional authentication information, for example, it may be used to represent an authentication token that the request was signed with. !!! note Don't forget that **authentication by itself won't allow or disallow an incoming request**, it simply identifies the credentials that the request was made with. For information on how to set up the permission policies for your API please see the [permissions documentation][permission]. ## How authentication is determined The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set `request.user` and `request.auth` using the return value of the first class that successfully authenticates. If no class authenticates, `request.user` will be set to an instance of `django.contrib.auth.models.AnonymousUser`, and `request.auth` will be set to `None`. The value of `request.user` and `request.auth` for unauthenticated requests can be modified using the `UNAUTHENTICATED_USER` and `UNAUTHENTICATED_TOKEN` settings. ## Setting the authentication scheme The default authentication schemes may be set globally, using the `DEFAULT_AUTHENTICATION_CLASSES` setting. For example. REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ] } You can also set the authentication scheme on a per-view or per-viewset basis, using the `APIView` class-based views. from rest_framework.authentication import SessionAuthentication, BasicAuthentication from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'user': str(request.user), # `django.contrib.auth.User` instance. 'auth': str(request.auth), # None } return Response(content) Or, if you're using the `@api_view` decorator with function based views. @api_view(['GET']) @authentication_classes([SessionAuthentication, BasicAuthentication]) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'user': str(request.user), # `django.contrib.auth.User` instance. 'auth': str(request.auth), # None } return Response(content) ## Unauthorized and Forbidden responses When an unauthenticated request is denied permission there are two different error codes that may be appropriate. * [HTTP 401 Unauthorized][http401] * [HTTP 403 Permission Denied][http403] HTTP 401 responses must always include a `WWW-Authenticate` header, that instructs the client how to authenticate. HTTP 403 responses do not include the `WWW-Authenticate` header. The kind of response that will be used depends on the authentication scheme. Although multiple authentication schemes may be in use, only one scheme may be used to determine the type of response. **The first authentication class set on the view is used when determining the type of response**. Note that when a request may successfully authenticate, but still be denied permission to perform the request, in which case a `403 Permission Denied` response will always be used, regardless of the authentication scheme. ## 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 on 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. If you are deploying to Apache, and using any non-session based authentication, you will need to explicitly configure mod_wsgi to pass the required headers through to the application. This can be done by specifying the `WSGIPassAuthorization` directive in the appropriate context and setting it to `'On'`. # this can go in either server config, virtual host, directory or .htaccess WSGIPassAuthorization On --- ## API Reference ### BasicAuthentication This authentication scheme uses [HTTP Basic Authentication][basicauth], signed against a user's username and password. Basic authentication is generally only appropriate for testing. If successfully authenticated, `BasicAuthentication` provides the following credentials. * `request.user` will be a Django `User` instance. * `request.auth` will be `None`. Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Basic realm="api" !!! note If you use `BasicAuthentication` in production you must ensure that your API is only available over `https`. You should also ensure that your API clients will always re-request the username and password at login, and will never store those details to persistent storage. ### TokenAuthentication !!! note The token authentication provided by Django REST framework is a fairly simple implementation. For an implementation which allows more than one token per user, has some tighter security implementation details, and supports token expiry, please see the [Django REST Knox][django-rest-knox] third party package. This authentication scheme uses a simple token-based HTTP Authentication scheme. Token authentication is appropriate for client-server setups, such as native desktop and mobile clients. To use the `TokenAuthentication` scheme you'll need to [configure the authentication classes](#setting-the-authentication-scheme) to include `TokenAuthentication`, and additionally include `rest_framework.authtoken` in your `INSTALLED_APPS` setting: INSTALLED_APPS = [ ... 'rest_framework.authtoken' ] Make sure to run `manage.py migrate` after changing your settings. The `rest_framework.authtoken` app provides Django database migrations. You'll also need to create tokens for your users. from rest_framework.authtoken.models import Token token = Token.objects.create(user=...) print(token.key) For clients to authenticate, the token key should be included in the `Authorization` HTTP header. The key should be prefixed by the string literal "Token", with whitespace separating the two strings. For example: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b *If you want to use a different keyword in the header, such as `Bearer`, simply subclass `TokenAuthentication` and set the `keyword` class variable.* If successfully authenticated, `TokenAuthentication` provides the following credentials. * `request.user` will be a Django `User` instance. * `request.auth` will be a `rest_framework.authtoken.models.Token` instance. Unauthenticated responses that are denied permission will result in an `HTTP 401 Unauthorized` response with an appropriate WWW-Authenticate header. For example: WWW-Authenticate: Token The `curl` command line tool may be useful for testing token authenticated APIs. For example: curl -X GET http://127.0.0.1:8000/api/example/ -H 'Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' !!! note If you use `TokenAuthentication` in production you must ensure that your API is only available over `https`. #### Generating Tokens ##### By using signals If you want every user to have an automatically generated Token, you can simply catch the User's `post_save` signal. from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) Note that you'll want to ensure you place this code snippet in an installed `models.py` module, or some other location that will be imported by Django on startup. If you've already created some users, you can generate tokens for all existing users like this: from django.contrib.auth.models import User from rest_framework.authtoken.models import Token for user in User.objects.all(): Token.objects.get_or_create(user=user) ##### By exposing an api endpoint When using `TokenAuthentication`, you may want to provide a mechanism for clients to obtain a token given the username and password. REST framework provides a built-in view to provide this behavior. To use it, add the `obtain_auth_token` view to your URLconf: from rest_framework.authtoken import views urlpatterns += [ path('api-token-auth/', views.obtain_auth_token) ] Note that the URL part of the pattern can be whatever you want to use. The `obtain_auth_token` view will return a JSON response when valid `username` and `password` fields are POSTed to the view using form data or JSON: { 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' } Note that the default `obtain_auth_token` view explicitly uses JSON requests and responses, rather than using default renderer and parser classes in your settings. 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. For example, you may return additional user information beyond the `token` value: from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.authtoken.models import Token from rest_framework.response import Response class CustomAuthToken(ObtainAuthToken): def post(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.data, context={'request': request}) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({ 'token': token.key, 'user_id': user.pk, 'email': user.email }) And in your `urls.py`: urlpatterns += [ path('api-token-auth/', CustomAuthToken.as_view()) ] ##### 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 to customize it to your needs, more specifically by declaring the `user` field as `raw_field`. `your_app/admin.py`: from rest_framework.authtoken.admin import TokenAdmin TokenAdmin.raw_id_fields = ['user'] ##### Using Django manage.py command Since version 3.6.4 it's possible to generate a user token using the following command: ./manage.py drf_create_token this command will return the API token for the given user, creating it if it doesn't exist: Generated token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b for user user1 In case you want to regenerate the token (for example if it has been compromised or leaked) you can pass an additional parameter: ./manage.py drf_create_token -r ### SessionAuthentication This authentication scheme uses Django's default session backend for authentication. Session authentication is appropriate for AJAX clients that are running in the same session context as your website. If successfully authenticated, `SessionAuthentication` provides the following credentials. * `request.user` will be a Django `User` instance. * `request.auth` will be `None`. Unauthenticated responses that are denied permission will result in an `HTTP 403 Forbidden` response. If you're using an AJAX-style API with SessionAuthentication, you'll need to make sure you include a valid CSRF token for any "unsafe" HTTP method calls, such as `PUT`, `PATCH`, `POST` or `DELETE` requests. See the [Django CSRF documentation][csrf-ajax] for more details. !!! warning Always use Django's standard login view when creating login pages. This will ensure your login views are properly protected. 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 This authentication scheme allows you to delegate authentication to your web server, which sets the `REMOTE_USER` 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 behavior, consult the [Django documentation](https://docs.djangoproject.com/en/stable/howto/auth-remote-user/). If successfully authenticated, `RemoteUserAuthentication` provides the following credentials: * `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, 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/) ## Custom authentication To implement a custom authentication scheme, subclass `BaseAuthentication` and override the `.authenticate(self, request)` method. The method should return a two-tuple of `(user, auth)` if authentication succeeds, or `None` otherwise. In some circumstances instead of returning `None`, you may want to raise an `AuthenticationFailed` exception from the `.authenticate()` method. Typically the approach you should take is: * If authentication is not attempted, return `None`. Any other authentication schemes also in use will still be checked. * If authentication is attempted but fails, raise an `AuthenticationFailed` exception. An error response will be returned immediately, regardless of any permissions checks, and without checking any other authentication schemes. You *may* also override the `.authenticate_header(self, request)` method. If implemented, it should return a string that will be used as the value of the `WWW-Authenticate` header in a `HTTP 401 Unauthorized` response. If the `.authenticate_header()` method is not overridden, the authentication scheme will return `HTTP 403 Forbidden` responses when an unauthenticated request is denied access. !!! note When your custom authenticator is invoked by the request object's `.user` or `.auth` properties, you may see an `AttributeError` re-raised as a `WrappedAttributeError`. This is necessary to prevent the original exception from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from your custom authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. These errors should be fixed or otherwise handled by your authenticator. ### Example 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 rest_framework import authentication from rest_framework import exceptions class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('HTTP_X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) --- ## Third party packages The following third-party packages are also available. ### django-rest-knox [Django-rest-knox][django-rest-knox] library provides models and views to handle token-based authentication in a more secure and extensible way than the built-in TokenAuthentication scheme - with Single Page Applications and Mobile clients in mind. It provides per-client tokens, and views to generate them when provided some other authentication (usually basic authentication), to delete the token (providing a server enforced logout) and to delete all tokens (logs out all clients that a user is logged into). ### Django OAuth Toolkit The [Django OAuth Toolkit][django-oauth-toolkit] package provides OAuth 2.0 support and works with Python 3.4+. The package is maintained by [jazzband][jazzband] and uses the excellent [OAuthLib][oauthlib]. The package is well documented, and well supported and is currently our **recommended package for OAuth 2.0 support**. #### Installation & configuration Install using `pip`. pip install django-oauth-toolkit Add the package to your `INSTALLED_APPS` and modify your REST framework settings. INSTALLED_APPS = [ ... 'oauth2_provider', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', ] } For more details see the [Django REST framework - Getting started][django-oauth-toolkit-getting-started] documentation. ### Django REST framework OAuth The [Django REST framework OAuth][django-rest-framework-oauth] package provides both OAuth1 and OAuth2 support for REST framework. This package was previously included directly in the REST framework but is now supported and maintained as a third-party package. #### Installation & configuration Install the package using `pip`. pip install djangorestframework-oauth For details on configuration and usage see the Django REST framework OAuth documentation for [authentication][django-rest-framework-oauth-authentication] and [permissions][django-rest-framework-oauth-permissions]. ### JSON Web Token Authentication JSON Web Token is a fairly new standard which can be used for token-based authentication. Unlike the built-in TokenAuthentication scheme, JWT Authentication doesn't need to use a database to validate a token. A package for JWT authentication is [djangorestframework-simplejwt][djangorestframework-simplejwt] which provides some features as well as a pluggable token blacklist app. ### Hawk HTTP Authentication The [HawkREST][hawkrest] library builds on the [Mohawk][mohawk] library to let you work with [Hawk][hawk] signed requests and responses in your API. [Hawk][hawk] lets two parties securely communicate with each other using messages signed by a shared key. It is based on [HTTP MAC access authentication][mac] (which was based on parts of [OAuth 1.0][oauth-1.0a]). ### 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]. ### 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 a ready to use REST implementation of the Django authentication system. ### DRF Auth Kit [DRF Auth Kit][drf-auth-kit] library provides a modern REST authentication solution with JWT cookies, social login, multi-factor authentication, and comprehensive user management. The package offers full type safety, automatic OpenAPI schema generation with DRF Spectacular. It supports multiple authentication types (JWT, DRF Token, or Custom) and includes built-in internationalization for 50+ languages. ### django-rest-auth / dj-rest-auth This library provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. By having these API endpoints, your client apps such as AngularJS, iOS, Android, and others can communicate to your Django backend site independently via REST APIs for user management. There are currently two forks of this project. * [Django-rest-auth][django-rest-auth] is the original project, [but is not currently receiving updates](https://github.com/Tivix/django-rest-auth/issues/568). * [Dj-rest-auth][dj-rest-auth] is a newer fork of the project. ### drf-social-oauth2 [Drf-social-oauth2][drf-social-oauth2] is a framework that helps you authenticate with major social oauth2 vendors, such as Facebook, Google, Twitter, Orcid, etc. It generates tokens in a JWTed way with an easy setup. ### drfpasswordless [drfpasswordless][drfpasswordless] adds (Medium, Square Cash inspired) passwordless support to Django REST Framework's TokenAuthentication scheme. Users log in and sign up with a token sent to a contact point like an email address or a mobile number. ### django-rest-authemail [django-rest-authemail][django-rest-authemail] provides a RESTful API interface for user signup and authentication. Email addresses are used for authentication, rather than usernames. API endpoints are available for signup, signup email verification, login, logout, password reset, password reset verification, email change, email change verification, password change, and user detail. A fully functional example project and detailed instructions are included. ### Django-Rest-Durin [Django-Rest-Durin][django-rest-durin] is built with the idea to have one library that does token auth for multiple Web/CLI/Mobile API clients via one interface but allows different token configuration for each API Client that consumes the API. It provides support for multiple tokens per user via custom models, views, permissions that work with Django-Rest-Framework. The token expiration time can be different per API client and is customizable via the Django Admin Interface. More information can be found in the [Documentation](https://django-rest-durin.readthedocs.io/en/latest/index.html). ### django-pyoidc [django_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/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/ [django-rest-framework-oauth-authentication]: https://jpadilla.github.io/django-rest-framework-oauth/authentication/ [django-rest-framework-oauth-permissions]: https://jpadilla.github.io/django-rest-framework-oauth/permissions/ [juanriaza]: https://github.com/juanriaza [djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth [oauth-1.0a]: https://oauth.net/core/1.0a/ [django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit [jazzband]: https://github.com/jazzband/ [oauthlib]: https://github.com/idan/oauthlib [djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt [etoccalino]: https://github.com/etoccalino/ [djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature [drf-httpsig]: https://github.com/ahknight/drf-httpsig [amazon-http-signature]: https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html [http-signature-ietf-draft]: https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ [hawkrest]: https://hawkrest.readthedocs.io/en/latest/ [hawk]: https://github.com/hueniverse/hawk [mohawk]: https://mohawk.readthedocs.io/en/latest/ [mac]: https://tools.ietf.org/html/draft-hammer-oauth-v2-mac-token-05 [djoser]: https://github.com/sunscrapers/djoser [django-rest-auth]: https://github.com/Tivix/django-rest-auth [dj-rest-auth]: https://github.com/jazzband/dj-rest-auth [drf-social-oauth2]: https://github.com/wagnerdelima/drf-social-oauth2 [django-rest-knox]: https://github.com/James1345/django-rest-knox [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 [drf-auth-kit]: https://github.com/huynguyengl99/drf-auth-kit ================================================ FILE: docs/api-guide/caching.md ================================================ # Caching > A certain woman had a very sharp consciousness but almost no > memory ... She remembered enough to work, and she worked hard. > - Lydia Davis Caching in REST Framework works well with the cache utilities provided in Django. --- ## Using cache with apiview and viewsets Django provides a [`method_decorator`][decorator] to use decorators with class based views. This can be used with other cache decorators such as [`cache_page`][page], [`vary_on_cookie`][cookie] and [`vary_on_headers`][headers]. ```python from django.utils.decorators import method_decorator from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_cookie, vary_on_headers from rest_framework.response import Response from rest_framework.views import APIView 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(vary_on_cookie) def list(self, request, format=None): content = { "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")) def get(self, request, format=None): content = { "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)) def get(self, request, format=None): 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/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 ================================================ FILE: docs/api-guide/content-negotiation.md ================================================ --- source: - negotiation.py --- > HTTP has provisions for several mechanisms for "content negotiation" - the process of selecting the best representation for a given response when there are multiple representations available. > > — [RFC 2616][cite], Fielding et al. [cite]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec12.html Content negotiation is the process of selecting one of multiple possible representations to return to a client, based on client or server preferences. ## Determining the accepted renderer REST framework uses a simple style of content negotiation to determine which media type should be returned to a client, based on the available renderers, the priorities of each of those renderers, and the client's `Accept:` header. The style used is partly client-driven, and partly server-driven. 1. More specific media types are given preference to less specific media types. 2. If multiple media types have the same specificity, then preference is given to based on the ordering of the renderers configured for the given view. For example, given the following `Accept` header: application/json; indent=4, application/json, application/yaml, text/html, */* The priorities for each of the given media types would be: * `application/json; indent=4` * `application/json`, `application/yaml` and `text/html` * `*/*` If the requested view was only configured with renderers for `YAML` and `HTML`, then REST framework would select whichever renderer was listed first in the `renderer_classes` list or `DEFAULT_RENDERER_CLASSES` setting. For more information on the `HTTP Accept` header, see [RFC 2616][accept-header] !!! note "q" values are not taken into account by REST framework when determining preference. The use of "q" values negatively impacts caching, and in the author's opinion they are an unnecessary and overcomplicated approach to content negotiation. This is a valid approach as the HTTP spec deliberately underspecifies how a server should weight server-based preferences against client-based preferences. ## Custom content negotiation It's unlikely that you'll want to provide a custom content negotiation scheme for REST framework, but you can do so if needed. To implement a custom content negotiation scheme override `BaseContentNegotiation`. REST framework's content negotiation classes handle selection of both the appropriate parser for the request, and the appropriate renderer for the response, so you should implement both the `.select_parser(request, parsers)` and `.select_renderer(request, renderers, format_suffix)` methods. The `select_parser()` method should return one of the parser instances from the list of available parsers, or `None` if none of the parsers can handle the incoming request. The `select_renderer()` method should return a two-tuple of (renderer instance, media type), or raise a `NotAcceptable` exception. ### Example The following is a custom content negotiation class which ignores the client request when selecting the appropriate parser or renderer. from rest_framework.negotiation import BaseContentNegotiation class IgnoreClientContentNegotiation(BaseContentNegotiation): def select_parser(self, request, parsers): """ Select the first parser in the `.parser_classes` list. """ return parsers[0] def select_renderer(self, request, renderers, format_suffix): """ Select the first renderer in the `.renderer_classes` list. """ return (renderers[0], renderers[0].media_type) ### Setting the content negotiation The default content negotiation class may be set globally, using the `DEFAULT_CONTENT_NEGOTIATION_CLASS` setting. For example, the following settings would use our example `IgnoreClientContentNegotiation` class. REST_FRAMEWORK = { 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'myapp.negotiation.IgnoreClientContentNegotiation', } You can also set the content negotiation used for an individual view, or viewset, using the `APIView` class-based views. from myapp.negotiation import IgnoreClientContentNegotiation from rest_framework.response import Response from rest_framework.views import APIView class NoNegotiationView(APIView): """ An example view that does not perform content negotiation. """ content_negotiation_class = IgnoreClientContentNegotiation def get(self, request, format=None): return Response({ 'accepted media type': request.accepted_renderer.media_type }) [accept-header]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html ================================================ FILE: docs/api-guide/exceptions.md ================================================ --- source: - exceptions.py --- # Exceptions > Exceptions… allow error handling to be organized cleanly in a central or high-level place within the program structure. > > — Doug Hellmann, [Python Exception Handling Techniques][cite] ## Exception handling in REST framework views REST framework's views handle various exceptions, and deal with returning appropriate error responses. The handled exceptions are: * Subclasses of `APIException` raised inside REST framework. * Django's `Http404` exception. * Django's `PermissionDenied` exception. In each case, REST framework will return a response with an appropriate status code and content-type. The body of the response will include any additional details regarding the nature of the error. Most error responses will include a key `detail` in the body of the response. For example, the following request: DELETE http://api.example.com/foo/bar HTTP/1.1 Accept: application/json Might receive an error response indicating that the `DELETE` method is not allowed on that resource: HTTP/1.1 405 Method Not Allowed Content-Type: application/json Content-Length: 42 {"detail": "Method 'DELETE' not allowed."} Validation errors are handled slightly differently, and will include the field names as the keys in the response. If the validation error was not specific to a particular field then it will use the "non_field_errors" key, or whatever string value has been set for the `NON_FIELD_ERRORS_KEY` setting. An example validation error might look like this: HTTP/1.1 400 Bad Request Content-Type: application/json Content-Length: 94 {"amount": ["A valid integer is required."], "description": ["This field may not be blank."]} ## Custom exception handling You can implement custom exception handling by creating a handler function that converts exceptions raised in your API views into response objects. This allows you to control the style of error responses used by your API. The function must take a pair of arguments, the first is the exception to be handled, and the second is a dictionary containing any extra context such as the view currently being handled. The exception handler function should either return a `Response` object, or return `None` if the exception cannot be handled. If the handler returns `None` then the exception will be re-raised and Django will return a standard HTTP 500 'server error' response. For example, you might want to ensure that all error responses include the HTTP status code in the body of the response, like so: HTTP/1.1 405 Method Not Allowed Content-Type: application/json Content-Length: 62 {"status_code": 405, "detail": "Method 'DELETE' not allowed."} In order to alter the style of the response, you could write the following custom exception handler: from rest_framework.views import exception_handler def custom_exception_handler(exc, context): # Call REST framework's default exception handler first, # to get the standard error response. response = exception_handler(exc, context) # Now add the HTTP status code to the response. if response is not None: response.data['status_code'] = response.status_code return response The context argument is not used by the default handler, but can be useful if the exception handler needs further information such as the view currently being handled, which can be accessed as `context['view']`. The exception handler must also be configured in your settings, using the `EXCEPTION_HANDLER` setting key. For example: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'my_project.my_app.utils.custom_exception_handler' } If not specified, the `'EXCEPTION_HANDLER'` setting defaults to the standard exception handler provided by REST framework: REST_FRAMEWORK = { 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler' } Note that the exception handler will only be called for responses generated by raised exceptions. It will not be used for any responses returned directly by the view, such as the `HTTP_400_BAD_REQUEST` responses that are returned by the generic views when serializer validation fails. --- ## API Reference ### APIException **Signature:** `APIException()` 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. For example, if your API relies on a third party service that may sometimes be unreachable, you might want to implement an exception for the "503 Service Unavailable" HTTP response code. You could do this like so: from rest_framework.exceptions import APIException class ServiceUnavailable(APIException): status_code = 503 default_detail = 'Service temporarily unavailable, try again later.' default_code = 'service_unavailable' #### Inspecting API exceptions There are a number of different properties available for inspecting the status of an API exception. You can use these to build custom exception handling for your project. The available attributes and methods are: * `.detail` - Return the textual description of the error. * `.get_codes()` - Return the code identifier of the error. * `.get_full_details()` - Return both the textual description and the code identifier. In most cases the error detail will be a simple item: >>> print(exc.detail) You do not have permission to perform this action. >>> print(exc.get_codes()) permission_denied >>> print(exc.get_full_details()) {'message':'You do not have permission to perform this action.','code':'permission_denied'} In the case of validation errors the error detail will be either a list or dictionary of items: >>> print(exc.detail) {"name":"This field is required.","age":"A valid integer is required."} >>> print(exc.get_codes()) {"name":"required","age":"invalid"} >>> print(exc.get_full_details()) {"name":{"message":"This field is required.","code":"required"},"age":{"message":"A valid integer is required.","code":"invalid"}} ### ParseError **Signature:** `ParseError(detail=None, code=None)` Raised if the request contains malformed data when accessing `request.data`. By default this exception results in a response with the HTTP status code "400 Bad Request". ### AuthenticationFailed **Signature:** `AuthenticationFailed(detail=None, code=None)` Raised when an incoming request includes incorrect authentication. By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details. ### NotAuthenticated **Signature:** `NotAuthenticated(detail=None, code=None)` Raised when an unauthenticated request fails the permission checks. By default this exception results in a response with the HTTP status code "401 Unauthenticated", but it may also result in a "403 Forbidden" response, depending on the authentication scheme in use. See the [authentication documentation][authentication] for more details. ### PermissionDenied **Signature:** `PermissionDenied(detail=None, code=None)` Raised when an authenticated request fails the permission checks. By default this exception results in a response with the HTTP status code "403 Forbidden". ### NotFound **Signature:** `NotFound(detail=None, code=None)` 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". ### MethodNotAllowed **Signature:** `MethodNotAllowed(method, detail=None, code=None)` Raised when an incoming request occurs that does not map to a handler method on the view. By default this exception results in a response with the HTTP status code "405 Method Not Allowed". ### NotAcceptable **Signature:** `NotAcceptable(detail=None, code=None)` Raised when an incoming request occurs with an `Accept` header that cannot be satisfied by any of the available renderers. By default this exception results in a response with the HTTP status code "406 Not Acceptable". ### UnsupportedMediaType **Signature:** `UnsupportedMediaType(media_type, detail=None, code=None)` Raised if there are no parsers that can handle the content type of the request data when accessing `request.data`. By default this exception results in a response with the HTTP status code "415 Unsupported Media Type". ### Throttled **Signature:** `Throttled(wait=None, detail=None, code=None)` Raised when an incoming request fails the throttling checks. By default this exception results in a response with the HTTP status code "429 Too Many Requests". ### ValidationError **Signature:** `ValidationError(detail=None, code=None)` The `ValidationError` exception is slightly different from the other `APIException` classes: * 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.')` The `ValidationError` class should be used for serializer and field validation, and by validator classes. It is also raised when calling `serializer.is_valid` with the `raise_exception` keyword argument: serializer.is_valid(raise_exception=True) The generic views use the `raise_exception=True` flag, which means that you can override the style of validation error responses globally in your API. To do so, use a custom exception handler, as described above. By default this exception results in a response with the HTTP status code "400 Bad Request". --- ## Generic Error Views Django REST Framework provides two error views suitable for providing generic JSON `500` Server Error and `400` Bad Request responses. (Django's default error views provide HTML responses, which may not be appropriate for an API-only application.) Use these as per [Django's Customizing error views documentation][django-custom-error-views]. ### `rest_framework.exceptions.server_error` Returns a response with status code `500` and `application/json` content type. Set as `handler500`: handler500 = 'rest_framework.exceptions.server_error' ### `rest_framework.exceptions.bad_request` Returns a response with status code `400` and `application/json` content type. Set as `handler400`: handler400 = 'rest_framework.exceptions.bad_request' ## Third party packages The following third-party packages are also available. ### DRF Standardized Errors The [drf-standardized-errors][drf-standardized-errors] package provides an exception handler that generates the same format for all 4xx and 5xx responses. It is a drop-in replacement for the default exception handler and allows customizing the error response format without rewriting the whole exception handler. The standardized error response format is easier to document and easier to handle by API consumers. [cite]: https://doughellmann.com/blog/2009/06/19/python-exception-handling-techniques/ [authentication]: authentication.md [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 ================================================ FILE: docs/api-guide/fields.md ================================================ --- source: - fields.py --- # Serializer fields > Each field in a Form class is responsible not only for validating data, but also for "cleaning" it — normalizing it to a consistent format. > > — [Django documentation][cite] Serializer fields handle converting between primitive values and internal datatypes. They also deal with validating input values, as well as retrieving and setting the values from their parent objects. !!! note The serializer fields are declared in `fields.py`, but by convention you should import them using `from rest_framework import serializers` and refer to fields as `serializers.`. ## Core arguments Each serializer field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted: ### `read_only` Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored. Set this to `True` to ensure that the field is used when serializing a representation, but is not used when creating or updating an instance during deserialization. Defaults to `False` ### `write_only` Set this to `True` to ensure that the field may be used when updating or creating an instance, but is not included when serializing the representation. Defaults to `False` ### `required` Normally an error will be raised if a field is not supplied during deserialization. Set to false if this field is not required to be present during deserialization. Setting this to `False` also allows the object attribute or dictionary key to be omitted from output when serializing the instance. If the key is not present it will simply not be included in the output representation. Defaults to `True`. If you're using [Model Serializer](https://www.django-rest-framework.org/api-guide/serializers/#modelserializer), the default value will be `False` when you have specified a `default`, or when the corresponding `Model` field has `blank=True` or `null=True` and is not part of a unique constraint at the same time. (Note that without a `default` value, [unique constraints will cause the field to be required](https://www.django-rest-framework.org/api-guide/validators/#optional-fields).) ### `default` If set, this gives the default value that will be used for the field if no input value is supplied. If not set the default behavior is to not populate the attribute at all. The `default` is not applied during partial update operations. In the partial update case only fields that are provided in the incoming data will have a validated value returned. May be set to a function or other callable, in which case the value will be evaluated each time it is used. When called, it will receive no arguments. If the callable has a `requires_context = True` attribute, then the serializer field will be passed as an argument. For example: class CurrentUserDefault: """ May be applied as a `default=...` value on a serializer field. Returns the current user. """ requires_context = True def __call__(self, serializer_field): return serializer_field.context['request'].user When serializing the instance, default will be used if the object attribute or dictionary key is not present in the instance. Note that setting a `default` value implies that the field is not required. Including both the `default` and `required` keyword arguments is invalid and will raise an error. ### `allow_null` Normally an error will be raised if `None` is passed to a serializer field. Set this keyword argument to `True` if `None` should be considered a valid value. Note that, without an explicit `default`, setting this argument to `True` will imply a `default` value of `null` for serialization output, but does not imply a default for input deserialization. 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')`. 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") 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. Defaults to the name of the field. ### `validators` A list of validator functions which should be applied to the incoming field input, and which either raise a validation error or simply return. Validator functions should typically raise `serializers.ValidationError`, but Django's built-in `ValidationError` is also supported for compatibility with validators defined in the Django codebase or third party Django packages. ### `error_messages` A dictionary of error codes to error messages. ### `label` A short text string that may be used as the name of the field in HTML form fields or other descriptive elements. ### `help_text` A text string that may be used as a description of the field in HTML form fields or other descriptive elements. ### `initial` A value that should be used for pre-populating the value of HTML form fields. You may pass a callable to it, just as you may do with any regular Django `Field`: import datetime from rest_framework import serializers class ExampleSerializer(serializers.Serializer): day = serializers.DateField(initial=datetime.date.today) ### `style` A dictionary of key-value pairs that can be used to control how renderers should render the field. Two examples here are `'input_type'` and `'base_template'`: # Use for the input. password = serializers.CharField( style={'input_type': 'password'} ) # Use a radio input instead of a select input. color_channel = serializers.ChoiceField( choices=['red', 'green', 'blue'], style={'base_template': 'radio.html'} ) For more details see the [HTML & Forms][html-and-forms] documentation. --- ## Boolean fields ### BooleanField A boolean representation. When using HTML encoded form input be aware that omitting a value will always be treated as setting a field to `False`, even if it has a `default=True` option specified. This is because HTML checkbox inputs represent the unchecked state by omitting the value, so REST framework treats omission as if it is an empty checkbox input. Note that Django 2.1 removed the `blank` kwarg from `models.BooleanField`. 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 behavior manually, explicitly declare the `BooleanField` on the serializer class, or use the `extra_kwargs` option to set the `required` flag. Corresponds to `django.db.models.fields.BooleanField`. **Signature:** `BooleanField()` --- ## String fields ### CharField A text representation. Optionally validates the text to be shorter than `max_length` and longer than `min_length`. Corresponds to `django.db.models.fields.CharField` or `django.db.models.fields.TextField`. **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`. The `allow_null` option is also available for string fields, although its usage is discouraged in favor of `allow_blank`. It is valid to set both `allow_blank=True` and `allow_null=True`, but doing so means that there will be two differing types of empty value permissible for string representations, which can lead to data inconsistencies and subtle application bugs. ### EmailField A text representation, validates the text to be a valid email address. Corresponds to `django.db.models.fields.EmailField` **Signature:** `EmailField(max_length=None, min_length=None, allow_blank=False)` ### RegexField A text representation, that validates the given value matches against a certain regular expression. Corresponds to `django.forms.fields.RegexField`. **Signature:** `RegexField(regex, max_length=None, min_length=None, allow_blank=False)` The mandatory `regex` argument may either be a string, or a compiled python regular expression object. Uses Django's `django.core.validators.RegexValidator` for validation. ### SlugField A `RegexField` that validates the input against the pattern `[a-zA-Z0-9_-]+`. Corresponds to `django.db.models.fields.SlugField`. **Signature:** `SlugField(max_length=50, min_length=None, allow_blank=False)` ### URLField A `RegexField` that validates the input against a URL matching pattern. Expects fully qualified URLs of the form `http:///`. Corresponds to `django.db.models.fields.URLField`. Uses Django's `django.core.validators.URLValidator` for validation. **Signature:** `URLField(max_length=200, min_length=None, allow_blank=False)` ### UUIDField A field that ensures the input is a valid UUID string. The `to_internal_value` method will return a `uuid.UUID` instance. On output the field will return a string in the canonical hyphenated format, for example: "de305d54-75b4-431b-adb2-eb6b9e546013" **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"` Changing the `format` parameters only affects representation values. All formats are accepted by `to_internal_value` ### FilePathField A field whose choices are limited to the filenames in a certain directory on the filesystem 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`. ### IPAddressField A field that ensures the input is a valid IPv4 or IPv6 string. Corresponds to `django.forms.fields.IPAddressField` and `django.forms.fields.GenericIPAddressField`. **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'. --- ## Numeric fields ### IntegerField An integer representation. Corresponds to `django.db.models.fields.IntegerField`, `django.db.models.fields.SmallIntegerField`, `django.db.models.fields.PositiveIntegerField` and `django.db.models.fields.PositiveSmallIntegerField`. **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. ### BigIntegerField A biginteger representation. Corresponds to `django.db.models.fields.BigIntegerField`. **Signature**: `BigIntegerField(max_value=None, min_value=None, coerce_to_string=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. * `coerce_to_string` Set to `True` if string values should be returned for the representation, or `False` if `BigInteger` objects should be returned. Defaults to the same value as the `COERCE_BIGINT_TO_STRING` settings key, which will be `False` unless overridden. If `BigInteger` objects are returned by the serializer, then the final output format will be determined by the renderer. ### FloatField A floating point representation. 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. ### DecimalField A decimal representation, represented in Python by a `Decimal` instance. Corresponds to `django.db.models.fields.DecimalField`. **Signature**: `DecimalField(max_digits, decimal_places, coerce_to_string=None, max_value=None, min_value=None)` * `max_digits` The maximum number of digits allowed in the number. 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 To validate numbers up to 999 with a resolution of 2 decimal places, you would use: serializers.DecimalField(max_digits=5, decimal_places=2) And to validate numbers up to anything less than one billion with a resolution of 10 decimal places: serializers.DecimalField(max_digits=19, decimal_places=10) --- ## Date and time fields ### DateTimeField A date and time representation. Corresponds to `django.db.models.fields.DateTimeField`. **Signature:** `DateTimeField(format=api_settings.DATETIME_FORMAT, input_formats=None, default_timezone=None)` * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATETIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `datetime` objects should be returned by `to_representation`. In this case the datetime encoding will be determined by the renderer. * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATETIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. * `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 be determined by the renderer class. #### `auto_now` and `auto_now_add` model fields. When using `ModelSerializer` or `HyperlinkedModelSerializer`, note that any model fields with `auto_now=True` or `auto_now_add=True` will use serializer fields that are `read_only=True` by default. If you want to override this behavior, you'll need to declare the `DateTimeField` explicitly on the serializer. For example: class CommentSerializer(serializers.ModelSerializer): created = serializers.DateTimeField() class Meta: model = Comment ### DateField A date representation. Corresponds to `django.db.models.fields.DateField` **Signature:** `DateField(format=api_settings.DATE_FORMAT, input_formats=None)` * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DATE_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `date` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer. * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `DATE_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. #### `DateField` format strings Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style dates should be used. (eg `'2013-01-29'`) ### TimeField A time representation. Corresponds to `django.db.models.fields.TimeField` **Signature:** `TimeField(format=api_settings.TIME_FORMAT, input_formats=None)` * `format` - A string representing the output format. If not specified, this defaults to the same value as the `TIME_FORMAT` settings key, which will be `'iso-8601'` unless set. Setting to a format string indicates that `to_representation` return values should be coerced to string output. Format strings are described below. Setting this value to `None` indicates that Python `time` objects should be returned by `to_representation`. In this case the time encoding will be determined by the renderer. * `input_formats` - A list of strings representing the input formats which may be used to parse the date. If not specified, the `TIME_INPUT_FORMATS` setting will be used, which defaults to `['iso-8601']`. #### `TimeField` format strings Format strings may either be [Python strftime formats][strftime] which explicitly specify the format, or the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style times should be used. (eg `'12:34:56.000000'`) ### DurationField A Duration representation. Corresponds to `django.db.models.fields.DurationField` The `validated_data` for these fields will contain a `datetime.timedelta` instance. **Signature:** `DurationField(format=api_settings.DURATION_FORMAT, max_value=None, min_value=None)` * `format` - A string representing the output format. If not specified, this defaults to the same value as the `DURATION_FORMAT` settings key, which will be `'django'` unless set. Formats are described below. Setting this value to `None` indicates that Python `timedelta` objects should be returned by `to_representation`. In this case the date encoding will be determined by the renderer. * `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. #### `DurationField` formats Format may either be the special string `'iso-8601'`, which indicates that [ISO 8601][iso8601] style intervals should be used (eg `'P4DT1H15M20S'`), or `'django'` which indicates that Django interval format `'[DD] [HH:[MM:]]ss[.uuuuuu]'` should be used (eg: `'4 1:15:20'`). --- ## Choice selection fields ### ChoiceField A field that can accept a value out of a limited set of choices. Used by `ModelSerializer` to automatically generate fields if the corresponding model field includes a `choices=…` argument. **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…"` Both the `allow_blank` and `allow_null` are valid options on `ChoiceField`, although it is highly recommended that you only use one and not both. `allow_blank` should be preferred for textual choices, and `allow_null` should be preferred for numeric or other non-textual choices. ### MultipleChoiceField A field that can accept a list of zero, one or many values, chosen from a limited set of choices. Takes a single mandatory argument. `to_internal_value` returns a `list` containing the selected values, deduplicated. **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…"` 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. --- ## File upload fields !!! note The `FileField` and `ImageField` classes are only suitable for use with `MultiPartParser` or `FileUploadParser`. Most parsers, such as e.g. JSON don't support file uploads. Django's regular [FILE_UPLOAD_HANDLERS] are used for handling uploaded files. ### FileField A file representation. Performs Django's standard FileField validation. Corresponds to `django.forms.fields.FileField`. **Signature:** `FileField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` * `max_length` - Designates the maximum length for the file name. * `allow_empty_file` - Designates if empty files are allowed. * `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. ### ImageField An image representation. Validates the uploaded file content as matching a known image format. Corresponds to `django.forms.fields.ImageField`. **Signature:** `ImageField(max_length=None, allow_empty_file=False, use_url=UPLOADED_FILES_USE_URL)` * `max_length` - Designates the maximum length for the file name. * `allow_empty_file` - Designates if empty files are allowed. * `use_url` - If set to `True` then URL string values will be used for the output representation. If set to `False` then filename string values will be used for the output representation. Defaults to the value of the `UPLOADED_FILES_USE_URL` settings key, which is `True` unless set otherwise. Requires either the `Pillow` package or `PIL` package. The `Pillow` package is recommended, as `PIL` is no longer actively maintained. --- ## Composite fields ### ListField 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. For example, to validate a list of integers you might use something like the following: scores = serializers.ListField( child=serializers.IntegerField(min_value=0, max_value=100) ) The `ListField` class also supports a declarative style that allows you to write reusable list field classes. class StringListField(serializers.ListField): child = serializers.CharField() We can now reuse our custom `StringListField` class throughout our application, without having to provide a `child` argument to it. ### DictField A field class that validates a dictionary of objects. The keys in `DictField` are always assumed to be string values. **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. For example, to create a field that validates a mapping of strings to strings, you would write something like this: document = DictField(child=CharField()) You can also use the declarative style, as with `ListField`. For example: class DocumentField(DictField): child = CharField() ### HStoreField A preconfigured `DictField` that is compatible with Django's postgres `HStoreField`. **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. Note that the child field **must** be an instance of `CharField`, as the hstore extension stores values as strings. ### JSONField A field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. **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`. --- ## Miscellaneous fields ### ReadOnlyField A field class that simply returns the value of the field without modification. This field is used by default with `ModelSerializer` when including field names that relate to an attribute rather than a model field. **Signature**: `ReadOnlyField()` For example, if `has_expired` was a property on the `Account` model, then the following serializer would automatically generate it as a `ReadOnlyField`: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'has_expired'] ### HiddenField A field class that does not take a value based on user input, but instead takes its value from a default value or callable. **Signature**: `HiddenField()` For example, to include a field that always provides the current time as part of the serializer validated data, you would use the following: modified = serializers.HiddenField(default=timezone.now) The `HiddenField` class is usually only needed if you have some validation that needs to run based on some pre-provided field values, but you do not want to expose all of those fields to the end user. 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. This field is used by `ModelSerializer` to correspond to custom model field classes. **Signature:** `ModelField(model_field=)` The `ModelField` class is generally intended for internal use, but can be used by your API if needed. In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model. For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))` ### SerializerMethodField This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object. **Signature**: `SerializerMethodField(method_name=None)` * `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_`. The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example: from django.contrib.auth.models import User from django.utils.timezone import now from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): days_since_joined = serializers.SerializerMethodField() class Meta: model = User fields = '__all__' def get_days_since_joined(self, obj): return (now() - obj.date_joined).days --- ## Custom fields If you want to create a custom field, you'll need to subclass `Field` and then override either one or both of the `.to_representation()` and `.to_internal_value()` methods. These two methods are used to convert between the initial datatype, and a primitive, serializable datatype. Primitive datatypes will typically be any of a number, string, boolean, `date`/`time`/`datetime` or `None`. They may also be any list or dictionary like object that only contains other primitive objects. Other types might be supported, depending on the renderer that you are using. The `.to_representation()` method is called to convert the initial datatype into a primitive, serializable datatype. The `.to_internal_value()` method is called to restore a primitive datatype into its internal python representation. This method should raise a `serializers.ValidationError` if the data is invalid. ### Examples #### A Basic Custom Field Let's look at an example of serializing a class that represents an RGB color value: class Color: """ A color represented in the RGB colorspace. """ def __init__(self, red, green, blue): assert(red >= 0 and green >= 0 and blue >= 0) assert(red < 256 and green < 256 and blue < 256) self.red, self.green, self.blue = red, green, blue class ColorField(serializers.Field): """ Color objects are serialized into 'rgb(#, #, #)' notation. """ def to_representation(self, value): return "rgb(%d, %d, %d)" % (value.red, value.green, value.blue) def to_internal_value(self, data): data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] return Color(red, green, blue) By default field values are treated as mapping to an attribute on the object. If you need to customize how the field value is accessed and set you need to override `.get_attribute()` and/or `.get_value()`. As an example, let's create a field that can be used to represent the class name of the object being serialized: class ClassNameField(serializers.Field): def get_attribute(self, instance): # We pass the object instance onto `to_representation`, # not just the field attribute. return instance def to_representation(self, value): """ Serialize the value's class name. """ return value.__class__.__name__ #### Raising validation errors Our `ColorField` class above currently does not perform any data validation. To indicate invalid data, we should raise a `serializers.ValidationError`, like so: def to_internal_value(self, data): if not isinstance(data, str): msg = 'Incorrect type. Expected a string, but got %s' raise ValidationError(msg % type(data).__name__) if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data): raise ValidationError('Incorrect format. Expected `rgb(#,#,#)`.') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): raise ValidationError('Value out of range. Must be between 0 and 255.') return Color(red, green, blue) The `.fail()` method is a shortcut for raising `ValidationError` that takes a message string from the `error_messages` dictionary. For example: default_error_messages = { 'incorrect_type': 'Incorrect type. Expected a string, but got {input_type}', 'incorrect_format': 'Incorrect format. Expected `rgb(#,#,#)`.', 'out_of_range': 'Value out of range. Must be between 0 and 255.' } def to_internal_value(self, data): if not isinstance(data, str): self.fail('incorrect_type', input_type=type(data).__name__) if not re.match(r'^rgb\([0-9]+,[0-9]+,[0-9]+\)$', data): self.fail('incorrect_format') data = data.strip('rgb(').rstrip(')') red, green, blue = [int(col) for col in data.split(',')] if any([col > 255 or col < 0 for col in (red, green, blue)]): self.fail('out_of_range') return Color(red, green, blue) This style keeps your error messages cleaner and more separated from your code, and should be preferred. #### Using `source='*'` Here we'll take an example of a _flat_ `DataPoint` model with `x_coordinate` and `y_coordinate` attributes. class DataPoint(models.Model): label = models.CharField(max_length=50) x_coordinate = models.SmallIntegerField() y_coordinate = models.SmallIntegerField() Using a custom field and `source='*'` we can provide a nested representation of the coordinate pair: class CoordinateField(serializers.Field): def to_representation(self, value): ret = { "x": value.x_coordinate, "y": value.y_coordinate } return ret def to_internal_value(self, data): ret = { "x_coordinate": data["x"], "y_coordinate": data["y"], } return ret class DataPointSerializer(serializers.ModelSerializer): coordinates = CoordinateField(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] Note that this example doesn't handle validation. Partly for that reason, in a real project, the coordinate nesting might be better handled with a nested serializer using `source='*'`, with two `IntegerField` instances, each with their own `source` pointing to the relevant field. The key points from the example, though, are: * `to_representation` is passed the entire `DataPoint` object and must map from that to the desired output. >>> instance = DataPoint(label='Example', x_coordinate=1, y_coordinate=2) >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'Example'), ('coordinates', {'x': 1, 'y': 2})]) * Unless our field is to be read-only, `to_internal_value` must map back to a dict suitable for updating our target object. With `source='*'`, the return from `to_internal_value` will update the root validated data dictionary, rather than a single key. >>> data = { ... "label": "Second Example", ... "coordinates": { ... "x": 3, ... "y": 4, ... } ... } >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'Second Example'), ('y_coordinate', 4), ('x_coordinate', 3)]) For completeness let's do the same thing again but with the nested serializer approach suggested above: class NestedCoordinateSerializer(serializers.Serializer): x = serializers.IntegerField(source='x_coordinate') y = serializers.IntegerField(source='y_coordinate') class DataPointSerializer(serializers.ModelSerializer): coordinates = NestedCoordinateSerializer(source='*') class Meta: model = DataPoint fields = ['label', 'coordinates'] 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 behavior as the custom field approach. Serializing: >>> out_serializer = DataPointSerializer(instance) >>> out_serializer.data ReturnDict([('label', 'testing'), ('coordinates', OrderedDict([('x', 1), ('y', 2)]))]) Deserializing: >>> in_serializer = DataPointSerializer(data=data) >>> in_serializer.is_valid() True >>> in_serializer.validated_data OrderedDict([('label', 'still testing'), ('x_coordinate', 3), ('y_coordinate', 4)]) But we also get the built-in validation for free: >>> invalid_data = { ... "label": "still testing", ... "coordinates": { ... "x": 'a', ... "y": 'b', ... } ... } >>> invalid_serializer = DataPointSerializer(data=invalid_data) >>> invalid_serializer.is_valid() False >>> invalid_serializer.errors ReturnDict([('coordinates', {'x': ['A valid integer is required.'], 'y': ['A valid integer is required.']})]) For this reason, the nested serializer approach would be the first to try. You would use the custom field approach when the nested serializer becomes infeasible or overly complex. ## Third party packages The following third party packages are also available. ### DRF Compound Fields The [drf-compound-fields][drf-compound-fields] package provides "compound" serializer fields, such as lists of simple values, which can be described by other fields rather than serializers with the `many=True` option. Also provided are fields for typed dictionaries and values that can be either a specific type or a list of items of that type. ### DRF Extra Fields The [drf-extra-fields][drf-extra-fields] package provides extra serializer fields for REST framework, including `Base64ImageField` and `PointField` classes. ### djangorestframework-recursive the [djangorestframework-recursive][djangorestframework-recursive] package provides a `RecursiveField` for serializing and deserializing recursive structures ### django-rest-framework-gis The [django-rest-framework-gis][django-rest-framework-gis] package provides geographic addons for django rest framework like a `GeometryField` field and a GeoJSON serializer. [cite]: https://docs.djangoproject.com/en/stable/ref/forms/api/#django.forms.Form.cleaned_data [html-and-forms]: ../topics/html-and-forms.md [FILE_UPLOAD_HANDLERS]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-FILE_UPLOAD_HANDLERS [strftime]: https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior [iso8601]: https://www.w3.org/TR/NOTE-datetime [drf-compound-fields]: https://drf-compound-fields.readthedocs.io [drf-extra-fields]: https://github.com/Hipo/drf-extra-fields [djangorestframework-recursive]: https://github.com/heywbj/django-rest-framework-recursive [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis [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/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related ================================================ FILE: docs/api-guide/filtering.md ================================================ --- source: - filters.py --- # Filtering > The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. > > — [Django documentation][cite] The default behavior of REST framework's generic list views is to return the entire queryset for a model manager. Often you will want your API to restrict the items that are returned by the queryset. The simplest way to filter the queryset of any view that subclasses `GenericAPIView` is to override the `.get_queryset()` method. Overriding this method allows you to customize the queryset returned by the view in a number of different ways. ## Filtering against the current user You might want to filter the queryset to ensure that only results relevant to the currently authenticated user making the request are returned. You can do so by filtering based on the value of `request.user`. For example: from myapp.models import Purchase from myapp.serializers import PurchaseSerializer from rest_framework import generics class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ This view should return a list of all the purchases for the currently authenticated user. """ user = self.request.user return Purchase.objects.filter(purchaser=user) ## Filtering against the URL Another style of filtering might involve restricting the queryset based on some part of the URL. For example if your URL config contained an entry like this: re_path('^purchases/(?P.+)/$', PurchaseList.as_view()), You could then write a view that returned a purchase queryset filtered by the username portion of the URL: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ This view should return a list of all the purchases for the user as determined by the username portion of the URL. """ username = self.kwargs['username'] return Purchase.objects.filter(purchaser__username=username) ## Filtering against query parameters A final example of filtering the initial queryset would be to determine the initial queryset based on query parameters in the url. We can override `.get_queryset()` to deal with URLs such as `http://example.com/api/purchases?username=denvercoder9`, and filter the queryset only if the `username` parameter is included in the URL: class PurchaseList(generics.ListAPIView): serializer_class = PurchaseSerializer def get_queryset(self): """ Optionally restricts the returned purchases to a given user, by filtering against a `username` query parameter in the URL. """ queryset = Purchase.objects.all() username = self.request.query_params.get('username') if username is not None: queryset = queryset.filter(purchaser__username=username) return queryset --- ## Generic Filtering As well as being able to override the default queryset, REST framework also includes support for generic filtering backends that allow you to easily construct complex searches and filters. Generic filters can also present themselves as HTML controls in the browsable API and admin API. ![Filter Example](../img/filter-controls.png) ### Setting filter backends The default filter backends may be set globally, using the `DEFAULT_FILTER_BACKENDS` setting. For example. REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } You can also set the filter backends on a per-view, or per-viewset basis, using the `GenericAPIView` class-based views. import django_filters.rest_framework from django.contrib.auth.models import User from myapp.serializers import UserSerializer from rest_framework import generics class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [django_filters.rest_framework.DjangoFilterBackend] ### Filtering and object lookups Note that if a filter backend is configured for a view, then as well as being used to filter list views, it will also be used to filter the querysets used for returning a single object. For instance, given the previous example, and a product with an id of `4675`, the following URL would either return the corresponding object, or return a 404 response, depending on if the filtering conditions were met by the given product instance: http://example.com/api/products/4675/?category=clothing&max_price=10.00 ### Overriding the initial queryset Note that you can use both an overridden `.get_queryset()` and generic filtering together, and everything will work as expected. For example, if `Product` had a many-to-many relationship with `User`, named `purchase`, you might want to write a view like this: class PurchasedProductsList(generics.ListAPIView): """ Return a list of all the products that the authenticated user has ever purchased, with optional filtering. """ model = Product serializer_class = ProductSerializer filterset_class = ProductFilter def get_queryset(self): user = self.request.user return user.purchase_set.all() --- ## API Guide ### DjangoFilterBackend The [`django-filter`][django-filter-docs] library includes a `DjangoFilterBackend` class which supports highly customizable field filtering for REST framework. To use `DjangoFilterBackend`, first install `django-filter`. pip install django-filter Then add `'django_filters'` to Django's `INSTALLED_APPS`: INSTALLED_APPS = [ ... 'django_filters', ... ] You should now either add the filter backend to your settings: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'] } Or add the filter backend to an individual View or ViewSet. from django_filters.rest_framework import DjangoFilterBackend class UserListView(generics.ListAPIView): ... filter_backends = [DjangoFilterBackend] If all you need is simple equality-based filtering, you can set a `filterset_fields` attribute on the view, or viewset, listing the set of fields you wish to filter against. class ProductList(generics.ListAPIView): queryset = Product.objects.all() serializer_class = ProductSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['category', 'in_stock'] This will automatically create a `FilterSet` class for the given fields, and will allow you to make requests such as: http://example.com/api/products?category=clothing&in_stock=True For more advanced filtering requirements you can specify a `FilterSet` class that should be used by the view. You can read more about `FilterSet`s in the [django-filter documentation][django-filter-docs]. It's also recommended that you read the section on [DRF integration][django-filter-drf-docs]. ### SearchFilter The `SearchFilter` class supports simple single query parameter based searching, and is based on the [Django admin's search functionality][search-django-admin]. When in use, the browsable API will include a `SearchFilter` control: ![Search Filter](../img/search-filter.png) The `SearchFilter` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`. from rest_framework import filters class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.SearchFilter] search_fields = ['username', 'email'] This will allow the client to filter the items in the list by making queries such as: http://example.com/api/users?search=russell You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API double-underscore notation: 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. Searches may contain _quoted phrases_ with spaces, each phrase is considered as a single search term. 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): | 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: search_fields = ['=username', '=email'] By default, the search parameter is named `'search'`, but this may be overridden with the `SEARCH_PARAM` setting in the `REST_FRAMEWORK` configuration. To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request: from rest_framework import filters class CustomSearchFilter(filters.SearchFilter): def get_search_fields(self, view, request): if request.query_params.get('title_only'): return ['title'] return super().get_search_fields(view, request) For more details, see the [Django documentation][search-django-admin]. --- ### OrderingFilter The `OrderingFilter` class supports simple query parameter controlled ordering of results. ![Ordering Filter](../img/ordering-filter.png) By default, the query parameter is named `'ordering'`, but this may be overridden with the `ORDERING_PARAM` setting in the `REST_FRAMEWORK` configuration. For example, to order users by username: http://example.com/api/users?ordering=username The client may also specify reverse orderings by prefixing the field name with '-', like so: http://example.com/api/users?ordering=-username Multiple orderings may also be specified: http://example.com/api/users?ordering=account,username #### Specifying which fields may be ordered against 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() serializer_class = UserSerializer filter_backends = [filters.OrderingFilter] ordering_fields = ['username', 'email'] This helps prevent unexpected data leakage, such as allowing users to order against a password hash field or other sensitive data. If you *don't* specify an `ordering_fields` attribute on the view, the filter class will default to allowing the user to filter on any readable fields on the serializer specified by the `serializer_class` attribute. If you are confident that the queryset being used by the view doesn't contain any sensitive data, you can also explicitly specify that a view should allow ordering on *any* model field or queryset aggregate, by using the special value `'__all__'`. class BookingsListView(generics.ListAPIView): queryset = Booking.objects.all() serializer_class = BookingSerializer filter_backends = [filters.OrderingFilter] ordering_fields = '__all__' #### Specifying a default ordering If an `ordering` attribute is set on the view, this will be used as the default ordering. Typically you'd instead control this by setting `order_by` on the initial queryset, but using the `ordering` parameter on the view allows you to specify the ordering in a way that it can then be passed automatically as context to a rendered template. This makes it possible to automatically render column headers differently if they are being used to order the results. class UserListView(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = [filters.OrderingFilter] ordering_fields = ['username', 'email'] ordering = ['username'] The `ordering` attribute may be either a string or a list/tuple of strings. --- ## Custom generic filtering You can also provide your own generic filtering backend, or write an installable app for other developers to use. To do so override `BaseFilterBackend`, and override the `.filter_queryset(self, request, queryset, view)` method. The method should return a new, filtered queryset. As well as allowing clients to perform searches and filtering, generic filter backends can be useful for restricting which objects should be visible to any given request or user. ### Example For example, you might need to restrict users to only being able to see objects they created. class IsOwnerFilterBackend(filters.BaseFilterBackend): """ Filter that only allows users to see their own objects. """ def filter_queryset(self, request, queryset, view): return queryset.filter(owner=request.user) We could achieve the same behavior by overriding `get_queryset()` on the views, but using a filter backend allows you to more easily add this restriction to multiple views, or to apply it across the entire API. ### Customizing the interface Generic filters may also present an interface in the browsable API. To do so you should implement a `to_html()` method which returns a rendered HTML representation of the filter. This method should have the following signature: `to_html(self, request, queryset, view)` The method should return a rendered HTML string. ## Third party packages The following third party packages provide additional filter implementations. ### Django REST framework filters package The [django-rest-framework-filters package][django-rest-framework-filters] works together with the `DjangoFilterBackend` class, and allows you to easily create filters across relationships, or create multiple filter lookup types for a given field. ### Django REST framework full word search filter The [djangorestframework-word-filter][django-rest-framework-word-search-filter] developed as alternative to `filters.SearchFilter` which will search full word in text, or exact match. ### Django URL Filter [django-url-filter][django-url-filter] provides a safe way to filter data via human-friendly URLs. It works very similar to DRF serializers and fields in a sense that they can be nested except they are called filtersets and filters. That provides easy way to filter related data. Also this library is generic-purpose so it can be used to filter other sources of data and not only Django `QuerySet`s. ### drf-url-filters [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. A beautiful python package `Voluptuous` is being used for validations on the incoming query parameters. The best part about voluptuous is you can define your own validations as per your query params requirements. [cite]: https://docs.djangoproject.com/en/stable/topics/db/queries/#retrieving-specific-objects-with-filters [django-filter-docs]: https://django-filter.readthedocs.io/en/latest/index.html [django-filter-drf-docs]: https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html [search-django-admin]: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields [django-rest-framework-filters]: https://github.com/philipn/django-rest-framework-filters [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/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/ ================================================ FILE: docs/api-guide/format-suffixes.md ================================================ --- source: - urlpatterns.py --- # Format suffixes > Section 6.2.1 does not say that content negotiation should be used all the time. > > — Roy Fielding, [REST discuss mailing list][cite] A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type. For example, 'http://example.com/api/users.json' to serve a JSON representation. Adding format-suffix patterns to each individual entry in the URLconf for your API is error-prone and non-DRY, so REST framework provides a shortcut to adding these patterns to your URLConf. ## format_suffix_patterns **Signature**: format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None) Returns a URL pattern list which includes format suffix patterns appended to each of the URL patterns provided. Arguments: * **urlpatterns**: Required. A URL pattern list. * **suffix_required**: Optional. A boolean indicating if suffixes in the URLs should be optional or mandatory. Defaults to `False`, meaning that suffixes are optional by default. * **allowed**: Optional. A list or tuple of valid format suffixes. If not provided, a wildcard format suffix pattern will be used. Example: from rest_framework.urlpatterns import format_suffix_patterns from blog import views urlpatterns = [ path('', views.apt_root), path('comments/', views.comment_list), path('comments//', views.comment_detail) ] urlpatterns = format_suffix_patterns(urlpatterns, allowed=['json', 'html']) When using `format_suffix_patterns`, you must make sure to add the `'format'` keyword argument to the corresponding views. For example: @api_view(['GET', 'POST']) def comment_list(request, format=None): # do stuff... Or with class-based views: class CommentList(APIView): def get(self, request, format=None): # do stuff... def post(self, request, format=None): # do stuff... The name of the kwarg used may be modified by using the `FORMAT_SUFFIX_KWARG` setting. Also note that `format_suffix_patterns` does not support descending into `include` URL patterns. ### Using with `i18n_patterns` If using the `i18n_patterns` function provided by Django, as well as `format_suffix_patterns` you should make sure that the `i18n_patterns` function is applied as the final, or outermost function. For example: urlpatterns = [ … ] urlpatterns = i18n_patterns( format_suffix_patterns(urlpatterns, allowed=['json', 'html']) ) --- ## Query parameter formats An alternative to the format suffixes is to include the requested format in a query parameter. REST framework provides this option by default, and it is used in the browsable API to switch between differing available representations. To select a representation using its short format, use the `format` query parameter. For example: `http://example.com/organizations/?format=csv`. The name of this query parameter can be modified using the `URL_FORMAT_OVERRIDE` setting. Set the value to `None` to disable this behavior. --- ## Accept headers vs. format suffixes There seems to be a view among some of the Web community that filename extensions are not a RESTful pattern, and that `HTTP Accept` headers should always be used instead. It is actually a misconception. For example, take the following quote from Roy Fielding discussing the relative merits of query parameter media-type indicators vs. file extension media-type indicators: “That's why I always prefer extensions. Neither choice has anything to do with REST.” — Roy Fielding, [REST discuss mailing list][cite2] The quote does not mention Accept headers, but it does make it clear that format suffixes should be considered an acceptable pattern. [cite]: http://tech.groups.yahoo.com/group/rest-discuss/message/5857 [cite2]: https://groups.yahoo.com/neo/groups/rest-discuss/conversations/topics/14844 ================================================ FILE: docs/api-guide/generic-views.md ================================================ --- source: - mixins.py - generics.py --- # Generic views > Django’s generic views... were developed as a shortcut for common usage patterns... They take certain common idioms and patterns found in view development and abstract them so that you can quickly write common views of data without having to repeat yourself. > > — [Django Documentation][cite] One of the key benefits of class-based views is the way they allow you to compose bits of reusable behavior. REST framework takes advantage of this by providing a number of pre-built views that provide for commonly used patterns. The generic views provided by REST framework allow you to quickly build API views that map closely to your database models. If the generic views don't suit the needs of your API, you can drop down to using the regular `APIView` class, or reuse the mixins and base classes used by the generic views to compose your own set of reusable generic views. ## Examples Typically when using the generic views, you'll override the view, and set several class attributes. from django.contrib.auth.models import User from myapp.serializers import UserSerializer from rest_framework import generics from rest_framework.permissions import IsAdminUser class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAdminUser] For more complex cases you might also want to override various methods on the view class. For example. class UserList(generics.ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = [IsAdminUser] def list(self, request): # Note the use of `get_queryset()` instead of `self.queryset` queryset = self.get_queryset() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) For very simple cases you might want to pass through any class attributes using the `.as_view()` method. For example, your URLconf might include something like the following entry: path('users/', ListCreateAPIView.as_view(queryset=User.objects.all(), serializer_class=UserSerializer), name='user-list') --- ## API Reference ### GenericAPIView This class extends REST framework's `APIView` class, adding commonly required behavior for standard list and detail views. Each of the concrete generic views provided is built by combining `GenericAPIView`, with one or more mixin classes. #### Attributes **Basic settings**: The following attributes control the basic view behavior. * `queryset` - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the `get_queryset()` method. If you are overriding a view method, it is important that you call `get_queryset()` instead of accessing this property directly, as `queryset` will get evaluated once, and those results will be cached for all subsequent requests. * `serializer_class` - The serializer class that should be used for validating and deserializing input, and for serializing output. Typically, you must either set this attribute, or override the `get_serializer_class()` method. * `lookup_field` - The model field that should be used for performing object lookup of individual model instances. Defaults to `'pk'`. Note that when using hyperlinked APIs you'll need to ensure that *both* the API views *and* the serializer classes set the lookup fields if you need to use a custom value. * `lookup_url_kwarg` - The URL keyword argument that should be used for object lookup. The URL conf should include a keyword argument corresponding to this value. If unset this defaults to using the same value as `lookup_field`. **Pagination**: The following attributes are used to control pagination when used with list views. * `pagination_class` - The pagination class that should be used when paginating list results. Defaults to the same value as the `DEFAULT_PAGINATION_CLASS` setting, which is `'rest_framework.pagination.PageNumberPagination'`. Setting `pagination_class=None` will disable pagination on this view. **Filtering**: * `filter_backends` - A list of filter backend classes that should be used for filtering the queryset. Defaults to the same value as the `DEFAULT_FILTER_BACKENDS` setting. #### Methods **Base methods**: ##### `get_queryset(self)` Returns the queryset that should be used for list views, and that should be used as the base for lookups in detail views. Defaults to returning the queryset specified by the `queryset` attribute. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. May be overridden to provide dynamic behavior, such as returning a queryset, that is specific to the user making the request. For example: def get_queryset(self): user = self.request.user return user.accounts.all() !!! tip 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]. #### Avoiding N+1 Queries When listing objects (e.g. using `ListAPIView` or `ModelViewSet`), serializers may trigger an N+1 query pattern if related objects are accessed individually for each item. To prevent this, optimize the queryset in `get_queryset()` or by setting the `queryset` class attribute using [`select_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-related) and [`prefetch_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related), depending on the type of relationship. **For ForeignKey and OneToOneField**: Use `select_related()` to fetch related objects in the same query: def get_queryset(self): return Order.objects.select_related("customer", "billing_address") **For reverse and many-to-many relationships**: Use `prefetch_related()` to efficiently load collections of related objects: def get_queryset(self): return Book.objects.prefetch_related("categories", "reviews__user") **Combining both**: def get_queryset(self): return ( Order.objects .select_related("customer") .prefetch_related("items__product") ) These optimizations reduce repeated database access and improve list view performance. --- ##### `get_object(self)` Returns an object instance that should be used for detail views. Defaults to using the `lookup_field` parameter to filter the base queryset. May be overridden to provide more complex behavior, such as object lookups based on more than one URL kwarg. For example: def get_object(self): queryset = self.get_queryset() filter = {} for field in self.multiple_lookup_fields: filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) self.check_object_permissions(self.request, obj) return obj Note that if your API doesn't include any object level permissions, you may optionally exclude the `self.check_object_permissions`, and simply return the object from the `get_object_or_404` lookup. ##### `filter_queryset(self, queryset)` Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. For example: def filter_queryset(self, queryset): filter_backends = [CategoryFilter] if 'geo_route' in self.request.query_params: filter_backends = [GeoRouteFilter, CategoryFilter] elif 'geo_point' in self.request.query_params: filter_backends = [GeoPointFilter, CategoryFilter] for backend in list(filter_backends): queryset = backend().filter_queryset(self.request, queryset, view=self) return queryset ##### `get_serializer_class(self)` Returns the class that should be used for the serializer. Defaults to returning the `serializer_class` attribute. May be overridden to provide dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users. For example: def get_serializer_class(self): if self.request.user.is_staff: return FullAccountSerializer return BasicAccountSerializer **Save and deletion hooks**: The following methods are provided by the mixin classes, and provide easy overriding of the object save or deletion behavior. * `perform_create(self, serializer)` - Called by `CreateModelMixin` when saving a new object instance. * `perform_update(self, serializer)` - Called by `UpdateModelMixin` when saving an existing object instance. * `perform_destroy(self, instance)` - Called by `DestroyModelMixin` when deleting an object instance. These hooks are particularly useful for setting attributes that are implicit in the request, but are not part of the request data. For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument. def perform_create(self, serializer): serializer.save(user=self.request.user) These override points are also particularly useful for adding behavior that occurs before or after saving an object, such as emailing a confirmation, or logging the update. def perform_update(self, serializer): instance = serializer.save() send_email_confirmation(user=self.request.user, modified=instance) You can also use these hooks to provide additional validation, by raising a `ValidationError()`. This can be useful if you need some validation logic to apply at the point of database save. For example: def perform_create(self, serializer): queryset = SignupRequest.objects.filter(user=self.request.user) if queryset.exists(): raise ValidationError('You have already signed up') serializer.save(user=self.request.user) **Other methods**: You won't typically need to override the following methods, although you might need to call into them if you're writing custom views using `GenericAPIView`. * `get_serializer_context(self)` - Returns a dictionary containing any extra context that should be supplied to the serializer. Defaults to including `'request'`, `'view'` and `'format'` keys. * `get_serializer(self, instance=None, data=None, many=False, partial=False)` - Returns a serializer instance. * `get_paginated_response(self, data)` - Returns a paginated style `Response` object. * `paginate_queryset(self, queryset)` - Paginate a queryset if required, either returning a page object, or `None` if pagination is not configured for this view. * `filter_queryset(self, queryset)` - Given a queryset, filter it with whichever filter backends are in use, returning a new queryset. --- ## Mixins The mixin classes provide the actions that are used to provide the basic view behavior. Note that the mixin classes provide action methods rather than defining the handler methods, such as `.get()` and `.post()`, directly. This allows for more flexible composition of behavior. The mixin classes can be imported from `rest_framework.mixins`. ### ListModelMixin Provides a `.list(request, *args, **kwargs)` method, that implements listing a queryset. If the queryset is populated, this returns a `200 OK` response, with a serialized representation of the queryset as the body of the response. The response data may optionally be paginated. ### CreateModelMixin Provides a `.create(request, *args, **kwargs)` method, that implements creating and saving a new model instance. If an object is created this returns a `201 Created` response, with a serialized representation of the object as the body of the response. If the representation contains a key named `url`, then the `Location` header of the response will be populated with that value. If the request data provided for creating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. ### RetrieveModelMixin Provides a `.retrieve(request, *args, **kwargs)` method, that implements returning an existing model instance in a response. If an object can be retrieved this returns a `200 OK` response, with a serialized representation of the object as the body of the response. Otherwise, it will return a `404 Not Found`. ### UpdateModelMixin Provides a `.update(request, *args, **kwargs)` method, that implements updating and saving an existing model instance. Also provides a `.partial_update(request, *args, **kwargs)` method, which is similar to the `update` method, except that all fields for the update will be optional. This allows support for HTTP `PATCH` requests. If an object is updated this returns a `200 OK` response, with a serialized representation of the object as the body of the response. If the request data provided for updating the object was invalid, a `400 Bad Request` response will be returned, with the error details as the body of the response. ### DestroyModelMixin Provides a `.destroy(request, *args, **kwargs)` method, that implements deletion of an existing model instance. If an object is deleted this returns a `204 No Content` response, otherwise it will return a `404 Not Found`. --- ## Concrete View Classes The following classes are the concrete generic views. If you're using generic views this is normally the level you'll be working at unless you need heavily customized behavior. The view classes can be imported from `rest_framework.generics`. ### CreateAPIView Used for **create-only** endpoints. Provides a `post` method handler. Extends: [GenericAPIView], [CreateModelMixin] ### ListAPIView Used for **read-only** endpoints to represent a **collection of model instances**. Provides a `get` method handler. Extends: [GenericAPIView], [ListModelMixin] ### RetrieveAPIView Used for **read-only** endpoints to represent a **single model instance**. Provides a `get` method handler. Extends: [GenericAPIView], [RetrieveModelMixin] ### DestroyAPIView Used for **delete-only** endpoints for a **single model instance**. Provides a `delete` method handler. Extends: [GenericAPIView], [DestroyModelMixin] ### UpdateAPIView Used for **update-only** endpoints for a **single model instance**. Provides `put` and `patch` method handlers. Extends: [GenericAPIView], [UpdateModelMixin] ### ListCreateAPIView Used for **read-write** endpoints to represent a **collection of model instances**. Provides `get` and `post` method handlers. Extends: [GenericAPIView], [ListModelMixin], [CreateModelMixin] ### RetrieveUpdateAPIView Used for **read or update** endpoints to represent a **single model instance**. Provides `get`, `put` and `patch` method handlers. Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin] ### RetrieveDestroyAPIView Used for **read or delete** endpoints to represent a **single model instance**. Provides `get` and `delete` method handlers. Extends: [GenericAPIView], [RetrieveModelMixin], [DestroyModelMixin] ### RetrieveUpdateDestroyAPIView Used for **read-write-delete** endpoints to represent a **single model instance**. Provides `get`, `put`, `patch` and `delete` method handlers. Extends: [GenericAPIView], [RetrieveModelMixin], [UpdateModelMixin], [DestroyModelMixin] --- ## Customizing the generic views Often you'll want to use the existing generic views, but use some slightly customized behavior. If you find yourself reusing some bit of customized behavior in multiple places, you might want to refactor the behavior into a common class that you can then just apply to any view or viewset as needed. ### Creating custom mixins For example, if you need to lookup objects based on multiple fields in the URL conf, you could create a mixin class like the following: class MultipleFieldLookupMixin: """ Apply this mixin to any view or viewset to get multiple field filtering based on a `lookup_fields` attribute, instead of the default single field filtering. """ def get_object(self): queryset = self.get_queryset() # Get the base queryset queryset = self.filter_queryset(queryset) # Apply any filter backends filter = {} for field in self.lookup_fields: if self.kwargs.get(field): # Ignore empty fields. filter[field] = self.kwargs[field] obj = get_object_or_404(queryset, **filter) # Lookup the object self.check_object_permissions(self.request, obj) return obj You can then simply apply this mixin to a view or viewset anytime you need to apply the custom behavior. class RetrieveUserView(MultipleFieldLookupMixin, generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer lookup_fields = ['account', 'username'] Using custom mixins is a good option if you have custom behavior that needs to be used. ### Creating custom base classes If you are using a mixin across multiple views, you can take this a step further and create your own set of base views that can then be used throughout your project. For example: class BaseRetrieveView(MultipleFieldLookupMixin, generics.RetrieveAPIView): pass class BaseRetrieveUpdateDestroyView(MultipleFieldLookupMixin, generics.RetrieveUpdateDestroyAPIView): pass Using custom base classes is a good option if you have custom behavior that consistently needs to be repeated across a large number of views throughout your project. --- ## PUT as create Prior to version 3.0 the REST framework mixins treated `PUT` as either an update or a create operation, depending on if the object already existed or not. Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but from version 3.0 onwards we now use 404 behavior as the default, due to it being simpler and more obvious. --- ## Third party packages The following third party packages provide additional generic view implementations. ### Django Rest Multiple Models [Django Rest Multiple Models][django-rest-multiple-models] provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request. [cite]: https://docs.djangoproject.com/en/stable/ref/class-based-views/#base-vs-generic-views [GenericAPIView]: #genericapiview [ListModelMixin]: #listmodelmixin [CreateModelMixin]: #createmodelmixin [RetrieveModelMixin]: #retrievemodelmixin [UpdateModelMixin]: #updatemodelmixin [DestroyModelMixin]: #destroymodelmixin [django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels [django-docs-select-related]: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related ================================================ FILE: docs/api-guide/metadata.md ================================================ --- source: - metadata.py --- # Metadata > [The `OPTIONS`] method allows a client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. > > — [RFC7231, Section 4.3.7.][cite] REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information. There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information. Here's an example response that demonstrates the information that is returned by default. HTTP 200 OK Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json { "name": "To Do List", "description": "List existing 'To Do' items, or create a new item.", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "note": { "type": "string", "required": false, "read_only": false, "label": "title", "max_length": 100 } } } } ## Setting the metadata scheme You can set the metadata class globally using the `'DEFAULT_METADATA_CLASS'` settings key: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata' } Or you can set the metadata class individually for a view: class APIRoot(APIView): metadata_class = APIRootMetadata def get(self, request, format=None): return Response({ ... }) The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class. ## Creating schema endpoints If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider reusing the metadata API for doing so. For example, the following additional route could be used on a viewset to provide a linkable schema endpoint. @action(methods=['GET'], detail=False) def api_schema(self, request): meta = self.metadata_class() data = meta.determine_metadata(request, self) return Response(data) There are a couple of reasons that you might choose to take this approach, including that `OPTIONS` responses [are not cacheable][no-options]. --- ## Custom metadata classes If you want to provide a custom metadata class you should override `BaseMetadata` and implement the `determine_metadata(self, request, view)` method. Useful things that you might want to do could include returning schema information, using a format such as [JSON schema][json-schema], or returning debug information to admin users. ### Example The following class could be used to limit the information that is returned to `OPTIONS` requests. class MinimalMetadata(BaseMetadata): """ Don't include field and other information for `OPTIONS` requests. Just return the name and description. """ def determine_metadata(self, request, view): return { 'name': view.get_view_name(), 'description': view.get_view_description() } Then configure your settings to use this custom class: REST_FRAMEWORK = { 'DEFAULT_METADATA_CLASS': 'myproject.apps.core.MinimalMetadata' } ## Third party packages The following third party packages provide additional metadata implementations. ### DRF-schema-adapter [drf-schema-adapter][drf-schema-adapter] is a set of tools that makes it easier to provide schema information to frontend frameworks and libraries. It provides a metadata mixin as well as 2 metadata classes and several adapters suitable to generate [json-schema][json-schema] as well as schema information readable by various libraries. You can also write your own adapter to work with your specific frontend. If you wish to do so, it also provides an exporter that can export those schema information to json files. [cite]: https://tools.ietf.org/html/rfc7231#section-4.3.7 [no-options]: https://www.mnot.net/blog/2012/10/29/NO_OPTIONS [json-schema]: https://json-schema.org/ [drf-schema-adapter]: https://github.com/drf-forms/drf-schema-adapter ================================================ FILE: docs/api-guide/pagination.md ================================================ --- source: - pagination.py --- # Pagination > Django provides a few classes that help you manage paginated data – that is, data that’s split across several pages, with “Previous/Next” links. > > — [Django documentation][cite] REST framework includes support for customizable pagination styles. This allows you to modify how large result sets are split into individual pages of data. The pagination API can support either: * Pagination links that are provided as part of the content of the response. * Pagination links that are included in response headers, such as `Content-Range` or `Link`. The built-in styles currently all use links included as part of the content of the response. This style is more accessible when using the browsable API. Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular `APIView`, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the `mixins.ListModelMixin` and `generics.GenericAPIView` classes for an example. Pagination can be turned off by setting the pagination class to `None`. ## Setting the pagination style The pagination style may be set globally, using the `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` setting keys. For example, to use the built-in limit/offset pagination, you would do something like this: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 100 } Note that you need to set both the pagination class, and the page size that should be used. Both `DEFAULT_PAGINATION_CLASS` and `PAGE_SIZE` are `None` by default. You can also set the pagination class on an individual view by using the `pagination_class` attribute. Typically you'll want to use the same pagination style throughout your API, although you might want to vary individual aspects of the pagination, such as default or maximum page size, on a per-view basis. ## Modifying the pagination style If you want to modify particular aspects of the pagination style, you'll want to override one of the pagination classes, and set the attributes that you want to change. class LargeResultsSetPagination(PageNumberPagination): page_size = 1000 page_size_query_param = 'page_size' max_page_size = 10000 class StandardResultsSetPagination(PageNumberPagination): page_size = 100 page_size_query_param = 'page_size' max_page_size = 1000 You can then apply your new style to a view using the `pagination_class` attribute: class BillingRecordsView(generics.ListAPIView): queryset = Billing.objects.all() serializer_class = BillingRecordsSerializer pagination_class = LargeResultsSetPagination Or apply the style globally, using the `DEFAULT_PAGINATION_CLASS` settings key. For example: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'apps.core.pagination.StandardResultsSetPagination' } --- ## API Reference ### PageNumberPagination This pagination style accepts a single number page number in the request query parameters. **Request**: GET https://api.example.org/accounts/?page=4 **Response**: HTTP 200 OK { "count": 1023, "next": "https://api.example.org/accounts/?page=5", "previous": "https://api.example.org/accounts/?page=3", "results": [ … ] } #### Setup To enable the `PageNumberPagination` style globally, use the following configuration, and set the `PAGE_SIZE` as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `PageNumberPagination` on a per-view basis. By default, the query parameter name used for pagination is `page`. This can be customized by subclassing `PageNumberPagination` and overriding the `page_query_param` attribute. For example: from rest_framework.pagination import PageNumberPagination class CustomPagination(PageNumberPagination): page_query_param = 'p' With this configuration, clients would request pages using `?p=2` instead of `?page=2`. #### Configuration The `PageNumberPagination` class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the `PageNumberPagination` class, and then enable your custom pagination class as above. * `django_paginator_class` - The Django Paginator class to use. Default is `django.core.paginator.Paginator`, which should be fine for most use cases. * `page_size` - A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key. * `page_query_param` - A string value indicating the name of the query parameter to use for the pagination control. * `page_size_query_param` - If set, this is a string value indicating the name of a query parameter that allows the client to set the page size on a per-request basis. Defaults to `None`, indicating that the client may not control the requested page size. * `max_page_size` - If set, this is a numeric value indicating the maximum allowable requested page size. This attribute is only valid if `page_size_query_param` is also set. * `last_page_strings` - A list or tuple of string values indicating values that may be used with the `page_query_param` to request the final page in the set. Defaults to `('last',)`. For example, use `?page=last` to go directly to the last page. * `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`. --- ### LimitOffsetPagination This pagination style mirrors the syntax used when looking up multiple database records. The client includes both a "limit" and an "offset" query parameter. The limit indicates the maximum number of items to return, and is equivalent to the `page_size` in other styles. The offset indicates the starting position of the query in relation to the complete set of unpaginated items. **Request**: GET https://api.example.org/accounts/?limit=100&offset=400 **Response**: HTTP 200 OK { "count": 1023, "next": "https://api.example.org/accounts/?limit=100&offset=500", "previous": "https://api.example.org/accounts/?limit=100&offset=300", "results": [ … ] } #### Setup To enable the `LimitOffsetPagination` style globally, use the following configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination' } Optionally, you may also set a `PAGE_SIZE` key. If the `PAGE_SIZE` parameter is also used then the `limit` query parameter will be optional, and may be omitted by the client. On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `LimitOffsetPagination` on a per-view basis. #### Configuration The `LimitOffsetPagination` class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the `LimitOffsetPagination` class, and then enable your custom pagination class as above. * `default_limit` - A numeric value indicating the limit to use if one is not provided by the client in a query parameter. Defaults to the same value as the `PAGE_SIZE` settings key. * `limit_query_param` - A string value indicating the name of the "limit" query parameter. Defaults to `'limit'`. * `offset_query_param` - A string value indicating the name of the "offset" query parameter. Defaults to `'offset'`. * `max_limit` - If set this is a numeric value indicating the maximum allowable limit that may be requested by the client. Defaults to `None`. * `template` - The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/numbers.html"`. --- ### CursorPagination The cursor-based pagination presents an opaque "cursor" indicator that the client may use to page through the result set. This pagination style only presents forward and reverse controls, and does not allow the client to navigate to arbitrary positions. Cursor based pagination requires that there is a unique, unchanging ordering of items in the result set. This ordering might typically be a creation timestamp on the records, as this presents a consistent ordering to paginate against. Cursor based pagination is more complex than other schemes. It also requires that the result set presents a fixed ordering, and does not allow the client to arbitrarily index into the result set. However it does provide the following benefits: * Provides a consistent pagination view. When used properly `CursorPagination` ensures that the client will never see the same item twice when paging through records, even when new items are being inserted by other clients during the pagination process. * Supports usage with very large datasets. With extremely large datasets pagination using offset-based pagination styles may become inefficient or unusable. Cursor based pagination schemes instead have fixed-time properties, and do not slow down as the dataset size increases. #### Details and limitations Proper use of cursor based pagination requires a little attention to detail. You'll need to think about what ordering you want the scheme to be applied against. The default is to order by `"-created"`. This assumes that **there must be a 'created' timestamp field** on the model instances, and will present a "timeline" style paginated view, with the most recently added items first. You can modify the ordering by overriding the `'ordering'` attribute on the pagination class, or by using the `OrderingFilter` filter class together with `CursorPagination`. When used with `OrderingFilter` you should strongly consider restricting the fields that the user may order by. Proper usage of cursor pagination should have an ordering field that satisfies the following: * Should be an unchanging value, such as a timestamp, slug, or other field that is only set once, on creation. * Should be unique, or nearly unique. Millisecond precision timestamps are a good example. This implementation of cursor pagination uses a smart "position plus offset" style that allows it to properly support not-strictly-unique values as the ordering. * Should be a non-nullable value that can be coerced to a string. * Should not be a float. Precision errors easily lead to incorrect results. Hint: use decimals instead. (If you already have a float field and must paginate on that, an [example `CursorPagination` subclass that uses decimals to limit precision is available here][float_cursor_pagination_example].) * The field should have a database index. Using an ordering field that does not satisfy these constraints will generally still work, but you'll be losing some of the benefits of cursor pagination. For more technical details on the implementation we use for cursor pagination, the ["Building cursors for the Disqus API"][disqus-cursor-api] blog post gives a good overview of the basic approach. #### Setup To enable the `CursorPagination` style globally, use the following configuration, modifying the `PAGE_SIZE` as desired: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.CursorPagination', 'PAGE_SIZE': 100 } On `GenericAPIView` subclasses you may also set the `pagination_class` attribute to select `CursorPagination` on a per-view basis. #### Configuration The `CursorPagination` class includes a number of attributes that may be overridden to modify the pagination style. To set these attributes you should override the `CursorPagination` class, and then enable your custom pagination class as above. * `page_size` = A numeric value indicating the page size. If set, this overrides the `PAGE_SIZE` setting. Defaults to the same value as the `PAGE_SIZE` settings key. * `cursor_query_param` = A string value indicating the name of the "cursor" query parameter. Defaults to `'cursor'`. * `ordering` = This should be a string, or list of strings, indicating the field against which the cursor based pagination will be applied. For example: `ordering = 'slug'`. Defaults to `-created`. This value may also be overridden by using `OrderingFilter` on the view. * `template` = The name of a template to use when rendering pagination controls in the browsable API. May be overridden to modify the rendering style, or set to `None` to disable HTML pagination controls completely. Defaults to `"rest_framework/pagination/previous_and_next.html"`. --- ## Custom pagination styles To create a custom pagination serializer class, you should inherit the subclass `pagination.BasePagination`, override the `paginate_queryset(self, queryset, request, view=None)`, and `get_paginated_response(self, data)` methods: * The `paginate_queryset` method is passed to the initial queryset and should return an iterable object. That object contains only the data in the requested page. * The `get_paginated_response` method is passed to the serialized page data and should return a `Response` instance. Note that the `paginate_queryset` method may set state on the pagination instance, that may later be used by the `get_paginated_response` method. ### 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: class CustomPagination(pagination.PageNumberPagination): def get_paginated_response(self, data): return Response({ 'links': { 'next': self.get_next_link(), 'previous': self.get_previous_link() }, 'count': self.page.paginator.count, 'results': data }) We'd then need to set up the custom class in our configuration: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.CustomPagination', 'PAGE_SIZE': 100 } Note that if you care about how the ordering of keys is displayed in responses in the browsable API you might choose to use an `OrderedDict` when constructing the body of paginated responses, but this is optional. ### Using your custom pagination class To have your custom pagination class be used by default, use the `DEFAULT_PAGINATION_CLASS` setting: REST_FRAMEWORK = { 'DEFAULT_PAGINATION_CLASS': 'my_project.apps.core.pagination.LinkHeaderPagination', 'PAGE_SIZE': 100 } API responses for list endpoints will now include a `Link` header, instead of including the pagination links as part of the body of the response, for example: ![Link Header][link-header] *A custom pagination style, using the 'Link' header* --- ## HTML pagination controls By default using the pagination classes will cause HTML pagination controls to be displayed in the browsable API. There are two built-in display styles. The `PageNumberPagination` and `LimitOffsetPagination` classes display a list of page numbers with previous and next controls. The `CursorPagination` class displays a simpler style that only displays a previous and next control. ### Customizing the controls You can override the templates that render the HTML pagination controls. The two built-in styles are: * `rest_framework/pagination/numbers.html` * `rest_framework/pagination/previous_and_next.html` Providing a template with either of these paths in a global template directory will override the default rendering for the relevant pagination classes. Alternatively you can disable HTML pagination controls completely by subclassing on of the existing classes, setting `template = None` as an attribute on the class. You'll then need to configure your `DEFAULT_PAGINATION_CLASS` settings key to use your custom class as the default pagination style. #### Low-level API The low-level API for determining if a pagination class should display the controls or not is exposed as a `display_page_controls` attribute on the pagination instance. Custom pagination classes should be set to `True` in the `paginate_queryset` method if they require the HTML pagination controls to be displayed. The `.to_html()` and `.get_html_context()` methods may also be overridden in a custom pagination class in order to further customize how the controls are rendered. --- ## Third party packages The following third party packages are also available. ### DRF-extensions The [`DRF-extensions` package][drf-extensions] includes a [`PaginateByMaxMixin` mixin class][paginate-by-max-mixin] that allows your API clients to specify `?page_size=max` to obtain the maximum allowed page size. ### drf-proxy-pagination The [`drf-proxy-pagination` package][drf-proxy-pagination] includes a `ProxyPagination` class which allows to choose pagination class with a query parameter. ### link-header-pagination The [`django-rest-framework-link-header-pagination` package][drf-link-header-pagination] includes a `LinkHeaderPagination` class which provides pagination via an HTTP `Link` header as described in [GitHub REST API documentation][github-traversing-with-pagination]. [cite]: https://docs.djangoproject.com/en/stable/topics/pagination/ [link-header]: ../img/link-header-pagination.png [drf-extensions]: https://chibisov.github.io/drf-extensions/docs/ [paginate-by-max-mixin]: https://chibisov.github.io/drf-extensions/docs/#paginatebymaxmixin [drf-proxy-pagination]: https://github.com/tuffnatty/drf-proxy-pagination [drf-link-header-pagination]: https://github.com/tbeadle/django-rest-framework-link-header-pagination [disqus-cursor-api]: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api [float_cursor_pagination_example]: https://gist.github.com/keturn/8bc88525a183fd41c73ffb729b8865be#file-fpcursorpagination-py [github-traversing-with-pagination]: https://docs.github.com/en/rest/guides/traversing-with-pagination ================================================ FILE: docs/api-guide/parsers.md ================================================ --- source: - parsers.py --- # Parsers > Machine interacting web services tend to use more structured formats for sending data than form-encoded, since they're 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. ## 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. !!! note When developing client applications always remember to make sure you're setting the `Content-Type` header when sending data in an HTTP request. If you don't set the content type, most clients will default to using `'application/x-www-form-urlencoded'`, which may not be what you want. As an example, if you are sending `json` encoded data using jQuery with the [.ajax() method][jquery-ajax], you should make sure to include the `contentType: 'application/json'` setting. ## Setting the parsers The default set of parsers may be set globally, using the `DEFAULT_PARSER_CLASSES` setting. For example, the following settings would allow only requests with `JSON` content, instead of the default of JSON or form data. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } You can also set the parsers used for an individual view, or viewset, using the `APIView` class-based views. from rest_framework.parsers import JSONParser from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): """ A view that can accept POST requests with JSON content. """ parser_classes = [JSONParser] def post(self, request, format=None): return Response({'received data': request.data}) Or, if you're using the `@api_view` decorator with function based views. from rest_framework.decorators import api_view from rest_framework.decorators import parser_classes from rest_framework.parsers import JSONParser @api_view(['POST']) @parser_classes([JSONParser]) def example_view(request, format=None): """ A view that can accept POST requests with JSON content. """ return Response({'received data': request.data}) --- ## API Reference ### JSONParser Parses `JSON` request content. `request.data` will be populated with a dictionary of data. **.media_type**: `application/json` ### FormParser Parses HTML form content. `request.data` will be populated with a `QueryDict` of data. You will typically want to use both `FormParser` and `MultiPartParser` together in order to fully support HTML form data. **.media_type**: `application/x-www-form-urlencoded` ### MultiPartParser 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. **.media_type**: `multipart/form-data` ### FileUploadParser Parses raw file upload content. The `request.data` property will be a dictionary with a single key `'file'` containing the uploaded file. If the view used with `FileUploadParser` is called with a `filename` URL keyword argument, then that argument will be used as the filename. If it is called without a `filename` URL keyword argument, then the client must set the filename in the `Content-Disposition` HTTP header. For example `Content-Disposition: attachment; filename=upload.jpg`. **.media_type**: `*/*` !!! note * The `FileUploadParser` is for usage with native clients that can upload the file as a raw data request. For web-based uploads, or for native clients with multipart upload support, you should use the `MultiPartParser` instead. * Since this parser's `media_type` matches any content type, `FileUploadParser` should generally be the only parser set on an API view. * `FileUploadParser` respects Django's standard `FILE_UPLOAD_HANDLERS` setting, and the `request.upload_handlers` attribute. See the [Django documentation][upload-handlers] for more details. #### Basic usage example # views.py class FileUploadView(views.APIView): parser_classes = [FileUploadParser] def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) # urls.py urlpatterns = [ # ... re_path(r'^upload/(?P[^/]+)$', FileUploadView.as_view()) ] --- ## Custom parsers To implement a custom parser, you should override `BaseParser`, set the `.media_type` property, and implement the `.parse(self, stream, media_type, parser_context)` method. The method should return the data that will be used to populate the `request.data` property. The arguments passed to `.parse()` are: ### stream A stream-like object representing the body of the request. ### media_type Optional. If provided, this is the media type of the incoming request content. Depending on the request's `Content-Type:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"text/plain; charset=utf-8"`. ### parser_context Optional. If supplied, this argument will be a dictionary containing any additional context that may be required to parse the request content. By default this will include the following keys: `view`, `request`, `args`, `kwargs`. ### Example The following is an example plaintext parser that will populate the `request.data` property with a string representing the body of the request. class PlainTextParser(BaseParser): """ Plain text parser. """ media_type = 'text/plain' def parse(self, stream, media_type=None, parser_context=None): """ Simply return a string representing the body of the request. """ return stream.read() --- ## Third party packages The following third party packages are also available. ### YAML [REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. #### Installation & configuration Install using pip. $ pip install djangorestframework-yaml Modify your REST framework settings. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework_yaml.parsers.YAMLParser', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework_yaml.renderers.YAMLRenderer', ], } ### XML [REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. #### Installation & configuration Install using pip. $ pip install djangorestframework-xml Modify your REST framework settings. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework_xml.parsers.XMLParser', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework_xml.renderers.XMLRenderer', ], } ### MessagePack [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework. ### CamelCase JSON [djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy]. [jquery-ajax]: https://api.jquery.com/jQuery.ajax/ [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion [upload-handlers]: https://docs.djangoproject.com/en/stable/topics/http/file-uploads/#upload-handlers [rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/ [rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/ [yaml]: http://www.yaml.org/ [messagepack]: https://github.com/juanriaza/django-rest-framework-msgpack [juanriaza]: https://github.com/juanriaza [vbabiy]: https://github.com/vbabiy [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case ================================================ FILE: docs/api-guide/permissions.md ================================================ --- source: - permissions.py --- # Permissions > Authentication or identification by itself is not usually sufficient to gain access to information or code. For that, the entity requesting access must have authorization. > > — [Apple Developer Documentation][cite] Together with [authentication] and [throttling], permissions determine whether a request should be granted or denied access. Permission checks are always run at the very start of the view, before any other code is allowed to proceed. Permission checks will typically use the authentication information in the `request.user` and `request.auth` properties to determine if the incoming request should be permitted. Permissions are used to grant or deny access for different classes of users to different parts of the API. The simplest style of permission would be to allow access to any authenticated user, and deny access to any unauthenticated user. This corresponds to the `IsAuthenticated` class in REST framework. A slightly less strict style of permission would be to allow full access to authenticated users, but allow read-only access to unauthenticated users. This corresponds to the `IsAuthenticatedOrReadOnly` class in REST framework. ## How permissions are determined Permissions in REST framework are always defined as a list of permission classes. Before running the main body of the view each permission in the list is checked. If any permission check fails, an `exceptions.PermissionDenied` or `exceptions.NotAuthenticated` exception will be raised, and the main body of the view will not run. When the permission checks fail, either a "403 Forbidden" or a "401 Unauthorized" response will be returned, according to the following rules: * The request was successfully authenticated, but permission was denied. *— An HTTP 403 Forbidden response will be returned.* * The request was not successfully authenticated, and the highest priority authentication class *does not* use `WWW-Authenticate` headers. *— An HTTP 403 Forbidden response will be returned.* * The request was not successfully authenticated, and the highest priority authentication class *does* use `WWW-Authenticate` headers. *— An HTTP 401 Unauthorized response, with an appropriate `WWW-Authenticate` header will be returned.* ## Object level permissions REST framework permissions also support object-level permissioning. Object level permissions are used to determine if a user should be allowed to act on a particular object, which will typically be a model instance. Object level permissions are run by REST framework's generic views when `.get_object()` is called. As with view level permissions, an `exceptions.PermissionDenied` exception will be raised if the user is not allowed to act on the given object. If you're writing your own views and want to enforce object level permissions, or if you override the `get_object` method on a generic view, then you'll need to explicitly call the `.check_object_permissions(request, obj)` method on the view at the point at which you've retrieved the object. This will either raise a `PermissionDenied` or `NotAuthenticated` exception, or simply return if the view has the appropriate permissions. For example: def get_object(self): obj = get_object_or_404(self.get_queryset(), pk=self.kwargs["pk"]) self.check_object_permissions(self.request, obj) return obj !!! note With the exception of `DjangoObjectPermissions`, the provided permission classes in `rest_framework.permissions` **do not** implement the methods necessary to check object permissions. If you wish to use the provided permission classes in order to check object permissions, **you must** subclass them and implement the `has_object_permission()` method described in the [_Custom permissions_](#custom-permissions) section (below). #### Limitations of object level permissions For performance reasons the generic views will not automatically apply object level permissions to each instance in a queryset when returning a list of objects. Often when you're using object level permissions you'll also want to [filter the queryset][filtering] appropriately, to ensure that users only have visibility onto instances that they are permitted to view. Because the `get_object()` method is not called, object level permissions from the `has_object_permission()` method **are not applied** when creating objects. In order to restrict object creation you need to implement the permission check either in your Serializer class or override the `perform_create()` method of your ViewSet class. ## Setting the permission policy The default permission policy may be set globally, using the `DEFAULT_PERMISSION_CLASSES` setting. For example. REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ] } If not specified, this setting defaults to allowing unrestricted access: 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ] You can also set the authentication policy on a per-view, or per-viewset basis, using the `APIView` class-based views. from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView class ExampleView(APIView): permission_classes = [IsAuthenticated] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) Or, if you're using the `@api_view` decorator with function based views. from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response @api_view(['GET']) @permission_classes([IsAuthenticated]) def example_view(request, format=None): content = { 'status': 'request was permitted' } return Response(content) !!! note When you set new permission classes via the class attribute or decorators you're telling the view to ignore the default list set in the ``settings.py`` file. Provided they inherit from `rest_framework.permissions.BasePermission`, permissions can be composed using standard Python bitwise operators. For example, `IsAuthenticatedOrReadOnly` could be written: from rest_framework.permissions import BasePermission, IsAuthenticated, SAFE_METHODS from rest_framework.response import Response from rest_framework.views import APIView class ReadOnly(BasePermission): def has_permission(self, request, view): return request.method in SAFE_METHODS class ExampleView(APIView): permission_classes = [IsAuthenticated | ReadOnly] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) !!! note Composition of permissions supports the `&` (and), `|` (or) and `~` (not) operators, and also allows the use of brackets `(` `)` to group expressions. Operators follow the same precedence and associativity rules as standard logical operators (`~` highest, then `&`, then `|`). ## API Reference ### AllowAny The `AllowAny` permission class will allow unrestricted access, **regardless of if the request was authenticated or unauthenticated**. This permission is not strictly required, since you can achieve the same result by using an empty list or tuple for the permissions setting, but you may find it useful to specify this class because it makes the intention explicit. ### IsAuthenticated The `IsAuthenticated` permission class will deny permission to any unauthenticated user, and allow permission otherwise. This permission is suitable if you want your API to only be accessible to registered users. ### IsAdminUser The `IsAdminUser` permission class will deny permission to any user, unless `user.is_staff` is `True` in which case permission will be allowed. This permission is suitable if you want your API to only be accessible to a subset of trusted administrators. ### IsAuthenticatedOrReadOnly 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. ### DjangoModelPermissions This permission class ties into Django's standard `django.contrib.auth` [model permissions][contribauth]. This permission must only be applied to views that have a `.queryset` property or `get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant model permissions* assigned. The appropriate model is determined by checking `get_queryset().model` or `queryset.model`. * `POST` requests require the user to have the `add` permission on the model. * `PUT` and `PATCH` requests require the user to have the `change` permission on the model. * `DELETE` requests require the user to have the `delete` permission on the model. 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. ### DjangoModelPermissionsOrAnonReadOnly Similar to `DjangoModelPermissions`, but also allows unauthenticated users to have read-only access to the API. ### DjangoObjectPermissions This permission class ties into Django's standard [object permissions framework][objectpermissions] that allows per-object permissions on models. In order to use this permission class, you'll also need to add a permission backend that supports object-level permissions, such as [django-guardian][guardian]. As with `DjangoModelPermissions`, this permission must only be applied to views that have a `.queryset` property or `.get_queryset()` method. Authorization will only be granted if the user *is authenticated* and has the *relevant per-object permissions* and *relevant model permissions* assigned. * `POST` requests require the user to have the `add` permission on the model instance. * `PUT` and `PATCH` requests require the user to have the `change` permission on the model instance. * `DELETE` requests require the user to have the `delete` permission on the model instance. Note that `DjangoObjectPermissions` **does not** require the `django-guardian` package, and should support other object-level backends equally well. As with `DjangoModelPermissions` you can use custom model permissions by overriding `DjangoObjectPermissions` and setting the `.perms_map` property. Refer to the source code for details. !!! note If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests 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. ## Custom permissions To implement a custom permission, override `BasePermission` and implement either, or both, of the following methods: * `.has_permission(self, request, view)` * `.has_object_permission(self, request, view, obj)` The methods should return `True` if the request should be granted access, and `False` otherwise. If you need to test if a request is a read operation or a write operation, you should check the request method against the constant `SAFE_METHODS`, which is a tuple containing `'GET'`, `'OPTIONS'` and `'HEAD'`. For example: if request.method in permissions.SAFE_METHODS: # Check permissions for read-only request else: # Check permissions for write request !!! note The instance-level `has_object_permission` method will only be called if the view-level `has_permission` checks have already passed. Also note that in order for the instance-level checks to run, the view code should explicitly call `.check_object_permissions(request, obj)`. If you are using the generic views then this will be handled for you by default. (Function-based views will need to check object permissions explicitly, raising `PermissionDenied` on failure.) Custom permissions will raise a `PermissionDenied` exception if the test fails. To change the error message associated with the exception, implement a `message` attribute directly on your custom permission. Otherwise the `default_detail` attribute from `PermissionDenied` will be used. Similarly, to change the code identifier associated with the exception, implement a `code` attribute directly on your custom permission - otherwise the `default_code` attribute from `PermissionDenied` will be used. from rest_framework import permissions class CustomerAccessPermission(permissions.BasePermission): message = 'Adding customers not allowed.' def has_permission(self, request, view): ... ### Examples The following is an example of a permission class that checks the incoming request's IP address against a blocklist, and denies the request if the IP has been blocked. from rest_framework import permissions class BlocklistPermission(permissions.BasePermission): """ Global permission check for blocked IPs. """ def has_permission(self, request, view): ip_addr = request.META['REMOTE_ADDR'] blocked = Blocklist.objects.filter(ip_addr=ip_addr).exists() return not blocked As well as global permissions, that are run against all incoming requests, you can also create object-level permissions, that are only run against operations that affect a particular object instance. For example: class IsOwnerOrReadOnly(permissions.BasePermission): """ Object-level permission to only allow owners of an object to edit it. Assumes the model instance has an `owner` attribute. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Instance must have an attribute named `owner`. return obj.owner == request.user Note that the generic views will check the appropriate object level permissions, but if you're writing your own custom views, you'll need to make sure you check the object level permission checks yourself. You can do so by calling `self.check_object_permissions(request, obj)` from the view once you have the object instance. This call will raise an appropriate `APIException` if any object-level permission checks fail, and will otherwise simply return. Also note that the generic views will only check the object-level permissions for views that retrieve a single model instance. If you require object-level filtering of list views, you'll need to filter the queryset separately. See the [filtering documentation][filtering] for more details. ## Overview of access restriction methods REST framework offers three different methods to customize access restrictions on a case-by-case basis. These apply in different scenarios and have different effects and limitations. * `queryset`/`get_queryset()`: Limits the general visibility of existing objects from the database. The queryset limits which objects will be listed and which objects can be modified or deleted. The `get_queryset()` method can apply different querysets based on the current action. * `permission_classes`/`get_permissions()`: General permission checks based on the current action, request and targeted object. Object level permissions can only be applied to retrieve, modify and deletion actions. Permission checks for list and create will be applied to the entire object type. (In case of list: subject to restrictions in the queryset.) * `serializer_class`/`get_serializer()`: Instance level restrictions that apply to all objects on input and output. The serializer may have access to the request context. The `get_serializer()` method can apply different serializers based on the current action. The following table lists the access restriction methods and the level of control they offer over which actions. | | `queryset` | `permission_classes` | `serializer_class` | |------------------------------------|------------|----------------------|--------------------| | Action: list | global | global | object-level* | | Action: create | no | global | object-level | | Action: retrieve | global | object-level | object-level | | Action: update | global | object-level | object-level | | Action: partial_update | global | object-level | object-level | | Action: destroy | global | object-level | no | | Can reference action in decision | no** | yes | no** | | Can reference request in decision | no** | yes | yes | \* A Serializer class should not raise PermissionDenied in a list action, or the entire list would not be returned.
\** The `get_*()` methods have access to the current view and can return different Serializer or QuerySet instances based on the request or action. --- ## Third party packages The following third party packages are also available. ### DRF - Access Policy The [Django REST - Access Policy][drf-access-policy] package provides a way to define complex access rules in declarative policy classes that are attached to view sets or function-based views. The policies are defined in JSON in a format similar to AWS' Identity & Access Management policies. ### Composed Permissions The [Composed Permissions][composed-permissions] package provides a simple way to define complex and multi-depth (with logic operators) permission objects, using small and reusable components. ### REST Condition The [REST Condition][rest-condition] package is another extension for building complex permissions in a simple and convenient way. The extension allows you to combine permissions with logical operators. ### DRY Rest Permissions The [DRY Rest Permissions][dry-rest-permissions] package provides the ability to define different permissions for individual default and custom actions. This package is made for apps with permissions that are derived from relationships defined in the app's data model. It also supports permission checks being returned to a client app through the API's serializer. Additionally it supports adding permissions to the default and custom list actions to restrict the data they retrieve per user. ### Django Rest Framework Roles The [Django Rest Framework Roles][django-rest-framework-roles] package makes it easier to parameterize your API over multiple types of users. ### 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. ### Django Rest Framework Role Filters The [Django Rest Framework Role Filters][django-rest-framework-role-filters] package provides simple filtering over multiple types of roles. ### Django Rest Framework PSQ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules. ### Axioms DRF PY The [Axioms DRF PY][axioms-drf-py] package is an extension that provides support for authentication and claim-based fine-grained authorization (**scopes**, **roles**, **groups**, **permissions**, etc. including object-level checks) using JWT tokens issued by an OAuth2/OIDC Authorization Server including AWS Cognito, Auth0, Okta, Microsoft Entra, etc. [cite]: https://developer.apple.com/library/mac/#documentation/security/Conceptual/AuthenticationAndAuthorizationGuide/Authorization/Authorization.html [authentication]: authentication.md [throttling]: throttling.md [filtering]: filtering.md [contribauth]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#custom-permissions [objectpermissions]: https://docs.djangoproject.com/en/stable/topics/auth/customizing/#handling-object-permissions [guardian]: https://github.com/lukaszb/django-guardian [filtering]: filtering.md [composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions [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 [drf-access-policy]: https://github.com/rsinger86/drf-access-policy [drf-psq]: https://github.com/drf-psq/drf-psq [axioms-drf-py]: https://github.com/abhishektiwari/axioms-drf-py ================================================ FILE: docs/api-guide/relations.md ================================================ --- source: - relations.py --- # Serializer relations > Data structures, not algorithms, are central to programming. > > — [Rob Pike][cite] Relational fields are used to represent model relationships. They can be applied to `ForeignKey`, `ManyToManyField` and `OneToOneField` relationships, as well as to reverse relationships, and custom relationships such as `GenericForeignKey`. !!! note The relational fields are declared in `relations.py`, but by convention you should import them from the `serializers` module, using `from rest_framework import serializers` and refer to fields as `serializers.`. !!! note REST Framework does not attempt to automatically optimize querysets passed to serializers in terms of `select_related` and `prefetch_related` since it would be too much magic. A serializer with a field spanning an ORM relation through its source attribute could require an additional database hit to fetch related objects from the database. It is the programmer's responsibility to optimize queries to avoid additional database hits which could occur while using such a serializer. For example, the following serializer would lead to a database hit each time evaluating the tracks field if it is not prefetched: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) 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) If `AlbumSerializer` is used to serialize a fairly large queryset with `many=True` then it could be a serious performance problem. Optimizing the queryset passed to `AlbumSerializer` with: qs = Album.objects.prefetch_related('tracks') # No additional database hits required print(AlbumSerializer(qs, many=True).data) would solve the issue. ## Inspecting relationships. When using the `ModelSerializer` class, serializer fields and relationships will be automatically generated for you. Inspecting these automatically generated fields can be a useful tool for determining how to customize the relationship style. To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation… >>> from myapp.serializers import AccountSerializer >>> serializer = AccountSerializer() >>> print(repr(serializer)) AccountSerializer(): id = IntegerField(label='ID', read_only=True) name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all()) ## API Reference In order to explain the various types of relational fields, we'll use a couple of simple models for our examples. Our models will be for music albums, and the tracks listed on each album. class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() class Meta: unique_together = ['album', 'order'] ordering = ['order'] def __str__(self): return '%d: %s' % (self.order, self.title) ### StringRelatedField `StringRelatedField` may be used to represent the target of the relationship using its `__str__` method. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.StringRelatedField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to the following representation: { 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [ '1: Sunflower', '2: Whitetail', '3: Dinosaur Act', ... ] } This field is read only. **Arguments**: * `many` - If applied to a to-many relationship, you should set this argument to `True`. ### PrimaryKeyRelatedField `PrimaryKeyRelatedField` may be used to represent the target of the relationship using its primary key. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Undun', 'artist': 'The Roots', 'tracks': [ 89, 90, 91, ... ] } By default this field is read-write, although you can change this behavior using the `read_only` flag. **Arguments**: * `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. * `many` - If applied to a to-many relationship, you should set this argument to `True`. * `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. * `pk_field` - Set to a field to control serialization/deserialization of the primary key's value. For example, `pk_field=UUIDField(format='hex')` would serialize a UUID primary key into its compact hex representation. ### HyperlinkedRelatedField `HyperlinkedRelatedField` may be used to represent the target of the relationship using a hyperlink. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.HyperlinkedRelatedField( many=True, read_only=True, view_name='track-detail' ) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Graceland', 'artist': 'Paul Simon', 'tracks': [ 'http://www.example.com/api/tracks/45/', 'http://www.example.com/api/tracks/46/', 'http://www.example.com/api/tracks/47/', ... ] } By default this field is read-write, although you can change this behavior using the `read_only` flag. !!! note This field is designed for objects that map to a URL that accepts a single URL keyword argument, as set using the `lookup_field` and `lookup_url_kwarg` arguments. This is suitable for URLs that contain a single primary key or slug argument as part of the URL. If you require more complex hyperlinked representation you'll need to customize the field, as described in the [custom hyperlinked fields](#custom-hyperlinked-fields) section, below. **Arguments**: * `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**. * `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. * `many` - If applied to a to-many relationship, you should set this argument to `True`. * `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. * `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. ### SlugRelatedField `SlugRelatedField` may be used to represent the target of the relationship using a field on the target. For example, the following serializer: class AlbumSerializer(serializers.ModelSerializer): tracks = serializers.SlugRelatedField( many=True, read_only=True, slug_field='title' ) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a representation like this: { 'album_name': 'Dear John', 'artist': 'Loney Dear', 'tracks': [ 'Airport Surroundings', 'Everything Turns to You', 'I Was Only Going Out', ... ] } By default this field is read-write, although you can change this behavior using the `read_only` flag. When using `SlugRelatedField` as a read-write field, you will normally want to ensure that the slug field corresponds to a model field with `unique=True`. **Arguments**: * `slug_field` - The field on the target that should be used to represent it. This should be a field that uniquely identifies any given instance. For example, `username`. **required** * `queryset` - The queryset used for model instance lookups when validating the field input. Relationships must either set a queryset explicitly, or set `read_only=True`. * `many` - If applied to a to-many relationship, you should set this argument to `True`. * `allow_null` - If set to `True`, the field will accept values of `None` or the empty string for nullable relationships. Defaults to `False`. ### 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: class AlbumSerializer(serializers.HyperlinkedModelSerializer): track_listing = serializers.HyperlinkedIdentityField(view_name='track-list') class Meta: model = Album fields = ['album_name', 'artist', 'track_listing'] Would serialize to a representation like this: { 'album_name': 'The Eraser', 'artist': 'Thom Yorke', 'track_listing': 'http://www.example.com/api/track_list/12/', } This field is always read-only. **Arguments**: * `view_name` - The view name that should be used as the target of the relationship. If you're using [the standard router classes][routers] this will be a string with the format `-detail`. **required**. * `lookup_field` - The field on the target that should be used for the lookup. Should correspond to a URL keyword argument on the referenced view. Default is `'pk'`. * `lookup_url_kwarg` - The name of the keyword argument defined in the URL conf that corresponds to the lookup field. Defaults to using the same value as `lookup_field`. * `format` - If using format suffixes, hyperlinked fields will use the same format suffix for the target unless overridden by using the `format` argument. --- ## Nested relationships 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. If the field is used to represent a to-many relationship, you should add the `many=True` flag to the serializer field. ### Example For example, the following serializer: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] Would serialize to a nested representation like this: >>> album = Album.objects.create(album_name="The Gray Album", artist='Danger Mouse') >>> Track.objects.create(album=album, order=1, title='Public Service Announcement', duration=245) >>> Track.objects.create(album=album, order=2, title='What More Can I Say', duration=264) >>> Track.objects.create(album=album, order=3, title='Encore', duration=159) >>> serializer = AlbumSerializer(instance=album) >>> serializer.data { 'album_name': 'The Gray Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ... ], } ### Writable nested serializers By default nested serializers are read-only. If you want to support write-operations to a nested serializer field you'll need to create `create()` and/or `update()` methods in order to explicitly specify how the child relationships should be saved: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ['order', 'title', 'duration'] class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] def create(self, validated_data): tracks_data = validated_data.pop('tracks') album = Album.objects.create(**validated_data) for track_data in tracks_data: Track.objects.create(album=album, **track_data) return album >>> data = { 'album_name': 'The Gray Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ], } >>> serializer = AlbumSerializer(data=data) >>> serializer.is_valid() True >>> serializer.save() --- ## Custom relational fields In rare cases where none of the existing relational styles fit the representation you need, you can implement a completely custom relational field, that describes exactly how the output representation should be generated from the model instance. To implement a custom relational field, you should override `RelatedField`, and implement the `.to_representation(self, value)` method. This method takes the target of the field as the `value` argument, and should return the representation that should be used to serialize the target. The `value` argument will typically be a model instance. If you want to implement a read-write relational field, you must also implement the [`.to_internal_value(self, data)` method][to_internal_value]. To provide a dynamic queryset based on the `context`, you can also override `.get_queryset(self)` instead of specifying `.queryset` on the class or when initializing the field. ### Example For example, we could define a relational field to serialize a track to a custom string representation, using its ordering, title, and duration: import time class TrackListingField(serializers.RelatedField): def to_representation(self, value): duration = time.strftime('%M:%S', time.gmtime(value.duration)) return 'Track %d: %s (%s)' % (value.order, value.name, duration) class AlbumSerializer(serializers.ModelSerializer): tracks = TrackListingField(many=True) class Meta: model = Album fields = ['album_name', 'artist', 'tracks'] This custom field would then serialize to the following representation: { 'album_name': 'Sometimes I Wish We Were an Eagle', 'artist': 'Bill Callahan', 'tracks': [ 'Track 1: Jim Cain (04:39)', 'Track 2: Eid Ma Clack Shaw (04:19)', 'Track 3: The Wind and the Dove (04:34)', ... ] } --- ## Custom hyperlinked fields In some cases you may need to customize the behavior of a hyperlinked field, in order to represent URLs that require more than a single lookup field. You can achieve this by overriding `HyperlinkedRelatedField`. There are two methods that may be overridden: **get_url(self, obj, view_name, request, format)** The `get_url` method is used to map the object instance to its URL representation. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf. **get_object(self, view_name, view_args, view_kwargs)** If you want to support a writable hyperlinked field then you'll also want to override `get_object`, in order to map incoming URLs back to the object they represent. For read-only hyperlinked fields there is no need to override this method. The return value of this method should the object that corresponds to the matched URL conf arguments. May raise an `ObjectDoesNotExist` exception. ### Example Say we have a URL for a customer object that takes two keyword arguments, like so: /api//customers// This cannot be represented with the default implementation, which accepts only a single lookup field. In this case we'd need to override `HyperlinkedRelatedField` to get the behavior we want: from rest_framework import serializers from rest_framework.reverse import reverse class CustomerHyperlink(serializers.HyperlinkedRelatedField): # We define these as class attributes, so we don't need to pass them as arguments. view_name = 'customer-detail' queryset = Customer.objects.all() def get_url(self, obj, view_name, request, format): url_kwargs = { 'organization_slug': obj.organization.slug, 'customer_pk': obj.pk } return reverse(view_name, kwargs=url_kwargs, request=request, format=format) def get_object(self, view_name, view_args, view_kwargs): lookup_kwargs = { 'organization__slug': view_kwargs['organization_slug'], 'pk': view_kwargs['customer_pk'] } return self.get_queryset().get(**lookup_kwargs) Note that if you wanted to use this style together with the generic views then you'd also need to override `.get_object` on the view in order to get the correct lookup behavior. Generally we recommend a flat style for API representations where possible, but the nested URL style can also be reasonable when used in moderation. --- ## Further notes ### The `queryset` argument The `queryset` argument is only ever required for *writable* relationship field, in which case it is used for performing the model instance lookup, that maps from the primitive user input, into a model instance. In version 2.x a serializer class could *sometimes* automatically determine the `queryset` argument *if* a `ModelSerializer` class was being used. This behavior is now replaced with *always* using an explicit `queryset` argument for writable relational fields. Doing so reduces the amount of hidden 'magic' that `ModelSerializer` provides, makes the behavior of the field more clear, and ensures that it is trivial to move between using the `ModelSerializer` shortcut, or using fully explicit `Serializer` classes. ### Customizing the HTML display The built-in `__str__` method of the model will be used to generate string representations of the objects used to populate the `choices` property. These choices are used to populate select HTML inputs in the browsable API. To provide customized representations for such inputs, override `display_value()` of a `RelatedField` subclass. This method will receive a model object, and should return a string suitable for representing it. For example: class TrackPrimaryKeyRelatedField(serializers.PrimaryKeyRelatedField): def display_value(self, instance): return 'Track: %s' % (instance.title) ### Select field cutoffs When rendered in the browsable API relational fields will default to only displaying a maximum of 1000 selectable items. If more items are present then a disabled option with "More than 1000 items…" will be displayed. This behavior is intended to prevent a template from being unable to render in an acceptable timespan due to a very large number of relationships being displayed. There are two keyword arguments you can use to control this behavior: * `html_cutoff` - If set this will be the maximum number of choices that will be displayed by a HTML select drop down. Set to `None` to disable any limiting. Defaults to `1000`. * `html_cutoff_text` - If set this will display a textual indicator if the maximum number of items have been cutoff in an HTML select drop down. Defaults to `"More than {count} items…"` You can also control these globally using the settings `HTML_SELECT_CUTOFF` and `HTML_SELECT_CUTOFF_TEXT`. In cases where the cutoff is being enforced you may want to instead use a plain input field in the HTML form. You can do so using the `style` keyword argument. For example: assigned_to = serializers.SlugRelatedField( queryset=User.objects.all(), slug_field='username', style={'base_template': 'input.html'} ) ### Reverse relations Note that reverse relationships are not automatically included by the `ModelSerializer` and `HyperlinkedModelSerializer` classes. To include a reverse relationship, you must explicitly add it to the fields list. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ['tracks', ...] You'll normally want to ensure that you've set an appropriate `related_name` argument on the relationship, that you can use as the field name. For example: class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks', on_delete=models.CASCADE) ... If you have not set a related name for the reverse relationship, you'll need to use the automatically generated related name in the `fields` argument. For example: class AlbumSerializer(serializers.ModelSerializer): class Meta: fields = ['track_set', ...] See the Django documentation on [reverse relationships][reverse-relationships] for more details. ### Generic relationships If you want to serialize a generic foreign key, you need to define a custom field, to determine explicitly how you want to serialize the targets of the relationship. For example, given the following model for a tag, which has a generic relationship with other arbitrary models: class TaggedItem(models.Model): """ Tags arbitrary model instances using a generic relation. See: https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/ """ tag_name = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() tagged_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag_name And the following two models, which may have associated tags: class Bookmark(models.Model): """ A bookmark consists of a URL, and 0 or more descriptive tags. """ url = models.URLField() tags = GenericRelation(TaggedItem) class Note(models.Model): """ A note consists of some text, and 0 or more descriptive tags. """ text = models.CharField(max_length=1000) tags = GenericRelation(TaggedItem) We could define a custom field that could be used to serialize tagged instances, using the type of each instance to determine how it should be serialized: class TaggedObjectRelatedField(serializers.RelatedField): """ A custom field to use for the `tagged_object` generic relationship. """ def to_representation(self, value): """ Serialize tagged objects to a simple textual representation. """ if isinstance(value, Bookmark): return 'Bookmark: ' + value.url elif isinstance(value, Note): return 'Note: ' + value.text raise Exception('Unexpected type of tagged object') If you need the target of the relationship to have a nested representation, you can use the required serializers inside the `.to_representation()` method: def to_representation(self, value): """ Serialize bookmark instances using a bookmark serializer, and note instances using a note serializer. """ if isinstance(value, Bookmark): serializer = BookmarkSerializer(value) elif isinstance(value, Note): serializer = NoteSerializer(value) else: raise Exception('Unexpected type of tagged object') return serializer.data Note that reverse generic keys, expressed using the `GenericRelation` field, can be serialized using the regular relational field types, since the type of the target in the relationship is always known. For more information see [the Django documentation on generic relations][generic-relations]. ### ManyToManyFields with a Through Model By default, relational fields that target a ``ManyToManyField`` with a ``through`` model specified are set to read-only. If you explicitly specify a relational field pointing to a ``ManyToManyField`` with a through model, be sure to set ``read_only`` to ``True``. If you wish to represent [extra fields on a through model][django-intermediary-manytomany] then you may serialize the through model as [a nested object][dealing-with-nested-objects]. --- ## Third Party Packages The following third party packages are also available. ### DRF Nested Routers The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources. ### Rest Framework Generic Relations 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 ================================================ FILE: docs/api-guide/renderers.md ================================================ --- source: - renderers.py --- # Renderers > Before a TemplateResponse instance can be returned to the client, it must be rendered. The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. > > — [Django documentation][cite] REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types. There is also support for defining your own custom renderers, which gives you the flexibility to design your own media types. ## How the renderer is determined The set of valid renderers for a view is always defined as a list of classes. When a view is entered REST framework will perform content negotiation on the incoming request, and determine the most appropriate renderer to satisfy the request. The basic process of content negotiation involves examining the request's `Accept` header, to determine which media types it expects in the response. Optionally, format suffixes on the URL may be used to explicitly request a particular representation. For example the URL `http://example.com/api/users_count.json` might be an endpoint that always returns JSON data. For more information see the documentation on [content negotiation][conneg]. ## Setting the renderers The default set of renderers may be set globally, using the `DEFAULT_RENDERER_CLASSES` setting. For example, the following settings would use `JSON` as the main media type and also include the self describing API. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] } You can also set the renderers used for an individual view, or viewset, using the `APIView` class-based views. from django.contrib.auth.models import User from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from rest_framework.views import APIView class UserCountView(APIView): """ A view that returns the count of active users in JSON. """ renderer_classes = [JSONRenderer] def get(self, request, format=None): user_count = User.objects.filter(active=True).count() content = {'user_count': user_count} return Response(content) Or, if you're using the `@api_view` decorator with function based views. @api_view(['GET']) @renderer_classes([JSONRenderer]) def user_count_view(request, format=None): """ A view that returns the count of active users in JSON. """ user_count = User.objects.filter(active=True).count() content = {'user_count': user_count} return Response(content) ## Ordering of renderer classes It's important when specifying the renderer classes for your API to think about what priority you want to assign to each media type. If a client underspecifies the representations it can accept, such as sending an `Accept: */*` header, or not including an `Accept` header at all, then REST framework will select the first renderer in the list to use for the response. For example if your API serves JSON responses and the HTML browsable API, you might want to make `JSONRenderer` your default renderer, in order to send `JSON` responses to clients that do not specify an `Accept` header. If your API includes views that can serve both regular webpages and API responses depending on the request, then you might consider making `TemplateHTMLRenderer` your default renderer, in order to play nicely with older browsers that send [broken accept headers][browser-accept-headers]. --- ## API Reference ### JSONRenderer Renders the request data into `JSON`, using utf-8 encoding. Note that the default style is to include unicode characters, and render the response using a compact style with no unnecessary whitespace: {"unicode black star":"★","value":999} The client may additionally include an `'indent'` media type parameter, in which case the returned `JSON` will be indented. For example `Accept: application/json; indent=4`. { "unicode black star": "★", "value": 999 } The default JSON encoding style can be altered using the `UNICODE_JSON` and `COMPACT_JSON` settings keys. **.media_type**: `application/json` **.format**: `'json'` **.charset**: `None` ### TemplateHTMLRenderer Renders data to HTML, using Django's standard template rendering. Unlike other renderers, the data passed to the `Response` does not need to be serialized. Also, unlike other renderers, you may want to include a `template_name` argument when creating the `Response`. The TemplateHTMLRenderer will create a `RequestContext`, using the `response.data` as the context dict, and determine a template name to use to render the context. !!! 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} The template name is determined by (in order of preference): 1. An explicit `template_name` argument passed to the response. 2. An explicit `.template_name` attribute set on this class. 3. The return result of calling `view.get_template_names()`. An example of a view that uses `TemplateHTMLRenderer`: class UserDetail(generics.RetrieveAPIView): """ A view that returns a templated HTML representation of a given user. """ queryset = User.objects.all() renderer_classes = [TemplateHTMLRenderer] def get(self, request, *args, **kwargs): self.object = self.get_object() return Response({'user': self.object}, template_name='user_detail.html') You can use `TemplateHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. If you're building websites that use `TemplateHTMLRenderer` along with other renderer classes, you should consider listing `TemplateHTMLRenderer` as the first class in the `renderer_classes` list, so that it will be prioritized first even for browsers that send poorly formed `ACCEPT:` headers. See the [_HTML & Forms_ Topic Page][html-and-forms] for further examples of `TemplateHTMLRenderer` usage. **.media_type**: `text/html` **.format**: `'html'` **.charset**: `utf-8` See also: `StaticHTMLRenderer` ### StaticHTMLRenderer A simple renderer that simply returns pre-rendered HTML. Unlike other renderers, the data passed to the response object should be a string representing the content to be returned. An example of a view that uses `StaticHTMLRenderer`: @api_view(['GET']) @renderer_classes([StaticHTMLRenderer]) def simple_html_view(request): data = '

Hello, world

' return Response(data) You can use `StaticHTMLRenderer` either to return regular HTML pages using REST framework, or to return both HTML and API responses from a single endpoint. **.media_type**: `text/html` **.format**: `'html'` **.charset**: `utf-8` See also: `TemplateHTMLRenderer` ### BrowsableAPIRenderer Renders data into HTML for the Browsable API: ![The BrowsableAPIRenderer](../img/quickstart.png) This renderer will determine which other renderer would have been given highest priority, and use that to display an API style response within the HTML page. **.media_type**: `text/html` **.format**: `'api'` **.charset**: `utf-8` **.template**: `'rest_framework/api.html'` #### Customizing BrowsableAPIRenderer By default the response content will be rendered with the highest priority renderer apart from `BrowsableAPIRenderer`. If you need to customize this behavior, for example to use HTML as the default return format, but use JSON in the browsable API, you can do so by overriding the `get_default_renderer()` method. For example: class CustomBrowsableAPIRenderer(BrowsableAPIRenderer): def get_default_renderer(self, view): return JSONRenderer() ### AdminRenderer Renders data into HTML for an admin-like display: ![The AdminRender view](../img/admin.png) This renderer is suitable for CRUD-style web APIs that should also present a user-friendly interface for managing the data. Note that views that have nested or list serializers for their input won't work well with the `AdminRenderer`, as the HTML forms are unable to properly support them. !!! note The `AdminRenderer` is only able to include links to detail pages when a properly configured `URL_FIELD_NAME` (`url` by default) attribute is present in the data. For `HyperlinkedModelSerializer` this will be the case, but for `ModelSerializer` or plain `Serializer` classes you'll need to make sure to include the field explicitly. For example here we use models `get_absolute_url` method: class AccountSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) class Meta: model = Account **.media_type**: `text/html` **.format**: `'admin'` **.charset**: `utf-8` **.template**: `'rest_framework/admin.html'` ### HTMLFormRenderer Renders data returned by a serializer into an HTML form. The output of this renderer does not include the enclosing `
` tags, a hidden CSRF input or any submit buttons. This renderer is not intended to be used directly, but can instead be used in templates by passing a serializer instance to the `render_form` template tag. {% load rest_framework %} {% csrf_token %} {% render_form serializer %}
For more information see the [HTML & Forms][html-and-forms] documentation. **.media_type**: `text/html` **.format**: `'form'` **.charset**: `utf-8` **.template**: `'rest_framework/horizontal/form.html'` ### MultiPartRenderer This renderer is used for rendering HTML multipart form data. **It is not suitable as a response renderer**, but is instead used for creating test requests, using REST framework's [test client and test request factory][testing]. **.media_type**: `multipart/form-data; boundary=BoUnDaRyStRiNg` **.format**: `'multipart'` **.charset**: `utf-8` --- ## Custom renderers To implement a custom renderer, you should override `BaseRenderer`, set the `.media_type` and `.format` properties, and implement the `.render(self, data, accepted_media_type=None, renderer_context=None)` method. The method should return a bytestring, which will be used as the body of the HTTP response. The arguments passed to the `.render()` method are: - `data`: the request data, as set by the `Response()` instantiation. - `accepted_media_type=None`: optional. If provided, this is the accepted media type, as determined by the content negotiation stage. Depending on the client's `Accept:` header, this may be more specific than the renderer's `media_type` attribute, and may include media type parameters. For example `"application/json; nested=true"`. - `renderer_context=None`: optional. If provided, this is a dictionary of contextual information provided by the view. By default this will include the following keys: `view`, `request`, `response`, `args`, `kwargs`. ### Example 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_str from rest_framework import renderers class PlainTextRenderer(renderers.BaseRenderer): media_type = 'text/plain' format = 'txt' def render(self, data, accepted_media_type=None, renderer_context=None): return smart_str(data, encoding=self.charset) ### Setting the character set By default renderer classes are assumed to be using the `UTF-8` encoding. To use a different encoding, set the `charset` attribute on the renderer. class PlainTextRenderer(renderers.BaseRenderer): media_type = 'text/plain' format = 'txt' charset = 'iso-8859-1' def render(self, data, accepted_media_type=None, renderer_context=None): return data.encode(self.charset) Note that if a renderer class returns a unicode string, then the response content will be coerced into a bytestring by the `Response` class, with the `charset` attribute set on the renderer used to determine the encoding. If the renderer returns a bytestring representing raw binary content, you should set a charset value of `None`, which will ensure the `Content-Type` header of the response will not have a `charset` value set. In some cases you may also want to set the `render_style` attribute to `'binary'`. Doing so will also ensure that the browsable API will not attempt to display the binary content as a string. class JPEGRenderer(renderers.BaseRenderer): media_type = 'image/jpeg' format = 'jpg' charset = None render_style = 'binary' def render(self, data, accepted_media_type=None, renderer_context=None): return data --- ## Advanced renderer usage You can do some pretty flexible things using REST framework's renderers. Some examples... * Provide either flat or nested representations from the same endpoint, depending on the requested media type. * Serve both regular HTML webpages, and JSON based API responses from the same endpoints. * 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 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. For example: @api_view(['GET']) @renderer_classes([TemplateHTMLRenderer, JSONRenderer]) def list_users(request): """ A view that can return JSON or HTML representations of the users in the system. """ queryset = Users.objects.filter(active=True) if request.accepted_renderer.format == 'html': # TemplateHTMLRenderer takes a context dict, # and additionally requires a 'template_name'. # It does not require serialization. data = {'users': queryset} return Response(data, template_name='list_users.html') # JSONRenderer requires serialized data as normal. serializer = UserSerializer(instance=queryset) data = serializer.data return Response(data) ### Underspecifying the media type In some cases you might want a renderer to serve a range of media types. In this case you can underspecify the media types it should respond to, by using a `media_type` value such as `image/*`, or `*/*`. If you underspecify the renderer's media type, you should make sure to specify the media type explicitly when you return the response, using the `content_type` attribute. For example: return Response(data, content_type='image/png') ### Designing your media types For the purposes of many Web APIs, simple `JSON` responses with hyperlinked relations may be sufficient. If you want to fully embrace RESTful design and [HATEOAS] you'll need to consider the design and usage of your media types in more detail. In [the words of Roy Fielding][quote], "A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types.". For good examples of custom media types, see GitHub's use of a custom [application/vnd.github+json] media type, and Mike Amundsen's IANA approved [application/vnd.collection+json] JSON-based hypermedia. ### HTML error views Typically a renderer will behave the same regardless of if it's dealing with a regular response, or with a response caused by an exception being raised, such as an `Http404` or `PermissionDenied` exception, or a subclass of `APIException`. If you're using either the `TemplateHTMLRenderer` or the `StaticHTMLRenderer` and an exception is raised, the behavior is slightly different, and mirrors [Django's default handling of error views][django-error-views]. Exceptions raised and handled by an HTML renderer will attempt to render using one of the following methods, by order of precedence. * Load and render a template named `{status_code}.html`. * Load and render a template named `api_exception.html`. * Render the HTTP status code and text, for example "404 Not Found". Templates will render with a `RequestContext` which includes the `status_code` and `details` keys. !!! note If `DEBUG=True`, Django's standard traceback error page will be displayed instead of rendering the HTTP status code and text. ## Third party packages The following third party packages are also available. ### YAML [REST framework YAML][rest-framework-yaml] provides [YAML][yaml] parsing and rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. #### Installation & configuration Install using pip. $ pip install djangorestframework-yaml Modify your REST framework settings. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework_yaml.parsers.YAMLParser', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework_yaml.renderers.YAMLRenderer', ], } ### XML [REST Framework XML][rest-framework-xml] provides a simple informal XML format. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. #### Installation & configuration Install using pip. $ pip install djangorestframework-xml Modify your REST framework settings. REST_FRAMEWORK = { 'DEFAULT_PARSER_CLASSES': [ 'rest_framework_xml.parsers.XMLParser', ], 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework_xml.renderers.XMLRenderer', ], } ### JSONP [REST framework JSONP][rest-framework-jsonp] provides JSONP rendering support. It was previously included directly in the REST framework package, and is now instead supported as a third-party package. !!! warning If you require cross-domain AJAX requests, you should generally be using the more modern approach of [CORS][cors] as an alternative to `JSONP`. See the [CORS documentation][cors-docs] for more details. The `jsonp` approach is essentially a browser hack, and is [only appropriate for globally readable API endpoints][jsonp-security], where `GET` requests are unauthenticated and do not require any user permissions. #### Installation & configuration Install using pip. $ pip install djangorestframework-jsonp Modify your REST framework settings. REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework_jsonp.renderers.JSONPRenderer', ], } ### MessagePack [MessagePack][messagepack] is a fast, efficient binary serialization format. [Juan Riaza][juanriaza] maintains the [djangorestframework-msgpack][djangorestframework-msgpack] package which provides MessagePack renderer and parser support for REST framework. ### Microsoft Excel: XLSX (Binary Spreadsheet Endpoints) XLSX is the world's most popular binary spreadsheet format. [Tim Allen][flipperpa] of [The Wharton School][wharton] maintains [drf-excel][drf-excel], which renders an endpoint as an XLSX spreadsheet using OpenPyXL, and allows the client to download it. Spreadsheets can be styled on a per-view basis. #### Installation & configuration Install using pip. $ pip install drf-excel Modify your REST framework settings. REST_FRAMEWORK = { ... 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'drf_excel.renderers.XLSXRenderer', ], } To avoid having a file streamed without a filename (which the browser will often default to the filename "download", with no extension), we need to use a mixin to override the `Content-Disposition` header. If no filename is provided, it will default to `export.xlsx`. For example: from rest_framework.viewsets import ReadOnlyModelViewSet from drf_excel.mixins import XLSXFileMixin from drf_excel.renderers import XLSXRenderer from .models import MyExampleModel from .serializers import MyExampleSerializer class MyExampleViewSet(XLSXFileMixin, ReadOnlyModelViewSet): queryset = MyExampleModel.objects.all() serializer_class = MyExampleSerializer renderer_classes = [XLSXRenderer] filename = 'my_export.xlsx' ### CSV Comma-separated values are a plain-text tabular data format, that can be easily imported into spreadsheet applications. [Mjumbe Poe][mjumbewu] maintains the [djangorestframework-csv][djangorestframework-csv] package which provides CSV renderer support for REST framework. ### UltraJSON [UltraJSON][ultrajson] is an optimized C JSON encoder which can give significantly faster JSON rendering. [Adam Mertz][Amertz08] maintains [drf_ujson2][drf_ujson2], a fork of the now unmaintained [drf-ujson-renderer][drf-ujson-renderer], which implements JSON rendering using the UJSON package. ### CamelCase JSON [djangorestframework-camel-case] provides camel case JSON renderers and parsers for REST framework. This allows serializers to use Python-style underscored field names, but be exposed in the API as Javascript-style camel case field names. It is maintained by [Vitaly Babiy][vbabiy]. ### Pandas (CSV, Excel, PNG) [Django REST Pandas] provides a serializer and renderers that support additional data processing and output via the [Pandas] DataFrame API. Django REST Pandas includes renderers for Pandas-style CSV files, Excel workbooks (both `.xls` and `.xlsx`), and a number of [other formats]. It is maintained by [S. Andrew Sheppard][sheppard] as part of the [wq Project][wq]. ### LaTeX [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 [conneg]: content-negotiation.md [html-and-forms]: ../topics/html-and-forms.md [browser-accept-headers]: http://www.gethifi.com/blog/browser-rest-http-accept-headers [testing]: testing.md [HATEOAS]: http://timelessrepo.com/haters-gonna-hateoas [quote]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven [application/vnd.github+json]: https://developer.github.com/v3/media/ [application/vnd.collection+json]: http://www.amundsen.com/media-types/collection/ [django-error-views]: https://docs.djangoproject.com/en/stable/topics/http/views/#customizing-error-views [rest-framework-jsonp]: https://jpadilla.github.io/django-rest-framework-jsonp/ [cors]: https://www.w3.org/TR/cors/ [cors-docs]: https://www.django-rest-framework.org/topics/ajax-csrf-cors/ [jsonp-security]: https://stackoverflow.com/questions/613962/is-jsonp-safe-to-use [rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/ [rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/ [messagepack]: https://msgpack.org/ [juanriaza]: https://github.com/juanriaza [mjumbewu]: https://github.com/mjumbewu [flipperpa]: https://github.com/flipperpa [wharton]: https://github.com/wharton [drf-excel]: https://github.com/wharton/drf-excel [vbabiy]: https://github.com/vbabiy [rest-framework-yaml]: https://jpadilla.github.io/django-rest-framework-yaml/ [rest-framework-xml]: https://jpadilla.github.io/django-rest-framework-xml/ [yaml]: http://www.yaml.org/ [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv [ultrajson]: https://github.com/esnme/ultrajson [Amertz08]: https://github.com/Amertz08 [drf-ujson-renderer]: https://github.com/gizmag/drf-ujson-renderer [drf_ujson2]: https://github.com/Amertz08/drf_ujson2 [djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case [Django REST Pandas]: https://github.com/wq/django-rest-pandas [Pandas]: https://pandas.pydata.org/ [other formats]: https://github.com/wq/django-rest-pandas#supported-formats [sheppard]: https://github.com/sheppard [wq]: https://github.com/wq [mypebble]: https://github.com/mypebble [Rest Framework Latex]: https://github.com/mypebble/rest-framework-latex ================================================ FILE: docs/api-guide/requests.md ================================================ --- source: - request.py --- > If you're doing REST-based web service stuff ... you should ignore request.POST. > > — Malcom Tredinnick, [Django developers group][cite] REST framework's `Request` class extends the standard `HttpRequest`, adding support for REST framework's flexible request parsing and request authentication. --- ## Request parsing REST framework's Request objects provide flexible request parsing that allows you to treat requests with JSON data or other media types in the same way that you would normally deal with form data. ### .data `request.data` returns the parsed content of the request body. This is similar to the standard `request.POST` and `request.FILES` attributes except that: * It includes all parsed content, including *file and non-file* inputs. * It supports parsing the content of HTTP methods other than `POST`, meaning that you can access the content of `PUT` and `PATCH` requests. * It supports REST framework's flexible request parsing, rather than just supporting form data. For example you can handle incoming [JSON data] similarly to how you handle incoming [form data]. For more details see the [parsers documentation]. ### .query_params `request.query_params` is a more correctly named synonym for `request.GET`. For clarity inside your code, we recommend using `request.query_params` instead of the Django's standard `request.GET`. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just `GET` requests. ### .parsers The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Parser` instances, based on the `parser_classes` set on the view or based on the `DEFAULT_PARSER_CLASSES` setting. You won't typically need to access this property. !!! note If a client sends malformed content, then accessing `request.data` may raise a `ParseError`. By default REST framework's `APIView` class or `@api_view` decorator will catch the error and return a `400 Bad Request` response. If a client sends a request with a content-type that cannot be parsed then a `UnsupportedMediaType` exception will be raised, which by default will be caught and return a `415 Unsupported Media Type` response. ## Content negotiation The request exposes some properties that allow you to determine the result of the content negotiation stage. This allows you to implement behavior such as selecting a different serialization schemes for different media types. ### .accepted_renderer The renderer instance that was selected by the content negotiation stage. ### .accepted_media_type A string representing the media type that was accepted by the content negotiation stage. --- ## Authentication REST framework provides flexible, per-request authentication, that gives you the ability to: * Use different authentication policies for different parts of your API. * Support the use of multiple authentication policies. * Provide both user and token information associated with the incoming request. ### .user `request.user` typically returns an instance of `django.contrib.auth.models.User`, although the behavior depends on the authentication policy being used. If the request is unauthenticated the default value of `request.user` is an instance of `django.contrib.auth.models.AnonymousUser`. For more details see the [authentication documentation]. ### .auth `request.auth` returns any additional authentication context. The exact behavior of `request.auth` depends on the authentication policy being used, but it may typically be an instance of the token that the request was authenticated against. If the request is unauthenticated, or if no additional context is present, the default value of `request.auth` is `None`. For more details see the [authentication documentation]. ### .authenticators The `APIView` class or `@api_view` decorator will ensure that this property is automatically set to a list of `Authentication` instances, based on the `authentication_classes` set on the view or based on the `DEFAULT_AUTHENTICATORS` setting. You won't typically need to access this property. !!! note You may see a `WrappedAttributeError` raised when calling the `.user` or `.auth` properties. These errors originate from an authenticator as a standard `AttributeError`, however it's necessary that they be re-raised as a different exception type in order to prevent them from being suppressed by the outer property access. Python will not recognize that the `AttributeError` originates from the authenticator and will instead assume that the request object does not have a `.user` or `.auth` property. The authenticator will need to be fixed. ## Browser enhancements REST framework supports a few browser enhancements such as browser-based `PUT`, `PATCH` and `DELETE` forms. ### .method `request.method` returns the **uppercased** string representation of the request's HTTP method. Browser-based `PUT`, `PATCH` and `DELETE` forms are transparently supported. For more information see the [browser enhancements documentation]. ### .content_type `request.content_type`, returns a string object representing the media type of the HTTP request's body, or an empty string if no media type was provided. You won't typically need to directly access the request's content type, as you'll normally rely on REST framework's default request parsing behavior. If you do need to access the content type of the request you should use the `.content_type` property in preference to using `request.META.get('HTTP_CONTENT_TYPE')`, as it provides transparent support for browser-based non-form content. For more information see the [browser enhancements documentation]. ### .stream `request.stream` returns a stream representing the content of the request body. You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior. --- ## Standard HttpRequest attributes As REST framework's `Request` extends Django's `HttpRequest`, all the other standard attributes and methods are also available. For example the `request.META` and `request.session` dictionaries are available as normal. Note that due to implementation reasons the `Request` class does not inherit from `HttpRequest` class, but instead extends the class using composition. [cite]: https://groups.google.com/d/topic/django-developers/dxI4qVzrBY4/discussion [parsers documentation]: parsers.md [JSON data]: parsers.md#jsonparser [form data]: parsers.md#formparser [authentication documentation]: authentication.md [browser enhancements documentation]: ../topics/browser-enhancements.md ================================================ FILE: docs/api-guide/responses.md ================================================ --- source: - response.py --- # Responses > Unlike basic HttpResponse objects, TemplateResponse objects retain the details of the context that was provided by the view to compute the response. The final output of the response is not computed until it is needed, later in the response process. > > — [Django documentation][cite] REST framework supports HTTP content negotiation by providing a `Response` class which allows you to return content that can be rendered into multiple content types, depending on the client request. The `Response` class subclasses Django's `SimpleTemplateResponse`. `Response` objects are initialized with data, which should consist of native Python primitives. REST framework then uses standard HTTP content negotiation to determine how it should render the final response content. There's no requirement for you to use the `Response` class, you can also return regular `HttpResponse` or `StreamingHttpResponse` objects from your views if required. Using the `Response` class simply provides a nicer interface for returning content-negotiated Web API responses, that can be rendered to multiple formats. Unless you want to heavily customize REST framework for some reason, you should always use an `APIView` class or `@api_view` function for views that return `Response` objects. Doing so ensures that the view can perform content negotiation and select the appropriate renderer for the response, before it is returned from the view. --- ## Creating responses ### Response() **Signature:** `Response(data, status=None, template_name=None, headers=None, content_type=None)` Unlike regular `HttpResponse` objects, you do not instantiate `Response` objects with rendered content. Instead you pass in unrendered data, which may consist of any Python primitives. The renderers used by the `Response` class cannot natively handle complex datatypes such as Django model instances, so you need to serialize the data into primitive datatypes before creating the `Response` object. You can use REST framework's `Serializer` classes to perform this data serialization, or use your own custom serialization. Arguments: * `data`: The serialized data for the response. * `status`: A status code for the response. Defaults to 200. See also [status codes][statuscodes]. * `template_name`: A template name to use if `HTMLRenderer` is selected. * `headers`: A dictionary of HTTP headers to use in the response. * `content_type`: The content type of the response. Typically, this will be set automatically by the renderer as determined by content negotiation, but there may be some cases where you need to specify the content type explicitly. --- ## Attributes ### .data The unrendered, serialized data of the response. ### .status_code The numeric status code of the HTTP response. ### .content The rendered content of the response. The `.render()` method must have been called before `.content` can be accessed. ### .template_name The `template_name`, if supplied. Only required if `HTMLRenderer` or some other custom template renderer is the accepted renderer for the response. ### .accepted_renderer The renderer instance that will be used to render the response. Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view. ### .accepted_media_type The media type that was selected by the content negotiation stage. Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view. ### .renderer_context A dictionary of additional context information that will be passed to the renderer's `.render()` method. Set automatically by the `APIView` or `@api_view` immediately before the response is returned from the view. --- ## Standard HttpResponse attributes The `Response` class extends `SimpleTemplateResponse`, and all the usual attributes and methods are also available on the response. For example you can set headers on the response in the standard way: response = Response() response['Cache-Control'] = 'no-cache' ### .render() **Signature:** `.render()` As with any other `TemplateResponse`, this method is called to render the serialized data of the response into the final response content. When `.render()` is called, the response content will be set to the result of calling the `.render(data, accepted_media_type, renderer_context)` method on the `accepted_renderer` instance. You won't typically need to call `.render()` yourself, as it's handled by Django's standard response cycle. [cite]: https://docs.djangoproject.com/en/stable/ref/template-response/ [statuscodes]: status-codes.md ================================================ FILE: docs/api-guide/reverse.md ================================================ --- source: - reverse.py --- # Returning URLs > The central feature that distinguishes the REST architectural style from other network-based styles is its emphasis on a uniform interface between components. > > — Roy Fielding, [Architectural Styles and the Design of Network-based Software Architectures][cite] As a rule, it's probably better practice to return absolute URIs from your Web APIs, such as `http://example.com/foobar`, rather than returning relative URIs, such as `/foobar`. The advantages of doing so are: * It's more explicit. * It leaves less work for your API clients. * There's no ambiguity about the meaning of the string when it's found in representations such as JSON that do not have a native URI type. * It makes it easy to do things like markup HTML representations with hyperlinks. REST framework provides two utility functions to make it more simple to return absolute URIs from your Web API. There's no requirement for you to use them, but if you do then the self-describing API will be able to automatically hyperlink its output for you, which makes browsing the API much easier. ## reverse **Signature:** `reverse(viewname, *args, **kwargs)` Has the same behavior as [`django.urls.reverse`][reverse], except that it returns a fully qualified URL, using the request to determine the host and port. You should **include the request as a keyword argument** to the function, for example: 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) } return Response(data) ## reverse_lazy **Signature:** `reverse_lazy(viewname, *args, **kwargs)` Has the same behavior as [`django.urls.reverse_lazy`][reverse-lazy], except that it returns a fully qualified URL, using the request to determine the host and port. As with the `reverse` function, you should **include the request as a keyword argument** to the function, for example: 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/ref/urlresolvers/#reverse [reverse-lazy]: https://docs.djangoproject.com/en/stable/ref/urlresolvers/#reverse-lazy ================================================ FILE: docs/api-guide/routers.md ================================================ --- source: - routers.py --- # Routers > Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index... a resourceful route declares them in a single line of code. > > — [Ruby on Rails Documentation][cite] Some Web frameworks such as Rails provide functionality for automatically determining how the URLs for an application should be mapped to the logic that deals with handling incoming requests. REST framework adds support for automatic URL routing to Django, and provides you with a simple, quick and consistent way of wiring your view logic to a set of URLs. ## Usage Here's an example of a simple URL conf, that uses `SimpleRouter`. from rest_framework import routers router = routers.SimpleRouter() router.register(r'users', UserViewSet) router.register(r'accounts', AccountViewSet) urlpatterns = router.urls There are two mandatory arguments to the `register()` method: * `prefix` - The URL prefix to use for this set of routes. * `viewset` - The viewset class. Optionally, you may also specify an additional argument: * `basename` - The base to use for the URL names that are created. If unset the basename will be automatically generated based on the `queryset` attribute of the viewset, if it has one. Note that if the viewset does not include a `queryset` attribute then you must set `basename` when registering the viewset. The example above would generate the following URL patterns: * URL pattern: `^users/$` Name: `'user-list'` * URL pattern: `^users/{pk}/$` Name: `'user-detail'` * URL pattern: `^accounts/$` Name: `'account-list'` * URL pattern: `^accounts/{pk}/$` Name: `'account-detail'` !!! note The `basename` argument is used to specify the initial part of the view name pattern. In the example above, that's the `user` or `account` part. Typically you won't *need* to specify the `basename` argument, but if you have a viewset where you've defined a custom `get_queryset` method, then the viewset may not have a `.queryset` attribute set. If you try to register that viewset you'll see an error like this: 'basename' argument not specified, and could not automatically determine the name from the viewset, as it does not have a '.queryset' attribute. This means you'll need to explicitly set the `basename` argument when registering the viewset, as it could not be automatically determined from the model name. ### Using `include` with routers The `.urls` attribute on a router instance is simply a standard list of URL patterns. There are a number of different styles for how you can include these URLs. For example, you can append `router.urls` to a list of existing views... router = routers.SimpleRouter() router.register(r'users', UserViewSet) router.register(r'accounts', AccountViewSet) urlpatterns = [ path('forgot-password/', ForgotPasswordFormView.as_view()), ] urlpatterns += router.urls Alternatively you can use Django's `include` function, like so... urlpatterns = [ path('forgot-password', ForgotPasswordFormView.as_view()), path('', include(router.urls)), ] You may use `include` with an application namespace: urlpatterns = [ path('forgot-password/', ForgotPasswordFormView.as_view()), path('api/', include((router.urls, 'app_name'))), ] Or both an application and instance namespace: urlpatterns = [ path('forgot-password/', ForgotPasswordFormView.as_view()), path('api/', include((router.urls, 'app_name'), namespace='instance_name')), ] See Django's [URL namespaces docs][url-namespace-docs] and the [`include` API reference][include-api-reference] for more details. !!! note If using namespacing with hyperlinked serializers you'll also need to ensure that any `view_name` parameters on the serializers correctly reflect the namespace. In the examples above you'd need to include a parameter such as `view_name='app_name:user-detail'` for serializer fields hyperlinked to the user detail view. The automatic `view_name` generation uses a pattern like `%(model_name)-detail`. Unless your models names actually clash you may be better off **not** namespacing your Django REST Framework views when using hyperlinked serializers. ### Routing for extra actions A viewset may [mark extra actions for routing][route-decorators] by decorating a method with the `@action` decorator. These extra actions will be included in the generated routes. For example, given the `set_password` method on the `UserViewSet` class: from myapp.permissions import IsAdminOrIsSelf from rest_framework.decorators import action class UserViewSet(ModelViewSet): ... @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... The following route would be generated: * URL pattern: `^users/{pk}/set_password/$` * URL name: `'user-set-password'` By default, the URL pattern is based on the method name, and the URL name is the combination of the `ViewSet.basename` and the hyphenated method name. If you don't want to use the defaults for either of these values, you can instead provide the `url_path` and `url_name` arguments to the `@action` decorator. For example, if you want to change the URL for our custom action to `^users/{pk}/change-password/$`, you could write: from myapp.permissions import IsAdminOrIsSelf from rest_framework.decorators import action class UserViewSet(ModelViewSet): ... @action(methods=['post'], detail=True, permission_classes=[IsAdminOrIsSelf], url_path='change-password', url_name='change_password') def set_password(self, request, pk=None): ... 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 This router includes routes for the standard set of `list`, `create`, `retrieve`, `update`, `partial_update` and `destroy` actions. The viewset can also mark additional methods to be routed, using the `@action` decorator.
URL StyleHTTP MethodActionURL Name
{prefix}/GETlist{basename}-list
POSTcreate
{prefix}/{url_path}/GET, or as specified by `methods` argument`@action(detail=False)` decorated method{basename}-{url_name}
{prefix}/{lookup}/GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{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. 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. ### 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.
URL StyleHTTP MethodActionURL Name
[.format]GETautomatically generated root viewapi-root
{prefix}/[.format]GETlist{basename}-list
POSTcreate
{prefix}/{url_path}/[.format]GET, or as specified by `methods` argument`@action(detail=False)` decorated method{basename}-{url_name}
{prefix}/{lookup}/[.format]GETretrieve{basename}-detail
PUTupdate
PATCHpartial_update
DELETEdestroy
{prefix}/{lookup}/{url_path}/[.format]GET, or as specified by `methods` argument`@action(detail=True)` decorated method{basename}-{url_name}
As with `SimpleRouter` the trailing slashes on the URL routes can be removed by setting the `trailing_slash` argument to `False` when instantiating the router. router = DefaultRouter(trailing_slash=False) ## Custom Routers Implementing a custom router isn't something you'd need to do very often, but it can be useful if you have specific requirements about how the URLs for your API are structured. Doing so allows you to encapsulate the URL structure in a reusable way that ensures you don't have to write your URL patterns explicitly for each new view. The simplest way to implement a custom router is to subclass one of the existing router classes. The `.routes` attribute is used to template the URL patterns that will be mapped to each viewset. The `.routes` attribute is a list of `Route` named tuples. The arguments to the `Route` named tuple are: **url**: A string representing the URL to be routed. May include the following format strings: * `{prefix}` - The URL prefix to use for this set of routes. * `{lookup}` - The lookup field used to match against a single instance. * `{trailing_slash}` - Either a '/' or an empty string, depending on the `trailing_slash` argument. **mapping**: A mapping of HTTP method names to the view methods **name**: The name of the URL as used in `reverse` calls. May include the following format string: * `{basename}` - The base to use for the URL names that are created. **initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. Note that the `detail`, `basename`, and `suffix` arguments are reserved for viewset introspection and are also used by the browsable API to generate the view name and breadcrumb links. ### Customizing dynamic routes You can also customize how the `@action` decorator is routed. Include the `DynamicRoute` named tuple in the `.routes` list, setting the `detail` argument as appropriate for the list-based and detail-based routes. In addition to `detail`, the arguments to `DynamicRoute` are: **url**: A string representing the URL to be routed. May include the same format strings as `Route`, and additionally accepts the `{url_path}` format string. **name**: The name of the URL as used in `reverse` calls. May include the following format strings: * `{basename}` - The base to use for the URL names that are created. * `{url_name}` - The `url_name` provided to the `@action`. **initkwargs**: A dictionary of any additional arguments that should be passed when instantiating the view. ### Example The following example will only route to the `list` and `retrieve` actions, and does not use the trailing slash convention. from rest_framework.routers import Route, DynamicRoute, SimpleRouter class CustomReadOnlyRouter(SimpleRouter): """ A router for read-only APIs, which doesn't use trailing slashes. """ routes = [ Route( url=r'^{prefix}$', mapping={'get': 'list'}, name='{basename}-list', detail=False, initkwargs={'suffix': 'List'} ), Route( url=r'^{prefix}/{lookup}$', mapping={'get': 'retrieve'}, name='{basename}-detail', detail=True, initkwargs={'suffix': 'Detail'} ), DynamicRoute( url=r'^{prefix}/{lookup}/{url_path}$', name='{basename}-{url_name}', detail=True, initkwargs={} ) ] Let's take a look at the routes our `CustomReadOnlyRouter` would generate for a simple viewset. `views.py`: class UserViewSet(viewsets.ReadOnlyModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'username' @action(detail=True) def group_names(self, request, pk=None): """ Returns a list of all the group names that the given user belongs to. """ user = self.get_object() groups = user.groups.all() return Response([group.name for group in groups]) `urls.py`: router = CustomReadOnlyRouter() router.register('users', UserViewSet) urlpatterns = router.urls The following mappings would be generated...
URLHTTP MethodActionURL Name
/usersGETlistuser-list
/users/{username}GETretrieveuser-detail
/users/{username}/group_namesGETgroup_namesuser-group-names
For another example of setting the `.routes` attribute, see the source code for the `SimpleRouter` class. ### Advanced custom routers If you want to provide totally custom behavior, you can override `BaseRouter` and override the `get_urls(self)` method. The method should inspect the registered viewsets and return a list of URL patterns. The registered prefix, viewset and basename tuples may be inspected by accessing the `self.registry` attribute. You may also want to override the `get_default_basename(self, viewset)` method, or else always explicitly set the `basename` argument when registering your viewsets with the router. ## Third Party Packages The following third party packages are also available. ### DRF Nested Routers The [drf-nested-routers package][drf-nested-routers] provides routers and relationship fields for working with nested resources. ### ModelRouter (wq.db.rest) The [wq.db package][wq.db] provides an advanced [ModelRouter][wq.db-router] class (and singleton instance) that extends `DefaultRouter` with a `register_model()` API. Much like Django's `admin.site.register`, the only required argument to `rest.router.register_model` is a model class. Reasonable defaults for a url prefix, serializer, and viewset will be inferred from the model and global configuration. from wq.db import rest from myapp.models import MyModel rest.router.register_model(MyModel) ### DRF-extensions The [`DRF-extensions` package][drf-extensions] provides [routers][drf-extensions-routers] for creating [nested viewsets][drf-extensions-nested-viewsets], [collection level controllers][drf-extensions-collection-level-controllers] with [customizable endpoint names][drf-extensions-customizable-endpoint-names]. [cite]: https://guides.rubyonrails.org/routing.html [route-decorators]: viewsets.md#marking-extra-actions-for-routing [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers [wq.db]: https://wq.io/wq.db [wq.db-router]: https://wq.io/docs/router [drf-extensions]: https://chibisov.github.io/drf-extensions/docs/ [drf-extensions-routers]: https://chibisov.github.io/drf-extensions/docs/#routers [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/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 ================================================ FILE: docs/api-guide/schemas.md ================================================ --- source: - schemas --- # Schema > 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] --- **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 customizable 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. Django REST Framework provides support for automatic generation of [OpenAPI][openapi] schemas. ## Overview Schema generation has several moving parts. It's worth having an overview: * `SchemaGenerator` is a top-level class that is responsible for walking your configured URL patterns, finding `APIView` subclasses, enquiring for their schema representation, and compiling the final schema object. * `AutoSchema` encapsulates all the details necessary for per-view schema introspection. Is attached to each view via the `schema` attribute. You subclass `AutoSchema` in order to customize your schema. * The `generateschema` management command allows you to generate a static schema offline. * Alternatively, you can route `SchemaView` to dynamically generate and serve your schema. * `settings.DEFAULT_SCHEMA_CLASS` allows you to specify an `AutoSchema` subclass to serve as your project's default. The following sections explain more. ## Generating an OpenAPI Schema ### Install dependencies 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 If your schema is static, you can use the `generateschema` management command: ```bash ./manage.py generateschema --file openapi-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. ### Generating a dynamic schema with `SchemaView` If you require a dynamic schema, because foreign key choices depend on database values, for example, you can route a `SchemaView` that will generate and serve your schema on demand. To route a `SchemaView`, use the `get_schema_view()` helper. In `urls.py`: ```python from rest_framework.schemas import get_schema_view 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", ), # ... ] ``` #### `get_schema_view()` The `get_schema_view()` helper takes the following keyword arguments: * `title`: May be used to provide a descriptive title for the schema definition. * `description`: Longer descriptive text. * `version`: The version of the API. * `url`: May be used to pass a canonical base 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' ) * `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, ) * `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`. * `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`. * `renderer_classes`: May be used to pass the set of renderer classes that can be used to render the API root endpoint. ## SchemaGenerator **Schema-level customization** ```python from rest_framework.schemas.openapi import SchemaGenerator ``` `SchemaGenerator` is a class that walks a list of routed URL patterns, requests the schema for each view and collates the resulting OpenAPI schema. Typically you won't need to instantiate `SchemaGenerator` yourself, but you can do so like so: generator = SchemaGenerator(title='Stock Prices API') Arguments: * `title` **required**: The name of the API. * `description`: Longer descriptive text. * `version`: The version of the API. Defaults to `0.1.0`. * `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`. In order to customize the top-level schema, subclass `rest_framework.schemas.openapi.SchemaGenerator` and provide your subclass as an argument to the `generateschema` command or `get_schema_view()` helper function. ### get_schema(self, request=None, public=False) Returns a dictionary that represents the OpenAPI schema: generator = SchemaGenerator(title='Stock Prices API') schema = 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. This is a good point to override if you want to customize the generated dictionary For example you might wish to add terms of service to the [top-level `info` object][info-object]: ``` class TOSSchemaGenerator(SchemaGenerator): def get_schema(self, *args, **kwargs): schema = super().get_schema(*args, **kwargs) schema["info"]["termsOfService"] = "https://example.com/tos.html" return schema ``` ## AutoSchema **Per-View Customization** ```python from rest_framework.schemas.openapi import AutoSchema ``` By default, view introspection is performed by an `AutoSchema` instance accessible via the `schema` attribute on `APIView`. auto_schema = some_view.schema `AutoSchema` provides the OpenAPI elements needed for each view, request method and path: * A list of [OpenAPI components][openapi-components]. In DRF terms these are mappings of serializers that describe request and response bodies. * The appropriate [OpenAPI operation object][openapi-operation] that describes the endpoint, including path and query parameters for pagination, filtering, and so on. ```python components = auto_schema.get_components(...) operation = auto_schema.get_operation(...) ``` In compiling the schema, `SchemaGenerator` calls `get_components()` and `get_operation()` for each view, allowed method, and path. !!! note The automatic introspection of components, and many operation parameters relies on the relevant attributes and methods of `GenericAPIView`: `get_serializer()`, `pagination_class`, `filter_backends`, etc. For basic `APIView` subclasses, default introspection is essentially limited to the URL kwarg path parameters for this reason. `AutoSchema` encapsulates the view introspection needed for schema generation. Because of this all the schema generation logic is kept in a single place, rather than being spread around the already extensive view, serializer and field APIs. Keeping with this pattern, try not to let schema logic leak into your own views, serializers, or fields when customizing the schema generation. You might be tempted to do something like this: ```python class CustomSchema(AutoSchema): """ AutoSchema subclass using schema_extra_info on the view. """ ... class CustomView(APIView): schema = CustomSchema() schema_extra_info = ... # some extra info ``` Here, the `AutoSchema` subclass goes looking for `schema_extra_info` on the view. This is _OK_ (it doesn't actually hurt) but it means you'll end up with your schema logic spread out in a number of different places. Instead try to subclass `AutoSchema` such that the `extra_info` doesn't leak out into the view: ```python class BaseSchema(AutoSchema): """ AutoSchema subclass that knows how to use extra_info. """ ... class CustomSchema(BaseSchema): extra_info = ... # some extra info class CustomView(APIView): schema = CustomSchema() ``` This style is slightly more verbose but maintains the encapsulation of the schema related code. It's more _cohesive_ in the _parlance_. It'll keep the rest of your API code more tidy. If an option applies to many view classes, rather than creating a specific subclass per-view, you may find it more convenient to allow specifying the option as an `__init__()` kwarg to your base `AutoSchema` subclass: ```python class CustomSchema(BaseSchema): def __init__(self, **kwargs): # store extra_info for later self.extra_info = kwargs.pop("extra_info") super().__init__(**kwargs) class CustomView(APIView): 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 the more commonly needed options do. ### `AutoSchema` methods #### `get_components()` Generates the OpenAPI components that describe request and response bodies, 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 `get_components()` to return multiple pairs if your view uses multiple serializers. #### `get_component_name()` Computes the component's name from the serializer. You may see warnings if your API has duplicate component names. If so you can override `get_component_name()` or pass the `component_name` `__init__()` kwarg (see below) to provide different names. #### `get_reference()` Returns a reference to the serializer component. This may be useful if you override `get_schema()`. #### `map_serializer()` Maps serializers to their OpenAPI representations. Most serializers should conform to the standard OpenAPI `object` type, but you may wish to override `map_serializer()` in order to customize this or other serializer-level fields. #### `map_field()` Maps individual serializer fields to their schema representation. The base implementation will handle the default fields that Django REST Framework provides. For `SerializerMethodField` instances, for which the schema is unknown, or custom field subclasses you should override `map_field()` to generate the correct schema: ```python class CustomSchema(AutoSchema): """Extension of ``AutoSchema`` to add support for custom field schemas.""" def map_field(self, field): # Handle SerializerMethodFields or custom fields here... # ... return super().map_field(field) ``` Authors of third-party packages should aim to provide an `AutoSchema` subclass, and a mixin, overriding `map_field()` so that users can easily generate schemas for their custom fields. #### `get_tags()` OpenAPI groups operations by tags. By default tags taken from the first path segment of the routed URL. For example, a URL like `/users/{id}/` will generate the tag `users`. You can pass an `__init__()` kwarg to manually specify tags (see below), or override `get_tags()` to provide custom logic. #### `get_operation()` Returns the [OpenAPI operation object][openapi-operation] that describes the endpoint, including path and query parameters for pagination, filtering, and so on. Together with `get_components()`, this is the main entry point to the view introspection. #### `get_operation_id()` There must be a unique [operationid][openapi-operationid] for each operation. By default the `operationId` is deduced from the model name, serializer name or view name. The operationId looks like "listItems", "retrieveItem", "updateItem", etc. The `operationId` is camelCase by convention. #### `get_operation_id_base()` If you have several views with the same model name, you may see duplicate operationIds. In order to work around this, you can override `get_operation_id_base()` to provide a different base for name part of the ID. #### `get_serializer()` If the view has implemented `get_serializer()`, returns the result. #### `get_request_serializer()` By default returns `get_serializer()` but can be overridden to differentiate between request and response objects. #### `get_response_serializer()` By default returns `get_serializer()` but can be overridden to differentiate between request and response objects. ### `AutoSchema.__init__()` kwargs `AutoSchema` provides a number of `__init__()` kwargs that can be used for common customizations, if the default generated values are not appropriate. The available kwargs are: * `tags`: Specify a list of tags. * `component_name`: Specify the component name. * `operation_id_base`: Specify the resource-name part of operation IDs. You pass the kwargs when declaring the `AutoSchema` instance on your view: ``` class PetDetailView(generics.RetrieveUpdateDestroyAPIView): schema = AutoSchema( tags=['Pets'], component_name='Pet', operation_id_base='Pet', ) ... ``` Assuming a `Pet` model and `PetSerializer` serializer, the kwargs in this example are probably not needed. Often, though, you'll need to pass the kwargs if you have multiple view targeting the same model, or have multiple views with identically named serializers. 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://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/main/versions/3.0.2.md#specification-extensions [openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#operationObject [openapi-tags]: https://swagger.io/specification/#tagObject [openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#fixed-fields-17 [openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#componentsObject [openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#referenceObject [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 ================================================ FILE: docs/api-guide/serializers.md ================================================ --- source: - serializers.py --- > Expanding the usefulness of the serializers is something that we would like to address. However, it's not a trivial problem, and it will take some serious design work. > > — Russell Keith-Magee, [Django users group][cite] Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into `JSON`, `XML` or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. The serializers in REST framework work very similarly to Django's `Form` and `ModelForm` classes. We provide a `Serializer` class which gives you a powerful, generic way to control the output of your responses, as well as a `ModelSerializer` class which provides a useful shortcut for creating serializers that deal with model instances and querysets. ## Serializers ### Declaring Serializers Let's start by creating a simple object we can use for example purposes: from datetime import datetime class Comment: def __init__(self, email, content, created=None): self.email = email self.content = content self.created = created or datetime.now() comment = Comment(email='leila@example.com', content='foo bar') We'll declare a serializer that we can use to serialize and deserialize data that corresponds to `Comment` objects. Declaring a serializer looks very similar to declaring a form: from rest_framework import serializers class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() ### Serializing objects We can now use `CommentSerializer` to serialize a comment, or list of comments. Again, using the `Serializer` class looks a lot like using a `Form` class. serializer = CommentSerializer(comment) serializer.data # {'email': 'leila@example.com', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'} At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. from rest_framework.renderers import JSONRenderer json = JSONRenderer().render(serializer.data) json # b'{"email":"leila@example.com","content":"foo bar","created":"2016-01-27T15:17:10.375877"}' ### Deserializing objects Deserialization is similar. First we parse a stream into Python native datatypes... import io from rest_framework.parsers import JSONParser stream = io.BytesIO(json) data = JSONParser().parse(stream) ...then we restore those native datatypes into a dictionary of validated data. serializer = CommentSerializer(data=data) serializer.is_valid() # True serializer.validated_data # {'content': 'foo bar', 'email': 'leila@example.com', 'created': datetime.datetime(2012, 08, 22, 16, 20, 09, 822243)} ### Saving instances If we want to be able to return complete object instances based on the validated data we need to implement one or both of the `.create()` and `.update()` methods. For example: class CommentSerializer(serializers.Serializer): email = serializers.EmailField() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() def create(self, validated_data): return Comment(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) return instance If your object instances correspond to Django models you'll also want to ensure that these methods save the object to the database. For example, if `Comment` was a Django model, the methods might look like this: def create(self, validated_data): return Comment.objects.create(**validated_data) def update(self, instance, validated_data): instance.email = validated_data.get('email', instance.email) instance.content = validated_data.get('content', instance.content) instance.created = validated_data.get('created', instance.created) instance.save() return instance Now when deserializing data, we can call `.save()` to return an object instance, based on the validated data. comment = serializer.save() Calling `.save()` will either create a new instance, or update an existing instance, depending on if an existing instance was passed when instantiating the serializer class: # .save() will create a new instance. serializer = CommentSerializer(data=data) # .save() will update the existing `comment` instance. serializer = CommentSerializer(comment, data=data) Both the `.create()` and `.update()` methods are optional. You can implement either none, one, or both of them, depending on the use-case for your serializer class. #### Passing additional attributes to `.save()` Sometimes you'll want your view code to be able to inject additional data at the point of saving the instance. This additional data might include information like the current user, the current time, or anything else that is not part of the request data. You can do so by including additional keyword arguments when calling `.save()`. For example: serializer.save(owner=request.user) Any additional keyword arguments will be included in the `validated_data` argument when `.create()` or `.update()` are called. #### Overriding `.save()` directly. In some cases the `.create()` and `.update()` method names may not be meaningful. For example, in a contact form we may not be creating new instances, but instead sending an email or other message. In these cases you might instead choose to override `.save()` directly, as being more readable and meaningful. For example: class ContactForm(serializers.Serializer): email = serializers.EmailField() message = serializers.CharField() def save(self): email = self.validated_data['email'] message = self.validated_data['message'] send_email(from=email, message=message) Note that in the case above we're now having to access the serializer `.validated_data` property directly. ### Validation When deserializing data, you always need to call `is_valid()` before attempting to access the validated data, or save an object instance. If any validation errors occur, the `.errors` property will contain a dictionary representing the resulting error messages. For example: serializer = CommentSerializer(data={'email': 'foobar', 'content': 'baz'}) serializer.is_valid() # False serializer.errors # {'email': ['Enter a valid email address.'], 'created': ['This field is required.']} Each key in the dictionary will be the field name, and the values will be lists of strings of any error messages corresponding to that field. The `non_field_errors` key may also be present, and will list any general validation errors. The name of the `non_field_errors` key may be customized using the `NON_FIELD_ERRORS_KEY` REST framework setting. When deserializing a list of items, errors will be returned as a list of dictionaries representing each of the deserialized items. #### Raising an exception on invalid data The `.is_valid()` method takes an optional `raise_exception` flag that will cause it to raise a `serializers.ValidationError` exception if there are validation errors. These exceptions are automatically dealt with by the default exception handler that REST framework provides, and will return `HTTP 400 Bad Request` responses by default. # Return a 400 response if the data was invalid. serializer.is_valid(raise_exception=True) #### Field-level validation You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. These are similar to the `.clean_` methods on Django forms. These methods take a single argument, which is the field value that requires validation. Your `validate_` methods should return the validated value or raise a `serializers.ValidationError`. For example: from rest_framework import serializers class BlogPostSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) content = serializers.CharField() def validate_title(self, value): """ Check that the blog post is about Django. """ if 'django' not in value.lower(): raise serializers.ValidationError("Blog post is not about Django") return value !!! note If your `` is declared on your serializer with the parameter `required=False` then this validation step will not take place if the field is not included. #### Object-level validation To do any other validation that requires access to multiple fields, add a method called `.validate()` to your `Serializer` subclass. This method takes a single argument, which is a dictionary of field values. It should raise a `serializers.ValidationError` if necessary, or just return the validated values. For example: from rest_framework import serializers class EventSerializer(serializers.Serializer): description = serializers.CharField(max_length=100) start = serializers.DateTimeField() finish = serializers.DateTimeField() def validate(self, data): """ Check that start is before finish. """ if data['start'] > data['finish']: raise serializers.ValidationError("finish must occur after start") return data #### Validators Individual fields on a serializer can include validators, by declaring them on the field instance, for example: def multiple_of_ten(value): if value % 10 != 0: raise serializers.ValidationError('Not a multiple of ten') class GameRecord(serializers.Serializer): score = 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.ChoiceField(choices=[101, 102, 103, 201]) date = serializers.DateField() class Meta: # Each room only has one event per day. validators = [ UniqueTogetherValidator( queryset=Event.objects.all(), fields=['room_number', 'date'] ) ] For more information see the [validators documentation](validators.md). ### Accessing the initial data and instance When passing an initial object or queryset to a serializer instance, the object will be made available as `.instance`. If no initial object is passed then the `.instance` attribute will be `None`. When passing data to a serializer instance, the unmodified data will be made available as `.initial_data`. If the `data` keyword argument is not passed then the `.initial_data` attribute will not exist. ### Partial updates By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the `partial` argument in order to allow partial updates. # Update `comment` with partial data serializer = CommentSerializer(comment, data={'content': 'foo bar'}, partial=True) ### Dealing with nested objects The previous examples are fine for dealing with objects that only have simple datatypes, but sometimes we also need to be able to represent more complex objects, where some of the attributes of an object might not be simple datatypes such as strings, dates or integers. The `Serializer` class is itself a type of `Field`, and can be used to represent relationships where one object type is nested inside another. class UserSerializer(serializers.Serializer): email = serializers.EmailField() username = serializers.CharField(max_length=100) class CommentSerializer(serializers.Serializer): user = UserSerializer() content = serializers.CharField(max_length=200) created = serializers.DateTimeField() If a nested representation may optionally accept the `None` value you should pass the `required=False` flag to the nested serializer. class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False) # May be an anonymous user. content = serializers.CharField(max_length=200) created = serializers.DateTimeField() Similarly if a nested representation should be a list of items, you should pass the `many=True` flag to the nested serializer. class CommentSerializer(serializers.Serializer): user = UserSerializer(required=False) edits = EditItemSerializer(many=True) # A nested list of 'edit' items. content = serializers.CharField(max_length=200) created = serializers.DateTimeField() ### Writable nested representations When dealing with nested representations that support deserializing the data, any errors with nested objects will be nested under the field name of the nested object. serializer = CommentSerializer(data={'user': {'email': 'foobar', 'username': 'doe'}, 'content': 'baz'}) serializer.is_valid() # False serializer.errors # {'user': {'email': ['Enter a valid email address.']}, 'created': ['This field is required.']} Similarly, the `.validated_data` property will include nested data structures. #### Writing `.create()` methods for nested representations If you're supporting writable nested representations you'll need to write `.create()` or `.update()` methods that handle saving multiple objects. The following example demonstrates how you might handle creating a user with a nested profile object. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user #### Writing `.update()` methods for nested representations For updates you'll want to think carefully about how to handle updates to relationships. For example if the data for the relationship is `None`, or not provided, which of the following should occur? * Set the relationship to `NULL` in the database. * Delete the associated instance. * Ignore the data and leave the instance as it is. * Raise a validation error. Here's an example for an `.update()` method on our previous `UserSerializer` class. def update(self, instance, validated_data): profile_data = validated_data.pop('profile') # Unless the application properly enforces that this field is # always set, the following could raise a `DoesNotExist`, which # would need to be handled. profile = instance.profile instance.username = validated_data.get('username', instance.username) instance.email = validated_data.get('email', instance.email) instance.save() profile.is_premium_member = profile_data.get( 'is_premium_member', profile.is_premium_member ) profile.has_support_contract = profile_data.get( 'has_support_contract', profile.has_support_contract ) profile.save() return instance Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default `ModelSerializer` `.create()` and `.update()` methods do not include support for writable nested representations. There are however, third-party packages available such as [DRF Writable Nested][thirdparty-writable-nested] that support automatic writable nested representations. #### Handling saving related instances in model manager classes An alternative to saving multiple related instances in the serializer is to write custom model manager classes that handle creating the correct instances. For example, suppose we wanted to ensure that `User` instances and `Profile` instances are always created together as a pair. We might write a custom manager class that looks something like this: class UserManager(models.Manager): ... def create(self, username, email, is_premium_member=False, has_support_contract=False): user = User(username=username, email=email) user.save() profile = Profile( user=user, is_premium_member=is_premium_member, has_support_contract=has_support_contract ) profile.save() return user This manager class now more nicely encapsulates that user instances and profile instances are always created at the same time. Our `.create()` method on the serializer class can now be re-written to use the new manager method. def create(self, validated_data): return User.objects.create( username=validated_data['username'], email=validated_data['email'], is_premium_member=validated_data['profile']['is_premium_member'], has_support_contract=validated_data['profile']['has_support_contract'] ) For more details on this approach see the Django documentation on [model managers][model-managers], and [this blogpost on using model and manager classes][encapsulation-blogpost]. ### Dealing with multiple objects The `Serializer` class can also handle serializing or deserializing lists of objects. #### Serializing multiple objects To serialize a queryset or list of objects instead of a single object instance, you should pass the `many=True` flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized. queryset = Book.objects.all() serializer = BookSerializer(queryset, many=True) serializer.data # [ # {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'}, # {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'}, # {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'} # ] #### Deserializing multiple objects The default behavior for deserializing multiple objects is to support multiple object creation, but not support multiple object updates. For more information on how to support or customize either of these cases, see the [ListSerializer](#listserializer) documentation below. ### Including extra context There are some cases where you need to provide extra context to the serializer in addition to the object being serialized. One common case is if you're using a serializer that includes hyperlinked relations, which requires the serializer to have access to the current request so that it can properly generate fully qualified URLs. You can provide arbitrary additional context by passing a `context` argument when instantiating the serializer. For example: serializer = AccountSerializer(account, context={'request': request}) serializer.data # {'id': 6, 'owner': 'denvercoder9', 'created': datetime.datetime(2013, 2, 12, 09, 44, 56, 678870), 'details': 'http://example.com/accounts/6/details'} The context dictionary can be used within any serializer field logic, such as a custom `.to_representation()` method, by accessing the `self.context` attribute. --- ## ModelSerializer Often you'll want serializer classes that map closely to Django model definitions. The `ModelSerializer` class provides a shortcut that lets you automatically create a `Serializer` class with fields that correspond to the Model fields. **The `ModelSerializer` class is the same as a regular `Serializer` class, except that**: * It will automatically generate a set of fields for you, based on the model. * It will automatically generate validators for the serializer, such as unique_together validators. * It includes simple default implementations of `.create()` and `.update()`. Declaring a `ModelSerializer` looks like this: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] By default, all the model fields on the class will be mapped to a corresponding serializer fields. Any relationships such as foreign keys on the model will be mapped to `PrimaryKeyRelatedField`. Reverse relationships are not included by default unless explicitly included as specified in the [serializer relations][relations] documentation. ### Inspecting a `ModelSerializer` Serializer classes generate helpful verbose representation strings, that allow you to fully inspect the state of their fields. This is particularly useful when working with `ModelSerializers` where you want to determine what set of fields and validators are being automatically created for you. To do so, open the Django shell, using `python manage.py shell`, then import the serializer class, instantiate it, and print the object representation… >>> from myapp.serializers import AccountSerializer >>> serializer = AccountSerializer() >>> print(repr(serializer)) AccountSerializer(): id = IntegerField(label='ID', read_only=True) name = CharField(allow_blank=True, max_length=100, required=False) owner = PrimaryKeyRelatedField(queryset=User.objects.all()) ### Specifying which fields to include If you only want a subset of the default fields to be used in a model serializer, you can do so using `fields` or `exclude` options, just as you would with a `ModelForm`. It is strongly recommended that you explicitly set all fields that should be serialized using the `fields` attribute. This will make it less likely to result in unintentionally exposing data when your models change. For example: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] You can also set the `fields` attribute to the special value `'__all__'` to indicate that all fields in the model should be used. For example: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = '__all__' You can set the `exclude` attribute to a list of fields to be excluded from the serializer. For example: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account exclude = ['users'] In the example above, if the `Account` model had 3 fields `account_name`, `users`, and `created`, this will result in the fields `account_name` and `created` to be serialized. The names in the `fields` and `exclude` attributes will normally map to model fields on the model class. Alternatively names in the `fields` options can map to properties or methods which take no arguments that exist on the model class. Since version 3.3.0, it is **mandatory** to provide one of the attributes `fields` or `exclude`. ### Specifying nested serialization The default `ModelSerializer` uses primary keys for relationships, but you can also easily generate nested representations using the `depth` option: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] depth = 1 The `depth` option should be set to an integer value that indicates the depth of relationships that should be traversed before reverting to a flat representation. If you want to customize the way the serialization is done you'll need to define the field yourself. ### Specifying fields explicitly You can add extra fields to a `ModelSerializer` or override the default fields by declaring fields on the class, just as you would for a `Serializer` class. class AccountSerializer(serializers.ModelSerializer): url = serializers.CharField(source='get_absolute_url', read_only=True) groups = serializers.PrimaryKeyRelatedField(many=True) class Meta: model = Account fields = ['url', 'groups'] Extra fields can correspond to any property or callable on the model. ### Specifying read only fields You may wish to specify multiple fields as read-only. Instead of adding each field explicitly with the `read_only=True` attribute, you may use the shortcut Meta option, `read_only_fields`. This option should be a list or tuple of field names, and is declared as follows: class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['id', 'account_name', 'users', 'created'] read_only_fields = ['account_name'] Model fields which have `editable=False` set, and `AutoField` fields will be set to read-only by default, and do not need to be added to the `read_only_fields` option. !!! note There is a special-case where a read-only field is part of a `unique_together` constraint at the model level. In this case the field is required by the serializer class in order to validate the constraint, but should also not be editable by the user. The right way to deal with this is to specify the field explicitly on the serializer, providing both the `read_only=True` and `default=…` keyword arguments. One example of this is a read-only relation to the currently authenticated `User` which is `unique_together` with another identifier. In this case you would declare the user field like so: user = serializers.PrimaryKeyRelatedField(read_only=True, default=serializers.CurrentUserDefault()) Please review the [Validators Documentation](/api-guide/validators/) for details on the [UniqueTogetherValidator](/api-guide/validators/#uniquetogethervalidator) and [CurrentUserDefault](/api-guide/validators/#currentuserdefault) classes. ### Additional keyword arguments There is also a shortcut allowing you to specify arbitrary additional keyword arguments on fields, using the `extra_kwargs` option. As in the case of `read_only_fields`, this means you do not need to explicitly declare the field on the serializer. This option is a dictionary, mapping field names to a dictionary of keyword arguments. For example: class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['email', 'username', 'password'] extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User( email=validated_data['email'], username=validated_data['username'] ) user.set_password(validated_data['password']) user.save() return user Please keep in mind that, if the field has already been explicitly declared on the serializer class, then the `extra_kwargs` option will be ignored. ### Relational fields When serializing model instances, there are a number of different ways you might choose to represent relationships. The default representation for `ModelSerializer` is to use the primary keys of the related instances. Alternative representations include serializing using hyperlinks, serializing complete nested representations, or serializing with a custom representation. For full details see the [serializer relations][relations] documentation. ### Customizing field mappings The ModelSerializer class also exposes an API that you can override in order to alter how serializer fields are automatically determined when instantiating the serializer. Normally if a `ModelSerializer` does not generate the fields you need by default then you should either add them to the class explicitly, or simply use a regular `Serializer` class instead. However in some cases you may want to create a new base class that defines how the serializer fields are created for any given model. #### `serializer_field_mapping` A mapping of Django model 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` This property should be the serializer field class, that is used for relational fields by default. For `ModelSerializer` this defaults to `serializers.PrimaryKeyRelatedField`. For `HyperlinkedModelSerializer` this defaults to `serializers.HyperlinkedRelatedField`. #### `serializer_url_field` The serializer field class that should be used for any `url` field on the serializer. Defaults to `serializers.HyperlinkedIdentityField` #### `serializer_choice_field` The serializer field class that should be used for any choice fields on the serializer. Defaults to `serializers.ChoiceField` #### The field_class and field_kwargs API The following methods are called to determine the class and keyword arguments for each field that should be automatically included on the serializer. Each of these methods should return a two tuple of `(field_class, field_kwargs)`. #### `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)` Called to generate a serializer field that maps to a relational model field. The default implementation returns a serializer class based on the `serializer_related_field` attribute. The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. #### `build_nested_field(self, field_name, relation_info, nested_depth)` Called to generate a serializer field that maps to a relational model field, when the `depth` option has been set. The default implementation dynamically creates a nested serializer class based on either `ModelSerializer` or `HyperlinkedModelSerializer`. The `nested_depth` will be the value of the `depth` option, minus one. The `relation_info` argument is a named tuple, that contains `model_field`, `related_model`, `to_many` and `has_through_model` properties. #### `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)` Called to generate a serializer field for the serializer's own `url` field. The default implementation returns a `HyperlinkedIdentityField` class. #### `build_unknown_field(self, field_name, model_class)` Called when the field name did not map to any model field or model property. The default implementation raises an error, although subclasses may customize this behavior. --- ## HyperlinkedModelSerializer The `HyperlinkedModelSerializer` class is similar to the `ModelSerializer` class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a `url` field instead of a primary key field. The url field will be represented using a `HyperlinkedIdentityField` serializer field, and any relationships on the model will be represented using a `HyperlinkedRelatedField` serializer field. You can explicitly include the primary key by adding it to the `fields` option, for example: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account fields = ['url', 'id', 'account_name', 'users', 'created'] ### Absolute and relative URLs When instantiating a `HyperlinkedModelSerializer` you must include the current `request` in the serializer context, for example: serializer = AccountSerializer(queryset, context={'request': request}) Doing so will ensure that the hyperlinks can include an appropriate hostname, so that the resulting representation uses fully qualified URLs, such as: http://api.example.com/accounts/1/ Rather than relative URLs, such as: /accounts/1/ If you *do* want to use relative URLs, you should explicitly pass `{'request': None}` in the serializer context. ### How hyperlinked views are determined There needs to be a way of determining which views should be used for hyperlinking to model instances. By default hyperlinks are expected to correspond to a view name that matches the style `'{model_name}-detail'`, and looks up the instance by a `pk` keyword argument. You can override a URL field view name and lookup field by using either, or both of, the `view_name` and `lookup_field` options in the `extra_kwargs` setting, like so: class AccountSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Account fields = ['url', 'account_name', 'users', 'created'] extra_kwargs = { 'url': {'view_name': 'accounts', 'lookup_field': 'account_name'}, 'users': {'lookup_field': 'username'} } Alternatively you can set the fields on the serializer explicitly. For example: class AccountSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='accounts', lookup_field='slug' ) users = serializers.HyperlinkedRelatedField( view_name='user-detail', lookup_field='username', many=True, read_only=True ) class Meta: model = Account fields = ['url', 'account_name', 'users', 'created'] --- **Tip**: Properly matching together hyperlinked representations and your URL conf can sometimes be a bit fiddly. Printing the `repr` of a `HyperlinkedModelSerializer` instance is a particularly useful way to inspect exactly which view names and lookup fields the relationships are expected to map too. --- ### Changing the URL field name The name of the URL field defaults to 'url'. You can override this globally, by using the `URL_FIELD_NAME` setting. --- ## ListSerializer The `ListSerializer` class provides the behavior for serializing and validating multiple objects at once. You won't *typically* need to use `ListSerializer` directly, but should instead simply pass `many=True` when instantiating a serializer. When a serializer is instantiated and `many=True` is passed, a `ListSerializer` instance will be created. The serializer class then becomes a child of the parent `ListSerializer` The following argument can also be passed to a `ListSerializer` field or a serializer that is passed `many=True`: - `allow_empty`: this is `True` by default, but can be set to `False` if you want to disallow empty lists as valid input. - `max_length`: 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 validate that the list contains no fewer than this number of elements. ### Customizing `ListSerializer` behavior There *are* a few use cases when you might want to customize the `ListSerializer` behavior. For example: * You want to provide particular validation of the lists, such as checking that one element does not conflict with another element in a list. * You want to customize the create or update behavior of multiple objects. For these cases you can modify the class that is used when `many=True` is passed, by using the `list_serializer_class` option on the serializer `Meta` class. For example: class CustomListSerializer(serializers.ListSerializer): ... class CustomSerializer(serializers.Serializer): ... class Meta: list_serializer_class = CustomListSerializer ### Customizing multiple create The default implementation for multiple object creation is to simply call `.create()` for each item in the list. If you want to customize this behavior, you'll need to customize the `.create()` method on `ListSerializer` class that is used when `many=True` is passed. For example: class BookListSerializer(serializers.ListSerializer): def create(self, validated_data): books = [Book(**item) for item in validated_data] return Book.objects.bulk_create(books) class BookSerializer(serializers.Serializer): ... class Meta: list_serializer_class = BookListSerializer ### Customizing multiple update By default the `ListSerializer` class does not support multiple updates. This is because the behavior that should be expected for insertions and deletions is ambiguous. To support multiple updates you'll need to do so explicitly. When writing your multiple update code make sure to keep the following in mind: * How do you determine which instance should be updated for each item in the list of data? * How should insertions be handled? Are they invalid, or do they create new objects? * How should removals be handled? Do they imply object deletion, or removing a relationship? Should they be silently ignored, or are they invalid? * How should ordering be handled? Does changing the position of two items imply any state change or is it ignored? You will need to add an explicit `id` field to the instance serializer. The default implicitly-generated `id` field is marked as `read_only`. This causes it to be removed on updates. Once you declare it explicitly, it will be available in the list serializer's `update` method. Here's an example of how you might choose to implement multiple updates: class BookListSerializer(serializers.ListSerializer): def update(self, instance, validated_data): # Maps for id->instance and id->data item. book_mapping = {book.id: book for book in instance} data_mapping = {item['id']: item for item in validated_data} # Perform creations and updates. ret = [] for book_id, data in data_mapping.items(): book = book_mapping.get(book_id, None) if book is None: ret.append(self.child.create(data)) else: ret.append(self.child.update(book, data)) # Perform deletions. for book_id, book in book_mapping.items(): if book_id not in data_mapping: book.delete() return ret class BookSerializer(serializers.Serializer): # We need to identify elements in the list using their primary key, # so use a writable field here, rather than the default which would be read-only. id = serializers.IntegerField() ... class Meta: list_serializer_class = BookListSerializer ### 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. The default implementation is to pass all arguments to both classes, except for `validators`, and any custom keyword arguments, both of which are assumed to be intended for the child serializer class. Occasionally you might need to explicitly specify how the child and parent classes should be instantiated when `many=True` is passed. You can do so by using the `many_init` class method. @classmethod def many_init(cls, *args, **kwargs): # Instantiate the child serializer. kwargs['child'] = cls() # Instantiate the parent list serializer. return CustomListSerializer(*args, **kwargs) --- ## BaseSerializer `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the `Serializer` class: * `.data` - Returns the outgoing primitive representation. * `.is_valid()` - Deserializes and validates incoming data. * `.validated_data` - Returns the validated incoming data. * `.errors` - Returns any errors during validation. * `.save()` - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: * `.to_representation()` - Override this to support serialization, for read operations. * `.to_internal_value()` - Override this to support deserialization, for write operations. * `.create()` and `.update()` - Override either or both of these to support saving instances. Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`. The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input. ### Read-only `BaseSerializer` classes To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: class HighScore(models.Model): created = models.DateTimeField(auto_now_add=True) player_name = models.CharField(max_length=10) score = models.IntegerField() It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer): def to_representation(self, instance): return { 'score': instance.score, 'player_name': instance.player_name } We can now use this class to serialize single `HighScore` instances: @api_view(['GET']) def high_score(request, pk): instance = HighScore.objects.get(pk=pk) serializer = HighScoreSerializer(instance) return Response(serializer.data) Or use it to serialize multiple instances: @api_view(['GET']) def all_high_scores(request): queryset = HighScore.objects.order_by('-score') serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data) ### Read-write `BaseSerializer` classes To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `serializers.ValidationError` if the supplied data is in an incorrect format. Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`. If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods. Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer): def to_internal_value(self, data): score = data.get('score') player_name = data.get('player_name') # Perform the data validation. if not score: raise serializers.ValidationError({ 'score': 'This field is required.' }) if not player_name: raise serializers.ValidationError({ 'player_name': 'This field is required.' }) if len(player_name) > 10: raise serializers.ValidationError({ 'player_name': 'May not be more than 10 characters.' }) # Return the validated values. This will be available as # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name } def to_representation(self, instance): return { 'score': instance.score, 'player_name': instance.player_name } def create(self, validated_data): return HighScore.objects.create(**validated_data) ### Creating new base classes The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. The following class is an example of a generic serializer that can handle coercing arbitrary complex objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer): """ A read-only serializer that coerces arbitrary complex objects into primitive representations. """ def to_representation(self, instance): output = {} for attribute_name in dir(instance): attribute = getattr(instance, attribute_name) if attribute_name.startswith('_'): # Ignore private attributes. pass elif hasattr(attribute, '__call__'): # Ignore methods and other callables. pass elif isinstance(attribute, (str, int, bool, float, type(None))): # Primitive types can be passed through unmodified. output[attribute_name] = attribute elif isinstance(attribute, list): # Recursively deal with items in lists. output[attribute_name] = [ self.to_representation(item) for item in attribute ] elif isinstance(attribute, dict): # Recursively deal with items in dictionaries. output[attribute_name] = { str(key): self.to_representation(value) for key, value in attribute.items() } else: # Force anything else to its string representation. output[attribute_name] = str(attribute) return output --- ## Advanced serializer usage ### Overriding serialization and deserialization behavior If you need to alter the serialization or deserialization behavior of a serializer class, you can do so by overriding the `.to_representation()` or `.to_internal_value()` methods. Some reasons this might be useful include... * Adding new behavior for new serializer base classes. * Modifying the behavior slightly for an existing class. * Improving serialization performance for a frequently accessed API endpoint that returns lots of data. The signatures for these methods are as follows: #### `to_representation(self, 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. May be overridden in order to modify the representation style. For example: def to_representation(self, instance): """Convert `username` to lowercase.""" ret = super().to_representation(instance) ret['username'] = ret['username'].lower() return ret #### ``to_internal_value(self, data)`` Takes the unvalidated incoming data as input and should return the validated data that will be made available as `serializer.validated_data`. The return value will also be passed to the `.create()` or `.update()` methods if `.save()` is called on the serializer class. If any of the validation fails, then the method should raise a `serializers.ValidationError(errors)`. The `errors` argument should be a dictionary mapping field names (or `settings.NON_FIELD_ERRORS_KEY`) to a list of error messages. If you don't need to alter deserialization behavior and instead want to provide object-level validation, it's recommended that you instead override the [`.validate()`](#object-level-validation) method. The `data` argument passed to this method will normally be the value of `request.data`, so the datatype it provides will depend on the parser classes you have configured for your API. ### Serializer Inheritance Similar to Django forms, you can extend and reuse serializers through inheritance. This allows you to declare a common set of fields or methods on a parent class that can then be used in a number of serializers. For example, class MyBaseSerializer(Serializer): my_field = serializers.CharField() def validate_my_field(self, value): ... class MySerializer(MyBaseSerializer): ... Like Django's `Model` and `ModelForm` classes, the inner `Meta` class on serializers does not implicitly inherit from it's parents' inner `Meta` classes. If you want the `Meta` class to inherit from a parent class you must do so explicitly. For example: class AccountSerializer(MyBaseSerializer): class Meta(MyBaseSerializer.Meta): model = Account Typically we would recommend *not* using inheritance on inner Meta classes, but instead declaring all options explicitly. Additionally, the following caveats apply to serializer inheritance: * Normal Python name resolution rules apply. If you have multiple base classes that declare a `Meta` inner class, only the first one will be used. This means the child’s `Meta`, if it exists, otherwise the `Meta` of the first parent, etc. * It’s possible to declaratively remove a `Field` inherited from a parent class by setting the name to be `None` on the subclass. class MyBaseSerializer(ModelSerializer): my_field = serializers.CharField() class MySerializer(MyBaseSerializer): my_field = None However, you can only use this technique to opt out from a field defined declaratively by a parent class; it won’t prevent the `ModelSerializer` from generating a default field. To opt-out from default fields, see [Specifying which fields to include](#specifying-which-fields-to-include). ### Dynamically modifying fields Once a serializer has been initialized, the dictionary of fields that are set on the serializer may be accessed using the `.fields` attribute. Accessing and modifying this attribute allows you to dynamically modify the serializer. Modifying the `fields` argument directly allows you to do interesting things such as changing the arguments on serializer fields at runtime, rather than at the point of declaring the serializer. #### Example For example, if you wanted to be able to set which fields should be used by a serializer at the point of initializing it, you could create a serializer class like so: class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) This would then allow you to do the following: >>> class UserSerializer(DynamicFieldsModelSerializer): >>> class Meta: >>> model = User >>> fields = ['id', 'username', 'email'] >>> >>> print(UserSerializer(user)) {'id': 2, 'username': 'jonwatts', 'email': 'jon@example.com'} >>> >>> print(UserSerializer(user, fields=('id', 'email'))) {'id': 2, 'email': 'jon@example.com'} ### Customizing the default fields REST framework 2 provided an API to allow developers to override how a `ModelSerializer` class would automatically generate the default set of fields. This API included the `.get_field()`, `.get_pk_field()` and other methods. Because the serializers have been fundamentally redesigned with 3.0 this API no longer exists. You can still modify the fields that get created but you'll need to refer to the source code, and be aware that if the changes you make are against private bits of API then they may be subject to change. --- ## Third party packages The following third party packages are also available. ### Django REST marshmallow The [django-rest-marshmallow][django-rest-marshmallow] package provides an alternative implementation for serializers, using the python [marshmallow][marshmallow] library. It exposes the same API as the REST framework serializers, and can be used as a drop-in replacement in some use-cases. ### Serpy The [serpy][serpy] package is an alternative implementation for serializers that is built for speed. [Serpy][serpy] serializes complex datatypes to simple native types. The native types can be easily converted to JSON or any other format needed. ### MongoengineModelSerializer The [django-rest-framework-mongoengine][mongoengine] package provides a `MongoEngineModelSerializer` serializer class that supports using MongoDB as the storage layer for Django REST framework. ### GeoFeatureModelSerializer The [django-rest-framework-gis][django-rest-framework-gis] package provides a `GeoFeatureModelSerializer` serializer class that supports GeoJSON both for read and write operations. ### HStoreSerializer The [django-rest-framework-hstore][django-rest-framework-hstore] package provides an `HStoreSerializer` to support [django-hstore][django-hstore] `DictionaryField` model field and its `schema-mode` feature. ### Dynamic REST The [dynamic-rest][dynamic-rest] package extends the ModelSerializer and ModelViewSet interfaces, adding API query parameters for filtering, sorting, and including / excluding all fields and relationships defined by your serializers. ### Dynamic Fields Mixin The [drf-dynamic-fields][drf-dynamic-fields] package provides a mixin to dynamically limit the fields per serializer to a subset specified by an URL parameter. ### DRF FlexFields The [drf-flex-fields][drf-flex-fields] package extends the ModelSerializer and ModelViewSet to provide commonly used functionality for dynamically setting fields and expanding primitive fields to nested models, both from URL parameters and your serializer class definitions. ### Serializer Extensions The [django-rest-framework-serializer-extensions][drf-serializer-extensions] package provides a collection of tools to DRY up your serializers, by allowing fields to be defined on a per-view/request basis. Fields can be whitelisted, blacklisted and child serializers can be optionally expanded. ### HTML JSON Forms The [html-json-forms][html-json-forms] package provides an algorithm and serializer for processing `
` submissions per the (inactive) [HTML JSON Form specification][json-form-spec]. The serializer facilitates processing of arbitrarily nested JSON structures within HTML. For example, `` will be interpreted as `{"items": [{"id": "5"}]}`. ### DRF-Base64 [DRF-Base64][drf-base64] provides a set of field and model serializers that handles the upload of base64-encoded files. ### QueryFields [djangorestframework-queryfields][djangorestframework-queryfields] allows API clients to specify which fields will be sent in the response via inclusion/exclusion query parameters. ### DRF Writable Nested The [drf-writable-nested][drf-writable-nested] package provides writable nested model serializer which allows to create/update models with nested related data. ### 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. ### Shapeless Serializers The [drf-shapeless-serializers][drf-shapeless-serializers] package provides dynamic serializer configuration capabilities, allowing runtime field selection, renaming, attribute modification, and nested relationship configuration without creating multiple serializer classes. It helps eliminate serializer boilerplate while providing flexible API responses. ### DRF Pydantic The [drf-pydantic][drf-pydantic] package allows you to use Pydantic with Django REST framework for data validation and (de)serialization. If you develop DRF APIs and rely on Pydantic for data validation, this package provides seamless integration between both libraries. [cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion [relations]: relations.md [model-managers]: https://docs.djangoproject.com/en/stable/topics/db/managers/ [encapsulation-blogpost]: https://www.dabapps.com/blog/django-models-and-encapsulation/ [thirdparty-writable-nested]: serializers.md#drf-writable-nested [django-rest-marshmallow]: https://marshmallow-code.github.io/django-rest-marshmallow/ [marshmallow]: https://marshmallow.readthedocs.io/en/latest/ [serpy]: https://github.com/clarkduvall/serpy [mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine [django-rest-framework-gis]: https://github.com/djangonauts/django-rest-framework-gis [django-rest-framework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore [django-hstore]: https://github.com/djangonauts/django-hstore [dynamic-rest]: https://github.com/AltSchool/dynamic-rest [html-json-forms]: https://github.com/wq/html-json-forms [drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields [json-form-spec]: https://www.w3.org/TR/html-json-forms/ [drf-dynamic-fields]: https://github.com/dbrgn/drf-dynamic-fields [drf-base64]: https://bitbucket.org/levit_scs/drf_base64 [drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions [djangorestframework-queryfields]: https://djangorestframework-queryfields.readthedocs.io/ [drf-writable-nested]: https://github.com/beda-software/drf-writable-nested [drf-encrypt-content]: https://github.com/oguzhancelikarslan/drf-encrypt-content [drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers [drf-pydantic]: https://github.com/georgebv/drf-pydantic ================================================ FILE: docs/api-guide/settings.md ================================================ --- source: - settings.py --- # Settings > Namespaces are one honking great idea - let's do more of those! > > — [The Zen of Python][cite] Configuration for REST framework is all namespaced inside a single Django setting, named `REST_FRAMEWORK`. For example your project's `settings.py` file might include something like this: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', ] } ## Accessing settings If you need to access the values of REST framework's API settings in your project, you should use the `api_settings` object. For example. from rest_framework.settings import api_settings print(api_settings.DEFAULT_AUTHENTICATION_CLASSES) The `api_settings` object will check for any user-defined settings, and otherwise fall back to the default values. Any setting that uses string import paths to refer to a class will automatically import and return the referenced class, instead of the string literal. --- ## API Reference ### API policy settings *The following settings control the basic API policies, and are applied to every `APIView` class-based view, or `@api_view` function based view.* #### DEFAULT_RENDERER_CLASSES A list or tuple of renderer classes, that determines the default set of renderers that may be used when returning a `Response` object. Default: [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ] #### DEFAULT_PARSER_CLASSES A list or tuple of parser classes, that determines the default set of parsers used when accessing the `request.data` property. Default: [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ] #### DEFAULT_AUTHENTICATION_CLASSES A list or tuple of authentication classes, that determines the default set of authenticators used when accessing the `request.user` or `request.auth` properties. Default: [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ] #### DEFAULT_PERMISSION_CLASSES A list or tuple of permission classes, that determines the default set of permissions checked at the start of a view. Permission must be granted by every class in the list. Default: [ 'rest_framework.permissions.AllowAny', ] #### DEFAULT_THROTTLE_CLASSES A list or tuple of throttle classes, that determines the default set of throttles checked at the start of a view. Default: `[]` #### DEFAULT_CONTENT_NEGOTIATION_CLASS A content negotiation class, that determines how a renderer is selected for the response, given an incoming request. Default: `'rest_framework.negotiation.DefaultContentNegotiation'` #### DEFAULT_SCHEMA_CLASS A view inspector class that will be used for schema generation. Default: `'rest_framework.schemas.openapi.AutoSchema'` --- ### Generic view settings *The following settings control the behavior of the generic class-based views.* #### DEFAULT_FILTER_BACKENDS A list of filter backend classes that should be used for generic filtering. If set to `None` then generic filtering is disabled. #### DEFAULT_PAGINATION_CLASS The default class to use for queryset pagination. If set to `None`, pagination is disabled by default. See the pagination documentation for further guidance on [setting](pagination.md#setting-the-pagination-style) and [modifying](pagination.md#modifying-the-pagination-style) the pagination style. Default: `None` #### PAGE_SIZE The default page size to use for pagination. If set to `None`, pagination is disabled by default. Default: `None` #### SEARCH_PARAM The name of a query parameter, which can be used to specify the search term used by `SearchFilter`. Default: `search` #### ORDERING_PARAM The name of a query parameter, which can be used to specify the ordering of results returned by `OrderingFilter`. Default: `ordering` --- ### Versioning settings #### DEFAULT_VERSION The value that should be used for `request.version` when no versioning information is present. Default: `None` #### ALLOWED_VERSIONS If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version if not in this set. Default: `None` #### VERSION_PARAM The string that should used for any versioning parameters, such as in the media type or URL query parameters. Default: `'version'` #### DEFAULT_VERSIONING_CLASS The default versioning scheme to use. Default: `None` --- ### Authentication settings *The following settings control the behavior of unauthenticated requests.* #### UNAUTHENTICATED_USER The class that should be used to initialize `request.user` for unauthenticated requests. (If removing authentication entirely, e.g. by removing `django.contrib.auth` from `INSTALLED_APPS`, set `UNAUTHENTICATED_USER` to `None`.) Default: `django.contrib.auth.models.AnonymousUser` #### UNAUTHENTICATED_TOKEN The class that should be used to initialize `request.auth` for unauthenticated requests. Default: `None` --- ### Test settings *The following settings control the behavior of APIRequestFactory and APIClient* #### TEST_REQUEST_DEFAULT_FORMAT The default format that should be used when making test requests. This should match up with the format of one of the renderer classes in the `TEST_REQUEST_RENDERER_CLASSES` setting. Default: `'multipart'` #### TEST_REQUEST_RENDERER_CLASSES The renderer classes that are supported when building test requests. The format of any of these renderer classes may be used when constructing a test request, for example: `client.post('/users', {'username': 'jamie'}, format='json')` Default: [ 'rest_framework.renderers.MultiPartRenderer', 'rest_framework.renderers.JSONRenderer' ] --- ### Schema generation controls #### SCHEMA_COERCE_PATH_PK If set, this maps the `'pk'` identifier in the URL conf onto the actual field name when generating a schema path parameter. Typically this will be `'id'`. This gives a more suitable representation as "primary key" is an implementation detail, whereas "identifier" is a more general concept. Default: `True` #### SCHEMA_COERCE_METHOD_NAMES If set, this is used to map internal viewset method names onto external action names used in the schema generation. This allows us to generate names that are more suitable for an external representation than those that are used internally in the codebase. Default: `{'retrieve': 'read', 'destroy': 'delete'}` --- ### Content type controls #### URL_FORMAT_OVERRIDE The name of a URL parameter that may be used to override the default content negotiation `Accept` header behavior, by using a `format=…` query parameter in the request URL. For example: `http://example.com/organizations/?format=csv` If the value of this setting is `None` then URL format overrides will be disabled. Default: `'format'` #### FORMAT_SUFFIX_KWARG The name of a parameter in the URL conf that may be used to provide a format suffix. This setting is applied when using `format_suffix_patterns` to include suffixed URL patterns. For example: `http://example.com/organizations.csv/` Default: `'format'` --- ### Date and time formatting *The following settings are used to control how date and time representations may be parsed and rendered.* #### DATETIME_FORMAT A format string that should be used by default for rendering the output of `DateTimeField` serializer fields. If `None`, then `DateTimeField` serializer fields will return Python `datetime` objects, and the datetime encoding will be determined by the renderer. May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. Default: `'iso-8601'` #### DATETIME_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to `DateTimeField` serializer fields. May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings. Default: `['iso-8601']` #### DATE_FORMAT A format string that should be used by default for rendering the output of `DateField` serializer fields. If `None`, then `DateField` serializer fields will return Python `date` objects, and the date encoding will be determined by the renderer. May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. Default: `'iso-8601'` #### DATE_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to `DateField` serializer fields. May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings. Default: `['iso-8601']` #### TIME_FORMAT A format string that should be used by default for rendering the output of `TimeField` serializer fields. If `None`, then `TimeField` serializer fields will return Python `time` objects, and the time encoding will be determined by the renderer. May be any of `None`, `'iso-8601'` or a Python [strftime format][strftime] string. Default: `'iso-8601'` #### TIME_INPUT_FORMATS A list of format strings that should be used by default for parsing inputs to `TimeField` serializer fields. May be a list including the string `'iso-8601'` or Python [strftime format][strftime] strings. Default: `['iso-8601']` #### DURATION_FORMAT Indicates the default format that should be used for rendering the output of `DurationField` serializer fields. If `None`, then `DurationField` serializer fields will return Python `timedelta` objects, and the duration encoding will be determined by the renderer. May be any of `None`, `'iso-8601'` or `'django'` (the format accepted by `django.utils.dateparse.parse_duration`). Default: `'django'` --- ### Encodings #### UNICODE_JSON When set to `True`, JSON responses will allow unicode characters in responses. For example: {"unicode black star":"★"} When set to `False`, JSON responses will escape non-ascii characters, like so: {"unicode black star":"\u2605"} Both styles conform to [RFC 4627][rfc4627], and are syntactically valid JSON. The unicode style is preferred as being more user-friendly when inspecting API responses. Default: `True` #### COMPACT_JSON When set to `True`, JSON responses will return compact representations, with no spacing after `':'` and `','` characters. For example: {"is_admin":false,"email":"jane@example"} When set to `False`, JSON responses will return slightly more verbose representations, like so: {"is_admin": false, "email": "jane@example"} The default style is to return minified responses, in line with [Heroku's API design guidelines][heroku-minified-json]. Default: `True` #### STRICT_JSON When set to `True`, JSON rendering and parsing will only observe syntactically valid JSON, raising an exception for the extended float values (`nan`, `inf`, `-inf`) accepted by Python's `json` module. This is the recommended setting, as these values are not generally supported. e.g., neither Javascript's `JSON.Parse` nor PostgreSQL's JSON data type accept these values. When set to `False`, JSON rendering and parsing will be permissive. However, these values are still invalid and will need to be specially handled in your code. Default: `True` #### COERCE_DECIMAL_TO_STRING When returning decimal objects in API representations that do not support a native decimal type, it is normally best to return the value as a string. This avoids the loss of precision that occurs with binary floating point implementations. When set to `True`, the serializer `DecimalField` class will return strings instead of `Decimal` objects. When set to `False`, serializers will return `Decimal` objects, which the default JSON encoder will return as floats. Default: `True` #### COERCE_BIGINT_TO_STRING When returning biginteger objects in API representations that do not support numbers up to 2^64, it is best to return the value as a string. This avoids the loss of precision that occurs with biginteger implementations. When set to `True`, the serializer `BigIntegerField` class (by default) will return strings instead of `BigInteger` objects. When set to `False`, serializers will return `BigInteger` objects, which the default JSON encoder will return as numbers. Default: `False` --- ### View names and descriptions **The following settings are used to generate the view names and descriptions, as used in responses to `OPTIONS` requests, and as used in the browsable API.** #### VIEW_NAME_FUNCTION A string representing the function that should be used when generating view names. This should be a function with the following signature: view_name(self) * `self`: The view instance. Typically the name function would inspect the name of the class when generating a descriptive name, by accessing `self.__class__.__name__`. If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments: * `name`: A name explicitly provided to a view in the viewset. Typically, this value should be used as-is when provided. * `suffix`: Text used when differentiating individual views in a viewset. This argument is mutually exclusive to `name`. * `detail`: Boolean that differentiates an individual view in a viewset as either being a 'list' or 'detail' view. Default: `'rest_framework.views.get_view_name'` #### VIEW_DESCRIPTION_FUNCTION A string representing the function that should be used when generating view descriptions. This setting can be changed to support markup styles other than the default markdown. For example, you can use it to support `rst` markup in your view docstrings being output in the browsable API. This should be a function with the following signature: view_description(self, html=False) * `self`: The view instance. Typically the description function would inspect the docstring of the class when generating a description, by accessing `self.__class__.__doc__` * `html`: A boolean indicating if HTML output is required. `True` when used in the browsable API, and `False` when used in generating `OPTIONS` responses. If the view instance inherits `ViewSet`, it may have been initialized with several optional arguments: * `description`: A description explicitly provided to the view in the viewset. Typically, this is set by extra viewset `action`s, and should be used as-is. Default: `'rest_framework.views.get_view_description'` ### HTML Select Field cutoffs Global settings for [select field cutoffs for rendering relational fields](relations.md#select-field-cutoffs) in the browsable API. #### HTML_SELECT_CUTOFF Global setting for the `html_cutoff` value. Must be an integer. Default: 1000 #### HTML_SELECT_CUTOFF_TEXT A string representing a global setting for `html_cutoff_text`. Default: `"More than {count} items..."` --- ### Miscellaneous settings #### EXCEPTION_HANDLER A string representing the function that should be used when returning a response for any given exception. If the function returns `None`, a 500 error will be raised. This setting can be changed to support error responses other than the default `{"detail": "Failure..."}` responses. For example, you can use it to provide API responses like `{"errors": [{"message": "Failure...", "code": ""} ...]}`. This should be a function with the following signature: exception_handler(exc, context) * `exc`: The exception. Default: `'rest_framework.views.exception_handler'` #### NON_FIELD_ERRORS_KEY A string representing the key that should be used for serializer errors that do not refer to a specific field, but are instead general errors. Default: `'non_field_errors'` #### URL_FIELD_NAME A string representing the key that should be used for the URL fields generated by `HyperlinkedModelSerializer`. Default: `'url'` #### NUM_PROXIES An integer of 0 or more, that may be used to specify the number of application proxies that the API runs behind. This allows throttling to more accurately identify client IP addresses. If set to `None` then less strict IP matching will be used by the throttle classes. 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/datetime.html#strftime-and-strptime-format-codes ================================================ FILE: docs/api-guide/status-codes.md ================================================ --- source: - status.py --- # Status Codes > 418 I'm a teapot - Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. > > — [RFC 2324][rfc2324], Hyper Text Coffee Pot Control Protocol Using bare status codes in your responses isn't recommended. REST framework includes a set of named constants that you can use to make your code more obvious and readable. from rest_framework import status from rest_framework.response import Response def empty_view(self): content = {'please move along': 'nothing to see here'} return Response(content, status=status.HTTP_404_NOT_FOUND) The full set of HTTP status codes included in the `status` module is listed below. The module also includes a set of helper functions for testing if a status code is in a given range. from rest_framework import status from rest_framework.test import APITestCase class ExampleTestCase(APITestCase): def test_url_root(self): url = reverse('index') response = self.client.get(url) self.assertTrue(status.is_success(response.status_code)) For more information on proper usage of HTTP status codes see [RFC 2616][rfc2616] and [RFC 6585][rfc6585]. ## Informational - 1xx This class of status code indicates a provisional response. There are no 1xx status codes used in REST framework by default. HTTP_100_CONTINUE HTTP_101_SWITCHING_PROTOCOLS HTTP_102_PROCESSING HTTP_103_EARLY_HINTS ## Successful - 2xx This class of status code indicates that the client's request was successfully received, understood, and accepted. HTTP_200_OK HTTP_201_CREATED HTTP_202_ACCEPTED HTTP_203_NON_AUTHORITATIVE_INFORMATION HTTP_204_NO_CONTENT HTTP_205_RESET_CONTENT HTTP_206_PARTIAL_CONTENT HTTP_207_MULTI_STATUS HTTP_208_ALREADY_REPORTED HTTP_226_IM_USED ## Redirection - 3xx This class of status code indicates that further action needs to be taken by the user agent in order to fulfill the request. HTTP_300_MULTIPLE_CHOICES HTTP_301_MOVED_PERMANENTLY HTTP_302_FOUND HTTP_303_SEE_OTHER HTTP_304_NOT_MODIFIED HTTP_305_USE_PROXY HTTP_306_RESERVED HTTP_307_TEMPORARY_REDIRECT HTTP_308_PERMANENT_REDIRECT ## Client Error - 4xx The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. HTTP_400_BAD_REQUEST HTTP_401_UNAUTHORIZED HTTP_402_PAYMENT_REQUIRED HTTP_403_FORBIDDEN HTTP_404_NOT_FOUND HTTP_405_METHOD_NOT_ALLOWED HTTP_406_NOT_ACCEPTABLE HTTP_407_PROXY_AUTHENTICATION_REQUIRED HTTP_408_REQUEST_TIMEOUT HTTP_409_CONFLICT HTTP_410_GONE HTTP_411_LENGTH_REQUIRED HTTP_412_PRECONDITION_FAILED HTTP_413_REQUEST_ENTITY_TOO_LARGE HTTP_414_REQUEST_URI_TOO_LONG 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 HTTP_431_REQUEST_HEADER_FIELDS_TOO_LARGE HTTP_451_UNAVAILABLE_FOR_LEGAL_REASONS ## Server Error - 5xx Response status codes beginning with the digit "5" indicate cases in which the server is aware that it has erred or is incapable of performing the request. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition. HTTP_500_INTERNAL_SERVER_ERROR HTTP_501_NOT_IMPLEMENTED HTTP_502_BAD_GATEWAY HTTP_503_SERVICE_UNAVAILABLE HTTP_504_GATEWAY_TIMEOUT HTTP_505_HTTP_VERSION_NOT_SUPPORTED HTTP_506_VARIANT_ALSO_NEGOTIATES HTTP_507_INSUFFICIENT_STORAGE HTTP_508_LOOP_DETECTED HTTP_509_BANDWIDTH_LIMIT_EXCEEDED HTTP_510_NOT_EXTENDED HTTP_511_NETWORK_AUTHENTICATION_REQUIRED ## Helper functions The following helper functions are available for identifying the category of the response code. is_informational() # 1xx is_success() # 2xx is_redirect() # 3xx is_client_error() # 4xx is_server_error() # 5xx [rfc2324]: https://www.ietf.org/rfc/rfc2324.txt [rfc2616]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html [rfc6585]: https://tools.ietf.org/html/rfc6585 ================================================ FILE: docs/api-guide/testing.md ================================================ --- source: - test.py --- # Testing > Code without tests is broken as designed. > > — [Jacob Kaplan-Moss][cite] REST framework includes a few helper classes that extend Django's existing test framework, and improve support for making API requests. ## APIRequestFactory Extends [Django's existing `RequestFactory` class][requestfactory]. ### Creating test requests The `APIRequestFactory` class supports an almost identical API to Django's standard `RequestFactory` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. from rest_framework.test import APIRequestFactory # Using the standard RequestFactory API to create a form POST request 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 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() request = factory.post('/notes/', {'title': 'new idea'}, format='json') By default the available formats are `'multipart'` and `'json'`. For compatibility with Django's existing `RequestFactory` the default format is `'multipart'`. To support a wider set of request formats, or change the default format, [see the configuration section][configuration]. #### Explicitly encoding the request body If you need to explicitly encode the request body, you can do so by setting the `content_type` flag. For example: request = factory.post('/notes/', yaml.dump({'title': 'new idea'}), content_type='application/yaml') #### PUT and PATCH with form data One difference worth noting between Django's `RequestFactory` and REST framework's `APIRequestFactory` is that multipart form data will be encoded for methods other than just `.post()`. For example, using `APIRequestFactory`, you can make a form PUT request like so: factory = APIRequestFactory() request = factory.put('/notes/547/', {'title': 'remember to email dave'}) Using Django's `RequestFactory`, you'd need to explicitly encode the data yourself: from django.test.client import encode_multipart, RequestFactory factory = RequestFactory() data = {'title': 'remember to email dave'} content = encode_multipart('BoUnDaRyStRiNg', data) content_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg' request = factory.put('/notes/547/', content, content_type=content_type) ### Forcing authentication When testing views directly using a request factory, it's often convenient to be able to directly authenticate the request, rather than having to construct the correct authentication credentials. To forcibly authenticate a request, use the `force_authenticate()` method. from rest_framework.test import force_authenticate factory = APIRequestFactory() user = User.objects.get(username='olivia') view = AccountDetail.as_view() # Make an authenticated request to the view... request = factory.get('/accounts/django-superstars/') force_authenticate(request, user=user) response = view(request) The signature for the method is `force_authenticate(request, user=None, token=None)`. When making the call, either or both of the user and token may be set. For example, when forcibly authenticating using a token, you might do something like the following: user = User.objects.get(username='olivia') request = factory.get('/accounts/django-superstars/') force_authenticate(request, user=user, token=user.auth_token) !!! note `force_authenticate` directly sets `request.user` to the in-memory `user` instance. If you are reusing the same `user` instance across multiple tests that update the saved `user` state, you may need to call [`refresh_from_db()`][refresh_from_db_docs] between tests. !!! note When using `APIRequestFactory`, the object that is returned is Django's standard `HttpRequest`, and not REST framework's `Request` object, which is only generated once the view is called. This means that setting attributes directly on the request object may not always have the effect you expect. For example, setting `.token` directly will have no effect, and setting `.user` directly will only work if session authentication is being used. # Request will only authenticate if `SessionAuthentication` is in use. request = factory.get('/accounts/django-superstars/') request.user = user response = view(request) If you want to test a request involving the REST framework’s 'Request' object, you’ll need to manually transform it first: class DummyView(APIView): ... factory = APIRequestFactory() request = factory.get('/', {'demo': 'test'}) drf_request = DummyView().initialize_request(request) assert drf_request.query_params == {'demo': ['test']} request = factory.post('/', {'example': 'test'}) drf_request = DummyView().initialize_request(request) assert drf_request.data.get('example') == 'test' ### Forcing CSRF validation By default, requests created with `APIRequestFactory` will not have CSRF validation applied when passed to a REST framework view. If you need to explicitly turn CSRF validation on, you can do so by setting the `enforce_csrf_checks` flag when instantiating the factory. factory = APIRequestFactory(enforce_csrf_checks=True) !!! note It's worth noting that Django's standard `RequestFactory` doesn't need to include this option, because when using regular Django the CSRF validation takes place in middleware, which is not run when testing views directly. When using REST framework, CSRF validation takes place inside the view, so the request factory needs to disable view-level CSRF checks. ## APIClient Extends [Django's existing `Client` class][client]. ### Making requests The `APIClient` class supports the same request interface as Django's standard `Client` class. This means that the standard `.get()`, `.post()`, `.put()`, `.patch()`, `.delete()`, `.head()` and `.options()` methods are all available. For example: from rest_framework.test import APIClient client = APIClient() client.post('/notes/', {'title': 'new idea'}, format='json') To support a wider set of request formats, or change the default format, [see the configuration section][configuration]. ### Authenticating #### .login(**kwargs) The `login` method functions exactly as it does with Django's regular `Client` class. This allows you to authenticate requests against any views which include `SessionAuthentication`. # Make all requests in the context of a logged in session. client = APIClient() client.login(username='lauren', password='secret') To logout, call the `logout` method as usual. # Log out client.logout() The `login` method is appropriate for testing APIs that use session authentication, for example web sites which include AJAX interaction with the API. #### .credentials(**kwargs) The `credentials` method can be used to set headers that will then be included on all subsequent requests by the test client. from rest_framework.authtoken.models import Token from rest_framework.test import APIClient # Include an appropriate `Authorization:` header on all requests. token = Token.objects.get(user__username='lauren') client = APIClient() client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) Note that calling `credentials` a second time overwrites any existing credentials. You can unset any existing credentials by calling the method with no arguments. # Stop including any credentials client.credentials() The `credentials` method is appropriate for testing APIs that require authentication headers, such as basic authentication, OAuth1a and OAuth2 authentication, and simple token authentication schemes. #### .force_authenticate(user=None, token=None) Sometimes you may want to bypass authentication entirely and force all requests by the test client to be automatically treated as authenticated. This can be a useful shortcut if you're testing the API but don't want to have to construct valid authentication credentials in order to make test requests. user = User.objects.get(username='lauren') client = APIClient() client.force_authenticate(user=user) To unauthenticate subsequent requests, call `force_authenticate` setting the user and/or token to `None`. client.force_authenticate(user=None) ### CSRF validation By default CSRF validation is not applied when using `APIClient`. If you need to explicitly enable CSRF validation, you can do so by setting the `enforce_csrf_checks` flag when instantiating the client. client = APIClient(enforce_csrf_checks=True) As usual CSRF validation will only apply to any session authenticated views. This means CSRF validation will only occur if the client has been logged in by calling `login()`. --- ## RequestsClient REST framework also includes a client for interacting with your application using the popular Python library, `requests`. This may be useful if: * You are expecting to interface with the API primarily from another Python service, and want to test the service at the same level as the client will see. * You want to write tests in such a way that they can also be run against a staging or live environment. (See "Live tests" below.) This exposes exactly the same interface as if you were using a requests session directly. from rest_framework.test import RequestsClient client = RequestsClient() response = client.get('http://testserver/users/') assert response.status_code == 200 Note that the requests client requires you to pass fully qualified URLs. ### RequestsClient and working with the database The `RequestsClient` class is useful if you want to write tests that solely interact with the service interface. This is a little stricter than using the standard Django test client, as it means that all interactions should be via the API. If you're using `RequestsClient` you'll want to ensure that test setup, and results assertions are performed as regular API calls, rather than interacting with the database models directly. For example, rather than checking that `Customer.objects.count() == 3` you would list the customers endpoint, and ensure that it contains three records. ### Headers & Authentication Custom headers and authentication credentials can be provided in the same way as [when using a standard `requests.Session` instance][session_objects]. from requests.auth import HTTPBasicAuth client.auth = HTTPBasicAuth('user', 'pass') client.headers.update({'x-test': 'true'}) ### CSRF If you're using `SessionAuthentication` then you'll need to include a CSRF token for any `POST`, `PUT`, `PATCH` or `DELETE` requests. You can do so by following the same flow that a JavaScript based client would use. First, make a `GET` request in order to obtain a CSRF token, then present that token in the following request. For example... client = RequestsClient() # Obtain a CSRF token. response = client.get('http://testserver/homepage/') assert response.status_code == 200 csrftoken = response.cookies['csrftoken'] # Interact with the API. response = client.post('http://testserver/organizations/', json={ 'name': 'MegaCorp', 'status': 'active' }, headers={'X-CSRFToken': csrftoken}) assert response.status_code == 200 ### Live tests With careful usage the `RequestsClient` provides the ability to write tests that exercise your API views in a more end-to-end fashion than `APIClient`, while still running entirely in-process against your local Django application. Note that `RequestsClient` mounts a WSGI adapter and does not perform real network I/O. It cannot be used to send HTTP requests to remote services such as staging or production servers. For live tests against a deployed service, you should instead use a plain `requests.Session` (or similar HTTP client) configured with the appropriate base URL and authentication. Using this style to create basic tests of a few core pieces of functionality is a powerful way to validate your live service. Doing so may require some careful attention to setup and teardown to ensure that the tests run in a way that they do not directly affect customer data. --- ## API Test cases REST framework includes the following test case classes, that mirror the existing [Django's test case classes][provided_test_case_classes], but use `APIClient` instead of Django's default `Client`. * `APISimpleTestCase` * `APITransactionTestCase` * `APITestCase` * `APILiveServerTestCase` ### Example You can use any of REST framework's test case classes as you would for the regular Django test case classes. The `self.client` attribute will be an `APIClient` instance. from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from myproject.apps.core.models import Account class AccountTests(APITestCase): def test_create_account(self): """ Ensure we can create a new account object. """ url = reverse('account-list') data = {'name': 'DabApps'} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(Account.objects.count(), 1) self.assertEqual(Account.objects.get().name, 'DabApps') --- ## URLPatternsTestCase REST framework also provides a test case class for isolating `urlpatterns` on a per-class basis. Note that this inherits from Django's `SimpleTestCase`, and will most likely need to be mixed with another test case class. ### Example from django.urls import include, path, reverse from rest_framework import status from rest_framework.test import APITestCase, URLPatternsTestCase class AccountTests(APITestCase, URLPatternsTestCase): urlpatterns = [ path('api/', include('api.urls')), ] def test_create_account(self): """ Ensure we can create a new account object. """ url = reverse('account-list') response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data), 1) --- ## Testing responses ### Checking the response data When checking the validity of test responses it's often more convenient to inspect the data that the response was created with, rather than inspecting the fully rendered response. For example, it's easier to inspect `response.data`: response = self.client.get('/users/4/') self.assertEqual(response.data, {'id': 4, 'username': 'lauren'}) Instead of inspecting the result of parsing `response.content`: response = self.client.get('/users/4/') self.assertEqual(json.loads(response.content), {'id': 4, 'username': 'lauren'}) ### Rendering responses If you're testing views directly using `APIRequestFactory`, the responses that are returned will not yet be rendered, as rendering of template responses is performed by Django's internal request-response cycle. In order to access `response.content`, you'll first need to render the response. view = UserDetail.as_view() request = factory.get('/users/4') response = view(request, pk='4') response.render() # Cannot access `response.content` without this. self.assertEqual(response.content, '{"username": "lauren", "id": 4}') --- ## Configuration ### Setting the default format The default format used to make test requests may be set using the `TEST_REQUEST_DEFAULT_FORMAT` setting key. For example, to always use JSON for test requests by default instead of standard multipart form requests, set the following in your `settings.py` file: REST_FRAMEWORK = { ... 'TEST_REQUEST_DEFAULT_FORMAT': 'json' } ### Setting the available formats If you need to test requests using something other than multipart or json requests, you can do so by setting the `TEST_REQUEST_RENDERER_CLASSES` setting. For example, to add support for using `format='html'` in test requests, you might have something like this in your `settings.py` file. REST_FRAMEWORK = { ... 'TEST_REQUEST_RENDERER_CLASSES': [ 'rest_framework.renderers.MultiPartRenderer', 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.TemplateHTMLRenderer' ] } [cite]: https://jacobian.org/writing/django-apps-with-buildout/#s-create-a-test-wrapper [client]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#the-test-client [requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory [configuration]: #configuration [refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db [session_objects]: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects [provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes ================================================ FILE: docs/api-guide/throttling.md ================================================ --- source: - throttling.py --- # Throttling > HTTP/1.1 420 Enhance Your Calm > > [Twitter API rate limiting response][cite] Throttling is similar to [permissions], in that it determines if a request should be authorized. Throttles indicate a temporary state, and are used to control the rate of requests that clients can make to an API. As with permissions, multiple throttles may be used. Your API might have a restrictive throttle for unauthenticated requests, and a less restrictive throttle for authenticated requests. Another scenario where you might want to use multiple throttles would be if you need to impose different constraints on different parts of the API, due to some services being particularly resource-intensive. Multiple throttles can also be used if you want to impose both burst throttling rates, and sustained throttling rates. For example, you might want to limit a user to a maximum of 60 requests per minute, and 1000 requests per day. Throttles do not necessarily only refer to rate-limiting requests. For example a storage service might also need to throttle against bandwidth, and a paid data service might want to throttle against a certain number of a records being accessed. **The application-level throttling that REST framework provides should not be considered a security measure or protection against brute forcing or denial-of-service attacks. Deliberately malicious actors will always be able to spoof IP origins. In addition to this, the built-in throttling implementations are implemented using Django's cache framework, and use non-atomic operations to determine the request rate, which may sometimes result in some fuzziness.** **The application-level throttling provided by REST framework is intended for implementing policies such as different business tiers and basic protections against service over-use.** ## How throttling is determined As with permissions and authentication, throttling in REST framework is always defined as a list of classes. Before running the main body of the view each throttle in the list is checked. If any throttle check fails an `exceptions.Throttled` exception will be raised, and the main body of the view will not run. ## Setting the throttling policy The default throttling policy may be set globally, using the `DEFAULT_THROTTLE_CLASSES` and `DEFAULT_THROTTLE_RATES` settings. For example. REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } } 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.throttling import UserRateThrottle from rest_framework.views import APIView class ExampleView(APIView): throttle_classes = [UserRateThrottle] def get(self, request, format=None): content = { 'status': 'request was permitted' } return Response(content) If you're using the `@api_view` decorator with function based views you can use the following decorator. @api_view(['GET']) @throttle_classes([UserRateThrottle]) def example_view(request, format=None): content = { 'status': 'request was permitted' } return Response(content) It's also possible to set throttle classes for routes that are created using the `@action` decorator. Throttle classes set in this way will override any viewset level class settings. @action(detail=True, methods=["post"], throttle_classes=[UserRateThrottle]) def example_adhoc_method(request, pk=None): content = { 'status': 'request was permitted' } return Response(content) ## How clients are identified The `X-Forwarded-For` HTTP header and `REMOTE_ADDR` WSGI variable are used to uniquely identify client IP addresses for throttling. If the `X-Forwarded-For` header is present then it will be used, otherwise the value of the `REMOTE_ADDR` variable from the WSGI environment will be used. If you need to strictly identify unique client IP addresses, you'll need to first configure the number of application proxies that the API runs behind by setting the `NUM_PROXIES` setting. This setting should be an integer of zero or more. If set to non-zero then the client IP will be identified as being the last IP address in the `X-Forwarded-For` header, once any application proxy IP addresses have first been excluded. If set to zero, then the `REMOTE_ADDR` value will always be used as the identifying IP address. It is important to understand that if you configure the `NUM_PROXIES` setting, then all clients behind a unique [NAT'd](https://en.wikipedia.org/wiki/Network_address_translation) gateway will be treated as a single client. Further context on how the `X-Forwarded-For` header works, and identifying a remote client IP can be [found here][identifying-clients]. ## Setting up the cache The throttle classes provided by REST framework use Django's cache backend. You should make sure that you've set appropriate [cache settings][cache-setting]. The default value of `LocMemCache` backend should be okay for simple setups. See Django's [cache documentation][cache-docs] for more details. If you need to use a cache other than `'default'`, you can do so by creating a custom throttle class and setting the `cache` attribute. For example: from django.core.cache import caches class CustomAnonRateThrottle(AnonRateThrottle): cache = caches['alternate'] You'll need to remember to also set your custom throttle class in the `'DEFAULT_THROTTLE_CLASSES'` settings key, or using the `throttle_classes` view attribute. ## A note on concurrency 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. --- ## API Reference ### AnonRateThrottle The `AnonRateThrottle` will only ever throttle unauthenticated users. The IP address of the incoming request is used to generate a unique key to throttle against. The allowed request rate is determined from one of the following (in order of preference). * The `rate` property on the class, which may be provided by overriding `AnonRateThrottle` and setting the property. * The `DEFAULT_THROTTLE_RATES['anon']` setting. `AnonRateThrottle` is suitable if you want to restrict the rate of requests from unknown sources. ### UserRateThrottle The `UserRateThrottle` will throttle users to a given rate of requests across the API. The user id is used to generate a unique key to throttle against. Unauthenticated requests will fall back to using the IP address of the incoming request to generate a unique key to throttle against. The allowed request rate is determined from one of the following (in order of preference). * The `rate` property on the class, which may be provided by overriding `UserRateThrottle` and setting the property. * The `DEFAULT_THROTTLE_RATES['user']` setting. An API may have multiple `UserRateThrottles` in place at the same time. To do so, override `UserRateThrottle` and set a unique "scope" for each class. For example, multiple user throttle rates could be implemented by using the following classes... class BurstRateThrottle(UserRateThrottle): scope = 'burst' class SustainedRateThrottle(UserRateThrottle): scope = 'sustained' ...and the following settings. REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'example.throttles.BurstRateThrottle', 'example.throttles.SustainedRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'burst': '60/min', 'sustained': '1000/day' } } `UserRateThrottle` is suitable if you want simple global rate restrictions per-user. ### ScopedRateThrottle The `ScopedRateThrottle` class can be used to restrict access to specific parts of the API. This throttle will only be applied if the view that is being accessed includes a `.throttle_scope` property. The unique throttle key will then be formed by concatenating the "scope" of the request with the unique user id or IP address. The allowed request rate is determined by the `DEFAULT_THROTTLE_RATES` setting using a key from the request "scope". For example, given the following views... class ContactListView(APIView): throttle_scope = 'contacts' ... class ContactDetailView(APIView): throttle_scope = 'contacts' ... class UploadView(APIView): throttle_scope = 'uploads' ... ...and the following settings. REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.ScopedRateThrottle', ], 'DEFAULT_THROTTLE_RATES': { 'contacts': '1000/day', 'uploads': '20/day' } } User requests to either `ContactListView` or `ContactDetailView` would be restricted to a total of 1000 requests per-day. User requests to `UploadView` would be restricted to 20 requests per day. --- ## Custom throttles To create a custom throttle, override `BaseThrottle` and implement `.allow_request(self, request, view)`. The method should return `True` if the request should be allowed, and `False` otherwise. Optionally you may also override the `.wait()` method. If implemented, `.wait()` should return a recommended number of seconds to wait before attempting the next request, or `None`. The `.wait()` method will only be called if `.allow_request()` has previously returned `False`. If the `.wait()` method is implemented and the request is throttled, then a `Retry-After` header will be included in the response. ### Example The following is an example of a rate throttle, that will randomly throttle 1 in every 10 requests. import random class RandomRateThrottle(throttling.BaseThrottle): def allow_request(self, request, view): return random.randint(1, 10) != 1 [cite]: https://developer.twitter.com/en/docs/basics/rate-limiting [permissions]: permissions.md [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 ================================================ FILE: docs/api-guide/validators.md ================================================ --- source: - validators.py --- # Validators > Validators can be useful for reusing validation logic between different types of fields. > > — [Django documentation][cite] Most of the time you're dealing with validation in REST framework you'll simply be relying on the default field validation, or writing explicit validation methods on serializer or field classes. However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes. ## Validation in REST framework Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class. With `ModelForm` the validation is performed partially on the form, and partially on the model instance. With REST framework the validation is performed entirely on the serializer class. This is advantageous for the following reasons: * It introduces a proper separation of concerns, making your code behavior more obvious. * It is easy to switch between using shortcut `ModelSerializer` classes and using explicit `Serializer` classes. Any validation behavior being used for `ModelSerializer` is simple to replicate. * Printing the `repr` of a serializer instance will show you exactly what validation rules it applies. There's no extra hidden validation behavior being called on the model instance. When you're using `ModelSerializer` all of this is handled automatically for you. If you want to drop down to using `Serializer` classes instead, then you need to define the validation rules explicitly. ### Example As an example of how REST framework uses explicit validation, we'll take a simple model class that has a field with a uniqueness constraint. class CustomerReportRecord(models.Model): time_raised = models.DateTimeField(default=timezone.now, editable=False) reference = models.CharField(unique=True, max_length=20) description = models.TextField() Here's a basic `ModelSerializer` that we can use for creating or updating instances of `CustomerReportRecord`: class CustomerReportSerializer(serializers.ModelSerializer): class Meta: model = CustomerReportRecord If we open up the Django shell using `manage.py shell` we can now >>> from project.example.serializers import CustomerReportSerializer >>> serializer = CustomerReportSerializer() >>> print(repr(serializer)) CustomerReportSerializer(): id = IntegerField(label='ID', read_only=True) time_raised = DateTimeField(read_only=True) reference = CharField(max_length=20, validators=[UniqueValidator(queryset=CustomerReportRecord.objects.all())]) description = CharField(style={'type': 'textarea'}) The interesting bit here is the `reference` field. We can see that the uniqueness constraint is being explicitly enforced by a validator on the serializer field. Because of this more explicit style REST framework includes a few validator classes that are not available in core Django. These classes are detailed below. REST framework validators, like their Django counterparts, implement the `__eq__` method, allowing you to compare instances for equality. --- ## UniqueValidator This validator can be used to enforce the `unique=True` constraint on model fields. It takes a single required argument, and an optional `messages` argument: * `queryset` *required* - This is the queryset against which uniqueness should be enforced. * `message` - The error message that should be used when validation fails. * `lookup` - The lookup used to find an existing instance with the value being validated. Defaults to `'exact'`. This validator should be applied to *serializer fields*, like so: from rest_framework.validators import UniqueValidator slug = SlugField( max_length=100, validators=[UniqueValidator(queryset=BlogPost.objects.all())] ) ## UniqueTogetherValidator This validator can be used to enforce `unique_together` constraints on model instances. It has two required arguments, and a single optional `messages` argument: * `queryset` *required* - This is the queryset against which uniqueness should be enforced. * `fields` *required* - A list or tuple of field names which should make a unique set. These must exist as fields on the serializer class. * `message` - The error message that should be used when validation fails. The validator should be applied to *serializer classes*, like so: from rest_framework.validators import UniqueTogetherValidator class ExampleSerializer(serializers.Serializer): # ... class Meta: # ToDo items belong to a parent list, and have an ordering defined # by the 'position' field. No two items in a given list may share # the same position. validators = [ UniqueTogetherValidator( queryset=ToDoItem.objects.all(), fields=['list', 'position'] ) ] !!! note The `UniqueTogetherValidator` class always imposes an implicit constraint that all the fields it applies to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. ## UniqueForDateValidator ## UniqueForMonthValidator ## UniqueForYearValidator These validators can be used to enforce the `unique_for_date`, `unique_for_month` and `unique_for_year` constraints on model instances. They take the following arguments: * `queryset` *required* - This is the queryset against which uniqueness should be enforced. * `field` *required* - A field name against which uniqueness in the given date range will be validated. This must exist as a field on the serializer class. * `date_field` *required* - A field name which will be used to determine date range for the uniqueness constrain. This must exist as a field on the serializer class. * `message` - The error message that should be used when validation fails. The validator should be applied to *serializer classes*, like so: from rest_framework.validators import UniqueForYearValidator class ExampleSerializer(serializers.Serializer): # ... class Meta: # Blog posts should have a slug that is unique for the current year. validators = [ UniqueForYearValidator( queryset=BlogPostItem.objects.all(), field='slug', date_field='published' ) ] The date field that is used for the validation is always required to be present on the serializer class. You can't simply rely on a model class `default=...`, because the value being used for the default wouldn't be generated until after the validation has run. There are a couple of styles you may want to use for this depending on how you want your API to behave. If you're using `ModelSerializer` you'll probably simply rely on the defaults that REST framework generates for you, but if you are using `Serializer` or simply want more explicit control, use on of the styles demonstrated below. ### Using with a writable date field. If you want the date field to be writable the only thing worth noting is that you should ensure that it is always available in the input data, either by setting a `default` argument, or by setting `required=True`. published = serializers.DateTimeField(required=True) ### Using with a read-only date field. If you want the date field to be visible, but not editable by the user, then set `read_only=True` and additionally set a `default=...` argument. published = serializers.DateTimeField(read_only=True, default=timezone.now) ### Using with a hidden date field. If you want the date field to be entirely hidden from the user, then use `HiddenField`. This field type does not accept user input, but instead always returns its default value to the `validated_data` in the serializer. published = serializers.HiddenField(default=timezone.now) !!! note The `UniqueForValidator` classes impose an implicit constraint that the fields they are applied to are always treated as required. Fields with `default` values are an exception to this as they always supply a value even when omitted from user input. !!! note `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. !!! 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-behavior-of-read_only-plus-default-on-field). REST framework includes a couple of defaults that may be useful in this context. ### CurrentUserDefault A default class that can be used to represent the current user. In order to use this, the 'request' must have been provided as part of the context dictionary when instantiating the serializer. owner = serializers.HiddenField( default=serializers.CurrentUserDefault() ) ### CreateOnlyDefault A default class that can be used to *only set a default argument during create operations*. During updates the field is omitted. It takes a single argument, which is the default value or callable that should be used during create operations. created_at = serializers.DateTimeField( default=serializers.CreateOnlyDefault(timezone.now) ) --- ## Limitations of validators There are some ambiguous cases where you'll need to instead handle validation explicitly, rather than relying on the default serializer classes that `ModelSerializer` generates. In these cases you may want to disable the automatically generated validators, by specifying an empty list for the serializer `Meta.validators` attribute. ### Optional fields 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 behavior of the validation is ambiguous. In this case you will typically need to exclude the validator from the serializer class, and instead write any validation logic explicitly, either in the `.validate()` method, or else in the view. For example: class BillingRecordSerializer(serializers.ModelSerializer): def validate(self, attrs): # Apply custom validation either here, or in the view. class Meta: fields = ['client', 'date', 'amount'] extra_kwargs = {'client': {'required': False}} validators = [] # Remove a default "unique together" constraint. ### Updating nested serializers When applying an update to an existing instance, uniqueness validators will exclude the current instance from the uniqueness check. The current instance is available in the context of the uniqueness check, because it exists as an attribute on the serializer, having initially been passed using `instance=...` when instantiating the serializer. In the case of update operations on *nested* serializers there's no way of applying this exclusion, because the instance is not available. Again, you'll probably want to explicitly remove the validator from the serializer class, and write the code for the validation constraint explicitly, in a `.validate()` method, or in the view. ### Debugging complex cases If you're not sure exactly what behavior a `ModelSerializer` class will generate it is usually a good idea to run `manage.py shell`, and print an instance of the serializer, so that you can inspect the fields and validators that it automatically generates for you. >>> serializer = MyComplexModelSerializer() >>> print(serializer) class MyComplexModelSerializer: my_fields = ... Also keep in mind that with complex cases it can often be better to explicitly define your serializer classes, rather than relying on the default `ModelSerializer` behavior. This involves a little more code, but ensures that the resulting behavior is more transparent. --- ## Writing custom validators You can use any of Django's existing validators, or write your own custom validators. ### Function based A validator may be any callable that raises a `serializers.ValidationError` on failure. def even_number(value): if value % 2 != 0: raise serializers.ValidationError('This field must be an even number.') #### Field-level validation You can specify custom field-level validation by adding `.validate_` methods to your `Serializer` subclass. This is documented in the [Serializer docs](https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation) ### Class-based To write a class-based validator, use the `__call__` method. Class-based validators are useful as they allow you to parameterize and reuse behavior. class MultipleOf: def __init__(self, base): self.base = base def __call__(self, value): if value % self.base != 0: message = 'This field must be a multiple of %d.' % self.base raise serializers.ValidationError(message) #### Accessing the context In some advanced cases you might want a validator to be passed the serializer field it is being used with as additional context. You can do so by setting 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. class MultipleOf: requires_context = True def __call__(self, value, serializer_field): ... [cite]: https://docs.djangoproject.com/en/stable/ref/validators/ ================================================ FILE: docs/api-guide/versioning.md ================================================ --- source: - versioning.py --- # Versioning > Versioning an interface is just a "polite" way to kill deployed clients. > > — [Roy Fielding][cite]. API versioning allows you to alter behavior between different clients. REST framework provides for a number of different versioning schemes. Versioning is determined by the incoming client request, and may either be based on the request URL, or based on the request headers. There are a number of valid approaches to approaching versioning. [Non-versioned systems can also be appropriate][roy-fielding-on-versioning], particularly if you're engineering for very long-term systems with multiple clients outside of your control. ## Versioning with REST framework When API versioning is enabled, the `request.version` attribute will contain a string that corresponds to the version requested in the incoming client request. By default, versioning is not enabled, and `request.version` will always return `None`. ### Varying behavior based on the version How you vary the API behavior is up to you, but one example you might typically want is to switch to a different serialization style in a newer version. For example: def get_serializer_class(self): if self.request.version == 'v1': return AccountSerializerVersion1 return AccountSerializer ### Reversing URLs for versioned APIs The `reverse` function included by REST framework ties in with the versioning scheme. You need to make sure to include the current `request` as a keyword argument, like so. from rest_framework.reverse import reverse reverse('bookings-list', request=request) The above function will apply any URL transformations appropriate to the request version. For example: * If `NamespaceVersioning` was being used, and the API version was 'v1', then the URL lookup used would be `'v1:bookings-list'`, which might resolve to a URL like `http://example.org/v1/bookings/`. * If `QueryParameterVersioning` was being used, and the API version was `1.0`, then the returned URL might be something like `http://example.org/bookings/?version=1.0` ### Versioned APIs and hyperlinked serializers When using hyperlinked serialization styles together with a URL based versioning scheme make sure to include the request as context to the serializer. def get(self, request): queryset = Booking.objects.all() serializer = BookingsSerializer(queryset, many=True, context={'request': request}) return Response({'all_bookings': serializer.data}) Doing so will allow any returned URLs to include the appropriate versioning. ## Configuring the versioning scheme The versioning scheme is defined by the `DEFAULT_VERSIONING_CLASS` settings key. REST_FRAMEWORK = { 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.NamespaceVersioning' } Unless it is explicitly set, the value for `DEFAULT_VERSIONING_CLASS` will be `None`. In this case the `request.version` attribute will always return `None`. You can also set the versioning scheme on an individual view. Typically you won't need to do this, as it makes more sense to have a single versioning scheme used globally. If you do need to do so, use the `versioning_class` attribute. class ProfileList(APIView): versioning_class = versioning.QueryParameterVersioning ### Other versioning settings The following settings keys are also used to control versioning: * `DEFAULT_VERSION`. The value that should be used for `request.version` when no versioning information is present. Defaults to `None`. * `ALLOWED_VERSIONS`. If set, this value will restrict the set of versions that may be returned by the versioning scheme, and will raise an error if the provided version is not in this set. Note that the value used for the `DEFAULT_VERSION` setting is always considered to be part of the `ALLOWED_VERSIONS` set (unless it is `None`). Defaults to `None`. * `VERSION_PARAM`. The string that should be used for any versioning parameters, such as in the media type or URL query parameters. Defaults to `'version'`. You can also set your versioning class plus those three values on a per-view or a per-viewset basis by defining your own versioning scheme and using the `default_version`, `allowed_versions` and `version_param` class variables. For example, if you want to use `URLPathVersioning`: from rest_framework.versioning import URLPathVersioning from rest_framework.views import APIView class ExampleVersioning(URLPathVersioning): default_version = ... allowed_versions = ... version_param = ... class ExampleView(APIVIew): versioning_class = ExampleVersioning --- ## API Reference ### AcceptHeaderVersioning This scheme requires the client to specify the version as part of the media type in the `Accept` header. The version is included as a media type parameter, that supplements the main media type. Here's an example HTTP request using the accept header versioning style. GET /bookings/ HTTP/1.1 Host: example.com Accept: application/json; version=1.0 In the example request above `request.version` attribute would return the string `'1.0'`. Versioning based on accept headers is [generally considered][klabnik-guidelines] as [best practice][heroku-guidelines], although other styles may be suitable depending on your client requirements. #### Using accept headers with vendor media types Strictly speaking the `json` media type is not specified as [including additional parameters][json-parameters]. If you are building a well-specified public API you might consider using a [vendor media type][vendor-media-type]. To do so, configure your renderers to use a JSON based renderer with a custom media type: class BookingsAPIRenderer(JSONRenderer): media_type = 'application/vnd.megacorp.bookings+json' Your client requests would now look like this: GET /bookings/ HTTP/1.1 Host: example.com Accept: application/vnd.megacorp.bookings+json; version=1.0 ### URLPathVersioning This scheme requires the client to specify the version as part of the URL path. GET /v1/bookings/ HTTP/1.1 Host: example.com Accept: application/json Your URL conf must include a pattern that matches the version with a `'version'` keyword argument, so that this information is available to the versioning scheme. urlpatterns = [ re_path( r'^(?P(v1|v2))/bookings/$', bookings_list, name='bookings-list' ), re_path( r'^(?P(v1|v2))/bookings/(?P[0-9]+)/$', bookings_detail, name='bookings-detail' ) ] ### NamespaceVersioning To the client, this scheme is the same as `URLPathVersioning`. The only difference is how it is configured in your Django application, as it uses URL namespacing, instead of URL keyword arguments. GET /v1/something/ HTTP/1.1 Host: example.com Accept: application/json With this scheme the `request.version` attribute is determined based on the `namespace` that matches the incoming request path. In the following example we're giving a set of views two different possible URL prefixes, each under a different namespace: # bookings/urls.py urlpatterns = [ re_path(r'^$', bookings_list, name='bookings-list'), re_path(r'^(?P[0-9]+)/$', bookings_detail, name='bookings-detail') ] # urls.py urlpatterns = [ re_path(r'^v1/bookings/', include('bookings.urls', namespace='v1')), re_path(r'^v2/bookings/', include('bookings.urls', namespace='v2')) ] Both `URLPathVersioning` and `NamespaceVersioning` are reasonable if you just need a simple versioning scheme. The `URLPathVersioning` approach might be better suitable for small ad-hoc projects, and the `NamespaceVersioning` is probably easier to manage for larger projects. ### HostNameVersioning The hostname versioning scheme requires the client to specify the requested version as part of the hostname in the URL. For example the following is an HTTP request to the `http://v1.example.com/bookings/` URL: GET /bookings/ HTTP/1.1 Host: v1.example.com Accept: application/json By default this implementation expects the hostname to match this simple regular expression: ^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$ Note that the first group is enclosed in brackets, indicating that this is the matched portion of the hostname. The `HostNameVersioning` scheme can be awkward to use in debug mode as you will typically be accessing a raw IP address such as `127.0.0.1`. There are various online tutorials on how to [access localhost with a custom subdomain][lvh] which you may find helpful in this case. Hostname based versioning can be particularly useful if you have requirements to route incoming requests to different servers based on the version, as you can configure different DNS records for different API versions. ### QueryParameterVersioning This scheme is a simple style that includes the version as a query parameter in the URL. For example: GET /something/?version=0.1 HTTP/1.1 Host: example.com Accept: application/json --- ## Custom versioning schemes To implement a custom versioning scheme, subclass `BaseVersioning` and override the `.determine_version` method. ### Example The following example uses a custom `X-API-Version` header to determine the requested version. class XAPIVersionScheme(versioning.BaseVersioning): def determine_version(self, request, *args, **kwargs): return request.META.get('HTTP_X_API_VERSION', None) If your versioning scheme is based on the request URL, you will also want to alter how versioned URLs are determined. In order to do so you should override the `.reverse()` method on the class. See the source code for examples. [cite]: https://www.slideshare.net/evolve_conference/201308-fielding-evolve/31 [roy-fielding-on-versioning]: https://www.infoq.com/articles/roy-fielding-on-versioning [klabnik-guidelines]: http://blog.steveklabnik.com/posts/2011-07-03-nobody-understands-rest-or-http#i_want_my_api_to_be_versioned [heroku-guidelines]: https://github.com/interagent/http-api-design/blob/master/en/foundations/require-versioning-in-the-accepts-header.md [json-parameters]: https://tools.ietf.org/html/rfc4627#section-6 [vendor-media-type]: https://en.wikipedia.org/wiki/Internet_media_type#Vendor_tree [lvh]: https://reinteractive.net/posts/199-developing-and-testing-rails-applications-with-subdomains ================================================ FILE: docs/api-guide/views.md ================================================ --- source: - decorators.py - views.py --- ## Class-based Views > Django's class-based views are a welcome departure from the old-style views. > > — [Reinout van Rees][cite] REST framework provides an `APIView` class, which subclasses Django's `View` class. `APIView` classes are different from regular `View` classes in the following ways: * Requests passed to the handler methods will be REST framework's `Request` instances, not Django's `HttpRequest` instances. * Handler methods may return REST framework's `Response`, instead of Django's `HttpResponse`. The view will manage content negotiation and setting the correct renderer on the response. * Any `APIException` exceptions will be caught and mediated into appropriate responses. * Incoming requests will be authenticated and appropriate permission and/or throttle checks will be run before dispatching the request to the handler method. Using the `APIView` class is pretty much the same as using a regular `View` class, as usual, the incoming request is dispatched to an appropriate handler method such as `.get()` or `.post()`. Additionally, a number of attributes may be set on the class that control various aspects of the API policy. For example: from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import authentication, permissions from django.contrib.auth.models import User class ListUsers(APIView): """ View to list all users in the system. * Requires token authentication. * Only admin users are able to access this view. """ authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAdminUser] def get(self, request, format=None): """ Return a list of all users. """ usernames = [user.username for user in User.objects.all()] return Response(usernames) !!! note The full methods, attributes on, and relations between Django REST Framework's `APIView`, `GenericAPIView`, various `Mixins`, and `Viewsets` can be initially complex. In addition to the documentation here, the [Classy Django REST Framework][classy-drf] resource provides a browsable reference, with full methods and attributes, for each of Django REST Framework's class-based views. ### API policy attributes The following attributes control the pluggable aspects of API views. #### .renderer_classes #### .parser_classes #### .authentication_classes #### .throttle_classes #### .permission_classes #### .content_negotiation_class ### API policy instantiation methods The following methods are used by REST framework to instantiate the various pluggable API policies. You won't typically need to override these methods. #### .get_renderers(self) #### .get_parsers(self) #### .get_authenticators(self) #### .get_throttles(self) #### .get_permissions(self) #### .get_content_negotiator(self) #### .get_exception_handler(self) ### API policy implementation methods The following methods are called before dispatching to the handler method. #### .check_permissions(self, request) #### .check_throttles(self, request) #### .perform_content_negotiation(self, request, force=False) ### Dispatch methods The following methods are called directly by the view's `.dispatch()` method. These perform any actions that need to occur before or after calling the handler methods such as `.get()`, `.post()`, `put()`, `patch()` and `.delete()`. #### .initial(self, request, \*args, **kwargs) Performs any actions that need to occur before the handler method gets called. This method is used to enforce permissions and throttling, and perform content negotiation. You won't typically need to override this method. #### .handle_exception(self, exc) Any exception thrown by the handler method will be passed to this method, which either returns a `Response` instance, or re-raises the exception. The default implementation handles any subclass of `rest_framework.exceptions.APIException`, as well as Django's `Http404` and `PermissionDenied` exceptions, and returns an appropriate error response. If you need to customize the error responses your API returns you should subclass this method. #### .initialize_request(self, request, \*args, **kwargs) Ensures that the request object that is passed to the handler method is an instance of `Request`, rather than the usual Django `HttpRequest`. You won't typically need to override this method. #### .finalize_response(self, request, response, \*args, **kwargs) Ensures that any `Response` object returned from the handler method will be rendered into the correct content type, as determined by the content negotiation. You won't typically need to override this method. --- ## Function Based Views > Saying [that class-based views] is always the superior solution is a mistake. > > — [Nick Coghlan][cite2] REST framework also allows you to work with regular function based views. It provides a set of simple decorators that wrap your function based views to ensure they receive an instance of `Request` (rather than the usual Django `HttpRequest`) and allows them to return a `Response` (instead of a Django `HttpResponse`), and allow you to configure how the request is processed. ### @api_view() **Signature:** `@api_view(http_method_names=['GET'])` The core of this functionality is the `api_view` decorator, which takes a list of HTTP methods that your view should respond to. For example, this is how you would write a very simple view that just manually returns some data: from rest_framework.decorators import api_view from rest_framework.response import Response @api_view() def hello_world(request): return Response({"message": "Hello, world!"}) This view will use the default renderers, parsers, authentication classes etc specified in the [settings]. By default only `GET` methods will be accepted. Other methods will respond with "405 Method Not Allowed". To alter this behavior, specify which methods the view allows, like so: @api_view(['GET', 'POST']) def hello_world(request): if request.method == 'POST': return Response({"message": "Got some data!", "data": request.data}) return Response({"message": "Hello, world!"}) ### API policy decorators To override the default settings, REST framework provides a set of additional decorators which can be added to your views. These must come *after* (below) the `@api_view` decorator. For example, to create a view that uses a [throttle][throttling] to ensure it can only be called once per day by a particular user, use the `@throttle_classes` decorator, passing a list of throttle classes: from rest_framework.decorators import api_view, throttle_classes from rest_framework.throttling import UserRateThrottle class OncePerDayUserThrottle(UserRateThrottle): rate = '1/day' @api_view(['GET']) @throttle_classes([OncePerDayUserThrottle]) def view(request): return Response({"message": "Hello for today! See you tomorrow!"}) These decorators correspond to the attributes set on `APIView` subclasses, described above. The available decorators are: * `@renderer_classes(...)` * `@parser_classes(...)` * `@authentication_classes(...)` * `@throttle_classes(...)` * `@permission_classes(...)` * `@content_negotiation_class(...)` * `@metadata_class(...)` * `@versioning_class(...)` Each of these decorators is equivalent to setting their respective [api policy attributes][api-policy-attributes]. All decorators take a single argument. The ones that end with `_class` expect a single class while the ones ending in `_classes` expect a list or tuple of classes. ### View schema decorator To override the default schema generation for function based views you may use the `@schema` decorator. This must come *after* (below) the `@api_view` decorator. For example: from rest_framework.decorators import api_view, schema from rest_framework.schemas import AutoSchema class CustomAutoSchema(AutoSchema): def get_operation(self, path, method): # override view introspection here... @api_view(['GET']) @schema(CustomAutoSchema()) def view(request): return Response({"message": "Hello for today! See you tomorrow!"}) This decorator takes a single `AutoSchema` instance or an `AutoSchema` subclass instance as described in the [Schemas documentation][schemas]. You may pass `None` in order to exclude the view from schema generation. @api_view(['GET']) @schema(None) def view(request): return Response({"message": "Will not appear in schema!"}) [cite]: https://reinout.vanrees.org/weblog/2011/08/24/class-based-views-usage.html [cite2]: http://www.boredomandlaziness.org/2012/05/djangos-cbvs-are-not-mistake-but.html [settings]: settings.md [throttling]: throttling.md [schemas]: schemas.md [classy-drf]: http://www.cdrf.co [api-policy-attributes]: views.md#api-policy-attributes ================================================ FILE: docs/api-guide/viewsets.md ================================================ --- source: - viewsets.py --- # ViewSets > After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. > > — [Ruby on Rails Documentation][cite] Django REST framework allows you to combine the logic for a set of related views in a single class, called a `ViewSet`. In other frameworks you may also find conceptually similar implementations named something like 'Resources' or 'Controllers'. A `ViewSet` class is simply **a type of class-based View, that does not provide any method handlers** such as `.get()` or `.post()`, and instead provides actions such as `.list()` and `.create()`. The method handlers for a `ViewSet` are only bound to the corresponding actions at the point of finalizing the view, using the `.as_view()` method. Typically, rather than explicitly registering the views in a viewset in the urlconf, you'll register the viewset with a router class, that automatically determines the urlconf for you. ## Example Let's define a simple viewset that can be used to list or retrieve all the users in the system. from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from myapps.serializers import UserSerializer from rest_framework import viewsets from rest_framework.response import Response class UserViewSet(viewsets.ViewSet): """ A simple ViewSet for listing or retrieving users. """ def list(self, request): queryset = User.objects.all() serializer = UserSerializer(queryset, many=True) return Response(serializer.data) def retrieve(self, request, pk=None): queryset = User.objects.all() user = get_object_or_404(queryset, pk=pk) serializer = UserSerializer(user) return Response(serializer.data) If we need to, we can bind this viewset into two separate views, like so: user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) !!! warning Do not use `.as_view()` with `@action` methods. It bypasses router setup and may ignore action settings like `permission_classes`. Use `DefaultRouter` for actions. Typically, we wouldn't do this, but would instead register the viewset with a router, and allow the urlconf to be automatically generated. from myapp.views import UserViewSet from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'users', UserViewSet, basename='user') urlpatterns = router.urls !!! warning When registering viewsets, do not include a trailing slash in the prefix (e.g., use `r'users'`, not `r'users/'`). Unlike standard Django URL patterns, DRF routers append slashes automatically based on your trailing slash configuration. Rather than writing your own viewsets, you'll often want to use the existing base classes that provide a default set of behavior. For example: class UserViewSet(viewsets.ModelViewSet): """ A viewset for viewing and editing user instances. """ serializer_class = UserSerializer queryset = User.objects.all() There are two main advantages of using a `ViewSet` class over using a `View` class. * Repeated logic can be combined into a single class. In the above example, we only need to specify the `queryset` once, and it'll be used across multiple views. * By using routers, we no longer need to deal with wiring up the URL conf ourselves. Both of these come with a trade-off. Using regular views and URL confs is more explicit and gives you more control. ViewSets are helpful if you want to get up and running quickly, or when you have a large API and you want to enforce a consistent URL configuration throughout. ## ViewSet actions The default routers included with REST framework will provide routes for a standard set of create/retrieve/update/destroy style actions, as shown below: class UserViewSet(viewsets.ViewSet): """ Example empty viewset demonstrating the standard actions that will be handled by a router class. If you're using format suffixes, make sure to also include the `format=None` keyword argument for each action. """ def list(self, request): pass def create(self, request): pass def retrieve(self, request, pk=None): pass def update(self, request, pk=None): pass def partial_update(self, request, pk=None): pass def destroy(self, request, pk=None): pass ## Introspecting ViewSet actions During dispatch, the following attributes are available on the `ViewSet`. * `basename` - the base to use for the URL names that are created. * `action` - the name of the current action (e.g., `list`, `create`). * `detail` - boolean indicating if the current action is configured for a list or detail view. * `suffix` - the display suffix for the viewset type - mirrors the `detail` attribute. * `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 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): """ Instantiates and returns the list of permissions that this view requires. """ if self.action == 'list': permission_classes = [IsAuthenticated] else: 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. A more complete example of extra actions: from django.contrib.auth.models import User from rest_framework import status, viewsets from rest_framework.decorators import action from rest_framework.response import Response from myapp.serializers import UserSerializer, PasswordSerializer class UserViewSet(viewsets.ModelViewSet): """ A viewset that provides the standard actions """ queryset = User.objects.all() serializer_class = UserSerializer @action(detail=True, methods=['post']) def set_password(self, request, pk=None): user = self.get_object() serializer = PasswordSerializer(data=request.data) if serializer.is_valid(): user.set_password(serializer.validated_data['password']) user.save() return Response({'status': 'password set'}) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @action(detail=False) def recent_users(self, request): recent_users = User.objects.all().order_by('-last_login') page = self.paginate_queryset(recent_users) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(recent_users, many=True) return Response(serializer.data) The `action` decorator will route `GET` requests by default, but may also accept other HTTP methods by setting the `methods` argument. For example: @action(detail=True, methods=['post', 'delete']) 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`...: @action(detail=True, methods=['post'], permission_classes=[IsAdminOrIsSelf]) def set_password(self, request, pk=None): ... The two new actions will then be available at the urls `^users/{pk}/set_password/$` and `^users/{pk}/unset_password/$`. Use the `url_path` and `url_name` parameters to change the URL segment and the reverse URL name of the action. To view all extra actions, call the `.get_extra_actions()` method. ### Routing additional HTTP methods for extra actions 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.""" ... ``` ## Reversing action URLs If you need to get the URL of an action, use the `.reverse_action()` method. This is a convenience wrapper for `reverse()`, automatically passing the view's `request` object and prepending the `url_name` with the `.basename` attribute. Note that the `basename` is provided by the router during `ViewSet` registration. If you are not using a router, then you must provide the `basename` argument to the `.as_view()` method. Using the example from the previous section: ```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. ```pycon >>> view.reverse_action(view.set_password.url_name, args=["1"]) 'http://localhost:8000/api/users/1/set_password' ``` The `url_name` argument for `.reverse_action()` should match the same argument to the `@action` decorator. Additionally, this method can be used to reverse the default actions, such as `list` and `create`. --- ## API Reference ### ViewSet The `ViewSet` class inherits from `APIView`. You can use any of the standard attributes such as `permission_classes`, `authentication_classes` in order to control the API policy on the viewset. The `ViewSet` class does not provide any implementations of actions. In order to use a `ViewSet` class you'll override the class and define the action implementations explicitly. ### GenericViewSet The `GenericViewSet` class inherits from `GenericAPIView`, and provides the default set of `get_object`, `get_queryset` methods and other generic view base behavior, but does not include any actions by default. In order to use a `GenericViewSet` class you'll override the class and either mixin the required mixin classes, or define the action implementations explicitly. ### ModelViewSet The `ModelViewSet` class inherits from `GenericAPIView` and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the `ModelViewSet` class are `.list()`, `.retrieve()`, `.create()`, `.update()`, `.partial_update()`, and `.destroy()`. #### Example Because `ModelViewSet` extends `GenericAPIView`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] Note that you can use any of the standard attributes or method overrides provided by `GenericAPIView`. For example, to use a `ViewSet` that dynamically determines the queryset it should operate on, you might do something like this: class AccountViewSet(viewsets.ModelViewSet): """ A simple ViewSet for viewing and editing the accounts associated with the user. """ serializer_class = AccountSerializer permission_classes = [IsAccountAdminOrReadOnly] def get_queryset(self): return self.request.user.accounts.all() Note however that upon removal of the `queryset` property from your `ViewSet`, any associated [router][routers] will be unable to derive the basename of your Model automatically, and so you will have to specify the `basename` kwarg as part of your [router registration][routers]. Also note that although this class provides the complete set of create/list/retrieve/update/destroy actions by default, you can restrict the available operations by using the standard permission classes. ### ReadOnlyModelViewSet The `ReadOnlyModelViewSet` class also inherits from `GenericAPIView`. As with `ModelViewSet` it also includes implementations for various actions, but unlike `ModelViewSet` only provides the 'read-only' actions, `.list()` and `.retrieve()`. #### Example As with `ModelViewSet`, you'll normally need to provide at least the `queryset` and `serializer_class` attributes. For example: class AccountViewSet(viewsets.ReadOnlyModelViewSet): """ A simple ViewSet for viewing accounts. """ queryset = Account.objects.all() serializer_class = AccountSerializer Again, as with `ModelViewSet`, you can use any of the standard attributes and method overrides available to `GenericAPIView`. ## Custom ViewSet base classes You may need to provide custom `ViewSet` classes that do not have the full set of `ModelViewSet` actions, or that customize the behavior in some other way. ### Example 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, viewsets class CreateListRetrieveViewSet(mixins.CreateModelMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ A viewset that provides `retrieve`, `create`, and `list` actions. To use it, override the class and set the `.queryset` and `.serializer_class` attributes. """ pass By creating your own base `ViewSet` classes, you can provide common behavior that can be reused in multiple viewsets across your API. [cite]: https://guides.rubyonrails.org/action_controller_overview.html [routers]: routers.md ================================================ FILE: docs/community/3.0-announcement.md ================================================ # Django REST framework 3.0 The 3.0 release of Django REST framework is the result of almost four years of iteration and refinement. It comprehensively addresses some of the previous remaining design issues in serializers, fields and the generic views. **This release is incremental in nature. There *are* some breaking API changes, and upgrading *will* require you to read the release notes carefully, but the migration path should otherwise be relatively straightforward.** The difference in quality of the REST framework API and implementation should make writing, maintaining and debugging your application far easier. 3.0 is the first of three releases that have been funded by our recent [Kickstarter campaign][kickstarter]. As ever, a huge thank you to our many [wonderful sponsors][sponsors]. If you're looking for a Django gig, and want to work with smart community-minded folks, you should probably check out that list and see who's hiring. --- ## New features Notable features of this new release include: * Printable representations on serializers that allow you to inspect exactly what fields are present on the instance. * Simple model serializers that are vastly easier to understand and debug, and that make it easy to switch between the implicit `ModelSerializer` class and the explicit `Serializer` class. * A new `BaseSerializer` class, making it easier to write serializers for alternative storage backends, or to completely customize your serialization and validation logic. * A cleaner fields API including new classes such as `ListField` and `MultipleChoiceField`. * [Super simple default implementations][mixins.py] for the generic views. * Support for overriding how validation errors are handled by your API. * A metadata API that allows you to customize how `OPTIONS` requests are handled by your API. * A more compact JSON output with unicode style encoding turned on by default. * Templated based HTML form rendering for serializers. This will be finalized as public API in the upcoming 3.1 release. Significant new functionality continues to be planned for the 3.1 and 3.2 releases. These releases will correspond to the two [Kickstarter stretch goals](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) - "Feature improvements" and "Admin interface". Further 3.x releases will present simple upgrades, without the same level of fundamental API changes necessary for the 3.0 release. --- #### REST framework: Under the hood. This talk from the [Django: Under the Hood](https://www.djangounderthehood.com/) event in Amsterdam, Nov 2014, gives some good background context on the design decisions behind 3.0. --- *Below is an in-depth guide to the API changes and migration notes for 3.0.* ## Request objects #### The `.data` and `.query_params` properties. The usage of `request.DATA` and `request.FILES` is now pending deprecation in favor of a single `request.data` attribute that contains *all* the parsed data. Having separate attributes is reasonable for web applications that only ever parse url-encoded or multipart requests, but makes less sense for the general-purpose request parsing that REST framework supports. You may now pass all the request data to a serializer class in a single argument: # Do this... ExampleSerializer(data=request.data) Instead of passing the files argument separately: # Don't do this... ExampleSerializer(data=request.DATA, files=request.FILES) The usage of `request.QUERY_PARAMS` is now pending deprecation in favor of the lowercased `request.query_params`. --- ## Serializers #### Single-step object creation. Previously the serializers used a two-step object creation, as follows: 1. Validating the data would create an object instance. This instance would be available as `serializer.object`. 2. Calling `serializer.save()` would then save the object instance to the database. This style is in-line with how the `ModelForm` class works in Django, but is problematic for a number of reasons: * Some data, such as many-to-many relationships, cannot be added to the object instance until after it has been saved. This type of data needed to be hidden in some undocumented state on the object instance, or kept as state on the serializer instance so that it could be used when `.save()` is called. * Instantiating model instances directly means that you cannot use model manager classes for instance creation, e.g. `ExampleModel.objects.create(...)`. Manager classes are an excellent layer at which to enforce business logic and application-level data constraints. * The two step process makes it unclear where to put deserialization logic. For example, should extra attributes such as the current user get added to the instance during object creation or during object save? We now use single-step object creation, like so: 1. Validating the data makes the cleaned data available as `serializer.validated_data`. 2. Calling `serializer.save()` then saves and returns the new object instance. The resulting API changes are further detailed below. #### The `.create()` and `.update()` methods. The `.restore_object()` method is now removed, and we instead have two separate methods, `.create()` and `.update()`. These methods work slightly different to the previous `.restore_object()`. When using the `.create()` and `.update()` methods you should both create *and save* the object instance. This is in contrast to the previous `.restore_object()` behavior that would instantiate the object but not save it. These methods also replace the optional `.save_object()` method, which no longer exists. The following example from the tutorial previously used `restore_object()` to handle both creating and updating object instances. def restore_object(self, attrs, instance=None): if instance: # Update existing instance instance.title = attrs.get('title', instance.title) instance.code = attrs.get('code', instance.code) instance.linenos = attrs.get('linenos', instance.linenos) instance.language = attrs.get('language', instance.language) instance.style = attrs.get('style', instance.style) return instance # Create new instance return Snippet(**attrs) This would now be split out into two separate methods. def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.code = validated_data.get('code', instance.code) instance.linenos = validated_data.get('linenos', instance.linenos) instance.language = validated_data.get('language', instance.language) instance.style = validated_data.get('style', instance.style) instance.save() return instance def create(self, validated_data): return Snippet.objects.create(**validated_data) Note that these methods should return the newly created object instance. #### Use `.validated_data` instead of `.object`. You must now use the `.validated_data` attribute if you need to inspect the data before saving, rather than using the `.object` attribute, which no longer exists. For example the following code *is no longer valid*: if serializer.is_valid(): name = serializer.object.name # Inspect validated field data. logging.info('Creating ticket "%s"' % name) serializer.object.user = request.user # Include the user when saving. serializer.save() Instead of using `.object` to inspect a partially constructed instance, you would now use `.validated_data` to inspect the cleaned incoming values. Also you can't set extra attributes on the instance directly, but instead pass them to the `.save()` method as keyword arguments. The corresponding code would now look like this: if serializer.is_valid(): name = serializer.validated_data['name'] # Inspect validated field data. logging.info('Creating ticket "%s"' % name) serializer.save(user=request.user) # Include the user when saving. #### Using `.is_valid(raise_exception=True)` The `.is_valid()` method now takes an optional boolean flag, `raise_exception`. Calling `.is_valid(raise_exception=True)` will cause a `ValidationError` to be raised if the serializer data contains validation errors. This error will be handled by REST framework's default exception handler, allowing you to remove error response handling from your view code. The handling and formatting of error responses may be altered globally by using the `EXCEPTION_HANDLER` settings key. This change also means it's now possible to alter the style of error responses used by the built-in generic views, without having to include mixin classes or other overrides. #### Using `serializers.ValidationError`. Previously `serializers.ValidationError` error was simply a synonym for `django.core.exceptions.ValidationError`. This has now been altered so that it inherits from the standard `APIException` base class. The reason behind this is that Django's `ValidationError` class is intended for use with HTML forms and its API makes using it slightly awkward with nested validation errors that can occur in serializers. For most users this change shouldn't require any updates to your codebase, but it is worth ensuring that whenever raising validation errors you should prefer using the `serializers.ValidationError` exception class, and not Django's built-in exception. We strongly recommend that you use the namespaced import style of `import serializers` and not `from serializers import ValidationError` in order to avoid any potential confusion. #### Change to `validate_`. The `validate_` method hooks that can be attached to serializer classes change their signature slightly and return type. Previously these would take a dictionary of all incoming data, and a key representing the field name, and would return a dictionary including the validated data for that field: def validate_score(self, attrs, source): if attrs['score'] % 10 != 0: raise serializers.ValidationError('This field should be a multiple of ten.') return attrs This is now simplified slightly, and the method hooks simply take the value to be validated, and return the validated value. def validate_score(self, value): if value % 10 != 0: raise serializers.ValidationError('This field should be a multiple of ten.') return value Any ad-hoc validation that applies to more than one field should go in the `.validate(self, attrs)` method as usual. Because `.validate_` would previously accept the complete dictionary of attributes, it could be used to validate a field depending on the input in another field. Now if you need to do this you should use `.validate()` instead. You can either return `non_field_errors` from the validate method by raising a simple `ValidationError` def validate(self, attrs): # serializer.errors == {'non_field_errors': ['A non field error']} raise serializers.ValidationError('A non field error') Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the `ValidationError`, like so: def validate(self, attrs): # serializer.errors == {'my_field': ['A field error']} raise serializers.ValidationError({'my_field': 'A field error'}) This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field. #### Removal of `transform_`. The under-used `transform_` on serializer classes is no longer provided. Instead you should just override `to_representation()` if you need to apply any modifications to the representation style. For example: def to_representation(self, instance): ret = super(UserSerializer, self).to_representation(instance) ret['username'] = ret['username'].lower() return ret Dropping the extra point of API means there's now only one right way to do things. This helps with repetition and reinforcement of the core API, rather than having multiple differing approaches. If you absolutely need to preserve `transform_` behavior, for example, in order to provide a simpler 2.x to 3.0 upgrade, you can use a mixin, or serializer base class that add the behavior back in. For example: class BaseModelSerializer(ModelSerializer): """ A custom ModelSerializer class that preserves 2.x style `transform_` behavior. """ def to_representation(self, instance): ret = super(BaseModelSerializer, self).to_representation(instance) for key, value in ret.items(): method = getattr(self, 'transform_' + key, None) if method is not None: ret[key] = method(value) return ret #### Differences between ModelSerializer validation and ModelForm. This change also means that we no longer use the `.full_clean()` method on model instances, but instead perform all validation explicitly on the serializer. This gives a cleaner separation, and ensures that there's no automatic validation behavior on `ModelSerializer` classes that can't also be easily replicated on regular `Serializer` classes. For the most part this change should be transparent. Field validation and uniqueness checks will still be run as normal, but the implementation is a little different. The one difference that you do need to note is that the `.clean()` method will not be called as part of serializer validation, as it would be if using a `ModelForm`. Use the serializer `.validate()` method to perform a final validation step on incoming data where required. There may be some cases where you really do need to keep validation logic in the model `.clean()` method, and cannot instead separate it into the serializer `.validate()`. You can do so by explicitly instantiating a model instance in the `.validate()` method. def validate(self, attrs): instance = ExampleModel(**attrs) instance.clean() return attrs Again, you really should look at properly separating the validation logic out of the model method if possible, but the above might be useful in some backwards compatibility cases, or for an easy migration path. #### Writable nested serialization. REST framework 2.x attempted to automatically support writable nested serialization, but the behavior was complex and non-obvious. Attempting to automatically handle these case is problematic: * There can be complex dependencies involved in order of saving multiple related model instances. * It's unclear what behavior the user should expect when related models are passed `None` data. * It's unclear how the user should expect to-many relationships to handle updates, creations and deletions of multiple records. Using the `depth` option on `ModelSerializer` will now create **read-only nested serializers** by default. If you try to use a writable nested serializer without writing a custom `create()` and/or `update()` method you'll see an assertion error when you attempt to save the serializer. For example: >>> class ProfileSerializer(serializers.ModelSerializer): >>> class Meta: >>> model = Profile >>> fields = ['address', 'phone'] >>> >>> class UserSerializer(serializers.ModelSerializer): >>> profile = ProfileSerializer() >>> class Meta: >>> model = User >>> fields = ['username', 'email', 'profile'] >>> >>> data = { >>> 'username': 'lizzy', >>> 'email': 'lizzy@example.com', >>> 'profile': {'address': '123 Acacia Avenue', 'phone': '01273 100200'} >>> } >>> >>> serializer = UserSerializer(data=data) >>> serializer.save() AssertionError: The `.create()` method does not support nested writable fields by default. Write an explicit `.create()` method for serializer `UserSerializer`, or set `read_only=True` on nested serializer fields. To use writable nested serialization you'll want to declare a nested field on the serializer class, and write the `create()` and/or `update()` methods explicitly. class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ['username', 'email', 'profile'] def create(self, validated_data): profile_data = validated_data.pop('profile') user = User.objects.create(**validated_data) Profile.objects.create(user=user, **profile_data) return user The single-step object creation makes this far simpler and more obvious than the previous `.restore_object()` behavior. #### Printable serializer representations. Serializer instances now support a printable representation that allows you to inspect the fields present on the instance. For instance, given the following example model: class LocationRating(models.Model): location = models.CharField(max_length=100) rating = models.IntegerField() created_by = models.ForeignKey(User) Let's create a simple `ModelSerializer` class corresponding to the `LocationRating` model. class LocationRatingSerializer(serializer.ModelSerializer): class Meta: model = LocationRating We can now inspect the serializer representation in the Django shell, using `python manage.py shell`... >>> serializer = LocationRatingSerializer() >>> print(serializer) # Or use `print serializer` in Python 2.x LocationRatingSerializer(): id = IntegerField(label='ID', read_only=True) location = CharField(max_length=100) rating = IntegerField() created_by = PrimaryKeyRelatedField(queryset=User.objects.all()) #### The `extra_kwargs` option. The `write_only_fields` option on `ModelSerializer` has been moved to `PendingDeprecation` and replaced with a more generic `extra_kwargs`. class MySerializer(serializer.ModelSerializer): class Meta: model = MyModel fields = ['id', 'email', 'notes', 'is_admin'] extra_kwargs = { 'is_admin': {'write_only': True} } Alternatively, specify the field explicitly on the serializer class: class MySerializer(serializer.ModelSerializer): is_admin = serializers.BooleanField(write_only=True) class Meta: model = MyModel fields = ['id', 'email', 'notes', 'is_admin'] The `read_only_fields` option remains as a convenient shortcut for the more common case. #### Changes to `HyperlinkedModelSerializer`. The `view_name` and `lookup_field` options have been moved to `PendingDeprecation`. They are no longer required, as you can use the `extra_kwargs` argument instead: class MySerializer(serializer.HyperlinkedModelSerializer): class Meta: model = MyModel fields = ['url', 'email', 'notes', 'is_admin'] extra_kwargs = { 'url': {'lookup_field': 'uuid'} } Alternatively, specify the field explicitly on the serializer class: class MySerializer(serializer.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField( view_name='mymodel-detail', lookup_field='uuid' ) class Meta: model = MyModel fields = ['url', 'email', 'notes', 'is_admin'] #### Fields for model methods and properties. With `ModelSerializer` you can now specify field names in the `fields` option that refer to model methods or properties. For example, suppose you have the following model: class Invitation(models.Model): created = models.DateTimeField() to_email = models.EmailField() message = models.CharField(max_length=1000) def expiry_date(self): return self.created + datetime.timedelta(days=30) You can include `expiry_date` as a field option on a `ModelSerializer` class. class InvitationSerializer(serializers.ModelSerializer): class Meta: model = Invitation fields = ['to_email', 'message', 'expiry_date'] These fields will be mapped to `serializers.ReadOnlyField()` instances. >>> serializer = InvitationSerializer() >>> print(repr(serializer)) InvitationSerializer(): to_email = EmailField(max_length=75) message = CharField(max_length=1000) expiry_date = ReadOnlyField() #### The `ListSerializer` class. The `ListSerializer` class has now been added, and allows you to create base serializer classes for only accepting multiple inputs. class MultipleUserSerializer(ListSerializer): child = UserSerializer() You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. You will typically want to *continue to use the existing `many=True` flag* rather than declaring `ListSerializer` classes explicitly, but declaring the classes explicitly can be useful if you need to write custom `create` or `update` methods for bulk updates, or provide for other custom behavior. See also the new `ListField` class, which validates input in the same way, but does not include the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on. #### The `BaseSerializer` class. REST framework now includes a simple `BaseSerializer` class that can be used to easily support alternative serialization and deserialization styles. This class implements the same basic API as the `Serializer` class: * `.data` - Returns the outgoing primitive representation. * `.is_valid()` - Deserializes and validates incoming data. * `.validated_data` - Returns the validated incoming data. * `.errors` - Returns an errors during validation. * `.save()` - Persists the validated data into an object instance. There are four methods that can be overridden, depending on what functionality you want the serializer class to support: * `.to_representation()` - Override this to support serialization, for read operations. * `.to_internal_value()` - Override this to support deserialization, for write operations. * `.create()` and `.update()` - Override either or both of these to support saving instances. Because this class provides the same interface as the `Serializer` class, you can use it with the existing generic class-based views exactly as you would for a regular `Serializer` or `ModelSerializer`. The only difference you'll notice when doing so is the `BaseSerializer` classes will not generate HTML forms in the browsable API. This is because the data they return does not include all the field information that would allow each field to be rendered into a suitable HTML input. ##### Read-only `BaseSerializer` classes. To implement a read-only serializer using the `BaseSerializer` class, we just need to override the `.to_representation()` method. Let's take a look at an example using a simple Django model: class HighScore(models.Model): created = models.DateTimeField(auto_now_add=True) player_name = models.CharField(max_length=10) score = models.IntegerField() It's simple to create a read-only serializer for converting `HighScore` instances into primitive data types. class HighScoreSerializer(serializers.BaseSerializer): def to_representation(self, obj): return { 'score': obj.score, 'player_name': obj.player_name } We can now use this class to serialize single `HighScore` instances: @api_view(['GET']) def high_score(request, pk): instance = HighScore.objects.get(pk=pk) serializer = HighScoreSerializer(instance) return Response(serializer.data) Or use it to serialize multiple instances: @api_view(['GET']) def all_high_scores(request): queryset = HighScore.objects.order_by('-score') serializer = HighScoreSerializer(queryset, many=True) return Response(serializer.data) ##### Read-write `BaseSerializer` classes. To create a read-write serializer we first need to implement a `.to_internal_value()` method. This method returns the validated values that will be used to construct the object instance, and may raise a `ValidationError` if the supplied data is in an incorrect format. Once you've implemented `.to_internal_value()`, the basic validation API will be available on the serializer, and you will be able to use `.is_valid()`, `.validated_data` and `.errors`. If you want to also support `.save()` you'll need to also implement either or both of the `.create()` and `.update()` methods. Here's a complete example of our previous `HighScoreSerializer`, that's been updated to support both read and write operations. class HighScoreSerializer(serializers.BaseSerializer): def to_internal_value(self, data): score = data.get('score') player_name = data.get('player_name') # Perform the data validation. if not score: raise ValidationError({ 'score': 'This field is required.' }) if not player_name: raise ValidationError({ 'player_name': 'This field is required.' }) if len(player_name) > 10: raise ValidationError({ 'player_name': 'May not be more than 10 characters.' }) # Return the validated values. This will be available as # the `.validated_data` property. return { 'score': int(score), 'player_name': player_name } def to_representation(self, obj): return { 'score': obj.score, 'player_name': obj.player_name } def create(self, validated_data): return HighScore.objects.create(**validated_data) #### Creating new generic serializers with `BaseSerializer`. The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. The following class is an example of a generic serializer that can handle coercing arbitrary objects into primitive representations. class ObjectSerializer(serializers.BaseSerializer): """ A read-only serializer that coerces arbitrary complex objects into primitive representations. """ def to_representation(self, obj): for attribute_name in dir(obj): attribute = getattr(obj, attribute_name) if attribute_name.startswith('_'): # Ignore private attributes. pass elif hasattr(attribute, '__call__'): # Ignore methods and other callables. pass elif isinstance(attribute, (str, int, bool, float, type(None))): # Primitive types can be passed through unmodified. output[attribute_name] = attribute elif isinstance(attribute, list): # Recursively deal with items in lists. output[attribute_name] = [ self.to_representation(item) for item in attribute ] elif isinstance(attribute, dict): # Recursively deal with items in dictionaries. output[attribute_name] = { str(key): self.to_representation(value) for key, value in attribute.items() } else: # Force anything else to its string representation. output[attribute_name] = str(attribute) --- ## Serializer fields #### The `Field` and `ReadOnly` field classes. There are some minor tweaks to the field base classes. Previously we had these two base classes: * `Field` as the base class for read-only fields. A default implementation was included for serializing data. * `WritableField` as the base class for read-write fields. We now use the following: * `Field` is the base class for all fields. It does not include any default implementation for either serializing or deserializing data. * `ReadOnlyField` is a concrete implementation for read-only fields that simply returns the attribute value without modification. #### The `required`, `allow_null`, `allow_blank` and `default` arguments. REST framework now has more explicit and clear control over validating empty values for fields. Previously the meaning of the `required=False` keyword argument was underspecified. In practice its use meant that a field could either be not included in the input, or it could be included, but be `None` or the empty string. We now have a better separation, with separate `required`, `allow_null` and `allow_blank` arguments. The following set of arguments are used to control validation of empty values: * `required=False`: The value does not need to be present in the input, and will not be passed to `.create()` or `.update()` if it is not seen. * `default=`: The value does not need to be present in the input, and a default value will be passed to `.create()` or `.update()` if it is not seen. * `allow_null=True`: `None` is a valid input. * `allow_blank=True`: `''` is valid input. For `CharField` and subclasses only. Typically you'll want to use `required=False` if the corresponding model field has a default value, and additionally set either `allow_null=True` or `allow_blank=True` if required. The `default` argument is also available and always implies that the field is not required to be in the input. It is unnecessary to use the `required` argument when a default is specified, and doing so will result in an error. #### Coercing output types. The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an `IntegerField` would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior. #### Removal of `.validate()`. The `.validate()` method is now removed from field classes. This method was in any case undocumented and not public API. You should instead simply override `to_internal_value()`. class UppercaseCharField(serializers.CharField): def to_internal_value(self, data): value = super(UppercaseCharField, self).to_internal_value(data) if value != value.upper(): raise serializers.ValidationError('The input should be uppercase only.') return value Previously validation errors could be raised in either `.to_native()` or `.validate()`, making it non-obvious which should be used. Providing only a single point of API ensures more repetition and reinforcement of the core API. #### The `ListField` class. The `ListField` class has now been added. This field validates list input. It takes a `child` keyword argument which is used to specify the field used to validate each item in the list. For example: scores = ListField(child=IntegerField(min_value=0, max_value=100)) You can also use a declarative style to create new subclasses of `ListField`, like this: class ScoresField(ListField): child = IntegerField(min_value=0, max_value=100) We can now use the `ScoresField` class inside another serializer: scores = ScoresField() See also the new `ListSerializer` class, which validates input in the same way, but also includes the serializer interfaces of `.is_valid()`, `.data`, `.save()` and so on. #### The `ChoiceField` class may now accept a flat list. The `ChoiceField` class may now accept a list of choices in addition to the existing style of using a list of pairs of `(name, display_value)`. The following is now valid: color = ChoiceField(choices=['red', 'green', 'blue']) #### The `MultipleChoiceField` class. The `MultipleChoiceField` class has been added. This field acts like `ChoiceField`, but returns a set, which may include none, one or many of the valid choices. #### Changes to the custom field API. The `from_native(self, value)` and `to_native(self, data)` method names have been replaced with the more obviously named `to_internal_value(self, data)` and `to_representation(self, value)`. The `field_from_native()` and `field_to_native()` methods are removed. Previously you could use these methods if you wanted to customize 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.""" return obj.__class__.__name__ Now if you need to access the entire object you'll instead need to override one or both of the following: * Use `get_attribute` to modify the attribute value passed to `to_representation()`. * Use `get_value` to modify the data value passed `to_internal_value()`. For example: def get_attribute(self, obj): # Pass the entire object through to `to_representation()`, # instead of the standard attribute lookup. return obj def to_representation(self, value): return value.__class__.__name__ #### Explicit `queryset` required on relational fields. Previously relational fields that were explicitly declared on a serializer class could omit the queryset argument if (and only if) they were declared on a `ModelSerializer`. This code *would be valid* in `2.4.3`: class AccountSerializer(serializers.ModelSerializer): organizations = serializers.SlugRelatedField(slug_field='name') class Meta: model = Account However this code *would not be valid* in `3.0`: # Missing `queryset` class AccountSerializer(serializers.Serializer): organizations = serializers.SlugRelatedField(slug_field='name') def restore_object(self, attrs, instance=None): # ... The queryset argument is now always required for writable relational fields. This removes some magic and makes it easier and more obvious to move between implicit `ModelSerializer` classes and explicit `Serializer` classes. class AccountSerializer(serializers.ModelSerializer): organizations = serializers.SlugRelatedField( slug_field='name', queryset=Organization.objects.all() ) class Meta: model = Account The `queryset` argument is only ever required for writable fields, and is not required or valid for fields with `read_only=True`. #### Optional argument to `SerializerMethodField`. The argument to `SerializerMethodField` is now optional, and defaults to `get_`. For example the following is valid: class AccountSerializer(serializers.Serializer): # `method_name='get_billing_details'` by default. billing_details = serializers.SerializerMethodField() def get_billing_details(self, account): return calculate_billing(account) In order to ensure a consistent code style an assertion error will be raised if you include a redundant method name argument that matches the default method name. For example, the following code *will raise an error*: billing_details = serializers.SerializerMethodField('get_billing_details') #### Enforcing consistent `source` usage. I've see several codebases that unnecessarily include the `source` argument, setting it to the same value as the field name. This usage is redundant and confusing, making it less obvious that `source` is usually not required. The following usage will *now raise an error*: email = serializers.EmailField(source='email') #### The `UniqueValidator` and `UniqueTogetherValidator` classes. REST framework now provides new validators that allow you to ensure field uniqueness, while still using a completely explicit `Serializer` class instead of using `ModelSerializer`. The `UniqueValidator` should be applied to a serializer field, and takes a single `queryset` argument. from rest_framework import serializers from rest_framework.validators import UniqueValidator class OrganizationSerializer(serializers.Serializer): url = serializers.HyperlinkedIdentityField(view_name='organization_detail') created = serializers.DateTimeField(read_only=True) name = serializers.CharField( max_length=100, validators=UniqueValidator(queryset=Organization.objects.all()) ) The `UniqueTogetherValidator` should be applied to a serializer, and takes a `queryset` argument and a `fields` argument which should be a list or tuple of field names. class RaceResultSerializer(serializers.Serializer): category = serializers.ChoiceField(['5k', '10k']) position = serializers.IntegerField() name = serializers.CharField(max_length=100) class Meta: validators = [UniqueTogetherValidator( queryset=RaceResult.objects.all(), fields=['category', 'position'] )] #### The `UniqueForDateValidator` classes. REST framework also now includes explicit validator classes for validating the `unique_for_date`, `unique_for_month`, and `unique_for_year` model field constraints. These are used internally instead of calling into `Model.full_clean()`. These classes are documented in the [Validators](../api-guide/validators.md) section of the documentation. --- ## Generic views #### Simplification of view logic. The view logic for the default method handlers has been significantly simplified, due to the new serializers API. #### Changes to pre/post save hooks. The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`. These methods should save the object instance by calling `serializer.save()`, adding in any additional arguments as required. They may also perform any custom pre-save or post-save behavior. For example: def perform_create(self, serializer): # Include the owner attribute directly, rather than from request data. instance = serializer.save(owner=self.request.user) # Perform a custom post-save action. send_email(instance.to_email, instance.message) The `pre_delete` and `post_delete` hooks no longer exist, and are replaced with `.perform_destroy(self, instance)`, which should delete the instance and perform any custom actions. def perform_destroy(self, instance): # Perform a custom pre-delete action. send_deletion_alert(user=instance.created_by, deleted=instance) # Delete the object instance. instance.delete() #### Removal of view attributes. The `.object` and `.object_list` attributes are no longer set on the view instance. Treating views as mutable object instances that store state during the processing of the view tends to be poor design, and can lead to obscure flow logic. I would personally recommend that developers treat view instances as immutable objects in their application code. #### PUT as create. Allowing `PUT` as create operations is problematic, as it necessarily exposes information about the existence or non-existence of objects. It's also not obvious that transparently allowing re-creating of previously deleted instances is necessarily a better default behavior than simply returning `404` responses. Both styles "`PUT` as 404" and "`PUT` as create" can be valid in different circumstances, but we've now opted for the 404 behavior as the default, due to it being simpler and more obvious. If you need to restore the previous behavior you may want to include [this `AllowPUTAsCreateMixin` class](https://gist.github.com/tomchristie/a2ace4577eff2c603b1b) as a mixin to your views. #### Customizing error responses. The generic views now raise `ValidationFailed` exception for invalid data. This exception is then dealt with by the exception handler, rather than the view returning a `400 Bad Request` response directly. This change means that you can now easily customize the style of error responses across your entire API, without having to modify any of the generic views. --- ## The metadata API Behavior for dealing with `OPTIONS` requests was previously built directly into the class-based views. This has now been properly separated out into a Metadata API that allows the same pluggable style as other API policies in REST framework. This makes it far easier to use a different style for `OPTIONS` responses throughout your API, and makes it possible to create third-party metadata policies. --- ## Serializers as HTML forms REST framework 3.0 includes templated HTML form rendering for serializers. This API should not yet be considered finalized, and will only be promoted to public API for the 3.1 release. Significant changes that you do need to be aware of include: * Nested HTML forms are now supported, for example, a `UserSerializer` with a nested `ProfileSerializer` will now render a nested `fieldset` when used in the browsable API. * Nested lists of HTML forms are not yet supported, but are planned for 3.1. * Because we now use templated HTML form generation, **the `widget` option is no longer available for serializer fields**. You can instead control the template that is used for a given field, by using the `style` dictionary. #### The `style` keyword argument for serializer fields. The `style` keyword argument can be used to pass through additional information from a serializer field, to the renderer class. In particular, the `HTMLFormRenderer` uses the `base_template` key to determine which template to render the field with. For example, to use a `textarea` control instead of the default `input` control, you would use the following… additional_notes = serializers.CharField( style={'base_template': 'textarea.html'} ) Similarly, to use a radio button control instead of the default `select` control, you would use the following… color_channel = serializers.ChoiceField( choices=['red', 'blue', 'green'], style={'base_template': 'radio.html'} ) This API should be considered provisional, and there may be minor alterations with the incoming 3.1 release. --- ## API style There are some improvements in the default style we use in our API responses. #### Unicode JSON by default. Unicode JSON is now the default. The `UnicodeJSONRenderer` class no longer exists, and the `UNICODE_JSON` setting has been added. To revert this behavior use the new setting: REST_FRAMEWORK = { 'UNICODE_JSON': False } #### Compact JSON by default. We now output compact JSON in responses by default. For example, we return: {"email":"amy@example.com","is_admin":true} Instead of the following: {"email": "amy@example.com", "is_admin": true} The `COMPACT_JSON` setting has been added, and can be used to revert this behavior if needed: REST_FRAMEWORK = { 'COMPACT_JSON': False } #### File fields as URLs The `FileField` and `ImageField` classes are now represented as URLs by default. You should ensure you set Django's [standard `MEDIA_URL` setting](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-MEDIA_URL) appropriately, and ensure your application [serves the uploaded files](https://docs.djangoproject.com/en/stable/howto/static-files/#serving-uploaded-files-in-development). You can revert this behavior, and display filenames in the representation by using the `UPLOADED_FILES_USE_URL` settings key: REST_FRAMEWORK = { 'UPLOADED_FILES_USE_URL': False } You can also modify serializer fields individually, using the `use_url` argument: uploaded_file = serializers.FileField(use_url=False) Also note that you should pass the `request` object to the serializer as context when instantiating it, so that a fully qualified URL can be returned. Returned URLs will then be of the form `https://example.com/url_path/filename.txt`. For example: context = {'request': request} serializer = ExampleSerializer(instance, context=context) return Response(serializer.data) If the request is omitted from the context, the returned URLs will be of the form `/url_path/filename.txt`. #### Throttle headers using `Retry-After`. The custom `X-Throttle-Wait-Second` header has now been dropped in favor of the standard `Retry-After` header. You can revert this behavior if needed by writing a custom exception handler for your application. #### Date and time objects as ISO-8601 strings in serializer data. Date and Time objects are now coerced to strings by default in the serializer output. Previously they were returned as `Date`, `Time` and `DateTime` objects, and later coerced to strings by the renderer. You can modify this behavior globally by settings the existing `DATE_FORMAT`, `DATETIME_FORMAT` and `TIME_FORMAT` settings keys. Setting these values to `None` instead of their default value of `'iso-8601'` will result in native objects being returned in serializer data. REST_FRAMEWORK = { # Return native `Date` and `Time` objects in `serializer.data` 'DATETIME_FORMAT': None 'DATE_FORMAT': None 'TIME_FORMAT': None } You can also modify serializer fields individually, using the `date_format`, `time_format` and `datetime_format` arguments: # Return `DateTime` instances in `serializer.data`, not strings. created = serializers.DateTimeField(format=None) #### Decimals as strings in serializer data. Decimals are now coerced to strings by default in the serializer output. Previously they were returned as `Decimal` objects, and later coerced to strings by the renderer. You can modify this behavior globally by using the `COERCE_DECIMAL_TO_STRING` settings key. REST_FRAMEWORK = { 'COERCE_DECIMAL_TO_STRING': False } Or modify it on an individual serializer field, using the `coerce_to_string` keyword argument. # Return `Decimal` instances in `serializer.data`, not strings. amount = serializers.DecimalField( max_digits=10, decimal_places=2, coerce_to_string=False ) The default JSON renderer will return float objects for un-coerced `Decimal` instances. This allows you to easily switch between string or float representations for decimals depending on your API design needs. --- ## Miscellaneous notes * The serializer `ChoiceField` does not currently display nested choices, as was the case in 2.4. This will be address as part of 3.1. * Due to the new templated form rendering, the 'widget' option is no longer valid. This means there's no easy way of using third party "autocomplete" widgets for rendering select inputs that contain a large number of choices. You'll either need to use a regular select or a plain text input. We may consider addressing this in 3.1 or 3.2 if there's sufficient demand. * Some of the default validation error messages were rewritten and might no longer be pre-translated. You can still [create language files with Django][django-localization] if you wish to localize them. * `APIException` subclasses could previously take any arbitrary type in the `detail` argument. These exceptions now use translatable text strings, and as a result call `force_text` on the `detail` argument, which *must be a string*. If you need complex arguments to an `APIException` class, you should subclass it and override the `__init__()` method. Typically you'll instead want to use a custom exception handler to provide for non-standard error responses. --- ## What's coming next 3.0 is an incremental release, and there are several upcoming features that will build on the baseline improvements that it makes. The 3.1 release is planned to address improvements in the following components: * Public API for using serializers as HTML forms. * Request parsing, mediatypes & the implementation of the browsable API. * Introduction of a new pagination API. * Better support for API versioning. The 3.2 release is planned to introduce an alternative admin-style interface to the browsable API. You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/encode/django-rest-framework/milestones). [kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3 [sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors [mixins.py]: https://github.com/encode/django-rest-framework/blob/main/rest_framework/mixins.py [django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files ================================================ FILE: docs/community/3.1-announcement.md ================================================ # Django REST framework 3.1 The 3.1 release is an intermediate step in the Kickstarter project releases, and includes a range of new functionality. Some highlights include: * A super-smart cursor pagination scheme. * An improved pagination API, supporting header or in-body pagination styles. * Pagination controls rendering in the browsable API. * Better support for API versioning. * Built-in internationalization support. * Support for Django 1.8's `HStoreField` and `ArrayField`. --- ## Pagination The pagination API has been improved, making it both easier to use, and more powerful. A guide to the headline features follows. For full details, see [the pagination documentation][pagination]. Note that as a result of this work a number of settings keys and generic view attributes are now moved to pending deprecation. Controlling pagination styles is now largely handled by overriding a pagination class and modifying its configuration attributes. * The `PAGINATE_BY` settings key will continue to work but is now pending deprecation. The more obviously named `PAGE_SIZE` settings key should now be used instead. * The `PAGINATE_BY_PARAM`, `MAX_PAGINATE_BY` settings keys will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. * The `paginate_by`, `page_query_param`, `paginate_by_param` and `max_paginate_by` generic view attributes will continue to work but are now pending deprecation, in favor of setting configuration attributes on the configured pagination class. * The `pagination_serializer_class` view attribute and `DEFAULT_PAGINATION_SERIALIZER_CLASS` settings key **are no longer valid**. The pagination API does not use serializers to determine the output format, and you'll need to instead override the `get_paginated_response` method on a pagination class in order to specify how the output format is controlled. #### New pagination schemes. Until now, there has only been a single built-in pagination style in REST framework. We now have page, limit/offset and cursor based schemes included by default. The cursor based pagination scheme is particularly smart, and is a better approach for clients iterating through large or frequently changing result sets. The scheme supports paging against non-unique indexes, by using both cursor and limit/offset information. It also allows for both forward and reverse cursor pagination. Much credit goes to David Cramer for [this blog post](https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api) on the subject. #### Pagination controls in the browsable API. Paginated results now include controls that render directly in the browsable API. If you're using the page or limit/offset style, then you'll see a page based control displayed in the browsable API: ![page number based pagination](../img/pages-pagination.png ) The cursor based pagination renders a more simple style of control: ![cursor based pagination](../img/cursor-pagination.png ) #### Support for header-based pagination. The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the `Link` or `Content-Range` headers. For more information, see the [custom pagination styles](../api-guide/pagination.md#custom-pagination-styles) documentation. --- ## Versioning We've made it [easier to build versioned APIs][versioning]. Built-in schemes for versioning include both URL based and Accept header based variations. When using a URL based scheme, hyperlinked serializers will resolve relationships to the same API version as used on the incoming request. For example, when using `NamespaceVersioning`, and the following hyperlinked serializer: class AccountsSerializer(serializer.HyperlinkedModelSerializer): class Meta: model = Accounts fields = ['account_name', 'users'] The output representation would match the version used on the incoming request. Like so: GET http://example.org/v2/accounts/10 # Version 'v2' { "account_name": "europa", "users": [ "http://example.org/v2/users/12", # Version 'v2' "http://example.org/v2/users/54", "http://example.org/v2/users/87" ] } --- ## Internationalization REST framework now includes a built-in set of translations, and [supports internationalized error responses][internationalization]. This allows you to either change the default language, or to allow clients to specify the language via the `Accept-Language` header. You can change the default language by using the standard Django `LANGUAGE_CODE` setting: LANGUAGE_CODE = "es-es" You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE_CLASSES` setting: MIDDLEWARE_CLASSES = [ ... 'django.middleware.locale.LocaleMiddleware' ] When per-request internationalization is enabled, client requests will respect the `Accept-Language` header where possible. For example, let's make a request for an unsupported media type: **Request** GET /api/users HTTP/1.1 Accept: application/xml Accept-Language: es-es Host: example.org **Response** HTTP/1.0 406 NOT ACCEPTABLE { "detail": "No se ha podido satisfacer la solicitud de cabecera de Accept." } Note that the structure of the error responses is still the same. We still have a `detail` key in the response. If needed you can modify this behavior too, by using a [custom exception handler][custom-exception-handler]. We include built-in translations both for standard exception cases, and for serializer validation errors. The full list of supported languages can be found on our [Transifex project page](https://www.transifex.com/django-rest-framework-1/django-rest-framework/). If you only wish to support a subset of the supported languages, use Django's standard `LANGUAGES` setting: LANGUAGES = [ ('de', _('German')), ('en', _('English')), ] For more details, see the [internationalization documentation][internationalization]. Many thanks to [Craig Blaszczyk](https://github.com/jakul) for helping push this through. --- ## New field types Django 1.8's new `ArrayField`, `HStoreField` and `UUIDField` are now all fully supported. This work also means that we now have both `serializers.DictField()`, and `serializers.ListField()` types, allowing you to express and validate a wider set of representations. If you're building a new 1.8 project, then you should probably consider using `UUIDField` as the primary keys for all your models. This style will work automatically with hyperlinked serializers, returning URLs in the following style: http://example.org/api/purchases/9b1a433f-e90d-4948-848b-300fdc26365d --- ## ModelSerializer API The serializer redesign in 3.0 did not include any public API for modifying how ModelSerializer classes automatically generate a set of fields from a given mode class. We've now re-introduced an API for this, allowing you to create new ModelSerializer base classes that behave differently, such as using a different default style for relationships. For more information, see the documentation on [customizing field mappings][customizing-field-mappings] for ModelSerializer classes. --- ## Moving packages out of core We've now moved a number of packages out of the core of REST framework, and into separately installable packages. If you're currently using these you don't need to worry, you simply need to `pip install` the new packages, and change any import paths. We're making this change in order to help distribute the maintenance workload, and keep better focus of the core essentials of the framework. The change also means we can be more flexible with which external packages we recommend. For example, the excellently maintained [Django OAuth toolkit](https://github.com/jazzband/django-oauth-toolkit) has now been promoted as our recommended option for integrating OAuth support. The following packages are now moved out of core and should be separately installed: * OAuth - [djangorestframework-oauth](https://jpadilla.github.io/django-rest-framework-oauth/) * XML - [djangorestframework-xml](https://jpadilla.github.io/django-rest-framework-xml/) * YAML - [djangorestframework-yaml](https://jpadilla.github.io/django-rest-framework-yaml/) * JSONP - [djangorestframework-jsonp](https://jpadilla.github.io/django-rest-framework-jsonp/) It's worth reiterating that this change in policy shouldn't mean any work in your codebase other than adding a new requirement and modifying some import paths. For example to install XML rendering, you would now do: pip install djangorestframework-xml And modify your settings, like so: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', 'rest_framework_xml.renderers.XMLRenderer' ] } Thanks go to the latest member of our maintenance team, [José Padilla](https://github.com/jpadilla/), for handling this work and taking on ownership of these packages. --- ## Deprecations The `request.DATA`, `request.FILES` and `request.QUERY_PARAMS` attributes move from pending deprecation, to deprecated. Use `request.data` and `request.query_params` instead, as discussed in the 3.0 release notes. The ModelSerializer Meta options for `write_only_fields`, `view_name` and `lookup_field` are also moved from pending deprecation, to deprecated. Use `extra_kwargs` instead, as discussed in the 3.0 release notes. All these attributes and options will still work in 3.1, but their usage will raise a warning. They will be fully removed in 3.2. --- ## What's next? The next focus will be on HTML renderings of API output and will include: * HTML form rendering of serializers. * Filtering controls built-in to the browsable API. * An alternative admin-style interface. This will either be made as a single 3.2 release, or split across two separate releases, with the HTML forms and filter controls coming in 3.2, and the admin-style interface coming in a 3.3 release. [custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling [pagination]: ../api-guide/pagination.md [versioning]: ../api-guide/versioning.md [internationalization]: ../topics/internationalization.md [customizing-field-mappings]: ../api-guide/serializers.md#customizing-field-mappings ================================================ FILE: docs/community/3.10-announcement.md ================================================ # Django REST framework 3.10 The 3.10 release drops support for Python 2. * Our supported Python versions are now: 3.5, 3.6, and 3.7. * Our supported Django versions are now: 1.11, 2.0, 2.1, and 2.2. ## OpenAPI Schema Generation Since we first introduced schema support in Django REST Framework 3.5, OpenAPI has emerged as the widely adopted standard for modeling Web APIs. This release begins the deprecation process for the CoreAPI based schema generation, and introduces OpenAPI schema generation in its place. --- ## Continuing to use CoreAPI If you're currently using the CoreAPI schemas, you'll need to make sure to update your REST framework settings to include `DEFAULT_SCHEMA_CLASS` explicitly. **settings.py**: ```python REST_FRAMEWORK = { ...: ..., "DEFAULT_SCHEMA_CLASS": "rest_framework.schemas.coreapi.AutoSchema", } ``` You'll still be able to keep using CoreAPI schemas, API docs, and client for the foreseeable future. We'll aim to ensure that the CoreAPI schema generator remains available as a third party package, even once it has eventually been removed from REST framework, scheduled for version 3.12. We have removed the old documentation for the CoreAPI based schema generation. You may view the [Legacy CoreAPI documentation here][legacy-core-api-docs]. ---- ## OpenAPI Quickstart You can generate a static OpenAPI schema, using the `generateschema` management command. Alternately, to have the project serve an API schema, use the `get_schema_view()` shortcut. In your `urls.py`: ```python from rest_framework.schemas import get_schema_view 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", ), # ... ] ``` ### Customization For customizations that you want to apply across the entire API, you can subclass `rest_framework.schemas.openapi.SchemaGenerator` and provide it as an argument to the `generateschema` command or `get_schema_view()` helper function. For specific per-view customizations, you can subclass `AutoSchema`, making sure to set `schema = ` on the view. For more details, see the [API Schema documentation](../api-guide/schemas.md). ### API Documentation There are some great third party options for documenting your API, based on the OpenAPI schema. See the [Documenting you API](../topics/documenting-your-api.md) section for more details. --- ## Feature Roadmap Given that our OpenAPI schema generation is a new feature, it's likely that there will still be some iterative improvements for us to make. There will be two main cases here: * Expanding the supported range of OpenAPI schemas that are generated by default. * Improving the ability for developers to customize the output. We'll aim to bring the first type of change quickly in point releases. For the second kind we'd like to adopt a slower approach, to make sure we keep the API simple, and as widely applicable as possible, before we bring in API changes. It's also possible that we'll end up implementing API documentation and API client tooling that are driven by the OpenAPI schema. The `apistar` project has a significant amount of work towards this. However, if we do so, we'll plan on keeping any tooling outside of the core framework. --- ## Funding REST framework is a *collaboratively funded project*. If you use REST framework commercially we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**. *Every single sign-up helps us make REST framework long-term financially sustainable.*
*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/3.14.0/docs/coreapi/index.md [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: https://opencollective.com/django-rest-framework ================================================ FILE: docs/community/3.11-announcement.md ================================================ # Django REST framework 3.11 The 3.11 release adds support for Django 3.0. * Our supported Python versions are now: 3.5, 3.6, 3.7, and 3.8. * Our supported Django versions are now: 1.11, 2.0, 2.1, 2.2, and 3.0. This release will be the last to support Python 3.5 or Django 1.11. ## OpenAPI Schema Generation Improvements The OpenAPI schema generation continues to mature. Some highlights in 3.11 include: * Automatic mapping of Django REST Framework renderers and parsers into OpenAPI request and response media-types. * Improved mapping JSON schema mapping types, for example in HStoreFields, and with large integer values. * Porting of the old CoreAPI parsing of docstrings to form OpenAPI operation descriptions. In this example view operation descriptions for the `get` and `post` methods will be extracted from the class docstring: ```python class DocStringExampleListView(APIView): """ get: A description of my GET operation. post: A description of my POST operation. """ permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get(self, request, *args, **kwargs): ... def post(self, request, *args, **kwargs): ... ``` ## Validator / Default Context In some circumstances a Validator class or a Default class may need to access the serializer field with which it is called, or the `.context` with which the serializer was instantiated. In particular: * 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. 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. The `__call__` method should then include an additional `serializer_field` argument. Validator implementations will look like this: ```python class CustomValidator: requires_context = True def __call__(self, value, serializer_field): ... ``` Default implementations will look like this: ```python class CustomDefault: requires_context = True def __call__(self, serializer_field): ... ``` --- ## Funding REST framework is a *collaboratively funded project*. If you use REST framework commercially we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**. *Every single sign-up helps us make REST framework long-term financially sustainable.*
*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), [Lights On Software](https://lightsonsoftware.com), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).* [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: https://opencollective.com/django-rest-framework ================================================ FILE: docs/community/3.12-announcement.md ================================================ # Django REST framework 3.12 REST framework 3.12 brings a handful of refinements to the OpenAPI schema generation, plus support for Django's new database-agnostic `JSONField`, and some improvements to the `SearchFilter` class. ## Grouping operations with tags. Open API schemas will now automatically include tags, based on the first element in the URL path. For example... 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']` The tags used for a particular view may also be overridden... ```python class MyOrders(APIView): schema = AutoSchema(tags=["users", "orders"]) ... ``` See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags) for more information. ## Customizing the operation ID. REST framework automatically determines operation IDs to use in OpenAPI schemas. The latest version provides more control for overriding the behavior used to generate the operation IDs. See [the schema documentation](https://www.django-rest-framework.org/api-guide/schemas/#operationid) for more information. ## Support for OpenAPI components. In order to output more graceful OpenAPI schemes, REST framework 3.12 now defines components in the schema, and then references them inside request and response objects. This is in contrast with the previous approach, which fully expanded the request and response bodies for each operation. The names used for a component default to using the serializer class name, [but may be overridden if needed](https://www.django-rest-framework.org/api-guide/schemas/#components )... ```python class MyOrders(APIView): schema = AutoSchema(component_name="OrderDetails") ``` ## More Public API Many methods on the `AutoSchema` class have now been promoted to public API, allowing you to more fully customize the schema generation. The following methods are now available for overriding... * `get_path_parameters` * `get_pagination_parameters` * `get_filter_parameters` * `get_request_body` * `get_responses` * `get_serializer` * `get_paginator` * `map_serializer` * `map_field` * `map_choice_field` * `map_field_validators` * `allows_filters`. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#per-view-customization) for details on using custom `AutoSchema` subclasses. ## Support for JSONField. Django 3.1 deprecated the existing `django.contrib.postgres.fields.JSONField` in favor of a new database-agnositic `JSONField`. REST framework 3.12 now supports this new model field, and `ModelSerializer` classes will correctly map the model field. ## SearchFilter improvements There are a couple of significant improvements to the `SearchFilter` class. ### Nested searches against JSONField and HStoreField The class now supports nested search within `JSONField` and `HStoreField`, using the double underscore notation for traversing which element of the field the search should apply to. ```python class SitesSearchView(generics.ListAPIView): """ An API view to return a list of archaeological sites, optionally filtered 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"] ``` ### Searches against annotate fields Django allows querysets to create additional virtual fields, using the `.annotate` method. We now support searching against annotate fields. ```python 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")) serializer_class = PublisherSerializer filter_backends = [filters.SearchFilter] 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 REST framework commercially we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**. *Every single sign-up helps us make REST framework long-term financially sustainable.*
*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), [Lights On Software](https://lightsonsoftware.com), and [Retool](https://retool.com/?utm_source=djangorest&utm_medium=sponsorship).* [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: https://opencollective.com/django-rest-framework ================================================ FILE: docs/community/3.13-announcement.md ================================================ # Django REST framework 3.13 ## Django 4.0 support The latest release now fully supports Django 4.0. Our requirements are now: * Python 3.6+ * Django 4.0, 3.2, 3.1, 2.2 (LTS) ## Fields arguments are now keyword-only When instantiating fields on serializers, you should always use keyword arguments, such as `serializers.CharField(max_length=200)`. This has always been the case, and all the examples that we have in the documentation use keyword arguments, rather than positional arguments. From REST framework 3.13 onwards, this is now *explicitly enforced*. The most feasible cases where users might be accidentally omitting the keyword arguments are likely in the composite fields, `ListField` and `DictField`. For instance... ```python aliases = serializers.ListField(serializers.CharField()) ``` They must now use the more explicit keyword argument style... ```python aliases = serializers.ListField(child=serializers.CharField()) ``` This change has been made because using positional arguments here *does not* result in the expected behavior. See Pull Request [#7632](https://github.com/encode/django-rest-framework/pull/7632) for more details. ================================================ FILE: docs/community/3.14-announcement.md ================================================ # Django REST framework 3.14 ## Django 4.1 support The latest release now fully supports Django 4.1, and drops support for Django 2.2. Our requirements are now: * Python 3.6+ * Django 4.1, 4.0, 3.2, 3.1, 3.0 ## `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_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. ## `ManyRelatedField` supports returning the default when the source attribute doesn't exist. Previously, if you used a serializer field with `many=True` with a dot notated source field that didn't exist, it would raise an `AttributeError`. Now it will return the default or be skipped depending on the other arguments. See Pull Request [#7574](https://github.com/encode/django-rest-framework/pull/7574) for more details. ## Make Open API `get_reference` public. Returns a reference to the serializer component. This may be useful if you override `get_schema()`. ## Change semantic of OR of two permission classes. When OR-ing two permissions, the request has to pass either class's `has_permission() and has_object_permission()`. Previously, both class's `has_permission()` was ignored when OR-ing two permissions together. See Pull Request [#7522](https://github.com/encode/django-rest-framework/pull/7522) for more details. ## 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. ================================================ FILE: docs/community/3.15-announcement.md ================================================ # 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` behavior 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 behavior. See the [release notes](release-notes.md) page for a complete listing. ================================================ FILE: docs/community/3.16-announcement.md ================================================ # 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 behavior 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 behavior. See the [release notes](release-notes.md) page for a complete listing. ================================================ FILE: docs/community/3.2-announcement.md ================================================ # Django REST framework 3.2 The 3.2 release is the first version to include an admin interface for the browsable API. ![The AdminRenderer](../img/admin.png) This interface is intended to act as a more user-friendly interface to the API. It can be used either as a replacement to the existing `BrowsableAPIRenderer`, or used together with it, allowing you to switch between the two styles as required. We've also fixed a huge number of issues, and made numerous cleanups and improvements. Over the course of the 3.1.x series we've [resolved nearly 600 tickets](https://github.com/encode/django-rest-framework/issues?utf8=%E2%9C%93&q=closed%3A%3E2015-03-05) on our GitHub issue tracker. This means we're currently running at a rate of **closing around 100 issues or pull requests per month**. None of this would have been possible without the support of our wonderful Kickstarter backers. If you're looking for a job in Django development we'd strongly recommend taking [a look through our sponsors](https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors) and finding out who's hiring. ## AdminRenderer To include `AdminRenderer` simply add it to your settings: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.AdminRenderer', 'rest_framework.renderers.BrowsableAPIRenderer' ], 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 100 } There are some limitations to the `AdminRenderer`, in particular it is not yet able to handle list or dictionary inputs, as we do not have any HTML form fields that support those. Also note that this is an initial release and we do not yet have a public API for modifying the behavior or documentation on overriding the templates. The idea is to get this released to users early, so we can start getting feedback and release a more fully featured version in 3.3. ## Supported versions This release drops support for Django 1.4. Our supported Django versions are now 1.5.6+, 1.6.3+, 1.7 and 1.8. ## Deprecations There are no new deprecations in 3.2, although a number of existing deprecations have now escalated in line with our deprecation policy. * `request.DATA` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.data` instead. * `request.QUERY_PARAMS` was put on the deprecation path in 3.0. It has now been removed and its usage will result in an error. Use the more pythonic style of `request.query_params` instead. * The following `ModelSerializer.Meta` options have now been removed: `write_only_fields`, `view_name`, `lookup_field`. Use the more general `extra_kwargs` option instead. The following pagination view attributes and settings have been moved into attributes on the pagination class since 3.1. Their usage was formerly in 'pending deprecation', and has now escalated to 'deprecated'. They will continue to function but will raise errors. * `view.paginate_by` - Use `paginator.page_size` instead. * `view.page_query_param` - Use `paginator.page_query_param` instead. * `view.paginate_by_param` - Use `paginator.page_size_query_param` instead. * `view.max_paginate_by` - Use `paginator.max_page_size` instead. * `settings.PAGINATE_BY` - Use `paginator.page_size` instead. * `settings.PAGINATE_BY_PARAM` - Use `paginator.page_size_query_param` instead. * `settings.MAX_PAGINATE_BY` - Use `paginator.max_page_size` instead. ## Modifications to list behaviors There are a couple of bug fixes that are worth calling out as they introduce differing behavior. These are a little subtle and probably won't affect most users, but are worth understanding before upgrading your project. ### 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. 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. Previously a many-to-many field on a model would map to a serializer field that would allow either empty or non-empty list inputs. Now, a many-to-many field will map to a serializer field that requires at least one input, unless the model field has `blank=True` set. Here's what the mapping looks like in practice: * `models.ManyToManyField()` → `serializers.PrimaryKeyRelatedField(many=True, allow_empty=False)` * `models.ManyToManyField(blank=True)` → `serializers.PrimaryKeyRelatedField(many=True)` The upshot is this: If you have many to many fields in your models, then make sure you've included the argument `blank=True` if you want to allow empty inputs in the equivalent `ModelSerializer` fields. ### List fields and allow_null When using `allow_null` with `ListField` or a nested `many=True` serializer the previous behavior was to allow `null` values as items in the list. The behavior is now to allow `null` values instead of the list. For example, take the following field: NestedSerializer(many=True, allow_null=True) Previously the validation behavior would be: * `[{…}, null, {…}]` is **valid**. * `null` is **invalid**. Our validation behavior as of 3.2.0 is now: * `[{…}, null, {…}]` is **invalid**. * `null` is **valid**. If you want to allow `null` child items, you'll need to instead specify `allow_null` on the child class, using an explicit `ListField` instead of `many=True`. For example: ListField(child=NestedSerializer(allow_null=True)) ## What's next? The 3.3 release is currently planned for the start of October, and will be the last Kickstarter-funded release. This release is planned to include: * Search and filtering controls in the browsable API and admin interface. * Improvements and public API for the admin interface. * Improvements and public API for our templated HTML forms and fields. * Nested object and list support in HTML forms. Thanks once again to all our sponsors and supporters. ================================================ FILE: docs/community/3.3-announcement.md ================================================ # Django REST framework 3.3 The 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a final resounding **thank you** to all our wonderful sponsors and supporters. The amount of work that has been achieved as a direct result of the funding is immense. We've added a huge amounts of new functionality, resolved nearly 2,000 tickets, and redesigned & refined large parts of the project. In order to continue driving REST framework forward, we'll shortly be announcing a new set of funding plans. Follow [@_tomchristie](https://twitter.com/_tomchristie) to keep up to date with these announcements, and be among the first set of sign ups. We strongly believe that collaboratively funded software development yields outstanding results for a relatively low investment-per-head. If you or your company use REST framework commercially, then we would strongly urge you to participate in this latest funding drive, and help us continue to build an increasingly polished & professional product. --- ## Release notes Significant new functionality in the 3.3 release includes: * Filters presented as HTML controls in the browsable API. * A [forms API][forms-api], allowing serializers to be rendered as HTML forms. * Django 1.9 support. * A [`JSONField` serializer field][jsonfield], corresponding to Django 1.9's Postgres `JSONField` model field. * Browsable API support [via AJAX][ajax-form], rather than server side request overloading. ![Filter Controls](../img/filter-controls.png) *Example of the new filter controls* --- ## Supported versions This release drops support for Django 1.5 and 1.6. Django 1.7, 1.8 or 1.9 are now required. This brings our supported versions into line with Django's [currently supported versions][django-supported-versions] ## Deprecations The AJAX based support for the browsable API means that there are a number of internal cleanups in the `request` class. For the vast majority of developers this should largely remain transparent: * 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 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. * `view.paginate_by` - Use `paginator.page_size` instead. * `view.page_query_param` - Use `paginator.page_query_param` instead. * `view.paginate_by_param` - Use `paginator.page_size_query_param` instead. * `view.max_paginate_by` - Use `paginator.max_page_size` instead. * `settings.PAGINATE_BY` - Use `paginator.page_size` instead. * `settings.PAGINATE_BY_PARAM` - Use `paginator.page_size_query_param` instead. * `settings.MAX_PAGINATE_BY` - Use `paginator.max_page_size` instead. The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now include either a `fields` or `exclude` option, although the `fields = '__all__'` shortcut may be used. Failing to include either of these two options is currently pending deprecation, and will be removed entirely in the 3.5 release. This behavior brings `ModelSerializer` more closely in line with Django's `ModelForm` behavior. [forms-api]: ../topics/html-and-forms.md [ajax-form]: https://github.com/encode/ajax-form [jsonfield]: ../api-guide/fields.md#jsonfield [accept-headers]: ../topics/browser-enhancements.md#url-based-accept-headers [method-override]: ../topics/browser-enhancements.md#http-header-based-method-overriding [django-supported-versions]: https://www.djangoproject.com/download/#supported-versions ================================================ FILE: docs/community/3.4-announcement.md ================================================ # Django REST framework 3.4 The 3.4 release is the first in a planned series that will be addressing schema generation, hypermedia support, API clients, and finally realtime support. --- ## Funding The 3.4 release has been made possible a recent [Mozilla grant][moss], and by our [collaborative funding model][funding]. If you use REST framework commercially, and would like to see this work continue, we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**. The initial aim is to provide a single full-time position on REST framework. Right now we're over 60% of the way towards achieving that. *Every single sign-up makes a significant impact.*
*Many thanks to all our [awesome sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), and [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf).* --- ## Schemas & client libraries REST framework 3.4 brings built-in support for generating API schemas. We provide this support by using [Core API][core-api], a Document Object Model for describing APIs. Because Core API represents the API schema in an format-independent manner, we're able to render the Core API `Document` object into many different schema formats, by allowing the renderer class to determine how the internal representation maps onto the external schema format. This approach should also open the door to a range of auto-generated API documentation options in the future, by rendering the `Document` object into HTML documentation pages. Alongside the built-in schema support, we're also now providing the following: * A [command line tool][command-line-client] for interacting with APIs. * A [Python client library][client-library] for interacting with APIs. These API clients are dynamically driven, and able to interact with any API that exposes a supported schema format. Dynamically driven clients allow you to interact with an API at an application layer interface, rather than a network layer interface, while still providing the benefits of RESTful Web API design. We're expecting to expand the range of languages that we provide client libraries for over the coming months. Further work on maturing the API schema support is also planned, including documentation on supporting file upload and download, and improved support for documentation generation and parameter annotation. --- Current support for schema formats is as follows: Name | Support | PyPI package ---------------------------------|-------------------------------------|-------------------------------- [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. [API Blueprint][api-blueprint] | Not yet available. | Not yet available. --- You can read more about any of this new functionality in the following: * New tutorial section on [schemas & client libraries][tut-7]. * Documentation page on [schema generation][schema-generation]. * Topic page on [API clients][api-clients]. It is also worth noting that Marc Gibbons is currently working towards a 2.0 release of the popular Django REST Swagger package, which will tie in with our new built-in support. --- ## Supported versions The 3.4.0 release adds support for Django 1.10. The following versions of Python and Django are now supported: * Django versions 1.8, 1.9, and 1.10. * Python versions 2.7, 3.2(\*), 3.3(\*), 3.4, 3.5. (\*) Note that Python 3.2 and 3.3 are not supported from Django 1.9 onwards. --- ## Deprecations and changes The 3.4 release includes very limited deprecation or behavioral changes, and should present a straightforward upgrade. ### Use fields or exclude on serializer classes. The following change in 3.3.0 is now escalated from "pending deprecation" to "deprecated". Its usage will continue to function but will raise warnings: `ModelSerializer` and `HyperlinkedModelSerializer` should include either a `fields` option, or an `exclude` option. The `fields = '__all__'` shortcut may be used to explicitly include all fields. ### Microsecond precision when returning time or datetime. Using the default JSON renderer and directly returning a `datetime` or `time` instance will now render with microsecond precision (6 digits), rather than millisecond precision (3 digits). This makes the output format consistent with the default string output of `serializers.DateTimeField` and `serializers.TimeField`. This change *does not affect the default behavior when using serializers*, which is to serialize `datetime` and `time` instances into strings with microsecond precision. The serializer behavior can be modified if needed, using the `DATETIME_FORMAT` and `TIME_FORMAT` settings. The renderer behavior can be modified by setting a custom `encoder_class` attribute on a `JSONRenderer` subclass. ### Relational choices no longer displayed in OPTIONS requests. Making an `OPTIONS` request to views that have a serializer choice field will result in a list of the available choices being returned in the response. In cases where there is a relational field, the previous behavior would be to return a list of available instances to choose from for that relational field. In order to minimize exposed information the behavior now is to *not* return choices information for relational fields. If you want to override this new behavior you'll need to [implement a custom metadata class][metadata]. See [issue #3751][gh3751] for more information on this behavioral change. --- ## Other improvements This release includes further work from a huge number of [pull requests and issues][milestone]. Many thanks to all our contributors who've been involved in the release, either through raising issues, giving feedback, improving the documentation, or suggesting and implementing code changes. The full set of itemized release notes [are available here][release-notes]. [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [moss]: mozilla-grant.md [funding]: https://opencollective.com/django-rest-framework [core-api]: https://www.coreapi.org/ [command-line-client]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/topics/api-clients.md#command-line-client [client-library]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/topics/api-clients.md#python-client-library [core-json]: https://www.coreapi.org/specification/encoding/#core-json-encoding [swagger]: https://openapis.org/specification [hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html [api-blueprint]: https://apiblueprint.org/ [tut-7]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/tutorial/7-schemas-and-client-libraries.md [schema-generation]: ../api-guide/schemas.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.md#34x-series [metadata]: ../api-guide/metadata.md#custom-metadata-classes [gh3751]: https://github.com/encode/django-rest-framework/issues/3751 ================================================ FILE: docs/community/3.5-announcement.md ================================================ # Django REST framework 3.5 The 3.5 release is the second in a planned series that is addressing schema generation, hypermedia support, API client libraries, and finally realtime support. --- ## Funding The 3.5 release would not have been possible without our [collaborative funding model][funding]. If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**.
*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), and [Machinalis](https://www.machinalis.com/#services).* --- ## Improved schema generation Docstrings on views are now pulled through into schema definitions, allowing you to [use the schema definition to document your API][schema-docs]. There is now also a shortcut function, `get_schema_view()`, which makes it easier to [adding schema views][schema-view] to your API. For example, to include a swagger schema to your API, you would do the following: * Run `pip install django-rest-swagger`. * Add `'rest_framework_swagger'` to your `INSTALLED_APPS` setting. * Include the schema view in your URL conf: ```py 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] ) urlpatterns = [path("swagger/", schema_view), ...] ``` There have been a large number of fixes to the schema generation. These should resolve issues for anyone using the latest version of the `django-rest-swagger` package. Some of these changes do affect the resulting schema structure, so if you're already using schema generation you should make sure to review [the deprecation notes](#deprecations), particularly if you're currently using a dynamic client library to interact with your API. Finally, we're also now exposing the schema generation as a [publicly documented API][schema-generation-api], allowing you to more easily override the behavior. ## Requests test client You can now test your project using the `requests` library. This exposes exactly the same interface as if you were using a standard requests session instance. client = RequestsClient() response = client.get('http://testserver/users/') assert response.status_code == 200 Rather than sending any HTTP requests to the network, this interface will coerce all outgoing requests into WSGI, and call into your application directly. ## Core API client You can also now test your project by interacting with it using the `coreapi` client library. # Fetch the API schema client = CoreAPIClient() schema = client.get('http://testserver/schema/') # Create a new organization params = {'name': 'MegaCorp', 'status': 'active'} client.action(schema, ['organizations', 'create'], params) # Ensure that the organization exists in the listing data = client.action(schema, ['organizations', 'list']) assert(len(data) == 1) assert(data == [{'name': 'MegaCorp', 'status': 'active'}]) Again, this will call directly into the application using the WSGI interface, rather than making actual network calls. This is a good option if you are planning for clients to mainly interact with your API using the `coreapi` client library, or some other auto-generated client. ## Live tests One interesting aspect of both the `requests` client and the `coreapi` client is that they allow you to write tests in such a way that they can also be made to run against a live service. By switching the WSGI based client instances to actual instances of `requests.Session` or `coreapi.Client` you can have the test cases make actual network calls. Being able to write test cases that can exercise your staging or production environment is a powerful tool. However in order to do this, you'll need to pay close attention to how you handle setup and teardown to ensure a strict isolation of test data from other live or staging data. ## RAML support We now have preliminary support for [RAML documentation generation][django-rest-raml]. ![RAML Example][raml-image] Further work on the encoding and documentation generation is planned, in order to make features such as the 'Try it now' support available at a later date. This work also now means that you can use the Core API client libraries to interact with APIs that expose a RAML specification. The [RAML codec][raml-codec] gives some examples of interacting with the Spotify API in this way. ## Validation codes Exceptions raised by REST framework now include short code identifiers. When used together with our customizable error handling, this now allows you to modify the style of API error messages. As an example, this allows for the following style of error responses: { "message": "You do not have permission to perform this action.", "code": "permission_denied" } This is particularly useful with validation errors, which use appropriate codes to identify differing kinds of failure... { "name": {"message": "This field is required.", "code": "required"}, "age": {"message": "A valid integer is required.", "code": "invalid"} } ## Client upload & download support The Python `coreapi` client library and the Core API command line tool both now fully support file [uploads][uploads] and [downloads][downloads]. --- ## Deprecations ### Generating schemas from Router The router arguments for generating a schema view, such as `schema_title`, are now pending deprecation. Instead of using `DefaultRouter(schema_title='Example API')`, you should use the `get_schema_view()` function, and include the view in your URL conf. Make sure to include the view before your router urls. For example: from rest_framework.schemas import get_schema_view from my_project.routers import router schema_view = get_schema_view(title='Example API') urlpatterns = [ path('', schema_view), path('', include(router.urls)), ] ### Schema path representations The `'pk'` identifier in schema paths is now mapped onto the actually model field name by default. This will typically be `'id'`. This gives a better external representation for schemas, with less implementation detail being exposed. It also reflects the behavior of using a ModelSerializer class with `fields = '__all__'`. You can revert to the previous behavior by setting `'SCHEMA_COERCE_PATH_PK': False` in the REST framework settings. ### Schema action name representations The internal `retrieve()` and `destroy()` method names are now coerced to an external representation of `read` and `delete`. You can revert to the previous behavior by setting `'SCHEMA_COERCE_METHOD_NAMES': {}` in the REST framework settings. ### DjangoFilterBackend The functionality of the built-in `DjangoFilterBackend` is now completely included by the `django-filter` package. You should change your imports and REST framework filter settings as follows: * `rest_framework.filters.DjangoFilterBackend` becomes `django_filters.rest_framework.DjangoFilterBackend`. * `rest_framework.filters.FilterSet` becomes `django_filters.rest_framework.FilterSet`. The existing imports will continue to work but are now pending deprecation. ### CoreJSON media type The media type for `CoreJSON` is now `application/json+coreapi`, rather than the previous `application/vnd.json+coreapi`. This brings it more into line with other custom media types, such as those used by Swagger and RAML. The clients currently accept either media type. The old style-media type will be deprecated at a later date. ### ModelSerializer 'fields' and 'exclude' ModelSerializer and HyperlinkedModelSerializer must include either a fields option, or an exclude option. The `fields = '__all__'` shortcut may be used to explicitly include all fields. Failing to set either `fields` or `exclude` raised a pending deprecation warning in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandatory. --- [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: https://opencollective.com/django-rest-framework [uploads]: https://core-api.github.io/python-client/api-guide/utils/#file [downloads]: https://core-api.github.io/python-client/api-guide/codecs/#downloadcodec [schema-generation-api]: ../api-guide/schemas.md#schemagenerator [schema-docs]: ../api-guide/schemas.md#schemas-as-documentation [schema-view]: ../api-guide/schemas.md#get_schema_view [django-rest-raml]: https://github.com/encode/django-rest-raml [raml-image]: ../img/raml.png [raml-codec]: https://github.com/core-api/python-raml-codec ================================================ FILE: docs/community/3.6-announcement.md ================================================ # Django REST framework 3.6 The 3.6 release adds two major new features to REST framework. 1. Built-in interactive API documentation support. 2. A new JavaScript client library. ![API Documentation](/img/api-docs.gif) *Above: The interactive API documentation.* --- ## Funding The 3.6 release would not have been possible without our [backing from Mozilla](mozilla-grant.md) to the project, and our [collaborative funding model][funding]. If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**.
*Many thanks to all our [sponsors][sponsors], and in particular to our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), [Rollbar](https://rollbar.com), and [MicroPyramid](https://micropyramid.com/django-rest-framework-development-services/).* --- ## Interactive API documentation REST framework's new API documentation supports a number of features: * Live API interaction. * Support for various authentication schemes. * Code snippets for the Python, JavaScript, and Command Line clients. The `coreapi` library is required as a dependency for the API docs. Make sure to install the latest version (2.3.0 or above). The `pygments` and `markdown` libraries are optional but recommended. To install the API documentation, you'll need to include it in your projects URLconf: from rest_framework.documentation import include_docs_urls API_TITLE = 'API title' API_DESCRIPTION = '...' urlpatterns = [ ... path('docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)) ] Once installed you should see something a little like this: ![API Documentation](/img/api-docs.png) We'll likely be making further refinements to the API documentation over the coming weeks. Keep in mind that this is a new feature, and please do give us feedback if you run into any issues or limitations. For more information on documenting your API endpoints see the ["Documenting your API"][api-docs] section. --- ## JavaScript client library The JavaScript client library allows you to load an API schema, and then interact with that API at an application layer interface, rather than constructing fetch requests explicitly. Here's a brief example that demonstrates: * Loading the client library and schema. * Instantiating an authenticated client. * Making an API request using the client. **index.html** The JavaScript client library supports various authentication schemes, and can be used by your project itself, or as an external client interacting with your API. The client is not limited to usage with REST framework APIs, although it does currently only support loading CoreJSON API schemas. Support for Swagger and other API schemas is planned. For more details see the [JavaScript client library documentation][js-docs]. ## Authentication classes for the Python client library Previous authentication support in the Python client library was limited to allowing users to provide explicit header values. We now have better support for handling the details of authentication, with the introduction of the `BasicAuthentication`, `TokenAuthentication`, and `SessionAuthentication` schemes. You can include the authentication scheme when instantiating a new client. auth = coreapi.auth.TokenAuthentication(scheme='JWT', token='xxx-xxx-xxx') client = coreapi.Client(auth=auth) For more information see the [Python client library documentation][py-docs]. --- ## Deprecations ### Updating coreapi If you're using REST framework's schema generation, or want to use the API docs, then you'll need to update to the latest version of coreapi. (2.3.0) ### Generating schemas from Router The 3.5 "pending deprecation" of router arguments for generating a schema view, such as `schema_title`, `schema_url` and `schema_renderers`, have now been escalated to a "deprecated" warning. Instead of using `DefaultRouter(schema_title='Example API')`, you should use the `get_schema_view()` function, and include the view explicitly in your URL conf. ### DjangoFilterBackend The 3.5 "pending deprecation" warning of the built-in `DjangoFilterBackend` has now been escalated to a "deprecated" warning. You should change your imports and REST framework filter settings as follows: * `rest_framework.filters.DjangoFilterBackend` becomes `django_filters.rest_framework.DjangoFilterBackend`. * `rest_framework.filters.FilterSet` becomes `django_filters.rest_framework.FilterSet`. --- ## What's next There are likely to be a number of refinements to the API documentation and JavaScript client library over the coming weeks, which could include some of the following: * Support for private API docs, requiring login. * File upload and download support in the JavaScript client & API docs. * Comprehensive documentation for the JavaScript client library. * Automatically including authentication details in the API doc code snippets. * Adding authentication support in the command line client. * Support for loading Swagger and other schemas in the JavaScript client. * Improved support for documenting parameter schemas and response schemas. * Refining the API documentation interaction modal. Once work on those refinements is complete, we'll be starting feature work on realtime support, for the 3.7 release. [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [funding]: https://opencollective.com/django-rest-framework [api-docs]: ../topics/documenting-your-api.md [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 ================================================ FILE: docs/community/3.7-announcement.md ================================================ # Django REST framework 3.7 The 3.7 release focuses on improvements to schema generation and the interactive API documentation. This release has been made possible by [Bayer](https://www.bayer.com/) who have sponsored the release. --- ## Funding If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**.
*As well as our release sponsor, we'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).* --- ## Customizing API docs & schema generation. The schema generation introduced in 3.5 and the related API docs generation in 3.6 are both hugely powerful features, however they've been somewhat limited in cases where the view introspection isn't able to correctly identify the schema for a particular view. In order to try to address this we're now adding the ability for per-view customization of the API schema. The interface that we're adding for this allows either basic manual overrides over which fields should be included on a view, or for more complex programmatic overriding of the schema generation. We believe this release comprehensively addresses some of the existing shortcomings of the schema features. Let's take a quick look at using the new functionality... The `APIView` class has a `schema` attribute, that is used to control how the Schema for that particular view is generated. The default behavior is to use the `AutoSchema` class. from rest_framework.views import APIView from rest_framework.schemas import AutoSchema class CustomView(APIView): schema = AutoSchema() # Included for demonstration only. This is the default behavior. We can remove a view from the API schema and docs, like so: class CustomView(APIView): schema = None If we want to mostly use the default behavior, but additionally include some additional fields on a particular view, we can now do so easily... class CustomView(APIView): schema = AutoSchema(manual_fields=[ coreapi.Field('search', location='query') ]) To ignore the automatic generation for a particular view, and instead specify the schema explicitly, we use the `ManualSchema` class instead... class CustomView(APIView): schema = ManualSchema(fields=[...]) For more advanced behaviors you can subclass `AutoSchema` to provide for customized schema generation, and apply that to particular views. class CustomView(APIView): schema = CustomizedSchemaGeneration() For full details on the new functionality, please see the [Schema Documentation][schema-docs]. --- ## Django 2.0 support REST framework 3.7 supports Django versions 1.10, 1.11, and 2.0 alpha. --- ## Minor fixes and improvements There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing. The number of [open tickets against the project](https://github.com/encode/django-rest-framework/issues) currently at its lowest number in quite some time, and we're continuing to focus on reducing these to a manageable amount. --- ## Deprecations ### `exclude_from_schema` Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` decorator and now `PendingDeprecation`. They will be moved to deprecated in the 3.8 release, and removed entirely in 3.9. For `APIView` you should instead set a `schema = None` attribute on the view class. For function based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`. ### `DjangoFilterBackend` The `DjangoFilterBackend` was moved to pending deprecation in 3.5, and deprecated in 3.6. It has now been removed from the core framework. The functionality remains fully available, but is instead provided in the `django-filter` package. --- ## What's next We're still planning to work on improving real-time support for REST framework by providing documentation on integrating with Django channels, as well adding support for more easily adding WebSocket support to existing HTTP endpoints. This will likely be timed so that any REST framework development here ties in with similar work on [API Star][api-star]. [funding]: https://opencollective.com/django-rest-framework [schema-docs]: ../api-guide/schemas.md [api-star]: https://github.com/encode/apistar ================================================ FILE: docs/community/3.8-announcement.md ================================================ # Django REST framework 3.8 The 3.8 release is a maintenance focused release resolving a large number of previously outstanding issues and laying the foundations for future changes. --- ## Funding If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its continued development by **[signing up for a paid plan][funding]**. *We'd like to say thanks in particular our premium backers, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Machinalis](https://machinalis.com/), and [Rollbar](https://rollbar.com).* --- ## Breaking Changes ### Altered the behavior of `read_only` plus `default` on Field. [#5886][gh5886] `read_only` fields will now **always** be excluded from writable fields. Previously `read_only` fields when combined with a `default` value would use the `default` for create and update operations. This was counter-intuitive in some circumstances and led to difficulties supporting dotted `source` attributes on nullable relations. In order to maintain the old behavior you may need to pass the value of `read_only` fields when calling `save()` in the view: def perform_create(self, serializer): serializer.save(owner=self.request.user) Alternatively you may override `save()` or `create()` or `update()` on the serializer as appropriate. --- ## Deprecations ### `action` decorator replaces `list_route` and `detail_route` [#5705][gh5705] `list_route` and `detail_route` have been merge into a single `action` decorator. This improves viewset action introspection, and will allow extra actions to be displayed in the Browsable API in future versions. Both `list_route` and `detail_route` are now pending deprecation. They will be deprecated in 3.9 and removed entirely in 3.10. The new `action` decorator takes a boolean `detail` argument. * Replace `detail_route` uses with `@action(detail=True)`. * Replace `list_route` uses with `@action(detail=False)`. ### `exclude_from_schema` Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` decorator are now deprecated. They will be removed entirely in 3.9. For `APIView` you should instead set a `schema = None` attribute on the view class. For function based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`. --- ## Minor fixes and improvements There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing. ## What's next 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. [funding]: https://opencollective.com/django-rest-framework [gh5886]: https://github.com/encode/django-rest-framework/issues/5886 [gh5705]: https://github.com/encode/django-rest-framework/issues/5705 [openapi]: https://www.openapis.org/ ================================================ FILE: docs/community/3.9-announcement.md ================================================ # Django REST framework 3.9 The 3.9 release gives access to _extra actions_ in the Browsable API, introduces composable permissions and built-in [OpenAPI][openapi] schema support. (Formerly known as Swagger) --- ## Funding If you use REST framework commercially and would like to see this work continue, we strongly encourage you to invest in its 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, [Rover](https://www.rover.com/careers/), [Sentry](https://sentry.io/welcome/), [Stream](https://getstream.io/?utm_source=drf&utm_medium=banner&utm_campaign=drf), [Auklet](https://auklet.io/), [Rollbar](https://rollbar.com), [Cadre](https://cadre.com), [Load Impact](https://loadimpact.com/?utm_campaign=Sponsorship%20links&utm_source=drf&utm_medium=drf), and [Kloudless](https://hubs.ly/H0f30Lf0).* --- ## Built-in OpenAPI schema support REST framework now has a first-pass at directly including OpenAPI schema support. (Formerly known as Swagger) Specifically: * There are now `OpenAPIRenderer`, and `JSONOpenAPIRenderer` classes that deal with encoding `coreapi.Document` instances into OpenAPI YAML or OpenAPI JSON. * The `get_schema_view(...)` method now defaults to OpenAPI YAML, with CoreJSON as a secondary option if it is selected via HTTP content negotiation. * There is a new management command `generateschema`, which you can use to dump the schema into your repository. Here's an example of adding an OpenAPI schema to the URL conf: ```python from rest_framework.schemas import get_schema_view 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], ) urlpatterns = [path("schema.json", schema_view), ...] ``` And here's how you can use the `generateschema` management command: ```shell $ python manage.py generateschema --format openapi > schema.yml ``` There's lots of different tooling that you can use for working with OpenAPI schemas. One option that we're working on is the [API Star](https://docs.apistar.com/) command line tool. You can use `apistar` to validate your API schema: ```shell $ apistar validate --path schema.json --format openapi ✓ Valid OpenAPI schema. ``` Or to build API documentation: ```shell $ apistar docs --path schema.json --format openapi ✓ Documentation built at "build/index.html". ``` API Star also includes a [dynamic client library](https://docs.apistar.com/client-library/) that uses an API schema to automatically provide a client library interface for making requests. ## Composable permission classes You can now compose permission classes using the and/or operators, `&` and `|`. For example... ```python permission_classes = [IsAuthenticated & (ReadOnly | IsAdminUser)] ``` If you're using custom permission classes then make sure that you are subclassing from `BasePermission` in order to enable this support. ## ViewSet _Extra Actions_ available in the Browsable API Following the introduction of the `action` decorator in v3.8, _extra actions_ defined on a ViewSet are now available from the Browsable API. ![Extra Actions displayed in the Browsable API](https://user-images.githubusercontent.com/2370209/32976956-1ca9ab7e-cbf1-11e7-981a-a20cb1e83d63.png) When defined, a dropdown of "Extra Actions", appropriately filtered to detail/non-detail actions, is displayed. --- ## Supported Versions REST framework 3.9 supports Django versions 1.11, 2.0, and 2.1. --- ## Deprecations ### `DjangoObjectPermissionsFilter` moved to third-party package. The `DjangoObjectPermissionsFilter` class is pending deprecation, will be deprecated in 3.10 and removed entirely in 3.11. It has been moved to the third-party [`djangorestframework-guardian`](https://github.com/rpkilby/django-rest-framework-guardian) package. Please use this instead. ### Router argument/method renamed to use `basename` for consistency. * The `Router.register` `base_name` argument has been renamed in favor of `basename`. * The `Router.get_default_base_name` method has been renamed in favor of `Router.get_default_basename`. [#5990][gh5990] See [#5990][gh5990]. [gh5990]: https://github.com/encode/django-rest-framework/pull/5990 `base_name` and `get_default_base_name()` are pending deprecation. They will be deprecated in 3.10 and removed entirely in 3.11. ### `action` decorator replaces `list_route` and `detail_route` Both `list_route` and `detail_route` are now deprecated in favor of the single `action` decorator. They will be removed entirely in 3.10. The `action` decorator takes a boolean `detail` argument. * Replace `detail_route` uses with `@action(detail=True)`. * Replace `list_route` uses with `@action(detail=False)`. ### `exclude_from_schema` Both `APIView.exclude_from_schema` and the `exclude_from_schema` argument to the `@api_view` have now been removed. For `APIView` you should instead set a `schema = None` attribute on the view class. For function-based views the `@schema` decorator can be used to exclude the view from the schema, by using `@schema(None)`. --- ## Minor fixes and improvements There are a large number of minor fixes and improvements in this release. See the [release notes](release-notes.md) page for a complete listing. ## What's next We're planning to iteratively work towards OpenAPI becoming the standard schema representation. This will mean that the `coreapi` dependency will gradually become removed, and we'll instead generate the schema directly, rather than building a CoreAPI `Document` object. OpenAPI has clearly become the standard for specifying Web APIs, so there's not much value any more in our schema-agnostic document model. Making this change will mean that we'll more easily be able to take advantage of the full set of OpenAPI functionality. This will also make a wider range of tooling available. We'll focus on continuing to develop the [API Star](https://docs.apistar.com/) library and client tool into a recommended option for generating API docs, validating API schemas, and providing a dynamic client library. There's also a huge amount of ongoing work on maturing the ASGI landscape, with the possibility that some of this work will eventually [feed back into Django](https://www.aeracode.org/2018/06/04/django-async-roadmap/). There will be further work on the [Uvicorn](https://www.uvicorn.org/) web server, as well as lots of functionality planned for the [Starlette](https://www.starlette.io/) web framework, which is building a foundational set of tooling for working with ASGI. [funding]: https://opencollective.com/django-rest-framework [gh5886]: https://github.com/encode/django-rest-framework/issues/5886 [gh5705]: https://github.com/encode/django-rest-framework/issues/5705 [openapi]: https://www.openapis.org/ [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors ================================================ FILE: docs/community/contributing.md ================================================ # Contributing to REST framework > The world can only really be changed one piece at a time. The art is picking that piece. > > — [Tim Berners-Lee][cite] There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project. !!! note 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 The most important thing you can do to help push the REST framework project forward is to be actively involved wherever possible. Code contributions are often overvalued as being the primary way to get involved in a project, we don't believe that needs to be the case. If you use REST framework, we'd love you to be vocal about your experiences with it - you might consider writing a blog post about using REST framework, or publishing a tutorial about building a project with a particular JavaScript framework. Experiences from beginners can be particularly helpful because you'll be in the best position to assess which bits of REST framework are more difficult to understand and work with. Other really great ways you can help move the community forward include helping to answer questions on the [discussion group][google-group], or setting up an [email alert on StackOverflow][so-filter] so that you get notified of any new questions with the `django-rest-framework` tag. When answering questions make sure to help future contributors find their way around by hyperlinking wherever possible to related threads and tickets, and include backlinks from those items if relevant. ## Code of conduct Please keep the tone polite & professional. For some users a discussion on the REST framework mailing list or ticket tracker may be their first engagement with the open source community. First impressions count, so let's try to make everyone feel welcome. Be mindful in the language you choose. As an example, in an environment that is heavily male-dominated, posts that start 'Hey guys,' can come across as unintentionally exclusive. It's just as easy, and more inclusive to use gender neutral language in those situations. The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines for participating in community forums. ## Issues Our contribution process is that the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Some tips on good potential issue reporting: * 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. * 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 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. ### 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, could the feature request instead be implemented as a third party package? * If a ticket hasn't had much activity and addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again. ## Development To start developing on Django REST framework, first create a Fork from the [Django REST Framework repo][repo] on GitHub. Then clone your fork. The clone command will look like this, with your GitHub username instead of YOUR-USERNAME: git clone https://github.com/YOUR-USERNAME/django-rest-framework See GitHub's [_Fork a Repo_][how-to-fork] Guide for more help. Changes should broadly follow the [PEP 8][pep-8] style conventions, and we recommend you set up your editor to automatically indicate non-conforming styles. You can check your contributions against these conventions each time you commit using the [pre-commit](https://pre-commit.com/) hooks, which we also run on CI. To set them up, first ensure you have the pre-commit tool installed, for example: python -m pip install pre-commit Then run: pre-commit install ### Testing To run the tests, clone the repository, and then: # Setup the virtual environment python3 -m venv env source env/bin/activate pip install -e . --group dev # Run the tests ./runtests.py !!! tip If your tests require access to the database, do not forget to inherit from `django.test.TestCase` or use the `@pytest.mark.django_db()` decorator. For example, with TestCase: from django.test import TestCase class MyDatabaseTest(TestCase): def test_something(self): # Your test code here pass Or with decorator: import pytest @pytest.mark.django_db() class MyDatabaseTest: def test_something(self): # Your test code here pass You can reuse existing models defined in `tests/models.py` for your tests. #### Test options Run using a more concise output style. ./runtests.py -q If you do not want the output to be captured (for example, to see print statements directly), you can use the `-s` flag. ./runtests.py -s Run the tests for a given test case. ./runtests.py MyTestCase Run the tests for a given test method. ./runtests.py MyTestCase.test_this_method Shorter form to run the tests for a given test method. ./runtests.py test_this_method !!! note The test case and test method matching is fuzzy and will sometimes run other tests that contain a partial string match to the given command line input. #### Running against multiple environments You can also use the excellent [tox][tox] testing tool to run the tests against all supported versions of Python and Django. Install `tox` globally, and then simply run: tox ### Pull requests It's a good idea to make pull requests early on. A pull request represents the start of a discussion, and doesn't necessarily need to be the final, finished submission. It's also always best to make a new branch before starting work on a pull request. This means that you'll be able to later switch back to working on another separate issue without interfering with an ongoing pull requests. It's also useful to remember that if you have an outstanding pull request then pushing new commits to your GitHub repo will also automatically update the pull requests. GitHub's documentation for working on pull requests is [available here][pull-requests]. Always run the tests before submitting pull requests, and ideally run `tox` in order to check that your modifications are compatible on all supported versions of Python and Django. Once you've made a pull request take a look at the build status in the GitHub interface and make sure the tests are running as you'd expect. ![Build status][build-status] *Above: build notifications* ### Managing compatibility issues Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into the `compat.py` module, and should provide a single common interface that the rest of the codebase can use. ## Documentation The documentation for REST framework is built from the [Markdown][markdown] source files in [the docs directory][docs]. There are many great Markdown editors that make working with the documentation really easy. The [Mou editor for Mac][mou] is one such editor that comes highly recommended. ### Building the documentation To build the documentation, install MkDocs with `pip install mkdocs` and then run the following command. mkdocs build This will build the documentation into the `site` directory. You can build the documentation and open a preview in a browser window by using the `serve` command. mkdocs serve ### Language style Documentation should be in American English. The tone of the documentation is very important - try to stick to a simple, plain, objective and well-balanced style where possible. Some other tips: * Keep paragraphs reasonably short. * Don't use abbreviations such as 'e.g.' but instead use the long form, such as 'For example'. ### Markdown style There are a couple of conventions you should follow when working on the documentation. #### 1. Headers Headers should use the hash style. For example: ### Some important topic The underline style should not be used. **Don't do this:** Some important topic ==================== #### 2. Links Links should always use the reference style, with the referenced hyperlinks kept at the end of the document. Here is a link to [some other thing][other-thing]. More text... [other-thing]: http://example.com/other/thing This style helps keep the documentation source consistent and readable. If you are hyperlinking to another REST framework document, you should use a relative link, and link to the `.md` suffix. For example: [authentication]: ../api-guide/authentication.md Linking in this style means you'll be able to click the hyperlink in your Markdown editor to open the referenced document. When the documentation is built, these links will be converted into regular links to HTML pages. #### 3. Notes If you want to draw attention to a note or warning, use an [admonition], like so: !!! note A useful documentation note. The documentation theme styles `info`, `warning`, `tip` and `danger` admonition types, but more could be added if the need arise. [cite]: https://www.w3.org/People/Berners-Lee/FAQ.html [code-of-conduct]: https://www.djangoproject.com/conduct/ [google-group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [so-filter]: https://stackexchange.com/filters/66475/rest-framework [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 [tox]: https://tox.readthedocs.io/en/latest/ [markdown]: https://daringfireball.net/projects/markdown/basics [docs]: https://github.com/encode/django-rest-framework/tree/main/docs [mou]: http://mouapp.com/ [repo]: https://github.com/encode/django-rest-framework [how-to-fork]: https://help.github.com/articles/fork-a-repo/ [admonition]: https://python-markdown.github.io/extensions/admonition/ ================================================ FILE: docs/community/jobs.md ================================================ # Jobs Looking for a new Django REST Framework related role? On this site we provide a list of job resources that may be helpful. It's also worth checking out if any of [our sponsors are hiring][sponsors]. ## Places to look for Django REST Framework Jobs * [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] * [https://www.indeed.com/q-Django-jobs.html][indeed-com] * [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.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]. Wonder how else you can help? One of the best ways you can help Django REST Framework is to ask interviewers if their company is signed up for [REST Framework sponsorship][sponsors] yet. [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 [indeed-com]: https://www.indeed.com/q-Django-jobs.html [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-com]: https://remoteok.com/remote-django-jobs [remotepython-com]: https://www.remotepython.com/jobs/ [pyjobs-com]: https://www.pyjobs.com/ [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors [submit-pr]: https://github.com/encode/django-rest-framework [anna-email]: mailto:anna@django-rest-framework.org ================================================ FILE: docs/community/kickstarter-announcement.md ================================================ # Kickstarting Django REST framework 3 --- --- In order to continue to drive the project forward, I'm launching a Kickstarter campaign to help fund the development of a major new release - Django REST framework 3. ## Project details This new release will allow us to comprehensively address some of the shortcomings of the framework, and will aim to include the following: * Faster, simpler and easier-to-use serializers. * An alternative admin-style interface for the browsable API. * Search and filtering controls made accessible in the browsable API. * Alternative API pagination styles. * Documentation around API versioning. * Triage of outstanding tickets. * Improving the ongoing quality and maintainability of the project. Full details are available now on the [project page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3). If you're interested in helping make sustainable open source development a reality please [visit the Kickstarter page](https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3) and consider funding the project. I can't wait to see where this takes us! Many thanks to everyone for your support so far, Tom Christie :) --- ## Sponsors We've now blazed way past all our goals, with a staggering £30,000 (~$50,000), meaning I'll be in a position to work on the project significantly beyond what we'd originally planned for. I owe a huge debt of gratitude to all the wonderful companies and individuals who have been backing the project so generously, and making this possible. --- ### Platinum sponsors Our platinum sponsors have each made a hugely substantial contribution to the future development of Django REST framework, and I simply can't thank them enough.
--- ### Gold sponsors Our gold sponsors include companies large and small. Many thanks for their significant funding of the project and their commitment to sustainable open-source development.
--- ### Silver sponsors The serious financial contribution that our silver sponsors have made is very much appreciated. I'd like to say a particular thank you to individuals who have chosen to privately support the project at this level.
**Individual backers**: Paul Hallett, Paul Whipp, Dylan Roy, Jannis Leidel, Xavier Ordoquy, Johannes Spielmann, Rob Spectre, Chris Heisel, Marwan Alsabbagh, Haris Ali, Tuomas Toivonen. --- ### Advocates The following individuals made a significant financial contribution to the development of Django REST framework 3, for which I can only offer a huge, warm and sincere thank you! **Individual backers**: Jure Cuhalev, Kevin Brolly, Ferenc Szalai, Dougal Matthews, Stefan Foulis, Carlos Hernando, Alen Mujezinovic, Ross Crawford-d'Heureuse, George Kappel, Alasdair Nicol, John Carr, Steve Winton, Trey, Manuel Miranda, David Horn, Vince Mi, Daniel Sears, Jamie Matthews, Ryan Currah, Marty Kemka, Scott Nixon, Moshin Elahi, Kevin Campbell, Jose Antonio Leiva Izquierdo, Kevin Stone, Andrew Godwin, Tijs Teulings, Roger Boardman, Xavier Antoviaque, Darian Moody, Lujeni, Jon Dugan, Wiley Kestner, Daniel C. Silverstein, Daniel Hahler, Subodh Nijsure, Philipp Weidenhiller, Yusuke Muraoka, Danny Roa, Reto Aebersold, Kyle Getrost, Décébal Hormuz, James Dacosta, Matt Long, Mauro Rocco, Tyrel Souza, Ryan Campbell, Ville Jyrkkä, Charalampos Papaloizou, Nikolai Røed Kristiansen, Antoni Aloy López, Celia Oakley, Michał Krawczak, Ivan VenOsdel, Tim Watts, Martin Warne, Nicola Jordan, Ryan Kaskel. **Corporate backers**: Savannah Informatics, Prism Skylabs, Musical Operating Devices. --- ### Supporters There were also almost 300 further individuals choosing to help fund the project at other levels or choosing to give anonymously. Again, thank you, thank you, thank you! ================================================ FILE: docs/community/mozilla-grant.md ================================================ # Mozilla Grant We have recently been [awarded a Mozilla grant](https://blog.mozilla.org/blog/2016/04/13/mozilla-open-source-support-moss-update-q1-2016/), in order to fund the next major releases of REST framework. This work will focus on seamless client-side integration by introducing supporting client libraries that are able to dynamically interact with REST framework APIs. The framework will provide for either hypermedia or schema endpoints, which will expose the available interface for the client libraries to interact with. Additionally, we will be building on the realtime support that Django Channels provides, supporting and documenting how to build realtime APIs with REST framework. Again, this will include supporting work in the associated client libraries, making it easier to build richly interactive applications. The [Core API](https://www.coreapi.org/) project will provide the foundations for our client library support, and will allow us to support interaction using a wide range of schemas and hypermedia formats. It's worth noting that these client libraries won't be tightly coupled to solely REST framework APIs either, and will be able to interact with *any* API that exposes a supported schema or hypermedia format. Specifically, the work includes: ## Client libraries This work will include built-in schema and hypermedia support, allowing dynamic client libraries to interact with the API. I'll also be releasing both Python and Javascript client libraries, plus a command-line client, a new tutorial section, and further documentation. * Client library support in REST framework. * Schema & hypermedia support for REST framework APIs. * A test client, allowing you to write tests that emulate a client library interacting with your API. * New tutorial sections on using client libraries to interact with REST framework APIs. * Python client library. * JavaScript client library. * Command line client. ## Realtime APIs The next goal is to build on the realtime support offered by Django Channels, adding support & documentation for building realtime API endpoints. * Support for API subscription endpoints, using REST framework and Django Channels. * New tutorial section on building realtime API endpoints with REST framework. * Realtime support in the Python & Javascript client libraries. ## Accountability In order to ensure that I can be fully focused on trying to secure a sustainable & well-funded open source business I will be leaving my current role at [DabApps](https://www.dabapps.com/) at the end of May 2016. I have formed a UK limited company, [Encode](https://www.encode.io/), which will act as the business entity behind REST framework. I will be issuing monthly reports from Encode on progress both towards the Mozilla grant, and for development time funded via the REST framework paid plans.

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

================================================ FILE: docs/community/project-management.md ================================================ # Project management > "No one can whistle a symphony; it takes a whole orchestra to play it" > > — Halford E. Luccock This document outlines our project management processes for REST framework. The aim is to ensure that the project has a high ["bus factor"][bus-factor], and can continue to remain well supported for the foreseeable future. Suggestions for improvements to our process are welcome. --- ## Maintenance team [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. #### Composition The composition of the maintenance team is handled by [@tomchristie](https://github.com/encode/). Team members will be added as collaborators to the repository. #### Responsibilities Team members have the following responsibilities. * Close invalid or resolved tickets. * Add triage labels and milestones to tickets. * Merge finalized pull requests. * Build and deploy the documentation, using `mkdocs gh-deploy`. * Build and update the included translation packs. Further notes for maintainers: * Code changes should come in the form of a pull request - do not push directly to main. * 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]. --- ## Release process * The release manager is selected. * 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 is automated in GitHub actions on tag pushes. The following template can be used as a release checklist: - Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/mains/docs/topics/release-notes.md): - Start drafting a [new release in GitHub](https://github.com/encode/django-rest-framework/releases/new) - Select the tag that you want to give to the release and the previous tag - Click the "Generate release notes" button - Don't confirm anything! Copy the generated content to a file `input.md` - Run `uv tool run linkify-gh-markdown input.md` to make the links absolute - Put the generated content in the `release-notes.md` file - Update supported versions: - `pyproject.toml` ensure the `requires-python` key is up to date - `pyproject.toml` Python & Django version trove classifiers - `README` Python & Django versions - `docs` Python & Django versions - Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/main/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 other maintainers that the release is finalized and ready to go. - Ensure that release date is included in pull request. - Merge the release pull request. - Tag the release, either with `git tag -a *.*.* -m 'version *.*.*'; git push --tags` or in GitHub. - Wait for the release workflow to run. It will build the distribution, upload it to Test PyPI, PyPI and create the GitHub release. - Make a release announcement on the [discussion group](https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework). - Make a release announcement on social media (Mastodon, etc...) and on the [Django forum](https://forum.djangoproject.com/). - Close the milestone on GitHub. --- ## Project ownership The PyPI package is owned by `@tomchristie`. As a backup `@j4mie` also has ownership of the package. If `@tomchristie` ceases to participate in the project then `@j4mie` has responsibility for handing over ownership duties. #### Outstanding management & ownership issues The following issues still need to be addressed: * 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 [mailing-list]: https://groups.google.com/forum/#!forum/django-rest-framework ================================================ FILE: docs/community/release-notes.md ================================================ # Release Notes ## 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. - **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. As REST Framework is considered feature-complete, most releases are expected to be minor releases. ## Deprecation policy REST framework releases follow a formal deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. The timeline for deprecation of a feature present in version 1.0 would work as follows: * Version 1.1 would remain **fully backwards compatible** with 1.0, but would raise `RemovedInDRF13Warning` warnings, subclassing `PendingDeprecationWarning`, if you use the feature that are due to be deprecated. These warnings are **silent by default**, but can be explicitly enabled when you're ready to start migrating any required changes. For example if you start running your tests using `python -Wd manage.py test`, you'll be warned of any API changes you need to make. * Version 1.2 would escalate these warnings to subclass `DeprecationWarning`, which is loud by default. * Version 1.3 would remove the deprecated bits of API entirely. Note that in line with Django's policy, any parts of the framework not mentioned in the documentation should generally be considered private API, and may be subject to change. ## Upgrading To upgrade Django REST framework to the latest version, use pip: pip install -U djangorestframework You can determine your currently installed version using `pip show`: pip show djangorestframework --- ## 3.17.x series ### 3.17.0 **Date**: 18th March 2026 #### Breaking changes * Drop support for Python 3.9 by [@auvipy](https://github.com/auvipy) in [#9781](https://github.com/encode/django-rest-framework/pull/9781) * Drop deprecated coreapi support by [@browniebroke](https://github.com/browniebroke) in [#9895](https://github.com/encode/django-rest-framework/pull/9895) #### Features * Add Django 6.0 support by [@MehrazRumman](https://github.com/MehrazRumman) in [#9819](https://github.com/encode/django-rest-framework/pull/9819) * Add support for Python 3.14 by [@cclauss](https://github.com/cclauss) in [#9780](https://github.com/encode/django-rest-framework/pull/9780) * Add ability to specify output format for `DurationField` by [@sevdog](https://github.com/sevdog) in [#8532](https://github.com/encode/django-rest-framework/pull/8532) * Add missing decorators: `@versioning_class()`, `@content_negotiation_class()`, `@metadata_class()` for function-based views by [@qqii](https://github.com/qqii) in [#9719](https://github.com/encode/django-rest-framework/pull/9719) * Support `violation_error_code` and `violation_error_message` from `UniqueConstraint` in `UniqueTogetherValidator` by [@s-aleshin](https://github.com/s-aleshin) in [#9766](https://github.com/encode/django-rest-framework/pull/9766) * Add support for `ipaddress` objects in `JSONEncoder` by [@corenting](https://github.com/corenting) in [#9087](https://github.com/encode/django-rest-framework/pull/9087) * Add optional support to serialize `BigInteger` to string by [@HoodyH](https://github.com/HoodyH) in [#9775](https://github.com/encode/django-rest-framework/pull/9775) #### Bug fixes * Prevent small risk of `Token` overwrite by [@mahdirahimi1999](https://github.com/mahdirahimi1999) in [#9754](https://github.com/encode/django-rest-framework/pull/9754) * Fix `UniqueTogetherValidator` validation when condition references a read-only field by [@ticosax](https://github.com/ticosax) in [#9764](https://github.com/encode/django-rest-framework/pull/9764) * Fix validation on many to many field when `default=None` by [@Genarito](https://github.com/Genarito) in [#9790](https://github.com/encode/django-rest-framework/pull/9790) * Fix invalid SPDX license expression in `__init__.py` by [@TheFunctionalGuy](https://github.com/TheFunctionalGuy) in [#9799](https://github.com/encode/django-rest-framework/pull/9799) * Fix `HTMLFormRenderer` to ensure a valid `datetime-local` format by [@mgaligniana](https://github.com/mgaligniana) in [#9365](https://github.com/encode/django-rest-framework/pull/9365) * Fix mutable default arguments in OrderingFilter methods by [@killerdevildog](https://github.com/killerdevildog) in [#9742](https://github.com/encode/django-rest-framework/pull/9742) * Update TokenAdmin to respect USERNAME_FIELD of the user model by [@m000](https://github.com/m000) in [#9836](https://github.com/encode/django-rest-framework/pull/9836) * Preserve ordering in `MultipleChoiceField` by [@fbozhang](https://github.com/fbozhang) in [#9735](https://github.com/encode/django-rest-framework/pull/9735) #### Translations * Update French translation by [@SebCorbin](https://github.com/SebCorbin) in [#9770](https://github.com/encode/django-rest-framework/pull/9770) * Update Brazilian Portuguese translations by [@JVPinheiroReis](https://github.com/JVPinheiroReis) in [#9828](https://github.com/encode/django-rest-framework/pull/9828) * Fix and improve French translations by [@deronnax](https://github.com/deronnax) in [#9896](https://github.com/encode/django-rest-framework/pull/9896) * Add missing Russian translation by [@minorytanaka](https://github.com/minorytanaka) in [#9903](https://github.com/encode/django-rest-framework/pull/9903) #### Packaging * Migrate packaging to `pyproject.toml` by [@deronnax](https://github.com/deronnax) in [#9056](https://github.com/encode/django-rest-framework/pull/9056) * Move package data rules from `MANIFEST.in` to `pyproject.toml` by [@p-r-a-v-i-n](https://github.com/p-r-a-v-i-n) in [#9825](https://github.com/encode/django-rest-framework/pull/9825) * Set up release workflow with trusted publisher by [@browniebroke](https://github.com/browniebroke) in [#9852](https://github.com/encode/django-rest-framework/pull/9852) #### Other changes * Refactor token generation to use the `secrets` module by [@mahdirahimi1999](https://github.com/mahdirahimi1999) in [#9760](https://github.com/encode/django-rest-framework/pull/9760) * Add validation for decorator out-of-order with `@api_view` by [@kernelshard](https://github.com/kernelshard) in [#9821](https://github.com/encode/django-rest-framework/pull/9821) * Switch to mkdocs material theme for documentation by [@browniebroke](https://github.com/browniebroke) in [#9849](https://github.com/encode/django-rest-framework/pull/9849) #### New Contributors * [@khaledsukkar2](https://github.com/khaledsukkar2) made their first contribution in [#9717](https://github.com/encode/django-rest-framework/pull/9717) * [@qqii](https://github.com/qqii) made their first contribution in [#9719](https://github.com/encode/django-rest-framework/pull/9719) * [@zankoAn](https://github.com/zankoAn) made their first contribution in [#9788](https://github.com/encode/django-rest-framework/pull/9788) * [@uche-wealth](https://github.com/uche-wealth) made their first contribution in [#9795](https://github.com/encode/django-rest-framework/pull/9795) * [@s-aleshin](https://github.com/s-aleshin) made their first contribution in [#9766](https://github.com/encode/django-rest-framework/pull/9766) * [@Infamous003](https://github.com/Infamous003) made their first contribution in [#9794](https://github.com/encode/django-rest-framework/pull/9794) * [@Genarito](https://github.com/Genarito) made their first contribution in [#9790](https://github.com/encode/django-rest-framework/pull/9790) * [@TheFunctionalGuy](https://github.com/TheFunctionalGuy) made their first contribution in [#9799](https://github.com/encode/django-rest-framework/pull/9799) * [@mahdighadiriii](https://github.com/mahdighadiriii) made their first contribution in [#9800](https://github.com/encode/django-rest-framework/pull/9800) * [@p-r-a-v-i-n](https://github.com/p-r-a-v-i-n) made their first contribution in [#9801](https://github.com/encode/django-rest-framework/pull/9801) * [@itssimon](https://github.com/itssimon) made their first contribution in [#9718](https://github.com/encode/django-rest-framework/pull/9718) * [@huynguyengl99](https://github.com/huynguyengl99) made their first contribution in [#9785](https://github.com/encode/django-rest-framework/pull/9785) * [@corenting](https://github.com/corenting) made their first contribution in [#9087](https://github.com/encode/django-rest-framework/pull/9087) * [@killerdevildog](https://github.com/killerdevildog) made their first contribution in [#9742](https://github.com/encode/django-rest-framework/pull/9742) * [@dayandavid](https://github.com/dayandavid) made their first contribution in [#9820](https://github.com/encode/django-rest-framework/pull/9820) * [@abhishektiwari](https://github.com/abhishektiwari) made their first contribution in [#9826](https://github.com/encode/django-rest-framework/pull/9826) * [@HoodyH](https://github.com/HoodyH) made their first contribution in [#9775](https://github.com/encode/django-rest-framework/pull/9775) * [@Shrikantgiri25](https://github.com/Shrikantgiri25) made their first contribution in [#9808](https://github.com/encode/django-rest-framework/pull/9808) * [@JVPinheiroReis](https://github.com/JVPinheiroReis) made their first contribution in [#9828](https://github.com/encode/django-rest-framework/pull/9828) * [@m000](https://github.com/m000) made their first contribution in [#9836](https://github.com/encode/django-rest-framework/pull/9836) * [@Nabute](https://github.com/Nabute) made their first contribution in [#9767](https://github.com/encode/django-rest-framework/pull/9767) * [@therealjozber](https://github.com/therealjozber) made their first contribution in [#9845](https://github.com/encode/django-rest-framework/pull/9845) * [@nexapytech](https://github.com/nexapytech) made their first contribution in [#9867](https://github.com/encode/django-rest-framework/pull/9867) * [@RispaJoseph](https://github.com/RispaJoseph) made their first contribution in [#9874](https://github.com/encode/django-rest-framework/pull/9874) * [@LorenzoGuideri](https://github.com/LorenzoGuideri) made their first contribution in [#9875](https://github.com/encode/django-rest-framework/pull/9875) * [@maldoinc](https://github.com/maldoinc) made their first contribution in [#9893](https://github.com/encode/django-rest-framework/pull/9893) * [@0Nafi0](https://github.com/0Nafi0) made their first contribution in [#9861](https://github.com/encode/django-rest-framework/pull/9861) * [@MoeSalah1999](https://github.com/MoeSalah1999) made their first contribution in [#9870](https://github.com/encode/django-rest-framework/pull/9870) * [@kelsonbrito50](https://github.com/kelsonbrito50) made their first contribution in [#9901](https://github.com/encode/django-rest-framework/pull/9901) * [@fbozhang](https://github.com/fbozhang) made their first contribution in [#9735](https://github.com/encode/django-rest-framework/pull/9735) * [@minorytanaka](https://github.com/minorytanaka) made their first contribution in [#9903](https://github.com/encode/django-rest-framework/pull/9903) * [@kosbemrunal](https://github.com/kosbemrunal) made their first contribution in [#9904](https://github.com/encode/django-rest-framework/pull/9904) * [@htvictoire](https://github.com/htvictoire) made their first contribution in [#9916](https://github.com/encode/django-rest-framework/pull/9916) **Full Changelog**: [3.16.1...3.17.0](https://github.com/encode/django-rest-framework/compare/3.16.1...3.17.0) ## 3.16.x series ### 3.16.1 **Date**: 6th August 2025 This release fixes a few bugs, clean-up some old code paths for unsupported Python versions and improve translations. #### Minor changes * Cleanup optional `backports.zoneinfo` dependency and conditions on unsupported Python 3.8 and lower in [#9681](https://github.com/encode/django-rest-framework/pull/9681). Python versions prior to 3.9 were already unsupported so this shouldn't be a breaking change. #### Bug fixes * Fix regression in `unique_together` validation with `SerializerMethodField` in [#9712](https://github.com/encode/django-rest-framework/pull/9712) * Fix `UniqueTogetherValidator` to handle fields with `source` attribute in [#9688](https://github.com/encode/django-rest-framework/pull/9688) * Drop HTML line breaks on long headers in browsable API in [#9438](https://github.com/encode/django-rest-framework/pull/9438) #### Translations * Add Kazakh locale support in [#9713](https://github.com/encode/django-rest-framework/pull/9713) * Update translations for Korean translations in [#9571](https://github.com/encode/django-rest-framework/pull/9571) * Update German translations in [#9676](https://github.com/encode/django-rest-framework/pull/9676) * Update Chinese translations in [#9675](https://github.com/encode/django-rest-framework/pull/9675) * Update Arabic translations-sal in [#9595](https://github.com/encode/django-rest-framework/pull/9595) * Update Persian translations in [#9576](https://github.com/encode/django-rest-framework/pull/9576) * Update Spanish translations in [#9701](https://github.com/encode/django-rest-framework/pull/9701) * Update Turkish Translations in [#9749](https://github.com/encode/django-rest-framework/pull/9749) * Fix some typos in Brazilian Portuguese translations in [#9673](https://github.com/encode/django-rest-framework/pull/9673) #### Documentation * Removed reference to GitHub Issues and Discussions in [#9660](https://github.com/encode/django-rest-framework/pull/9660) * Add `drf-restwind` and update outdated images in `browsable-api.md` in [#9680](https://github.com/encode/django-rest-framework/pull/9680) * Updated funding page to represent current scope in [#9686](https://github.com/encode/django-rest-framework/pull/9686) * Fix broken Heroku JSON Schema link in [#9693](https://github.com/encode/django-rest-framework/pull/9693) * Update Django documentation links to use stable version in [#9698](https://github.com/encode/django-rest-framework/pull/9698) * Expand docs on unique constraints cause 'required=True' in [#9725](https://github.com/encode/django-rest-framework/pull/9725) * Revert extension back from `djangorestframework-guardian2` to `djangorestframework-guardian` in [#9734](https://github.com/encode/django-rest-framework/pull/9734) * Add note to tutorial about required `request` in serializer context when using `HyperlinkedModelSerializer` in [#9732](https://github.com/encode/django-rest-framework/pull/9732) #### Internal changes * Update GitHub Actions to use Ubuntu 24.04 for testing in [#9677](https://github.com/encode/django-rest-framework/pull/9677) * Update test matrix to use Django 5.2 stable version in [#9679](https://github.com/encode/django-rest-framework/pull/9679) * Add `pyupgrade` to `pre-commit` hooks in [#9682](https://github.com/encode/django-rest-framework/pull/9682) * Fix test with Django 5 when `pytz` is available in [#9715](https://github.com/encode/django-rest-framework/pull/9715) #### New Contributors * [`@araggohnxd`](https://github.com/araggohnxd) made their first contribution in [#9673](https://github.com/encode/django-rest-framework/pull/9673) * [`@mbeijen`](https://github.com/mbeijen) made their first contribution in [#9660](https://github.com/encode/django-rest-framework/pull/9660) * [`@stefan6419846`](https://github.com/stefan6419846) made their first contribution in [#9676](https://github.com/encode/django-rest-framework/pull/9676) * [`@ren000thomas`](https://github.com/ren000thomas) made their first contribution in [#9675](https://github.com/encode/django-rest-framework/pull/9675) * [`@ulgens`](https://github.com/ulgens) made their first contribution in [#9682](https://github.com/encode/django-rest-framework/pull/9682) * [`@bukh-sal`](https://github.com/bukh-sal) made their first contribution in [#9595](https://github.com/encode/django-rest-framework/pull/9595) * [`@rezatn0934`](https://github.com/rezatn0934) made their first contribution in [#9576](https://github.com/encode/django-rest-framework/pull/9576) * [`@Rohit10jr`](https://github.com/Rohit10jr) made their first contribution in [#9693](https://github.com/encode/django-rest-framework/pull/9693) * [`@kushibayev`](https://github.com/kushibayev) made their first contribution in [#9713](https://github.com/encode/django-rest-framework/pull/9713) * [`@alihassancods`](https://github.com/alihassancods) made their first contribution in [#9732](https://github.com/encode/django-rest-framework/pull/9732) * [`@kulikjak`](https://github.com/kulikjak) made their first contribution in [#9715](https://github.com/encode/django-rest-framework/pull/9715) * [`@Natgho`](https://github.com/Natgho) made their first contribution in [#9749](https://github.com/encode/django-rest-framework/pull/9749) **Full Changelog**: https://github.com/encode/django-rest-framework/compare/3.16.0...3.16.1 ### 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 behavior of existing features and pre-existing behavior. 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 behavior 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 Date: 22nd September 2022 * Django 2.2 is no longer supported. [[#8662](https://github.com/encode/django-rest-framework/pull/8662)] * Django 4.1 compatibility. [[#8591](https://github.com/encode/django-rest-framework/pull/8591)] * Add `--api-version` CLI option to `generateschema` management command. [[#8663](https://github.com/encode/django-rest-framework/pull/8663)] * Enforce `is_valid(raise_exception=False)` as a keyword-only argument. [[#7952](https://github.com/encode/django-rest-framework/pull/7952)] * 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 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)] * Update throttling to check if `request.user` is set before checking if the user is authenticated. [[#8370](https://github.com/encode/django-rest-framework/pull/8370)] ## 3.13.x series ### 3.13.1 Date: 15th December 2021 * Revert schema naming changes with function based `@api_view`. [#8297] ### 3.13.0 Date: 13th December 2021 * 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] * Respect `UNICODE_JSON` setting in API schema outputs. [#7991] * Fix for `RemoteUserAuthentication`. [#7158] * Make Field constructors keyword-only. [#7632] --- ## 3.12.x series ### 3.12.4 Date: 26th March 2021 * Revert use of `deque` instead of `list` for tracking throttling `.history`. (Due to incompatibility with DjangoRedis cache backend. See #7870) [#7872] ### 3.12.3 Date: 25th March 2021 * Properly handle ATOMIC_REQUESTS when multiple database configurations are used. [#7739] * Bypass `COUNT` query when `LimitOffsetPagination` is configured but pagination params are not included on the request. [#6098] * Respect `allow_null=True` on `DecimalField`. [#7718] * Allow title cased `"Yes"`/`"No"` values with `BooleanField`. [#7739] * Add `PageNumberPagination.get_page_number()` method for overriding behavior. [#7652] * Fixed rendering of timedelta values in OpenAPI schemas, when present as default, min, or max fields. [#7641] * Render JSONFields with indentation in browsable API forms. [#6243] * Remove unnecessary database query in admin Token views. [#7852] * Raise validation errors when bools are passed to `PrimaryKeyRelatedField` fields, instead of casting to ints. [#7597] * Don't include model properties as automatically generated ordering fields with `OrderingFilter`. [#7609] * Use `deque` instead of `list` for tracking throttling `.history`. [#7849] ### 3.12.2 Date: 13th October 2020 * Fix issue if `rest_framework.authtoken.models` is imported, but `rest_framework.authtoken` is not in INSTALLED_APPS. [#7571] * Ignore subclasses of BrowsableAPIRenderer in OpenAPI schema. [#7497] * Narrower exception catching in serilizer fields, to ensure that any errors in broken `get_queryset()` methods are not masked. [#7480] ### 3.12.1 Date: 28th September 2020 * Add `TokenProxy` migration. [#7557] ### 3.12.0 Date: 28th September 2020 * Add `--file` option to `generateschema` command. [#7130] * Support `tags` for OpenAPI schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#grouping-operations-with-tags). [#7184] * Support customizing the operation ID for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#operationid). [#7190] * Support OpenAPI components for schema generation. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#components). [#7124] * The following methods on `AutoSchema` become public API: `get_path_parameters`, `get_pagination_parameters`, `get_filter_parameters`, `get_request_body`, `get_responses`, `get_serializer`, `get_paginator`, `map_serializer`, `map_field`, `map_choice_field`, `map_field_validators`, `allows_filters`. See [the schema docs](https://www.django-rest-framework.org/api-guide/schemas/#autoschema) * Add support for Django 3.1's database-agnositic `JSONField`. [#7467] * `SearchFilter` now supports nested search on `JSONField` and `HStoreField` model fields. [#7121] * `SearchFilter` now supports searching on `annotate()` fields. [#6240] * The authtoken model no longer exposes the `pk` in the admin URL. [#7341] * Add `__repr__` for Request instances. [#7239] * UTF-8 decoding with Latin-1 fallback for basic auth credentials. [#7193] * CharField treats surrogate characters as a validation failure. [#7026] * Don't include callables as default values in schemas. [#7105] * Improve `ListField` schema output to include all available child information. [#7137] * Allow `default=False` to be included for `BooleanField` schema outputs. [#7165] * Include `"type"` information in `ChoiceField` schema outputs. [#7161] * Include `"type": "object"` on schema objects. [#7169] * Don't include component in schema output for DELETE requests. [#7229] * Fix schema types for `DecimalField`. [#7254] * Fix schema generation for `ObtainAuthToken` view. [#7211] * Support passing `context=...` to view `.get_serializer()` methods. [#7298] * Pass custom code to `PermissionDenied` if permission class has one set. [#7306] * Include "example" in schema pagination output. [#7275] * Default status code of 201 on schema output for POST requests. [#7206] * Use camelCase for operation IDs in schema output. [#7208] * Warn if duplicate operation IDs exist in schema output. [#7207] * Improve handling of decimal type when mapping `ChoiceField` to a schema output. [#7264] * Disable YAML aliases for OpenAPI schema outputs. [#7131] * Fix action URL names for APIs included under a namespaced URL. [#7287] * Update jQuery version from 3.4 to 3.5. [#7313] * Fix `UniqueTogether` handling when serializer fields use `source=...`. [#7143] * HTTP `HEAD` requests now set `self.action` correctly on a ViewSet instance. [#7223] * Return a valid OpenAPI schema for the case where no API schema paths exist. [#7125] * Include tests in package distribution. [#7145] * Allow type checkers to support annotations like `ModelSerializer[Author]`. [#7385] * Don't include invalid `charset=None` portion in the request `Content-Type` header when using APIClient. [#7400] * Fix `\Z`/`\z` tokens in OpenAPI regexs. [#7389] * 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 favor of `serializers.BooleanField` with `allow_null=True` [#7122] --- ## 3.11.x series ### 3.11.2 **Date**: 30th September 2020 * **Security**: Drop `urlize_quoted_links` template tag in favor of Django's built-in `urlize`. Removes a XSS vulnerability for some kinds of content in the browsable API. ### 3.11.1 **Date**: 5th August 2020 * Fix compat with Django 3.1 ### 3.11.0 **Date**: 12th December 2019 * Drop `.set_context` API [in favor of a `requires_context` marker](3.11-announcement.md#validator-default-context). * Changed default widget for TextField with choices to select box. [#6892][gh6892] * Supported nested writes on non-relational fields, such as JSONField. [#6916][gh6916] * Include request/response media types in OpenAPI schemas, based on configured parsers/renderers. [#6865][gh6865] * Include operation descriptions in OpenAPI schemas, based on the docstring on the view. [#6898][gh6898] * Fix representation of serializers with all optional fields in OpenAPI schemas. [#6941][gh6941], [#6944][gh6944] * Fix representation of `serializers.HStoreField` in OpenAPI schemas. [#6914][gh6914] * Fix OpenAPI generation when title or version is not provided. [#6912][gh6912] * Use `int64` representation for large integers in OpenAPI schemas. [#7018][gh7018] * Improved error messages if no `.to_representation` implementation is provided on a field subclass. [#6996][gh6996] * Fix for serializer classes that use multiple inheritance. [#6980][gh6980] * Fix for reversing Hyperlinked URL fields with percent encoded components in the path. [#7059][gh7059] * Update bootstrap to 3.4.1. [#6923][gh6923] ## 3.10.x series ### 3.10.3 **Date**: 4th September 2019 * Include API version in OpenAPI schema generation, defaulting to empty string. * Add pagination properties to OpenAPI response schemas. * Add missing "description" property to OpenAPI response schemas. * Only include "required" for non-empty cases in OpenAPI schemas. * Fix response schemas for "DELETE" case in OpenAPI schemas. * Use an array type for list view response schemas. * Use consistent `lowerInitialCamelCase` style in OpenAPI operation IDs. * Fix `minLength`/`maxLength`/`minItems`/`maxItems` properties in OpenAPI schemas. * Only call `FileField.url` once in serialization, for improved performance. * Fix an edge case where throttling calculations could error after a configuration change. ### 3.10.2 **Date**: 29th July 2019 * Various `OpenAPI` schema fixes. * Ability to specify urlconf in include_docs_urls. ### 3.10.1 **Date**: 17th July 2019 * Don't include autocomplete fields on TokenAuth admin, since it forces constraints on custom user models & admin. * Require `uritemplate` for OpenAPI schema generation, but not `coreapi`. ### 3.10.0 **Date**: [15th July 2019][3.10.0-milestone] * Switch to OpenAPI schema generation. * Drop Python 2 support. * Add `generateschema --generator_class` CLI option * Updated PyYaml dependency for OpenAPI schema generation to `pyyaml>=5.1` [#6680][gh6680] * Resolve DeprecationWarning with markdown. [#6317][gh6317] * Use `user.get_username` in templates, in preference to `user.username`. * Fix for cursor pagination issue that could occur after object deletions. * Fix for nullable fields with `source="*"` * Always apply all throttle classes during throttling checks. * Updates to jQuery and Markdown dependencies. * Don't strict disallow redundant `SerializerMethodField` field name arguments. * Don't render extra actions in browable API if not authenticated. * Strip null characters from search parameters. * Deprecate the `detail_route` decorator in favor of `action`, which accepts a `detail` bool. Use `@action(detail=True)` instead. [gh6687] * Deprecate the `list_route` decorator in favor of `action`, which accepts a `detail` bool. Use `@action(detail=False)` instead. [gh6687] ## 3.9.x series ### 3.9.4 **Date**: 10th May 2019 This is a maintenance release that fixes an error handling bug under Python 2. ### 3.9.3 **Date**: 29th April 2019 This is the last Django REST Framework release that will support Python 2. Be sure to upgrade to Python 3 before upgrading to Django REST Framework 3.10. * Adjusted the compat check for django-guardian to allow the last guardian version (v1.4.9) compatible with Python 2. [#6613][gh6613] ### 3.9.2 **Date**: [3rd March 2019][3.9.2-milestone] * Routers: invalidate `_urls` cache on `register()` [#6407][gh6407] * Deferred schema renderer creation to avoid requiring pyyaml. [#6416][gh6416] * Added 'request_forms' block to base.html [#6340][gh6340] * Fixed SchemaView to reset renderer on exception. [#6429][gh6429] * Update Django Guardian dependency. [#6430][gh6430] * Ensured support for Django 2.2 [#6422][gh6422] & [#6455][gh6455] * Made templates compatible with session-based CSRF. [#6207][gh6207] * Adjusted field `validators` to accept non-list iterables. [#6282][gh6282] * Added SearchFilter.get_search_fields() hook. [#6279][gh6279] * Fix DeprecationWarning when accessing collections.abc classes via collections [#6268][gh6268] * Allowed Q objects in limit_choices_to introspection. [#6472][gh6472] * Added lazy evaluation to composed permissions. [#6463][gh6463] * Add negation ~ operator to permissions composition [#6361][gh6361] * Avoided calling distinct on annotated fields in SearchFilter. [#6240][gh6240] * Introduced `RemovedInDRF…Warning` classes to simplify deprecations. [#6480][gh6480] ### 3.9.1 **Date**: [16th January 2019][3.9.1-milestone] * Resolve XSS issue in browsable API. [#6330][gh6330] * Upgrade Bootstrap to 3.4.0 to resolve XSS issue. * Resolve issues with composable permissions. [#6299][gh6299] * Respect `limit_choices_to` on foreign keys. [#6371][gh6371] ### 3.9.0 **Date**: [18th October 2018][3.9.0-milestone] * Improvements to ViewSet extra actions [#5605][gh5605] * Fix `action` support for ViewSet suffixes [#6081][gh6081] * Allow `action` docs sections [#6060][gh6060] * Deprecate the `Router.register` `base_name` argument in favor of `basename`. [#5990][gh5990] * Deprecate the `Router.get_default_base_name` method in favor of `Router.get_default_basename`. [#5990][gh5990] * Change `CharField` to disallow null bytes. [#6073][gh6073] To revert to the old behavior, subclass `CharField` and remove `ProhibitNullCharactersValidator` from the validators. ```python 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) ] ``` * Add `OpenAPIRenderer` and `generate_schema` management command. [#6229][gh6229] * Add OpenAPIRenderer by default, and add schema docs. [#6233][gh6233] * Allow permissions to be composed [#5753][gh5753] * Allow nullable BooleanField in Django 2.1 [#6183][gh6183] * Add testing of Python 3.7 support [#6141][gh6141] * Test using Django 2.1 final release. [#6109][gh6109] * Added djangorestframework-datatables to third-party packages [#5931][gh5931] * Change ISO 8601 date format to exclude year/month-only options [#5936][gh5936] * Update all pypi.python.org URLs to pypi.org [#5942][gh5942] * Ensure that html forms (multipart form data) respect optional fields [#5927][gh5927] * 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 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] * Fixed Javascript `e.indexOf` is not a function error [#5982][gh5982] * Fix schemas for extra actions [#5992][gh5992] * Improved get_error_detail to use error_dict/error_list [#5785][gh5785] * Improved URLs in Admin renderer [#5988][gh5988] * Add "Community" section to docs, minor cleanup [#5993][gh5993] * Moved guardian imports out of compat [#6054][gh6054] * Deprecate the `DjangoObjectPermissionsFilter` class, moved to the `djangorestframework-guardian` package. [#6075][gh6075] * Drop Django 1.10 support [#5657][gh5657] * Only catch TypeError/ValueError for object lookups [#6028][gh6028] * Handle models without .objects manager in ModelSerializer. [#6111][gh6111] * Improve ModelSerializer.create() error message. [#6112][gh6112] * Fix CSRF cookie check failure when using session auth with django 1.11.6+ [#6113][gh6113] * Updated JWT docs. [#6138][gh6138] * Fix autoescape not getting passed to urlize_quoted_links filter [#6191][gh6191] ## 3.8.x series ### 3.8.2 **Date**: [6th April 2018][3.8.2-milestone] * Fix `read_only` + `default` `unique_together` validation. [#5922][gh5922] * authtoken.views import coreapi from rest_framework.compat, not directly. [#5921][gh5921] * Docs: Add missing argument 'detail' to Route [#5920][gh5920] ### 3.8.1 **Date**: [4th April 2018][3.8.1-milestone] * Use old `url_name` behavior in route decorators [#5915][gh5915] For `list_route` and `detail_route` maintain the old behavior of `url_name`, basing it on the `url_path` instead of the function name. ### 3.8.0 **Date**: [3rd April 2018][3.8.0-milestone] * **Breaking Change**: Alter `read_only` plus `default` behavior. [#5886][gh5886] `read_only` fields will now **always** be excluded from writable fields. Previously `read_only` fields with a `default` value would use the `default` for create and update operations. In order to maintain the old behavior you may need to pass the value of `read_only` fields when calling `save()` in the view: def perform_create(self, serializer): serializer.save(owner=self.request.user) Alternatively you may override `save()` or `create()` or `update()` on the serializer as appropriate. * Correct allow_null behavior when required=False [#5888][gh5888] Without an explicit `default`, `allow_null` implies a default of `null` for outgoing serialization. Previously such fields were being skipped when read-only or otherwise not required. **Possible backwards compatibility break** if you were relying on such fields being excluded from the outgoing representation. In order to restore the old behavior you can override `data` to exclude the field when `None`. For example: @property def data(self): """ Drop `maybe_none` field if None. """ data = super().data if 'maybe_none' in data and data['maybe_none'] is None: del data['maybe_none'] return data * Refactor dynamic route generation and improve viewset action introspectibility. [#5705][gh5705] `ViewSet`s have been provided with new attributes and methods that allow it to introspect its set of actions and the details of the current action. * Merged `list_route` and `detail_route` into a single `action` decorator. * Get all extra actions on a `ViewSet` with `.get_extra_actions()`. * Extra actions now set the `url_name` and `url_path` on the decorated method. * `url_name` is now based on the function name, instead of the `url_path`, as the path is not always suitable (e.g., capturing arguments in the path). * Enable action url reversing through `.reverse_action()` method (added in 3.7.4) * Example reverse call: `self.reverse_action(self.custom_action.url_name)` * Add `detail` initkwarg to indicate if the current action is operating on a collection or a single instance. Additional changes: * Deprecated `list_route` & `detail_route` in favor of `action` decorator with `detail` boolean. * Deprecated dynamic list/detail route variants in favor of `DynamicRoute` with `detail` boolean. * Refactored the router's dynamic route generation. * `list_route` and `detail_route` maintain the old behavior of `url_name`, basing it on the `url_path` instead of the function name. * Fix formatting of the 3.7.4 release note [#5704][gh5704] * Docs: Update DRF Writable Nested Serializers references [#5711][gh5711] * Docs: Fixed typo in auth URLs example. [#5713][gh5713] * Improve composite field child errors [#5655][gh5655] * Disable HTML inputs for dict/list fields [#5702][gh5702] * Fix typo in HostNameVersioning doc [#5709][gh5709] * Use rsplit to get module and classname for imports [#5712][gh5712] * Formalize URLPatternsTestCase [#5703][gh5703] * Add exception translation test [#5700][gh5700] * Test staticfiles [#5701][gh5701] * Add drf-yasg to documentation and schema 3rd party packages [#5720][gh5720] * Remove unused `compat._resolve_model()` [#5733][gh5733] * Drop compat workaround for unsupported Python 3.2 [#5734][gh5734] * Prefer `iter(dict)` over `iter(dict.keys())` [#5736][gh5736] * Pass `python_requires` argument to setuptools [#5739][gh5739] * Remove unused links from docs [#5735][gh5735] * Prefer https protocol for links in docs when available [#5729][gh5729] * Add HStoreField, postgres fields tests [#5654][gh5654] * Always fully qualify ValidationError in docs [#5751][gh5751] * Remove unreachable code from ManualSchema [#5766][gh5766] * Allowed customizing API documentation code samples [#5752][gh5752] * Updated docs to use `pip show` [#5757][gh5757] * Load 'static' instead of 'staticfiles' in templates [#5773][gh5773] * Fixed a typo in `fields` docs [#5783][gh5783] * Refer to "NamespaceVersioning" instead of "NamespacedVersioning" in the documentation [#5754][gh5754] * ErrorDetail: add `__eq__`/`__ne__` and `__repr__` [#5787][gh5787] * Replace `background-attachment: fixed` in docs [#5777][gh5777] * Make 404 & 403 responses consistent with `exceptions.APIException` output [#5763][gh5763] * Small fix to API documentation: schemas [#5796][gh5796] * Fix schema generation for PrimaryKeyRelatedField [#5764][gh5764] * Represent serializer DictField as an Object in schema [#5765][gh5765] * Added docs example reimplementing ObtainAuthToken [#5802][gh5802] * Add schema to the ObtainAuthToken view [#5676][gh5676] * Fix request formdata handling [#5800][gh5800] * Fix authtoken views imports [#5818][gh5818] * Update pytest, isort [#5815][gh5815] [#5817][gh5817] [#5894][gh5894] * Fixed active timezone handling for non ISO8601 datetimes. [#5833][gh5833] * Made TemplateHTMLRenderer render IntegerField inputs when value is `0`. [#5834][gh5834] * Corrected endpoint in tutorial instructions [#5835][gh5835] * Add Django Rest Framework Role Filters to Third party packages [#5809][gh5809] * Use single copy of static assets. Update jQuery [#5823][gh5823] * Changes ternary conditionals to be PEP308 compliant [#5827][gh5827] * Added links to 'A Todo List API with React' and 'Blog API' tutorials [#5837][gh5837] * Fix comment typo in ModelSerializer [#5844][gh5844] * Add admin to installed apps to avoid test failures. [#5870][gh5870] * Fixed schema for UUIDField in SimpleMetadata. [#5872][gh5872] * Corrected docs on router include with namespaces. [#5843][gh5843] * Test using model objects for dotted source default [#5880][gh5880] * Allow traversing nullable related fields [#5849][gh5849] * Added: Tutorial: Django REST with React (Django 2.0) [#5891][gh5891] * Add `LimitOffsetPagination.get_count` to allow method override [#5846][gh5846] * Don't show hidden fields in metadata [#5854][gh5854] * Enable OrderingFilter to handle an empty tuple (or list) for the 'ordering' field. [#5899][gh5899] * Added generic 500 and 400 JSON error handlers. [#5904][gh5904] ## 3.7.x series ### 3.7.7 **Date**: [21st December 2017][3.7.7-milestone] * Fix typo to include *.mo locale files to packaging. [#5697][gh5697], [#5695][gh5695] ### 3.7.6 **Date**: [21st December 2017][3.7.6-milestone] * Add missing *.ico icon files to packaging. ### 3.7.5 **Date**: [21st December 2017][3.7.5-milestone] * Add missing *.woff2 font files to packaging. [#5692][gh5692] * Add missing *.mo locale files to packaging. [#5695][gh5695], [#5696][gh5696] ### 3.7.4 **Date**: [20th December 2017][3.7.4-milestone] * Schema: Extract method for `manual_fields` processing [#5633][gh5633] Allows for easier customization of `manual_fields` processing, for example to provide per-method manual fields. `AutoSchema` adds `get_manual_fields`, as the intended override point, and a utility method `update_fields`, to handle by-name field replacement from a list, which, in general, you are not expected to override. Note: `AutoSchema.__init__` now ensures `manual_fields` is a list. Previously may have been stored internally as `None`. * Remove ulrparse compatibility shim; use six instead [#5579][gh5579] * Drop compat wrapper for `TimeDelta.total_seconds()` [#5577][gh5577] * Clean up all whitespace throughout project [#5578][gh5578] * Compat cleanup [#5581][gh5581] * Add pygments CSS block in browsable API views [#5584][gh5584] [#5587][gh5587] * Remove `set_rollback()` from compat [#5591][gh5591] * Fix request body/POST access [#5590][gh5590] * Rename test to reference correct issue [#5610][gh5610] * Documentation Fixes [#5611][gh5611] [#5612][gh5612] * Remove references to unsupported Django versions in docs and code [#5602][gh5602] * Test Serializer exclude for declared fields [#5599][gh5599] * Fixed schema generation for filter backends [#5613][gh5613] * Minor cleanup for ModelSerializer tests [#5598][gh5598] * Reimplement request attribute access w/ `__getattr__` [#5617][gh5617] * Fixed SchemaJSRenderer renders invalid Javascript [#5607][gh5607] * Make Django 2.0 support official/explicit [#5619][gh5619] * Perform type check on passed request argument [#5618][gh5618] * Fix AttributeError hiding on request authenticators [#5600][gh5600] * Update test requirements [#5626][gh5626] * Docs: `Serializer._declared_fields` enable modifying fields on a serializer [#5629][gh5629] * Fix packaging [#5624][gh5624] * Fix readme rendering for PyPI, add readme build to CI [#5625][gh5625] * Update tutorial [#5622][gh5622] * Non-required fields with `allow_null=True` should not imply a default value [#5639][gh5639] * Docs: Add `allow_null` serialization output note [#5641][gh5641] * Update to use the Django 2.0 release in tox.ini [#5645][gh5645] * Fix `Serializer.data` for Browsable API rendering when provided invalid `data` [#5646][gh5646] * Docs: Note AutoSchema limitations on bare APIView [#5649][gh5649] * Add `.basename` and `.reverse_action()` to ViewSet [#5648][gh5648] * Docs: Fix typos in serializers documentation [#5652][gh5652] * Fix `override_settings` compat [#5668][gh5668] * Add DEFAULT_SCHEMA_CLASS setting [#5658][gh5658] * Add docs note re generated BooleanField being `required=False` [#5665][gh5665] * Add 'dist' build [#5656][gh5656] * Fix typo in docstring [#5678][gh5678] * Docs: Add `UNAUTHENTICATED_USER = None` note [#5679][gh5679] * Update OPTIONS example from “Documenting Your API” [#5680][gh5680] * Docs: Add note on object permissions for FBVs [#5681][gh5681] * Docs: Add example to `to_representation` docs [#5682][gh5682] * Add link to Classy DRF in docs [#5683][gh5683] * Document ViewSet.action [#5685][gh5685] * Fix schema docs typo [#5687][gh5687] * Fix URL pattern parsing in schema generation [#5689][gh5689] * Add example using `source=‘*’` to custom field docs. [#5688][gh5688] * Fix format_suffix_patterns behavior with Django 2 path() routes [#5691][gh5691] ### 3.7.3 **Date**: [6th November 2017][3.7.3-milestone] * Fix `AppRegistryNotReady` error from contrib.auth view imports [#5567][gh5567] ### 3.7.2 **Date**: [6th November 2017][3.7.2-milestone] * Fixed Django 2.1 compatibility due to removal of django.contrib.auth.login()/logout() views. [#5510][gh5510] * Add missing import for TextLexer. [#5512][gh5512] * Adding examples and documentation for caching [#5514][gh5514] * Include date and date-time format for schema generation [#5511][gh5511] * Use triple backticks for markdown code blocks [#5513][gh5513] * Interactive docs - make bottom sidebar items sticky [#5516][gh5516] * Clarify pagination system check [#5524][gh5524] * Stop JSONBoundField mangling invalid JSON [#5527][gh5527] * Have JSONField render as textarea in Browsable API [#5530][gh5530] * Schema: Exclude OPTIONS/HEAD for ViewSet actions [#5532][gh5532] * Fix ordering for dotted sources [#5533][gh5533] * Fix: Fields with `allow_null=True` should imply a default serialization value [#5518][gh5518] * Ensure Location header is strictly a 'str', not subclass. [#5544][gh5544] * Add import to example in api-guide/parsers [#5547][gh5547] * Catch OverflowError for "out of range" datetimes [#5546][gh5546] * Add djangorestframework-rapidjson to third party packages [#5549][gh5549] * Increase test coverage for `drf_create_token` command [#5550][gh5550] * Add trove classifier for Python 3.6 support. [#5555][gh5555] * Add pip cache support to the Travis CI configuration [#5556][gh5556] * Rename [`wheel`] section to [`bdist_wheel`] as the former is legacy [#5557][gh5557] * Fix invalid escape sequence deprecation warnings [#5560][gh5560] * Add interactive docs error template [#5548][gh5548] * Add rounding parameter to DecimalField [#5562][gh5562] * Fix all BytesWarning caught during tests [#5561][gh5561] * Use dict and set literals instead of calls to dict() and set() [#5559][gh5559] * Change ImageField validation pattern, use validators from DjangoImageField [#5539][gh5539] * Fix processing unicode symbols in query_string by Python 2 [#5552][gh5552] ### 3.7.1 **Date**: [16th October 2017][3.7.1-milestone] * Fix Interactive documentation always uses false for boolean fields in requests [#5492][gh5492] * Improve compatibility with Django 2.0 alpha. [#5500][gh5500] [#5503][gh5503] * Improved handling of schema naming collisions [#5486][gh5486] * Added additional docs and tests around providing a default value for dotted `source` fields [#5489][gh5489] ### 3.7.0 **Date**: [6th October 2017][3.7.0-milestone] * Fix `DjangoModelPermissions` to ensure user authentication before calling the view's `get_queryset()` method. As a side effect, this changes the order of the HTTP method permissions and authentication checks, and 405 responses will only be returned when authenticated. If you want to replicate the old behavior, see the PR for details. [#5376][gh5376] * Deprecated `exclude_from_schema` on `APIView` and `api_view` decorator. Set `schema = None` or `@schema(None)` as appropriate. [#5422][gh5422] * Timezone-aware `DateTimeField`s now respect active or default `timezone` during serialization, instead of always using UTC. [#5435][gh5435] Resolves inconsistency whereby instances were serialized with supplied datetime for `create` but UTC for `retrieve`. [#3732][gh3732] **Possible backwards compatibility break** if you were relying on datetime strings being UTC. Have client interpret datetimes or [set default or active timezone (docs)][djangodocs-set-timezone] to UTC if needed. * Removed DjangoFilterBackend inline with deprecation policy. Use `django_filters.rest_framework.FilterSet` and/or `django_filters.rest_framework.DjangoFilterBackend` instead. [#5273][gh5273] * Don't strip microseconds from `time` when encoding. Makes consistent with `datetime`. **BC Change**: Previously only milliseconds were encoded. [#5440][gh5440] * Added `STRICT_JSON` setting (default `True`) to raise exception for the extended float values (`nan`, `inf`, `-inf`) accepted by Python's `json` module. **BC Change**: Previously these values would converted to corresponding strings. Set `STRICT_JSON` to `False` to restore the previous behavior. [#5265][gh5265] * Add support for `page_size` parameter in CursorPaginator class [#5250][gh5250] * Make `DEFAULT_PAGINATION_CLASS` `None` by default. **BC Change**: If your were **just** setting `PAGE_SIZE` to enable pagination you will need to add `DEFAULT_PAGINATION_CLASS`. The previous default was `rest_framework.pagination.PageNumberPagination`. There is a system check warning to catch this case. You may silence that if you are setting pagination class on a per-view basis. [#5170][gh5170] * Catch `APIException` from `get_serializer_fields` in schema generation. [#5443][gh5443] * Allow custom authentication and permission classes when using `include_docs_urls` [#5448][gh5448] * Defer translated string evaluation on validators. [#5452][gh5452] * Added default value for 'detail' param into 'ValidationError' exception [#5342][gh5342] * Adjust schema get_filter_fields rules to match framework [#5454][gh5454] * Updated test matrix to add Django 2.0 and drop Django 1.8 & 1.9 **BC Change**: This removes Django 1.8 and Django 1.9 from Django REST Framework supported versions. [#5457][gh5457] * Fixed a deprecation warning in serializers.ModelField [#5058][gh5058] * Added a more explicit error message when `get_queryset` returned `None` [#5348][gh5348] * Fix docs for Response `data` description [#5361][gh5361] * Fix __pycache__/.pyc excludes when packaging [#5373][gh5373] * Fix default value handling for dotted sources [#5375][gh5375] * Ensure content_type is set when passing empty body to RequestFactory [#5351][gh5351] * Fix ErrorDetail Documentation [#5380][gh5380] * Allow optional content in the generic content form [#5372][gh5372] * Updated supported values for the NullBooleanField [#5387][gh5387] * Fix ModelSerializer custom named fields with source on model [#5388][gh5388] * Fixed the MultipleFieldLookupMixin documentation example to properly check for object level permission [#5398][gh5398] * Update get_object() example in permissions.md [#5401][gh5401] * Fix authtoken management command [#5415][gh5415] * Fix schema generation markdown [#5421][gh5421] * Allow `ChoiceField.choices` to be set dynamically [#5426][gh5426] * Add the project layout to the quickstart [#5434][gh5434] * Reuse 'apply_markdown' function in 'render_markdown' templatetag [#5469][gh5469] * Added links to `drf-openapi` package in docs [#5470][gh5470] * Added docstrings code highlighting with pygments [#5462][gh5462] * Fixed documentation rendering for views named `data` [#5472][gh5472] * Docs: Clarified 'to_internal_value()' validation behavior [#5466][gh5466] * Fix missing six.text_type() call on APIException.__str__ [#5476][gh5476] * Document documentation.py [#5478][gh5478] * Fix naming collisions in Schema Generation [#5464][gh5464] * Call Django's authenticate function with the request object [#5295][gh5295] * Update coreapi JS to 0.1.1 [#5479][gh5479] * Have `is_list_view` recognize RetrieveModel… views [#5480][gh5480] * Remove Django 1.8 & 1.9 compatibility code [#5481][gh5481] * Remove deprecated schema code from DefaultRouter [#5482][gh5482] * Refactor schema generation to allow per-view customization. **BC Change**: `SchemaGenerator.get_serializer_fields` has been refactored as `AutoSchema.get_serializer_fields` and drops the `view` argument [#5354][gh5354] ## 3.6.x series ### 3.6.4 **Date**: [21st August 2017][3.6.4-milestone] * Ignore any invalidly formed query parameters for OrderingFilter. [#5131][gh5131] * Improve memory footprint when reading large JSON requests. [#5147][gh5147] * Fix schema generation for pagination. [#5161][gh5161] * Fix exception when `HTML_CUTOFF` is set to `None`. [#5174][gh5174] * Fix browsable API not supporting `multipart/form-data` correctly. [#5176][gh5176] * Fixed `test_hyperlinked_related_lookup_url_encoded_exists`. [#5179][gh5179] * Make sure max_length is in FileField kwargs. [#5186][gh5186] * Fix `list_route` & `detail_route` with kwargs contains curly bracket in `url_path` [#5187][gh5187] * Add Django manage command to create a DRF user Token. [#5188][gh5188] * Ensure API documentation templates do not check for user authentication [#5162][gh5162] * Fix special case where OneToOneField is also primary key. [#5192][gh5192] * Added aria-label and a new region for accessibility purposes in base.html [#5196][gh5196] * Quote nested API parameters in api.js. [#5214][gh5214] * Set ViewSet args/kwargs/request before dispatch. [#5229][gh5229] * Added unicode support to SlugField. [#5231][gh5231] * Fix HiddenField appears in Raw Data form initial content. [#5259][gh5259] * Raise validation error on invalid timezone parsing. [#5261][gh5261] * Fix SearchFilter to-many behavior/performance. [#5264][gh5264] * Simplified chained comparisons and minor code fixes. [#5276][gh5276] * RemoteUserAuthentication, docs, and tests. [#5306][gh5306] * Revert "Cached the field's root and context property" [#5313][gh5313] * Fix introspection of list field in schema. [#5326][gh5326] * Fix interactive docs for multiple nested and extra methods. [#5334][gh5334] * Fix/remove undefined template var "schema" [#5346][gh5346] ### 3.6.3 **Date**: [12th May 2017][3.6.3-milestone] * Raise 404 if a URL lookup results in ValidationError. ([#5126][gh5126]) * Honor http_method_names on class based view, when generating API schemas. ([#5085][gh5085]) * Allow overridden `get_limit` in LimitOffsetPagination to return all records. ([#4437][gh4437]) * Fix partial update for the ListSerializer. ([#4222][gh4222]) * Render JSONField control correctly in browsable API. ([#4999][gh4999], [#5042][gh5042]) * Raise validation errors for invalid datetime in given timezone. ([#4987][gh4987]) * Support restricting doc & schema shortcuts to a subset of urls. ([#4979][gh4979]) * Resolve SchemaGenerator error with paginators that have no `page_size` attribute. ([#5086][gh5086], [#3692][gh3692]) * Resolve HyperlinkedRelatedField exception on string with %20 instead of space. ([#4748][gh4748], [#5078][gh5078]) * Customizable schema generator classes. ([#5082][gh5082]) * Update existing vary headers in response instead of overwriting them. ([#5047][gh5047]) * Support passing `.as_view()` to view instance. ([#5053][gh5053]) * Use correct exception handler when settings overridden on a view. ([#5055][gh5055], [#5054][gh5054]) * Update Boolean field to support 'yes' and 'no' values. ([#5038][gh5038]) * Fix unique validator for ChoiceField. ([#5004][gh5004], [#5026][gh5026], [#5028][gh5028]) * JavaScript cleanups in API Docs. ([#5001][gh5001]) * Include URL path regexs in API schemas where valid. ([#5014][gh5014]) * Correctly set scheme in coreapi TokenAuthentication. ([#5000][gh5000], [#4994][gh4994]) * HEAD requests on ViewSets should not return 405. ([#4705][gh4705], [#4973][gh4973], [#4864][gh4864]) * Support usage of 'source' in `extra_kwargs`. ([#4688][gh4688]) * Fix invalid content type for schema.js ([#4968][gh4968]) * Fix DjangoFilterBackend inheritance issues. ([#5089][gh5089], [#5117][gh5117]) ### 3.6.2 **Date**: [10th March 2017][3.6.2-milestone] * Support for Safari & IE in API docs. ([#4959][gh4959], [#4961][gh4961]) * Add missing `mark_safe` in API docs template tags. ([#4952][gh4952], [#4953][gh4953]) * Add missing glyphicon fonts. ([#4950][gh4950], [#4951][gh4951]) * Fix One-to-one fields in API docs. ([#4955][gh4955], [#4956][gh4956]) * Test clean ups. ([#4949][gh4949]) ### 3.6.1 **Date**: [9th March 2017][3.6.1-milestone] * Ensure `markdown` dependency is optional. ([#4947][gh4947]) ### 3.6.0 **Date**: [9th March 2017][3.6.0-milestone] See the [release announcement][3.6-release]. --- ## 3.5.x series ### 3.5.4 **Date**: [10th February 2017][3.5.4-milestone] * Add max_length and min_length arguments for ListField. ([#4877][gh4877]) * Add per-view custom exception handler support. ([#4753][gh4753]) * Support disabling of declared fields on serializer subclasses. ([#4764][gh4764]) * Support custom view names on `@list_route` and `@detail_route` endpoints. ([#4821][gh4821]) * Correct labels for fields in login template when custom user model is used. ([#4841][gh4841]) * Whitespace fixes for descriptions generated from docstrings. ([#4759][gh4759], [#4869][gh4869], [#4870][gh4870]) * Better error reporting when schemas are returned by views without a schema renderer. ([#4790][gh4790]) * Fix for returned response of `PUT` requests when `prefetch_related` is used. ([#4661][gh4661], [#4668][gh4668]) * Fix for breadcrumb view names. ([#4750][gh4750]) * Fix for RequestsClient ensuring fully qualified URLs. ([#4678][gh4678]) * Fix for incorrect behavior of writable-nested fields check in some cases. ([#4634][gh4634], [#4669][gh4669]) * Resolve Django deprecation warnings. ([#4712][gh4712]) * Various cleanup of test cases. ### 3.5.3 **Date**: [7th November 2016][3.5.3-milestone] * Don't raise incorrect FilterSet deprecation warnings. ([#4660][gh4660], [#4643][gh4643], [#4644][gh4644]) * Schema generation should not raise 404 when a view permission class does. ([#4645][gh4645], [#4646][gh4646]) * Add `autofocus` support for input controls. ([#4650][gh4650]) ### 3.5.2 **Date**: [1st November 2016][3.5.2-milestone] * Restore exception tracebacks in Python 2.7. ([#4631][gh4631], [#4638][gh4638]) * Properly display dicts in the admin console. ([#4532][gh4532], [#4636][gh4636]) * Fix is_simple_callable with variable args, kwargs. ([#4622][gh4622], [#4602][gh4602]) * Support 'on'/'off' literals with BooleanField. ([#4640][gh4640], [#4624][gh4624]) * Enable cursor pagination of value querysets. ([#4569][gh4569]) * Fix support of get_full_details() for Throttled exceptions. ([#4627][gh4627]) * Fix FilterSet proxy. ([#4620][gh4620]) * Make serializer fields import explicit. ([#4628][gh4628]) * Drop redundant requests adapter. ([#4639][gh4639]) ### 3.5.1 **Date**: [21st October 2016][3.5.1-milestone] * Make `rest_framework/compat.py` imports. ([#4612][gh4612], [#4608][gh4608], [#4601][gh4601]) * Fix bug in schema base path generation. ([#4611][gh4611], [#4605][gh4605]) * Fix broken case of ListSerializer with single item. ([#4609][gh4609], [#4606][gh4606]) * Remove bare `raise` for Python 3.5 compat. ([#4600][gh4600]) ### 3.5.0 **Date**: [20th October 2016][3.5.0-milestone] --- ## 3.4.x series ### 3.4.7 **Date**: [21st September 2016][3.4.7-milestone] * Fallback behavior for request parsing when request.POST already accessed. ([#3951][gh3951], [#4500][gh4500]) * Fix regression of `RegexField`. ([#4489][gh4489], [#4490][gh4490], [#2617][gh2617]) * Missing comma in `admin.html` causing CSRF error. ([#4472][gh4472], [#4473][gh4473]) * Fix response rendering with empty context. ([#4495][gh4495]) * Fix indentation regression in API listing. ([#4493][gh4493]) * Fixed an issue where the incorrect value is set to `ResolverMatch.func_name` of api_view decorated view. ([#4465][gh4465], [#4462][gh4462]) * Fix `APIClient.get()` when path contains unicode arguments ([#4458][gh4458]) ### 3.4.6 **Date**: [23rd August 2016][3.4.6-milestone] * Fix malformed Javascript in browsable API. ([#4435][gh4435]) * Skip HiddenField from Schema fields. ([#4425][gh4425], [#4429][gh4429]) * Improve Create to show the original exception traceback. ([#3508][gh3508]) * Fix `AdminRenderer` display of PK only related fields. ([#4419][gh4419], [#4423][gh4423]) ### 3.4.5 **Date**: [19th August 2016][3.4.5-milestone] * Improve debug error handling. ([#4416][gh4416], [#4409][gh4409]) * Allow custom CSRF_HEADER_NAME setting. ([#4415][gh4415], [#4410][gh4410]) * Include .action attribute on viewsets when generating schemas. ([#4408][gh4408], [#4398][gh4398]) * Do not include request.FILES items in request.POST. ([#4407][gh4407]) * Fix rendering of checkbox multiple. ([#4403][gh4403]) * Fix docstring of Field.get_default. ([#4404][gh4404]) * Replace utf8 character with its ascii counterpart in README. ([#4412][gh4412]) ### 3.4.4 **Date**: [12th August 2016][3.4.4-milestone] * Ensure views are fully initialized when generating schemas. ([#4373][gh4373], [#4382][gh4382], [#4383][gh4383], [#4279][gh4279], [#4278][gh4278]) * Add form field descriptions to schemas. ([#4387][gh4387]) * Fix category generation for schema endpoints. ([#4391][gh4391], [#4394][gh4394], [#4390][gh4390], [#4386][gh4386], [#4376][gh4376], [#4329][gh4329]) * Don't strip empty query params when paginating. ([#4392][gh4392], [#4393][gh4393], [#4260][gh4260]) * Do not re-run query for empty results with LimitOffsetPagination. ([#4201][gh4201], [#4388][gh4388]) * Stricter type validation for CharField. ([#4380][gh4380], [#3394][gh3394]) * RelatedField.choices should preserve non-string values. ([#4111][gh4111], [#4379][gh4379], [#3365][gh3365]) * Test case for rendering checkboxes in vertical form style. ([#4378][gh4378], [#3868][gh3868], [#3868][gh3868]) * Show error traceback HTML in browsable API ([#4042][gh4042], [#4172][gh4172]) * Fix handling of ALLOWED_VERSIONS and no DEFAULT_VERSION. [#4370][gh4370] * Allow `max_digits=None` on DecimalField. ([#4377][gh4377], [#4372][gh4372]) * Limit queryset when rendering relational choices. ([#4375][gh4375], [#4122][gh4122], [#3329][gh3329], [#3330][gh3330], [#3877][gh3877]) * Resolve form display with ChoiceField, MultipleChoiceField and non-string choices. ([#4374][gh4374], [#4119][gh4119], [#4121][gh4121], [#4137][gh4137], [#4120][gh4120]) * Fix call to TemplateHTMLRenderer.resolve_context() fallback method. ([#4371][gh4371]) ### 3.4.3 **Date**: [5th August 2016][3.4.3-milestone] * Include fallback for users of older TemplateHTMLRenderer internal API. ([#4361][gh4361]) ### 3.4.2 **Date**: [5th August 2016][3.4.2-milestone] * Include kwargs passed to 'as_view' when generating schemas. ([#4359][gh4359], [#4330][gh4330], [#4331][gh4331]) * Access `request.user.is_authenticated` as property not method, under Django 1.10+ ([#4358][gh4358], [#4354][gh4354]) * Filter HEAD out from schemas. ([#4357][gh4357]) * extra_kwargs takes precedence over uniqueness kwargs. ([#4198][gh4198], [#4199][gh4199], [#4349][gh4349]) * Correct descriptions when tabs are used in code indentation. ([#4345][gh4345], [#4347][gh4347])* * Change template context generation in TemplateHTMLRenderer. ([#4236][gh4236]) * Serializer defaults should not be included in partial updates. ([#4346][gh4346], [#3565][gh3565]) * Consistent behavior & descriptive error from FileUploadParser when filename not included. ([#4340][gh4340], [#3610][gh3610], [#4292][gh4292], [#4296][gh4296]) * DecimalField quantizes incoming digitals. ([#4339][gh4339], [#4318][gh4318]) * Handle non-string input for IP fields. ([#4335][gh4335], [#4336][gh4336], [#4338][gh4338]) * Fix leading slash handling when Schema generation includes a root URL. ([#4332][gh4332]) * Test cases for DictField with allow_null options. ([#4348][gh4348]) * Update tests from Django 1.10 beta to Django 1.10. ([#4344][gh4344]) ### 3.4.1 **Date**: [28th July 2016][3.4.1-milestone] * Added `root_renderers` argument to `DefaultRouter`. ([#4323][gh4323], [#4268][gh4268]) * Added `url` and `schema_url` arguments. ([#4321][gh4321], [#4308][gh4308], [#4305][gh4305]) * Unique together checks should apply to read-only fields which have a default. ([#4316][gh4316], [#4294][gh4294]) * Set view.format_kwarg in schema generator. ([#4293][gh4293], [#4315][gh4315]) * Fix schema generator for views with `pagination_class = None`. ([#4314][gh4314], [#4289][gh4289]) * Fix schema generator for views with no `get_serializer_class`. ([#4265][gh4265], [#4285][gh4285]) * Fixes for media type parameters in `Accept` and `Content-Type` headers. ([#4287][gh4287], [#4313][gh4313], [#4281][gh4281]) * Use verbose_name instead of object_name in error messages. ([#4299][gh4299]) * Minor version update to Twitter Bootstrap. ([#4307][gh4307]) * SearchFilter raises error when using with related field. ([#4302][gh4302], [#4303][gh4303], [#4298][gh4298]) * Adding support for RFC 4918 status codes. ([#4291][gh4291]) * Add LICENSE.md to the built wheel. ([#4270][gh4270]) * Serializing "complex" field returns None instead of the value since 3.4 ([#4272][gh4272], [#4273][gh4273], [#4288][gh4288]) ### 3.4.0 **Date**: [14th July 2016][3.4.0-milestone] * Don't strip microseconds in JSON output. ([#4256][gh4256]) * Two slightly different iso 8601 datetime serialization. ([#4255][gh4255]) * Resolve incorrect inclusion of media type parameters. ([#4254][gh4254]) * Response Content-Type potentially malformed. ([#4253][gh4253]) * Fix setup.py error on some platforms. ([#4246][gh4246]) * Move alternate formats in coreapi into separate packages. ([#4244][gh4244]) * Add localize keyword argument to `DecimalField`. ([#4233][gh4233]) * Fix issues with routers for custom list-route and detail-routes. ([#4229][gh4229]) * Namespace versioning with nested namespaces. ([#4219][gh4219]) * Robust uniqueness checks. ([#4217][gh4217]) * Minor refactoring of `must_call_distinct`. ([#4215][gh4215]) * Overridable offset cutoff in CursorPagination. ([#4212][gh4212]) * Pass through strings as-in with date/time fields. ([#4196][gh4196]) * Add test confirming that required=False is valid on a relational field. ([#4195][gh4195]) * In LimitOffsetPagination `limit=0` should revert to default limit. ([#4194][gh4194]) * Exclude read_only=True fields from unique_together validation & add docs. ([#4192][gh4192]) * Handle bytestrings in JSON. ([#4191][gh4191]) * JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. ([#4187][gh4187]) * JSONField(binary=True) represents using binary strings, which JSONRenderer does not support. ([#4185][gh4185]) * More robust form rendering in the browsable API. ([#4181][gh4181]) * Empty cases of `.validated_data` and `.errors` as lists not dicts for ListSerializer. ([#4180][gh4180]) * Schemas & client libraries. ([#4179][gh4179]) * Removed `AUTH_USER_MODEL` compat property. ([#4176][gh4176]) * Clean up existing deprecation warnings. ([#4166][gh4166]) * Django 1.10 support. ([#4158][gh4158]) * Updated jQuery version to 1.12.4. ([#4157][gh4157]) * More robust default behavior on OrderingFilter. ([#4156][gh4156]) * 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 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]) * Fix incorrectly named zh-hans and zh-hant locale path. ([#4103][gh4103]) * 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 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]) * No auth view failing permission should raise 403. ([#4040][gh4040]) * Fix string_types / text_types confusion. ([#4025][gh4025]) * Do not list related field choices in OPTIONS requests. ([#4021][gh4021]) * Fix typo. ([#4008][gh4008]) * Reorder initializing the view. ([#4006][gh4006]) * Type error in DjangoObjectPermissionsFilter on Python 3.4. ([#4005][gh4005]) * Fixed use of deprecated Query.aggregates. ([#4003][gh4003]) * Fix blank lines around docstrings. ([#4002][gh4002]) * Fixed admin pagination when limit is 0. ([#3990][gh3990]) * OrderingFilter adjustments. ([#3983][gh3983]) * Non-required serializer related fields. ([#3976][gh3976]) * Using safer calling way of "@api_view" in tutorial. ([#3971][gh3971]) * ListSerializer doesn't handle unique_together constraints. ([#3970][gh3970]) * Add missing migration file. ([#3968][gh3968]) * `OrderingFilter` should call `get_serializer_class()` to determine default fields. ([#3964][gh3964]) * Remove old Django checks from tests and compat. ([#3953][gh3953]) * Support callable as the value of `initial` for any `serializer.Field`. ([#3943][gh3943]) * Prevented unnecessary distinct() call in SearchFilter. ([#3938][gh3938]) * Fix None UUID ForeignKey serialization. ([#3936][gh3936]) * Drop EOL Django 1.7. ([#3933][gh3933]) * Add missing space in serializer error message. ([#3926][gh3926]) * Fixed _force_text_recursive typo. ([#3908][gh3908]) * Attempt to address Django 2.0 deprecate warnings related to `field.rel`. ([#3906][gh3906]) * Fix parsing multipart data using a nested serializer with list. ([#3820][gh3820]) * Resolving APIs URL to different namespaces. ([#3816][gh3816]) * Do not HTML-escape `help_text` in Browsable API forms. ([#3812][gh3812]) * OPTIONS fetches and shows all possible foreign keys in choices field. ([#3751][gh3751]) * Django 1.9 deprecation warnings ([#3729][gh3729]) * Test case for #3598 ([#3710][gh3710]) * Adding support for multiple values for search filter. ([#3541][gh3541]) * Use get_serializer_class in ordering filter. ([#3487][gh3487]) * Serializers with many=True should return empty list rather than empty dict. ([#3476][gh3476]) * LimitOffsetPagination limit=0 fix. ([#3444][gh3444]) * Enable Validators to defer string evaluation and handle new string format. ([#3438][gh3438]) * Unique validator is executed and breaks if field is invalid. ([#3381][gh3381]) * Do not ignore overridden View.get_view_name() in breadcrumbs. ([#3273][gh3273]) * Retry form rendering when rendering with serializer fails. ([#3164][gh3164]) * Unique constraint prevents nested serializers from updating. ([#2996][gh2996]) * Uniqueness validators should not be run for excluded (read_only) fields. ([#2848][gh2848]) * UniqueValidator raises exception for nested objects. ([#2403][gh2403]) * `lookup_type` is deprecated in favor of `lookup_expr`. ([#4259][gh4259]) --- ## 3.3.x series ### 3.3.3 **Date**: [14th March 2016][3.3.3-milestone]. * Remove version string from templates. Thanks to @blag for the report and fixes. ([#3878][gh3878], [#3913][gh3913], [#3912][gh3912]) * Fixes vertical html layout for `BooleanField`. Thanks to Mikalai Radchuk for the fix. ([#3910][gh3910]) * Silenced deprecation warnings on Django 1.8. Thanks to Simon Charette for the fix. ([#3903][gh3903]) * Internationalization for authtoken. Thanks to Michael Nacharov for the fix. ([#3887][gh3887], [#3968][gh3968]) * Fix `Token` model as `abstract` when the authtoken application isn't declared. Thanks to Adam Thomas for the report. ([#3860][gh3860], [#3858][gh3858]) * Improve Markdown version compatibility. Thanks to Michael J. Schultz for the fix. ([#3604][gh3604], [#3842][gh3842]) * `QueryParameterVersioning` does not use `DEFAULT_VERSION` setting. Thanks to Brad Montgomery for the fix. ([#3833][gh3833]) * Add an explicit `on_delete` on the models. Thanks to Mads Jensen for the fix. ([#3832][gh3832]) * Fix `DateField.to_representation` to work with Python 2 unicode. Thanks to Mikalai Radchuk for the fix. ([#3819][gh3819]) * Fixed `TimeField` not handling string times. Thanks to Areski Belaid for the fix. ([#3809][gh3809]) * Avoid updates of `Meta.extra_kwargs`. Thanks to Kevin Massey for the report and fix. ([#3805][gh3805], [#3804][gh3804]) * Fix nested validation error being rendered incorrectly. Thanks to Craig de Stigter for the fix. ([#3801][gh3801]) * Document how to avoid CSRF and missing button issues with `django-crispy-forms`. Thanks to Emmanuelle Delescolle, José Padilla and Luis San Pablo for the report, analysis and fix. ([#3787][gh3787], [#3636][gh3636], [#3637][gh3637]) * Improve Rest Framework Settings file setup time. Thanks to Miles Hutson for the report and Mads Jensen for the fix. ([#3786][gh3786], [#3815][gh3815]) * Improve authtoken compatibility with Django 1.9. Thanks to S. Andrew Sheppard for the fix. ([#3785][gh3785]) * Fix `Min/MaxValueValidator` transfer from a model's `DecimalField`. Thanks to Kevin Brown for the fix. ([#3774][gh3774]) * Improve HTML title in the Browsable API. Thanks to Mike Lissner for the report and fix. ([#3769][gh3769]) * Fix `AutoFilterSet` to inherit from `default_filter_set`. Thanks to Tom Linford for the fix. ([#3753][gh3753]) * Fix transifex config to handle the new Chinese language codes. Thanks to @nypisces for the report and fix. ([#3739][gh3739]) * `DateTimeField` does not handle empty values correctly. Thanks to Mick Parker for the report and fix. ([#3731][gh3731], [#3726][gh3728]) * Raise error when setting a removed rest_framework setting. Thanks to Luis San Pablo for the fix. ([#3715][gh3715]) * Add missing csrf_token in AdminRenderer post form. Thanks to Piotr Śniegowski for the fix. ([#3703][gh3703]) * Refactored `_get_reverse_relationships()` to use correct `to_field`. Thanks to Benjamin Phillips for the fix. ([#3696][gh3696]) * Document the use of `get_queryset` for `RelatedField`. Thanks to Ryan Hiebert for the fix. ([#3605][gh3605]) * Fix empty pk detection in HyperlinkRelatedField.get_url. Thanks to @jslang for the fix ([#3962][gh3962]) ### 3.3.2 **Date**: [14th December 2015][3.3.2-milestone]. * `ListField` enforces input is a list. ([#3513][gh3513]) * Fix regression hiding raw data form. ([#3600][gh3600], [#3578][gh3578]) * Fix Python 3.5 compatibility. ([#3534][gh3534], [#3626][gh3626]) * Allow setting a custom Django Paginator in `pagination.PageNumberPagination`. ([#3631][gh3631], [#3684][gh3684]) * Fix relational fields without `to_fields` attribute. ([#3635][gh3635], [#3634][gh3634]) * Fix `template.render` deprecation warnings for Django 1.9. ([#3654][gh3654]) * Sort response headers in browsable API renderer. ([#3655][gh3655]) * Use related_objects api for Django 1.9+. ([#3656][gh3656], [#3252][gh3252]) * Add confirm modal when deleting. ([#3228][gh3228], [#3662][gh3662]) * Reveal previously hidden AttributeErrors and TypeErrors while calling has_[object_]permissions. ([#3668][gh3668]) * Make DRF compatible with multi template engine in Django 1.8. ([#3672][gh3672]) * Update `NestedBoundField` to also handle empty string when rendering its form. ([#3677][gh3677]) * Fix UUID validation to properly catch invalid input types. ([#3687][gh3687], [#3679][gh3679]) * Fix caching issues. ([#3628][gh3628], [#3701][gh3701]) * Fix Admin and API browser for views without a filter_class. ([#3705][gh3705], [#3596][gh3596], [#3597][gh3597]) * Add app_name to rest_framework.urls. ([#3714][gh3714]) * Improve authtoken's views to support url versioning. ([#3718][gh3718], [#3723][gh3723]) ### 3.3.1 **Date**: [4th November 2015][3.3.1-milestone]. * Resolve parsing bug when accessing `request.POST` ([#3592][gh3592]) * Correctly deal with `to_field` referring to primary key. ([#3593][gh3593]) * Allow filter HTML to render when no `filter_class` is defined. ([#3560][gh3560]) * Fix admin rendering issues. ([#3564][gh3564], [#3556][gh3556]) * Fix issue with DecimalValidator. ([#3568][gh3568]) ### 3.3.0 **Date**: [28th October 2015][3.3.0-milestone]. * HTML controls for filters. ([#3315][gh3315]) * Forms API. ([#3475][gh3475]) * AJAX browsable API. ([#3410][gh3410]) * Added JSONField. ([#3454][gh3454]) * Correctly map `to_field` when creating `ModelSerializer` relational fields. ([#3526][gh3526]) * Include keyword arguments when mapping `FilePathField` to a serializer field. ([#3536][gh3536]) * Map appropriate model `error_messages` on `ModelSerializer` uniqueness constraints. ([#3435][gh3435]) * Include `max_length` constraint for `ModelSerializer` fields mapped from TextField. ([#3509][gh3509]) * Added support for Django 1.9. ([#3450][gh3450], [#3525][gh3525]) * Removed support for Django 1.5 & 1.6. ([#3421][gh3421], [#3429][gh3429]) * Removed 'south' migrations. ([#3495][gh3495]) --- ## 3.2.x series ### 3.2.5 **Date**: [27th October 2015][3.2.5-milestone]. * Escape `username` in optional logout tag. ([#3550][gh3550]) ### 3.2.4 **Date**: [21th September 2015][3.2.4-milestone]. * Don't error on missing `ViewSet.search_fields` attribute. ([#3324][gh3324], [#3323][gh3323]) * Fix `allow_empty` not working on serializers with `many=True`. ([#3361][gh3361], [#3364][gh3364]) * Let `DurationField` accepts integers. ([#3359][gh3359]) * Multi-level dictionaries not supported in multipart requests. ([#3314][gh3314]) * Fix `ListField` truncation on HTTP PATCH ([#3415][gh3415], [#2761][gh2761]) ### 3.2.3 **Date**: [24th August 2015][3.2.3-milestone]. * Added `html_cutoff` and `html_cutoff_text` for limiting select dropdowns. ([#3313][gh3313]) * Added regex style to `SearchFilter`. ([#3316][gh3316]) * Resolve issues with setting blank HTML fields. ([#3318][gh3318]) ([#3321][gh3321]) * Correctly display existing 'select multiple' values in browsable API forms. ([#3290][gh3290]) * Resolve duplicated validation message for `IPAddressField`. ([#3249[gh3249]) ([#3250][gh3250]) * Fix to ensure admin renderer continues to work when pagination is disabled. ([#3275][gh3275]) * Resolve error with `LimitOffsetPagination` when count=0, offset=0. ([#3303][gh3303]) ### 3.2.2 **Date**: [13th August 2015][3.2.2-milestone]. * Add `display_value()` method for use when displaying relational field select inputs. ([#3254][gh3254]) * Fix issue with `BooleanField` checkboxes incorrectly displaying as checked. ([#3258][gh3258]) * Ensure empty checkboxes properly set `BooleanField` to `False` in all cases. ([#2776][gh2776]) * Allow `WSGIRequest.FILES` property without raising incorrect deprecated error. ([#3261][gh3261]) * Resolve issue with rendering nested serializers in forms. ([#3260][gh3260]) * Raise an error if user accidentally pass a serializer instance to a response, rather than data. ([#3241][gh3241]) ### 3.2.1 **Date**: [7th August 2015][3.2.1-milestone]. * Fix for relational select widgets rendering without any choices. ([#3237][gh3237]) * Fix for `1`, `0` rendering as `true`, `false` in the admin interface. [#3227][gh3227]) * Fix for ListFields with single value in HTML form input. ([#3238][gh3238]) * Allow `request.FILES` for compat with Django's `HTTPRequest` class. ([#3239][gh3239]) ### 3.2.0 **Date**: [6th August 2015][3.2.0-milestone]. * Add `AdminRenderer`. ([#2926][gh2926]) * Add `FilePathField`. ([#1854][gh1854]) * Add `allow_empty` to `ListField`. ([#2250][gh2250]) * Support django-guardian 1.3. ([#3165][gh3165]) * Support grouped choices. ([#3225][gh3225]) * Support error forms in browsable API. ([#3024][gh3024]) * Allow permission classes to customize the error message. ([#2539][gh2539]) * Support `source=` on hyperlinked fields. ([#2690][gh2690]) * `ListField(allow_null=True)` now allows null as the list value, not null items in the list. ([#2766][gh2766]) * `ManyToMany()` maps to `allow_empty=False`, `ManyToMany(blank=True)` maps to `allow_empty=True`. ([#2804][gh2804]) * Support custom serialization styles for primary key fields. ([#2789][gh2789]) * `OPTIONS` requests support nested representations. ([#2915][gh2915]) * Set `view.action == "metadata"` for viewsets with `OPTIONS` requests. ([#3115][gh3115]) * Support `allow_blank` on `UUIDField`. ([#3130][gh#3130]) * Do not display view docstrings with 401 or 403 response codes. ([#3216][gh3216]) * Resolve Django 1.8 deprecation warnings. ([#2886][gh2886]) * Fix for `DecimalField` validation. ([#3139][gh3139]) * Fix behavior of `allow_blank=False` when used with `trim_whitespace=True`. ([#2712][gh2712]) * Fix issue with some field combinations incorrectly mapping to an invalid `allow_blank` argument. ([#3011][gh3011]) * Fix for output representations with prefetches and modified querysets. ([#2704][gh2704], [#2727][gh2727]) * Fix assertion error when CursorPagination is provided with certain invalid query parameters. (#2920)[gh2920]. * Fix `UnicodeDecodeError` when invalid characters included in header with `TokenAuthentication`. ([#2928][gh2928]) * Fix transaction rollbacks with `@non_atomic_requests` decorator. ([#3016][gh3016]) * Fix duplicate results issue with Oracle databases using `SearchFilter`. ([#2935][gh2935]) * Fix checkbox alignment and rendering in browsable API forms. ([#2783][gh2783]) * Fix for unsaved file objects which should use `"url": null` in the representation. ([#2759][gh2759]) * Fix field value rendering in browsable API. ([#2416][gh2416]) * Fix `HStoreField` to include `allow_blank=True` in `DictField` mapping. ([#2659][gh2659]) * Numerous other cleanups, improvements to error messaging, private API & minor fixes. --- ## 3.1.x series ### 3.1.3 **Date**: [4th June 2015][3.1.3-milestone]. * Add `DurationField`. ([#2481][gh2481], [#2989][gh2989]) * Add `format` argument to `UUIDField`. ([#2788][gh2788], [#3000][gh3000]) * `MultipleChoiceField` empties incorrectly on a partial update using multipart/form-data ([#2993][gh2993], [#2894][gh2894]) * Fix a bug in options related to read-only `RelatedField`. ([#2981][gh2981], [#2811][gh2811]) * Fix nested serializers with `unique_together` relations. ([#2975][gh2975]) * Allow unexpected values for `ChoiceField`/`MultipleChoiceField` representations. ([#2839][gh2839], [#2940][gh2940]) * Rollback the transaction on error if `ATOMIC_REQUESTS` is set. ([#2887][gh2887], [#2034][gh2034]) * Set the action on a view when override_method regardless of its None-ness. ([#2933][gh2933]) * `DecimalField` accepts `2E+2` as 200 and validates decimal place correctly. ([#2948][gh2948], [#2947][gh2947]) * Support basic authentication with custom `UserModel` that change `username`. ([#2952][gh2952]) * `IPAddressField` improvements. ([#2747][gh2747], [#2618][gh2618], [#3008][gh3008]) * Improve `DecimalField` for easier subclassing. ([#2695][gh2695]) ### 3.1.2 **Date**: [13rd May 2015][3.1.2-milestone]. * `DateField.to_representation` can handle str and empty values. ([#2656][gh2656], [#2687][gh2687], [#2869][gh2869]) * Use default reason phrases from HTTP standard. ([#2764][gh2764], [#2763][gh2763]) * Raise error when `ModelSerializer` used with abstract model. ([#2757][gh2757], [#2630][gh2630]) * Handle reversal of non-API view_name in `HyperLinkedRelatedField` ([#2724][gh2724], [#2711][gh2711]) * Don't require pk strictly for related fields. ([#2745][gh2745], [#2754][gh2754]) * Metadata detects null boolean field type. ([#2762][gh2762]) * Proper handling of depth in nested serializers. ([#2798][gh2798]) * Display viewset without paginator. ([#2807][gh2807]) * Don't check for deprecated `.model` attribute in permissions ([#2818][gh2818]) * Restrict integer field to integers and strings. ([#2835][gh2835], [#2836][gh2836]) * Improve `IntegerField` to use compiled decimal regex. ([#2853][gh2853]) * Prevent empty `queryset` to raise AssertionError. ([#2862][gh2862]) * `DjangoModelPermissions` rely on `get_queryset`. ([#2863][gh2863]) * Check `AcceptHeaderVersioning` with content negotiation in place. ([#2868][gh2868]) * Allow `DjangoObjectPermissions` to use views that define `get_queryset`. ([#2905][gh2905]) ### 3.1.1 **Date**: [23rd March 2015][3.1.1-milestone]. * **Security fix**: Escape tab switching cookie name in browsable API. * Display input forms in browsable API if `serializer_class` is used, even when `get_serializer` method does not exist on the view. ([#2743][gh2743]) * Use a password input for the AuthTokenSerializer. ([#2741][gh2741]) * Fix missing anchor closing tag after next button. ([#2691][gh2691]) * Fix `lookup_url_kwarg` handling in viewsets. ([#2685][gh2685], [#2591][gh2591]) * Fix problem with importing `rest_framework.views` in `apps.py` ([#2678][gh2678]) * LimitOffsetPagination raises `TypeError` if PAGE_SIZE not set ([#2667][gh2667], [#2700][gh2700]) * German translation for `min_value` field error message references `max_value`. ([#2645][gh2645]) * Remove `MergeDict`. ([#2640][gh2640]) * Support serializing unsaved models with related fields. ([#2637][gh2637], [#2641][gh2641]) * Allow blank/null on radio.html choices. ([#2631][gh2631]) ### 3.1.0 **Date**: [5th March 2015][3.1.0-milestone]. For full details see the [3.1 release announcement](3.1-announcement.md). --- ## 3.0.x series ### 3.0.5 **Date**: [10th February 2015][3.0.5-milestone]. * Fix a bug where `_closable_objects` breaks pickling. ([#1850][gh1850], [#2492][gh2492]) * Allow non-standard `User` models with `Throttling`. ([#2524][gh2524]) * Support custom `User.db_table` in TokenAuthentication migration. ([#2479][gh2479]) * Fix misleading `AttributeError` tracebacks on `Request` objects. ([#2530][gh2530], [#2108][gh2108]) * `ManyRelatedField.get_value` clearing field on partial update. ([#2475][gh2475]) * Removed '.model' shortcut from code. ([#2486][gh2486]) * Fix `detail_route` and `list_route` mutable argument. ([#2518][gh2518]) * Prefetching the user object when getting the token in `TokenAuthentication`. ([#2519][gh2519]) ### 3.0.4 **Date**: [28th January 2015][3.0.4-milestone]. * Django 1.8a1 support. ([#2425][gh2425], [#2446][gh2446], [#2441][gh2441]) * Add `DictField` and support Django 1.8 `HStoreField`. ([#2451][gh2451], [#2106][gh2106]) * Add `UUIDField` and support Django 1.8 `UUIDField`. ([#2448][gh2448], [#2433][gh2433], [#2432][gh2432]) * `BaseRenderer.render` now raises `NotImplementedError`. ([#2434][gh2434]) * Fix timedelta JSON serialization on Python 2.6. ([#2430][gh2430]) * `ResultDict` and `ResultList` now appear as standard dict/list. ([#2421][gh2421]) * Fix visible `HiddenField` in the HTML form of the web browsable API page. ([#2410][gh2410]) * Use `OrderedDict` for `RelatedField.choices`. ([#2408][gh2408]) * Fix ident format when using `HTTP_X_FORWARDED_FOR`. ([#2401][gh2401]) * Fix invalid key with memcached while using throttling. ([#2400][gh2400]) * Fix `FileUploadParser` with version 3.x. ([#2399][gh2399]) * Fix the serializer inheritance. ([#2388][gh2388]) * Fix caching issues with `ReturnDict`. ([#2360][gh2360]) ### 3.0.3 **Date**: [8th January 2015][3.0.3-milestone]. * Fix `MinValueValidator` on `models.DateField`. ([#2369][gh2369]) * Fix serializer missing context when pagination is used. ([#2355][gh2355]) * Namespaced router URLs are now supported by the `DefaultRouter`. ([#2351][gh2351]) * `required=False` allows omission of value for output. ([#2342][gh2342]) * Use textarea input for `models.TextField`. ([#2340][gh2340]) * Use custom `ListSerializer` for pagination if required. ([#2331][gh2331], [#2327][gh2327]) * Better behavior with null and '' for blank HTML fields. ([#2330][gh2330]) * Ensure fields in `exclude` are model fields. ([#2319][gh2319]) * Fix `IntegerField` and `max_length` argument incompatibility. ([#2317][gh2317]) * Fix the YAML encoder for 3.0 serializers. ([#2315][gh2315], [#2283][gh2283]) * Fix the behavior of empty HTML fields. ([#2311][gh2311], [#1101][gh1101]) * Fix Metaclass attribute depth ignoring fields attribute. ([#2287][gh2287]) * Fix `format_suffix_patterns` to work with Django's `i18n_patterns`. ([#2278][gh2278]) * Ability to customize router URLs for custom actions, using `url_path`. ([#2010][gh2010]) * Don't install Django REST Framework as egg. ([#2386][gh2386]) ### 3.0.2 **Date**: [17th December 2014][3.0.2-milestone]. * Ensure `request.user` is made available to response middleware. ([#2155][gh2155]) * `Client.logout()` also cancels any existing `force_authenticate`. ([#2218][gh2218], [#2259][gh2259]) * Extra assertions and better checks to preventing incorrect serializer API use. ([#2228][gh2228], [#2234][gh2234], [#2262][gh2262], [#2263][gh2263], [#2266][gh2266], [#2267][gh2267], [#2289][gh2289], [#2291][gh2291]) * Fixed `min_length` message for `CharField`. ([#2255][gh2255]) * Fix `UnicodeDecodeError`, which can occur on serializer `repr`. ([#2270][gh2270], [#2279][gh2279]) * Fix empty HTML values when a default is provided. ([#2280][gh2280], [#2294][gh2294]) * Fix `SlugRelatedField` raising `UnicodeEncodeError` when used as a multiple choice input. ([#2290][gh2290]) ### 3.0.1 **Date**: [11th December 2014][3.0.1-milestone]. * More helpful error message when the default Serializer `create()` fails. ([#2013][gh2013]) * Raise error when attempting to save serializer if data is not valid. ([#2098][gh2098]) * Fix `FileUploadParser` breaks with empty file names and multiple upload handlers. ([#2109][gh2109]) * Improve `BindingDict` to support standard dict-functions. ([#2135][gh2135], [#2163][gh2163]) * Add `validate()` to `ListSerializer`. ([#2168][gh2168], [#2225][gh2225], [#2232][gh2232]) * Fix JSONP renderer failing to escape some characters. ([#2169][gh2169], [#2195][gh2195]) * Add missing default style for `FileField`. ([#2172][gh2172]) * Actions are required when calling `ViewSet.as_view()`. ([#2175][gh2175]) * Add `allow_blank` to `ChoiceField`. ([#2184][gh2184], [#2239][gh2239]) * Cosmetic fixes in the HTML renderer. ([#2187][gh2187]) * Raise error if `fields` on serializer is not a list of strings. ([#2193][gh2193], [#2213][gh2213]) * Improve checks for nested creates and updates. ([#2194][gh2194], [#2196][gh2196]) * `validated_attrs` argument renamed to `validated_data` in `Serializer` `create()`/`update()`. ([#2197][gh2197]) * Remove deprecated code to reflect the dropped Django versions. ([#2200][gh2200]) * Better serializer errors for nested writes. ([#2202][gh2202], [#2215][gh2215]) * Fix pagination and custom permissions incompatibility. ([#2205][gh2205]) * Raise error if `fields` on serializer is not a list of strings. ([#2213][gh2213]) * Add missing translation markers for relational fields. ([#2231][gh2231]) * Improve field lookup behavior for dicts/mappings. ([#2244][gh2244], [#2243][gh2243]) * Optimized hyperlinked PK. ([#2242][gh2242]) ### 3.0.0 **Date**: 1st December 2014 For full details see the [3.0 release announcement](3.0-announcement.md). --- For older release notes, [please see the version 2.x documentation][old-release-notes]. [cite]: http://www.catb.org/~esr/writings/cathedral-bazaar/cathedral-bazaar/ar01s04.html [deprecation-policy]: #deprecation-policy [django-deprecation-policy]: https://docs.djangoproject.com/en/stable/internals/release-process/#internal-release-deprecation-policy [old-release-notes]: https://github.com/encode/django-rest-framework/blob/version-2.4.x/docs/topics/release-notes.md [3.6-release]: 3.6-announcement.md [3.0.1-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.0.1+Release%22 [3.0.2-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.0.2+Release%22 [3.0.3-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.0.3+Release%22 [3.0.4-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.0.4+Release%22 [3.0.5-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.0.5+Release%22 [3.1.0-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.1.0+Release%22 [3.1.1-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.1.1+Release%22 [3.1.2-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.1.2+Release%22 [3.1.3-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.1.3+Release%22 [3.2.0-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.2.0+Release%22 [3.2.1-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.2.1+Release%22 [3.2.2-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.2.2+Release%22 [3.2.3-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.2.3+Release%22 [3.2.4-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.2.4+Release%22 [3.2.5-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.2.5+Release%22 [3.3.0-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.3.0+Release%22 [3.3.1-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.3.1+Release%22 [3.3.2-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.3.2+Release%22 [3.3.3-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.3.3+Release%22 [3.4.0-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.0+Release%22 [3.4.1-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.1+Release%22 [3.4.2-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.2+Release%22 [3.4.3-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.3+Release%22 [3.4.4-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.4+Release%22 [3.4.5-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.5+Release%22 [3.4.6-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.6+Release%22 [3.4.7-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.4.7+Release%22 [3.5.0-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.5.0+Release%22 [3.5.1-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.5.1+Release%22 [3.5.2-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.5.2+Release%22 [3.5.3-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.5.3+Release%22 [3.5.4-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.5.4+Release%22 [3.6.0-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.6.0+Release%22 [3.6.1-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.6.1+Release%22 [3.6.2-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.6.2+Release%22 [3.6.3-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.6.3+Release%22 [3.6.4-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.6.4+Release%22 [3.7.0-milestone]: https://github.com/encode/django-rest-framework/issues?q=milestone%3A%223.7.0+Release%22 [3.7.1-milestone]: https://github.com/encode/django-rest-framework/milestone/58?closed=1 [3.7.2-milestone]: https://github.com/encode/django-rest-framework/milestone/59?closed=1 [3.7.3-milestone]: https://github.com/encode/django-rest-framework/milestone/60?closed=1 [3.7.4-milestone]: https://github.com/encode/django-rest-framework/milestone/62?closed=1 [3.7.5-milestone]: https://github.com/encode/django-rest-framework/milestone/63?closed=1 [3.7.6-milestone]: https://github.com/encode/django-rest-framework/milestone/64?closed=1 [3.7.7-milestone]: https://github.com/encode/django-rest-framework/milestone/65?closed=1 [3.8.0-milestone]: https://github.com/encode/django-rest-framework/milestone/61?closed=1 [3.8.1-milestone]: https://github.com/encode/django-rest-framework/milestone/67?closed=1 [3.8.2-milestone]: https://github.com/encode/django-rest-framework/milestone/68?closed=1 [3.9.0-milestone]: https://github.com/encode/django-rest-framework/milestone/66?closed=1 [3.9.1-milestone]: https://github.com/encode/django-rest-framework/milestone/70?closed=1 [3.9.2-milestone]: https://github.com/encode/django-rest-framework/milestone/71?closed=1 [3.10.0-milestone]: https://github.com/encode/django-rest-framework/milestone/69?closed=1 [gh2013]: https://github.com/encode/django-rest-framework/issues/2013 [gh2098]: https://github.com/encode/django-rest-framework/issues/2098 [gh2109]: https://github.com/encode/django-rest-framework/issues/2109 [gh2135]: https://github.com/encode/django-rest-framework/issues/2135 [gh2163]: https://github.com/encode/django-rest-framework/issues/2163 [gh2168]: https://github.com/encode/django-rest-framework/issues/2168 [gh2169]: https://github.com/encode/django-rest-framework/issues/2169 [gh2172]: https://github.com/encode/django-rest-framework/issues/2172 [gh2175]: https://github.com/encode/django-rest-framework/issues/2175 [gh2184]: https://github.com/encode/django-rest-framework/issues/2184 [gh2187]: https://github.com/encode/django-rest-framework/issues/2187 [gh2193]: https://github.com/encode/django-rest-framework/issues/2193 [gh2194]: https://github.com/encode/django-rest-framework/issues/2194 [gh2195]: https://github.com/encode/django-rest-framework/issues/2195 [gh2196]: https://github.com/encode/django-rest-framework/issues/2196 [gh2197]: https://github.com/encode/django-rest-framework/issues/2197 [gh2200]: https://github.com/encode/django-rest-framework/issues/2200 [gh2202]: https://github.com/encode/django-rest-framework/issues/2202 [gh2205]: https://github.com/encode/django-rest-framework/issues/2205 [gh2213]: https://github.com/encode/django-rest-framework/issues/2213 [gh2213]: https://github.com/encode/django-rest-framework/issues/2213 [gh2215]: https://github.com/encode/django-rest-framework/issues/2215 [gh2225]: https://github.com/encode/django-rest-framework/issues/2225 [gh2231]: https://github.com/encode/django-rest-framework/issues/2231 [gh2232]: https://github.com/encode/django-rest-framework/issues/2232 [gh2239]: https://github.com/encode/django-rest-framework/issues/2239 [gh2242]: https://github.com/encode/django-rest-framework/issues/2242 [gh2243]: https://github.com/encode/django-rest-framework/issues/2243 [gh2244]: https://github.com/encode/django-rest-framework/issues/2244 [gh2155]: https://github.com/encode/django-rest-framework/issues/2155 [gh2218]: https://github.com/encode/django-rest-framework/issues/2218 [gh2228]: https://github.com/encode/django-rest-framework/issues/2228 [gh2234]: https://github.com/encode/django-rest-framework/issues/2234 [gh2255]: https://github.com/encode/django-rest-framework/issues/2255 [gh2259]: https://github.com/encode/django-rest-framework/issues/2259 [gh2262]: https://github.com/encode/django-rest-framework/issues/2262 [gh2263]: https://github.com/encode/django-rest-framework/issues/2263 [gh2266]: https://github.com/encode/django-rest-framework/issues/2266 [gh2267]: https://github.com/encode/django-rest-framework/issues/2267 [gh2270]: https://github.com/encode/django-rest-framework/issues/2270 [gh2279]: https://github.com/encode/django-rest-framework/issues/2279 [gh2280]: https://github.com/encode/django-rest-framework/issues/2280 [gh2289]: https://github.com/encode/django-rest-framework/issues/2289 [gh2290]: https://github.com/encode/django-rest-framework/issues/2290 [gh2291]: https://github.com/encode/django-rest-framework/issues/2291 [gh2294]: https://github.com/encode/django-rest-framework/issues/2294 [gh1101]: https://github.com/encode/django-rest-framework/issues/1101 [gh2010]: https://github.com/encode/django-rest-framework/issues/2010 [gh2278]: https://github.com/encode/django-rest-framework/issues/2278 [gh2283]: https://github.com/encode/django-rest-framework/issues/2283 [gh2287]: https://github.com/encode/django-rest-framework/issues/2287 [gh2311]: https://github.com/encode/django-rest-framework/issues/2311 [gh2315]: https://github.com/encode/django-rest-framework/issues/2315 [gh2317]: https://github.com/encode/django-rest-framework/issues/2317 [gh2319]: https://github.com/encode/django-rest-framework/issues/2319 [gh2327]: https://github.com/encode/django-rest-framework/issues/2327 [gh2330]: https://github.com/encode/django-rest-framework/issues/2330 [gh2331]: https://github.com/encode/django-rest-framework/issues/2331 [gh2340]: https://github.com/encode/django-rest-framework/issues/2340 [gh2342]: https://github.com/encode/django-rest-framework/issues/2342 [gh2351]: https://github.com/encode/django-rest-framework/issues/2351 [gh2355]: https://github.com/encode/django-rest-framework/issues/2355 [gh2369]: https://github.com/encode/django-rest-framework/issues/2369 [gh2386]: https://github.com/encode/django-rest-framework/issues/2386 [gh2425]: https://github.com/encode/django-rest-framework/issues/2425 [gh2446]: https://github.com/encode/django-rest-framework/issues/2446 [gh2441]: https://github.com/encode/django-rest-framework/issues/2441 [gh2451]: https://github.com/encode/django-rest-framework/issues/2451 [gh2106]: https://github.com/encode/django-rest-framework/issues/2106 [gh2448]: https://github.com/encode/django-rest-framework/issues/2448 [gh2433]: https://github.com/encode/django-rest-framework/issues/2433 [gh2432]: https://github.com/encode/django-rest-framework/issues/2432 [gh2434]: https://github.com/encode/django-rest-framework/issues/2434 [gh2430]: https://github.com/encode/django-rest-framework/issues/2430 [gh2421]: https://github.com/encode/django-rest-framework/issues/2421 [gh2410]: https://github.com/encode/django-rest-framework/issues/2410 [gh2408]: https://github.com/encode/django-rest-framework/issues/2408 [gh2401]: https://github.com/encode/django-rest-framework/issues/2401 [gh2400]: https://github.com/encode/django-rest-framework/issues/2400 [gh2399]: https://github.com/encode/django-rest-framework/issues/2399 [gh2388]: https://github.com/encode/django-rest-framework/issues/2388 [gh2360]: https://github.com/encode/django-rest-framework/issues/2360 [gh1850]: https://github.com/encode/django-rest-framework/issues/1850 [gh2108]: https://github.com/encode/django-rest-framework/issues/2108 [gh2475]: https://github.com/encode/django-rest-framework/issues/2475 [gh2479]: https://github.com/encode/django-rest-framework/issues/2479 [gh2486]: https://github.com/encode/django-rest-framework/issues/2486 [gh2492]: https://github.com/encode/django-rest-framework/issues/2492 [gh2518]: https://github.com/encode/django-rest-framework/issues/2518 [gh2519]: https://github.com/encode/django-rest-framework/issues/2519 [gh2524]: https://github.com/encode/django-rest-framework/issues/2524 [gh2530]: https://github.com/encode/django-rest-framework/issues/2530 [gh2691]: https://github.com/encode/django-rest-framework/issues/2691 [gh2685]: https://github.com/encode/django-rest-framework/issues/2685 [gh2591]: https://github.com/encode/django-rest-framework/issues/2591 [gh2678]: https://github.com/encode/django-rest-framework/issues/2678 [gh2667]: https://github.com/encode/django-rest-framework/issues/2667 [gh2700]: https://github.com/encode/django-rest-framework/issues/2700 [gh2645]: https://github.com/encode/django-rest-framework/issues/2645 [gh2640]: https://github.com/encode/django-rest-framework/issues/2640 [gh2637]: https://github.com/encode/django-rest-framework/issues/2637 [gh2641]: https://github.com/encode/django-rest-framework/issues/2641 [gh2631]: https://github.com/encode/django-rest-framework/issues/2631 [gh2741]: https://github.com/encode/django-rest-framework/issues/2641 [gh2743]: https://github.com/encode/django-rest-framework/issues/2643 [gh2656]: https://github.com/encode/django-rest-framework/issues/2656 [gh2687]: https://github.com/encode/django-rest-framework/issues/2687 [gh2869]: https://github.com/encode/django-rest-framework/issues/2869 [gh2764]: https://github.com/encode/django-rest-framework/issues/2764 [gh2763]: https://github.com/encode/django-rest-framework/issues/2763 [gh2757]: https://github.com/encode/django-rest-framework/issues/2757 [gh2630]: https://github.com/encode/django-rest-framework/issues/2630 [gh2724]: https://github.com/encode/django-rest-framework/issues/2724 [gh2711]: https://github.com/encode/django-rest-framework/issues/2711 [gh2745]: https://github.com/encode/django-rest-framework/issues/2745 [gh2754]: https://github.com/encode/django-rest-framework/issues/2754 [gh2762]: https://github.com/encode/django-rest-framework/issues/2762 [gh2798]: https://github.com/encode/django-rest-framework/issues/2798 [gh2807]: https://github.com/encode/django-rest-framework/issues/2807 [gh2818]: https://github.com/encode/django-rest-framework/issues/2818 [gh2835]: https://github.com/encode/django-rest-framework/issues/2835 [gh2836]: https://github.com/encode/django-rest-framework/issues/2836 [gh2853]: https://github.com/encode/django-rest-framework/issues/2853 [gh2862]: https://github.com/encode/django-rest-framework/issues/2862 [gh2863]: https://github.com/encode/django-rest-framework/issues/2863 [gh2868]: https://github.com/encode/django-rest-framework/issues/2868 [gh2905]: https://github.com/encode/django-rest-framework/issues/2905 [gh2481]: https://github.com/encode/django-rest-framework/issues/2481 [gh2989]: https://github.com/encode/django-rest-framework/issues/2989 [gh2788]: https://github.com/encode/django-rest-framework/issues/2788 [gh3000]: https://github.com/encode/django-rest-framework/issues/3000 [gh2993]: https://github.com/encode/django-rest-framework/issues/2993 [gh2894]: https://github.com/encode/django-rest-framework/issues/2894 [gh2981]: https://github.com/encode/django-rest-framework/issues/2981 [gh2811]: https://github.com/encode/django-rest-framework/issues/2811 [gh2975]: https://github.com/encode/django-rest-framework/issues/2975 [gh2839]: https://github.com/encode/django-rest-framework/issues/2839 [gh2940]: https://github.com/encode/django-rest-framework/issues/2940 [gh2887]: https://github.com/encode/django-rest-framework/issues/2887 [gh2034]: https://github.com/encode/django-rest-framework/issues/2034 [gh2933]: https://github.com/encode/django-rest-framework/issues/2933 [gh2948]: https://github.com/encode/django-rest-framework/issues/2948 [gh2947]: https://github.com/encode/django-rest-framework/issues/2947 [gh2952]: https://github.com/encode/django-rest-framework/issues/2952 [gh2747]: https://github.com/encode/django-rest-framework/issues/2747 [gh2618]: https://github.com/encode/django-rest-framework/issues/2618 [gh3008]: https://github.com/encode/django-rest-framework/issues/3008 [gh2695]: https://github.com/encode/django-rest-framework/issues/2695 [gh1854]: https://github.com/encode/django-rest-framework/issues/1854 [gh2250]: https://github.com/encode/django-rest-framework/issues/2250 [gh2416]: https://github.com/encode/django-rest-framework/issues/2416 [gh2539]: https://github.com/encode/django-rest-framework/issues/2539 [gh2659]: https://github.com/encode/django-rest-framework/issues/2659 [gh2690]: https://github.com/encode/django-rest-framework/issues/2690 [gh2704]: https://github.com/encode/django-rest-framework/issues/2704 [gh2712]: https://github.com/encode/django-rest-framework/issues/2712 [gh2727]: https://github.com/encode/django-rest-framework/issues/2727 [gh2759]: https://github.com/encode/django-rest-framework/issues/2759 [gh2766]: https://github.com/encode/django-rest-framework/issues/2766 [gh2783]: https://github.com/encode/django-rest-framework/issues/2783 [gh2789]: https://github.com/encode/django-rest-framework/issues/2789 [gh2804]: https://github.com/encode/django-rest-framework/issues/2804 [gh2886]: https://github.com/encode/django-rest-framework/issues/2886 [gh2915]: https://github.com/encode/django-rest-framework/issues/2915 [gh2920]: https://github.com/encode/django-rest-framework/issues/2920 [gh2926]: https://github.com/encode/django-rest-framework/issues/2926 [gh2928]: https://github.com/encode/django-rest-framework/issues/2928 [gh2935]: https://github.com/encode/django-rest-framework/issues/2935 [gh3011]: https://github.com/encode/django-rest-framework/issues/3011 [gh3016]: https://github.com/encode/django-rest-framework/issues/3016 [gh3024]: https://github.com/encode/django-rest-framework/issues/3024 [gh3115]: https://github.com/encode/django-rest-framework/issues/3115 [gh3139]: https://github.com/encode/django-rest-framework/issues/3139 [gh3165]: https://github.com/encode/django-rest-framework/issues/3165 [gh3216]: https://github.com/encode/django-rest-framework/issues/3216 [gh3225]: https://github.com/encode/django-rest-framework/issues/3225 [gh3237]: https://github.com/encode/django-rest-framework/issues/3237 [gh3227]: https://github.com/encode/django-rest-framework/issues/3227 [gh3238]: https://github.com/encode/django-rest-framework/issues/3238 [gh3239]: https://github.com/encode/django-rest-framework/issues/3239 [gh3254]: https://github.com/encode/django-rest-framework/issues/3254 [gh3258]: https://github.com/encode/django-rest-framework/issues/3258 [gh2776]: https://github.com/encode/django-rest-framework/issues/2776 [gh3261]: https://github.com/encode/django-rest-framework/issues/3261 [gh3260]: https://github.com/encode/django-rest-framework/issues/3260 [gh3241]: https://github.com/encode/django-rest-framework/issues/3241 [gh3249]: https://github.com/encode/django-rest-framework/issues/3249 [gh3250]: https://github.com/encode/django-rest-framework/issues/3250 [gh3275]: https://github.com/encode/django-rest-framework/issues/3275 [gh3290]: https://github.com/encode/django-rest-framework/issues/3290 [gh3303]: https://github.com/encode/django-rest-framework/issues/3303 [gh3313]: https://github.com/encode/django-rest-framework/issues/3313 [gh3316]: https://github.com/encode/django-rest-framework/issues/3316 [gh3318]: https://github.com/encode/django-rest-framework/issues/3318 [gh3321]: https://github.com/encode/django-rest-framework/issues/3321 [gh2761]: https://github.com/encode/django-rest-framework/issues/2761 [gh3314]: https://github.com/encode/django-rest-framework/issues/3314 [gh3323]: https://github.com/encode/django-rest-framework/issues/3323 [gh3324]: https://github.com/encode/django-rest-framework/issues/3324 [gh3359]: https://github.com/encode/django-rest-framework/issues/3359 [gh3361]: https://github.com/encode/django-rest-framework/issues/3361 [gh3364]: https://github.com/encode/django-rest-framework/issues/3364 [gh3415]: https://github.com/encode/django-rest-framework/issues/3415 [gh3550]:https://github.com/encode/django-rest-framework/issues/3550 [gh3315]: https://github.com/encode/django-rest-framework/issues/3315 [gh3410]: https://github.com/encode/django-rest-framework/issues/3410 [gh3435]: https://github.com/encode/django-rest-framework/issues/3435 [gh3450]: https://github.com/encode/django-rest-framework/issues/3450 [gh3454]: https://github.com/encode/django-rest-framework/issues/3454 [gh3475]: https://github.com/encode/django-rest-framework/issues/3475 [gh3495]: https://github.com/encode/django-rest-framework/issues/3495 [gh3509]: https://github.com/encode/django-rest-framework/issues/3509 [gh3421]: https://github.com/encode/django-rest-framework/issues/3421 [gh3525]: https://github.com/encode/django-rest-framework/issues/3525 [gh3526]: https://github.com/encode/django-rest-framework/issues/3526 [gh3429]: https://github.com/encode/django-rest-framework/issues/3429 [gh3536]: https://github.com/encode/django-rest-framework/issues/3536 [gh3556]: https://github.com/encode/django-rest-framework/issues/3556 [gh3560]: https://github.com/encode/django-rest-framework/issues/3560 [gh3564]: https://github.com/encode/django-rest-framework/issues/3564 [gh3568]: https://github.com/encode/django-rest-framework/issues/3568 [gh3592]: https://github.com/encode/django-rest-framework/issues/3592 [gh3593]: https://github.com/encode/django-rest-framework/issues/3593 [gh3228]: https://github.com/encode/django-rest-framework/issues/3228 [gh3252]: https://github.com/encode/django-rest-framework/issues/3252 [gh3513]: https://github.com/encode/django-rest-framework/issues/3513 [gh3534]: https://github.com/encode/django-rest-framework/issues/3534 [gh3578]: https://github.com/encode/django-rest-framework/issues/3578 [gh3596]: https://github.com/encode/django-rest-framework/issues/3596 [gh3597]: https://github.com/encode/django-rest-framework/issues/3597 [gh3600]: https://github.com/encode/django-rest-framework/issues/3600 [gh3626]: https://github.com/encode/django-rest-framework/issues/3626 [gh3628]: https://github.com/encode/django-rest-framework/issues/3628 [gh3631]: https://github.com/encode/django-rest-framework/issues/3631 [gh3634]: https://github.com/encode/django-rest-framework/issues/3634 [gh3635]: https://github.com/encode/django-rest-framework/issues/3635 [gh3654]: https://github.com/encode/django-rest-framework/issues/3654 [gh3655]: https://github.com/encode/django-rest-framework/issues/3655 [gh3656]: https://github.com/encode/django-rest-framework/issues/3656 [gh3662]: https://github.com/encode/django-rest-framework/issues/3662 [gh3668]: https://github.com/encode/django-rest-framework/issues/3668 [gh3672]: https://github.com/encode/django-rest-framework/issues/3672 [gh3677]: https://github.com/encode/django-rest-framework/issues/3677 [gh3679]: https://github.com/encode/django-rest-framework/issues/3679 [gh3684]: https://github.com/encode/django-rest-framework/issues/3684 [gh3687]: https://github.com/encode/django-rest-framework/issues/3687 [gh3701]: https://github.com/encode/django-rest-framework/issues/3701 [gh3705]: https://github.com/encode/django-rest-framework/issues/3705 [gh3714]: https://github.com/encode/django-rest-framework/issues/3714 [gh3718]: https://github.com/encode/django-rest-framework/issues/3718 [gh3723]: https://github.com/encode/django-rest-framework/issues/3723 [gh3968]: https://github.com/encode/django-rest-framework/issues/3968 [gh3962]: https://github.com/encode/django-rest-framework/issues/3962 [gh3913]: https://github.com/encode/django-rest-framework/issues/3913 [gh3912]: https://github.com/encode/django-rest-framework/issues/3912 [gh3910]: https://github.com/encode/django-rest-framework/issues/3910 [gh3903]: https://github.com/encode/django-rest-framework/issues/3903 [gh3887]: https://github.com/encode/django-rest-framework/issues/3887 [gh3878]: https://github.com/encode/django-rest-framework/issues/3878 [gh3860]: https://github.com/encode/django-rest-framework/issues/3860 [gh3858]: https://github.com/encode/django-rest-framework/issues/3858 [gh3842]: https://github.com/encode/django-rest-framework/issues/3842 [gh3833]: https://github.com/encode/django-rest-framework/issues/3833 [gh3832]: https://github.com/encode/django-rest-framework/issues/3832 [gh3819]: https://github.com/encode/django-rest-framework/issues/3819 [gh3815]: https://github.com/encode/django-rest-framework/issues/3815 [gh3809]: https://github.com/encode/django-rest-framework/issues/3809 [gh3805]: https://github.com/encode/django-rest-framework/issues/3805 [gh3804]: https://github.com/encode/django-rest-framework/issues/3804 [gh3801]: https://github.com/encode/django-rest-framework/issues/3801 [gh3787]: https://github.com/encode/django-rest-framework/issues/3787 [gh3786]: https://github.com/encode/django-rest-framework/issues/3786 [gh3785]: https://github.com/encode/django-rest-framework/issues/3785 [gh3774]: https://github.com/encode/django-rest-framework/issues/3774 [gh3769]: https://github.com/encode/django-rest-framework/issues/3769 [gh3753]: https://github.com/encode/django-rest-framework/issues/3753 [gh3739]: https://github.com/encode/django-rest-framework/issues/3739 [gh3731]: https://github.com/encode/django-rest-framework/issues/3731 [gh3728]: https://github.com/encode/django-rest-framework/issues/3726 [gh3715]: https://github.com/encode/django-rest-framework/issues/3715 [gh3703]: https://github.com/encode/django-rest-framework/issues/3703 [gh3696]: https://github.com/encode/django-rest-framework/issues/3696 [gh3637]: https://github.com/encode/django-rest-framework/issues/3637 [gh3636]: https://github.com/encode/django-rest-framework/issues/3636 [gh3605]: https://github.com/encode/django-rest-framework/issues/3605 [gh3604]: https://github.com/encode/django-rest-framework/issues/3604 [gh2403]: https://github.com/encode/django-rest-framework/issues/2403 [gh2848]: https://github.com/encode/django-rest-framework/issues/2848 [gh2996]: https://github.com/encode/django-rest-framework/issues/2996 [gh3164]: https://github.com/encode/django-rest-framework/issues/3164 [gh3273]: https://github.com/encode/django-rest-framework/issues/3273 [gh3381]: https://github.com/encode/django-rest-framework/issues/3381 [gh3438]: https://github.com/encode/django-rest-framework/issues/3438 [gh3444]: https://github.com/encode/django-rest-framework/issues/3444 [gh3476]: https://github.com/encode/django-rest-framework/issues/3476 [gh3487]: https://github.com/encode/django-rest-framework/issues/3487 [gh3541]: https://github.com/encode/django-rest-framework/issues/3541 [gh3710]: https://github.com/encode/django-rest-framework/issues/3710 [gh3729]: https://github.com/encode/django-rest-framework/issues/3729 [gh3751]: https://github.com/encode/django-rest-framework/issues/3751 [gh3812]: https://github.com/encode/django-rest-framework/issues/3812 [gh3816]: https://github.com/encode/django-rest-framework/issues/3816 [gh3820]: https://github.com/encode/django-rest-framework/issues/3820 [gh3906]: https://github.com/encode/django-rest-framework/issues/3906 [gh3908]: https://github.com/encode/django-rest-framework/issues/3908 [gh3926]: https://github.com/encode/django-rest-framework/issues/3926 [gh3933]: https://github.com/encode/django-rest-framework/issues/3933 [gh3936]: https://github.com/encode/django-rest-framework/issues/3936 [gh3938]: https://github.com/encode/django-rest-framework/issues/3938 [gh3943]: https://github.com/encode/django-rest-framework/issues/3943 [gh3953]: https://github.com/encode/django-rest-framework/issues/3953 [gh3964]: https://github.com/encode/django-rest-framework/issues/3964 [gh3968]: https://github.com/encode/django-rest-framework/issues/3968 [gh3970]: https://github.com/encode/django-rest-framework/issues/3970 [gh3971]: https://github.com/encode/django-rest-framework/issues/3971 [gh3976]: https://github.com/encode/django-rest-framework/issues/3976 [gh3983]: https://github.com/encode/django-rest-framework/issues/3983 [gh3990]: https://github.com/encode/django-rest-framework/issues/3990 [gh4002]: https://github.com/encode/django-rest-framework/issues/4002 [gh4003]: https://github.com/encode/django-rest-framework/issues/4003 [gh4005]: https://github.com/encode/django-rest-framework/issues/4005 [gh4006]: https://github.com/encode/django-rest-framework/issues/4006 [gh4008]: https://github.com/encode/django-rest-framework/issues/4008 [gh4021]: https://github.com/encode/django-rest-framework/issues/4021 [gh4025]: https://github.com/encode/django-rest-framework/issues/4025 [gh4040]: https://github.com/encode/django-rest-framework/issues/4040 [gh4041]: https://github.com/encode/django-rest-framework/issues/4041 [gh4049]: https://github.com/encode/django-rest-framework/issues/4049 [gh4075]: https://github.com/encode/django-rest-framework/issues/4075 [gh4079]: https://github.com/encode/django-rest-framework/issues/4079 [gh4090]: https://github.com/encode/django-rest-framework/issues/4090 [gh4097]: https://github.com/encode/django-rest-framework/issues/4097 [gh4098]: https://github.com/encode/django-rest-framework/issues/4098 [gh4103]: https://github.com/encode/django-rest-framework/issues/4103 [gh4105]: https://github.com/encode/django-rest-framework/issues/4105 [gh4106]: https://github.com/encode/django-rest-framework/issues/4106 [gh4107]: https://github.com/encode/django-rest-framework/issues/4107 [gh4118]: https://github.com/encode/django-rest-framework/issues/4118 [gh4146]: https://github.com/encode/django-rest-framework/issues/4146 [gh4149]: https://github.com/encode/django-rest-framework/issues/4149 [gh4153]: https://github.com/encode/django-rest-framework/issues/4153 [gh4156]: https://github.com/encode/django-rest-framework/issues/4156 [gh4157]: https://github.com/encode/django-rest-framework/issues/4157 [gh4158]: https://github.com/encode/django-rest-framework/issues/4158 [gh4166]: https://github.com/encode/django-rest-framework/issues/4166 [gh4176]: https://github.com/encode/django-rest-framework/issues/4176 [gh4179]: https://github.com/encode/django-rest-framework/issues/4179 [gh4180]: https://github.com/encode/django-rest-framework/issues/4180 [gh4181]: https://github.com/encode/django-rest-framework/issues/4181 [gh4185]: https://github.com/encode/django-rest-framework/issues/4185 [gh4187]: https://github.com/encode/django-rest-framework/issues/4187 [gh4191]: https://github.com/encode/django-rest-framework/issues/4191 [gh4192]: https://github.com/encode/django-rest-framework/issues/4192 [gh4194]: https://github.com/encode/django-rest-framework/issues/4194 [gh4195]: https://github.com/encode/django-rest-framework/issues/4195 [gh4196]: https://github.com/encode/django-rest-framework/issues/4196 [gh4212]: https://github.com/encode/django-rest-framework/issues/4212 [gh4215]: https://github.com/encode/django-rest-framework/issues/4215 [gh4217]: https://github.com/encode/django-rest-framework/issues/4217 [gh4219]: https://github.com/encode/django-rest-framework/issues/4219 [gh4229]: https://github.com/encode/django-rest-framework/issues/4229 [gh4233]: https://github.com/encode/django-rest-framework/issues/4233 [gh4244]: https://github.com/encode/django-rest-framework/issues/4244 [gh4246]: https://github.com/encode/django-rest-framework/issues/4246 [gh4253]: https://github.com/encode/django-rest-framework/issues/4253 [gh4254]: https://github.com/encode/django-rest-framework/issues/4254 [gh4255]: https://github.com/encode/django-rest-framework/issues/4255 [gh4256]: https://github.com/encode/django-rest-framework/issues/4256 [gh4259]: https://github.com/encode/django-rest-framework/issues/4259 [gh4323]: https://github.com/encode/django-rest-framework/issues/4323 [gh4268]: https://github.com/encode/django-rest-framework/issues/4268 [gh4321]: https://github.com/encode/django-rest-framework/issues/4321 [gh4308]: https://github.com/encode/django-rest-framework/issues/4308 [gh4305]: https://github.com/encode/django-rest-framework/issues/4305 [gh4316]: https://github.com/encode/django-rest-framework/issues/4316 [gh4294]: https://github.com/encode/django-rest-framework/issues/4294 [gh4293]: https://github.com/encode/django-rest-framework/issues/4293 [gh4315]: https://github.com/encode/django-rest-framework/issues/4315 [gh4314]: https://github.com/encode/django-rest-framework/issues/4314 [gh4289]: https://github.com/encode/django-rest-framework/issues/4289 [gh4265]: https://github.com/encode/django-rest-framework/issues/4265 [gh4285]: https://github.com/encode/django-rest-framework/issues/4285 [gh4287]: https://github.com/encode/django-rest-framework/issues/4287 [gh4313]: https://github.com/encode/django-rest-framework/issues/4313 [gh4281]: https://github.com/encode/django-rest-framework/issues/4281 [gh4299]: https://github.com/encode/django-rest-framework/issues/4299 [gh4307]: https://github.com/encode/django-rest-framework/issues/4307 [gh4302]: https://github.com/encode/django-rest-framework/issues/4302 [gh4303]: https://github.com/encode/django-rest-framework/issues/4303 [gh4298]: https://github.com/encode/django-rest-framework/issues/4298 [gh4291]: https://github.com/encode/django-rest-framework/issues/4291 [gh4270]: https://github.com/encode/django-rest-framework/issues/4270 [gh4272]: https://github.com/encode/django-rest-framework/issues/4272 [gh4273]: https://github.com/encode/django-rest-framework/issues/4273 [gh4288]: https://github.com/encode/django-rest-framework/issues/4288 [gh3565]: https://github.com/encode/django-rest-framework/issues/3565 [gh3610]: https://github.com/encode/django-rest-framework/issues/3610 [gh4198]: https://github.com/encode/django-rest-framework/issues/4198 [gh4199]: https://github.com/encode/django-rest-framework/issues/4199 [gh4236]: https://github.com/encode/django-rest-framework/issues/4236 [gh4292]: https://github.com/encode/django-rest-framework/issues/4292 [gh4296]: https://github.com/encode/django-rest-framework/issues/4296 [gh4318]: https://github.com/encode/django-rest-framework/issues/4318 [gh4330]: https://github.com/encode/django-rest-framework/issues/4330 [gh4331]: https://github.com/encode/django-rest-framework/issues/4331 [gh4332]: https://github.com/encode/django-rest-framework/issues/4332 [gh4335]: https://github.com/encode/django-rest-framework/issues/4335 [gh4336]: https://github.com/encode/django-rest-framework/issues/4336 [gh4338]: https://github.com/encode/django-rest-framework/issues/4338 [gh4339]: https://github.com/encode/django-rest-framework/issues/4339 [gh4340]: https://github.com/encode/django-rest-framework/issues/4340 [gh4344]: https://github.com/encode/django-rest-framework/issues/4344 [gh4345]: https://github.com/encode/django-rest-framework/issues/4345 [gh4346]: https://github.com/encode/django-rest-framework/issues/4346 [gh4347]: https://github.com/encode/django-rest-framework/issues/4347 [gh4348]: https://github.com/encode/django-rest-framework/issues/4348 [gh4349]: https://github.com/encode/django-rest-framework/issues/4349 [gh4354]: https://github.com/encode/django-rest-framework/issues/4354 [gh4357]: https://github.com/encode/django-rest-framework/issues/4357 [gh4358]: https://github.com/encode/django-rest-framework/issues/4358 [gh4359]: https://github.com/encode/django-rest-framework/issues/4359 [gh4361]: https://github.com/encode/django-rest-framework/issues/4361 [gh3329]: https://github.com/encode/django-rest-framework/issues/3329 [gh3330]: https://github.com/encode/django-rest-framework/issues/3330 [gh3365]: https://github.com/encode/django-rest-framework/issues/3365 [gh3394]: https://github.com/encode/django-rest-framework/issues/3394 [gh3868]: https://github.com/encode/django-rest-framework/issues/3868 [gh3868]: https://github.com/encode/django-rest-framework/issues/3868 [gh3877]: https://github.com/encode/django-rest-framework/issues/3877 [gh4042]: https://github.com/encode/django-rest-framework/issues/4042 [gh4111]: https://github.com/encode/django-rest-framework/issues/4111 [gh4119]: https://github.com/encode/django-rest-framework/issues/4119 [gh4120]: https://github.com/encode/django-rest-framework/issues/4120 [gh4121]: https://github.com/encode/django-rest-framework/issues/4121 [gh4122]: https://github.com/encode/django-rest-framework/issues/4122 [gh4137]: https://github.com/encode/django-rest-framework/issues/4137 [gh4172]: https://github.com/encode/django-rest-framework/issues/4172 [gh4201]: https://github.com/encode/django-rest-framework/issues/4201 [gh4260]: https://github.com/encode/django-rest-framework/issues/4260 [gh4278]: https://github.com/encode/django-rest-framework/issues/4278 [gh4279]: https://github.com/encode/django-rest-framework/issues/4279 [gh4329]: https://github.com/encode/django-rest-framework/issues/4329 [gh4370]: https://github.com/encode/django-rest-framework/issues/4370 [gh4371]: https://github.com/encode/django-rest-framework/issues/4371 [gh4372]: https://github.com/encode/django-rest-framework/issues/4372 [gh4373]: https://github.com/encode/django-rest-framework/issues/4373 [gh4374]: https://github.com/encode/django-rest-framework/issues/4374 [gh4375]: https://github.com/encode/django-rest-framework/issues/4375 [gh4376]: https://github.com/encode/django-rest-framework/issues/4376 [gh4377]: https://github.com/encode/django-rest-framework/issues/4377 [gh4378]: https://github.com/encode/django-rest-framework/issues/4378 [gh4379]: https://github.com/encode/django-rest-framework/issues/4379 [gh4380]: https://github.com/encode/django-rest-framework/issues/4380 [gh4382]: https://github.com/encode/django-rest-framework/issues/4382 [gh4383]: https://github.com/encode/django-rest-framework/issues/4383 [gh4386]: https://github.com/encode/django-rest-framework/issues/4386 [gh4387]: https://github.com/encode/django-rest-framework/issues/4387 [gh4388]: https://github.com/encode/django-rest-framework/issues/4388 [gh4390]: https://github.com/encode/django-rest-framework/issues/4390 [gh4391]: https://github.com/encode/django-rest-framework/issues/4391 [gh4392]: https://github.com/encode/django-rest-framework/issues/4392 [gh4393]: https://github.com/encode/django-rest-framework/issues/4393 [gh4394]: https://github.com/encode/django-rest-framework/issues/4394 [gh4416]: https://github.com/encode/django-rest-framework/issues/4416 [gh4409]: https://github.com/encode/django-rest-framework/issues/4409 [gh4415]: https://github.com/encode/django-rest-framework/issues/4415 [gh4410]: https://github.com/encode/django-rest-framework/issues/4410 [gh4408]: https://github.com/encode/django-rest-framework/issues/4408 [gh4398]: https://github.com/encode/django-rest-framework/issues/4398 [gh4407]: https://github.com/encode/django-rest-framework/issues/4407 [gh4403]: https://github.com/encode/django-rest-framework/issues/4403 [gh4404]: https://github.com/encode/django-rest-framework/issues/4404 [gh4412]: https://github.com/encode/django-rest-framework/issues/4412 [gh4435]: https://github.com/encode/django-rest-framework/issues/4435 [gh4425]: https://github.com/encode/django-rest-framework/issues/4425 [gh4429]: https://github.com/encode/django-rest-framework/issues/4429 [gh3508]: https://github.com/encode/django-rest-framework/issues/3508 [gh4419]: https://github.com/encode/django-rest-framework/issues/4419 [gh4423]: https://github.com/encode/django-rest-framework/issues/4423 [gh3951]: https://github.com/encode/django-rest-framework/issues/3951 [gh4500]: https://github.com/encode/django-rest-framework/issues/4500 [gh4489]: https://github.com/encode/django-rest-framework/issues/4489 [gh4490]: https://github.com/encode/django-rest-framework/issues/4490 [gh2617]: https://github.com/encode/django-rest-framework/issues/2617 [gh4472]: https://github.com/encode/django-rest-framework/issues/4472 [gh4473]: https://github.com/encode/django-rest-framework/issues/4473 [gh4495]: https://github.com/encode/django-rest-framework/issues/4495 [gh4493]: https://github.com/encode/django-rest-framework/issues/4493 [gh4465]: https://github.com/encode/django-rest-framework/issues/4465 [gh4462]: https://github.com/encode/django-rest-framework/issues/4462 [gh4458]: https://github.com/encode/django-rest-framework/issues/4458 [gh4612]: https://github.com/encode/django-rest-framework/issues/4612 [gh4608]: https://github.com/encode/django-rest-framework/issues/4608 [gh4601]: https://github.com/encode/django-rest-framework/issues/4601 [gh4611]: https://github.com/encode/django-rest-framework/issues/4611 [gh4605]: https://github.com/encode/django-rest-framework/issues/4605 [gh4609]: https://github.com/encode/django-rest-framework/issues/4609 [gh4606]: https://github.com/encode/django-rest-framework/issues/4606 [gh4600]: https://github.com/encode/django-rest-framework/issues/4600 [gh4631]: https://github.com/encode/django-rest-framework/issues/4631 [gh4638]: https://github.com/encode/django-rest-framework/issues/4638 [gh4532]: https://github.com/encode/django-rest-framework/issues/4532 [gh4636]: https://github.com/encode/django-rest-framework/issues/4636 [gh4622]: https://github.com/encode/django-rest-framework/issues/4622 [gh4602]: https://github.com/encode/django-rest-framework/issues/4602 [gh4640]: https://github.com/encode/django-rest-framework/issues/4640 [gh4624]: https://github.com/encode/django-rest-framework/issues/4624 [gh4569]: https://github.com/encode/django-rest-framework/issues/4569 [gh4627]: https://github.com/encode/django-rest-framework/issues/4627 [gh4620]: https://github.com/encode/django-rest-framework/issues/4620 [gh4628]: https://github.com/encode/django-rest-framework/issues/4628 [gh4639]: https://github.com/encode/django-rest-framework/issues/4639 [gh4660]: https://github.com/encode/django-rest-framework/issues/4660 [gh4643]: https://github.com/encode/django-rest-framework/issues/4643 [gh4644]: https://github.com/encode/django-rest-framework/issues/4644 [gh4645]: https://github.com/encode/django-rest-framework/issues/4645 [gh4646]: https://github.com/encode/django-rest-framework/issues/4646 [gh4650]: https://github.com/encode/django-rest-framework/issues/4650 [gh4877]: https://github.com/encode/django-rest-framework/issues/4877 [gh4753]: https://github.com/encode/django-rest-framework/issues/4753 [gh4764]: https://github.com/encode/django-rest-framework/issues/4764 [gh4821]: https://github.com/encode/django-rest-framework/issues/4821 [gh4841]: https://github.com/encode/django-rest-framework/issues/4841 [gh4759]: https://github.com/encode/django-rest-framework/issues/4759 [gh4869]: https://github.com/encode/django-rest-framework/issues/4869 [gh4870]: https://github.com/encode/django-rest-framework/issues/4870 [gh4790]: https://github.com/encode/django-rest-framework/issues/4790 [gh4661]: https://github.com/encode/django-rest-framework/issues/4661 [gh4668]: https://github.com/encode/django-rest-framework/issues/4668 [gh4750]: https://github.com/encode/django-rest-framework/issues/4750 [gh4678]: https://github.com/encode/django-rest-framework/issues/4678 [gh4634]: https://github.com/encode/django-rest-framework/issues/4634 [gh4669]: https://github.com/encode/django-rest-framework/issues/4669 [gh4712]: https://github.com/encode/django-rest-framework/issues/4712 [gh4947]: https://github.com/encode/django-rest-framework/issues/4947 [gh4959]: https://github.com/encode/django-rest-framework/issues/4959 [gh4961]: https://github.com/encode/django-rest-framework/issues/4961 [gh4952]: https://github.com/encode/django-rest-framework/issues/4952 [gh4953]: https://github.com/encode/django-rest-framework/issues/4953 [gh4950]: https://github.com/encode/django-rest-framework/issues/4950 [gh4951]: https://github.com/encode/django-rest-framework/issues/4951 [gh4955]: https://github.com/encode/django-rest-framework/issues/4955 [gh4956]: https://github.com/encode/django-rest-framework/issues/4956 [gh4949]: https://github.com/encode/django-rest-framework/issues/4949 [gh5126]: https://github.com/encode/django-rest-framework/issues/5126 [gh5085]: https://github.com/encode/django-rest-framework/issues/5085 [gh4437]: https://github.com/encode/django-rest-framework/issues/4437 [gh4222]: https://github.com/encode/django-rest-framework/issues/4222 [gh4999]: https://github.com/encode/django-rest-framework/issues/4999 [gh5042]: https://github.com/encode/django-rest-framework/issues/5042 [gh4987]: https://github.com/encode/django-rest-framework/issues/4987 [gh4979]: https://github.com/encode/django-rest-framework/issues/4979 [gh5086]: https://github.com/encode/django-rest-framework/issues/5086 [gh3692]: https://github.com/encode/django-rest-framework/issues/3692 [gh4748]: https://github.com/encode/django-rest-framework/issues/4748 [gh5078]: https://github.com/encode/django-rest-framework/issues/5078 [gh5082]: https://github.com/encode/django-rest-framework/issues/5082 [gh5047]: https://github.com/encode/django-rest-framework/issues/5047 [gh5053]: https://github.com/encode/django-rest-framework/issues/5053 [gh5055]: https://github.com/encode/django-rest-framework/issues/5055 [gh5054]: https://github.com/encode/django-rest-framework/issues/5054 [gh5038]: https://github.com/encode/django-rest-framework/issues/5038 [gh5004]: https://github.com/encode/django-rest-framework/issues/5004 [gh5026]: https://github.com/encode/django-rest-framework/issues/5026 [gh5028]: https://github.com/encode/django-rest-framework/issues/5028 [gh5001]: https://github.com/encode/django-rest-framework/issues/5001 [gh5014]: https://github.com/encode/django-rest-framework/issues/5014 [gh5000]: https://github.com/encode/django-rest-framework/issues/5000 [gh4994]: https://github.com/encode/django-rest-framework/issues/4994 [gh4705]: https://github.com/encode/django-rest-framework/issues/4705 [gh4973]: https://github.com/encode/django-rest-framework/issues/4973 [gh4864]: https://github.com/encode/django-rest-framework/issues/4864 [gh4688]: https://github.com/encode/django-rest-framework/issues/4688 [gh4968]: https://github.com/encode/django-rest-framework/issues/4968 [gh5089]: https://github.com/encode/django-rest-framework/issues/5089 [gh5117]: https://github.com/encode/django-rest-framework/issues/5117 [gh5346]: https://github.com/encode/django-rest-framework/issues/5346 [gh5334]: https://github.com/encode/django-rest-framework/issues/5334 [gh5326]: https://github.com/encode/django-rest-framework/issues/5326 [gh5313]: https://github.com/encode/django-rest-framework/issues/5313 [gh5306]: https://github.com/encode/django-rest-framework/issues/5306 [gh5276]: https://github.com/encode/django-rest-framework/issues/5276 [gh5264]: https://github.com/encode/django-rest-framework/issues/5264 [gh5261]: https://github.com/encode/django-rest-framework/issues/5261 [gh5259]: https://github.com/encode/django-rest-framework/issues/5259 [gh5231]: https://github.com/encode/django-rest-framework/issues/5231 [gh5229]: https://github.com/encode/django-rest-framework/issues/5229 [gh5214]: https://github.com/encode/django-rest-framework/issues/5214 [gh5196]: https://github.com/encode/django-rest-framework/issues/5196 [gh5192]: https://github.com/encode/django-rest-framework/issues/5192 [gh5162]: https://github.com/encode/django-rest-framework/issues/5162 [gh5188]: https://github.com/encode/django-rest-framework/issues/5188 [gh5187]: https://github.com/encode/django-rest-framework/issues/5187 [gh5186]: https://github.com/encode/django-rest-framework/issues/5186 [gh5179]: https://github.com/encode/django-rest-framework/issues/5179 [gh5176]: https://github.com/encode/django-rest-framework/issues/5176 [gh5174]: https://github.com/encode/django-rest-framework/issues/5174 [gh5161]: https://github.com/encode/django-rest-framework/issues/5161 [gh5147]: https://github.com/encode/django-rest-framework/issues/5147 [gh5131]: https://github.com/encode/django-rest-framework/issues/5131 [gh5481]: https://github.com/encode/django-rest-framework/issues/5481 [gh5480]: https://github.com/encode/django-rest-framework/issues/5480 [gh5479]: https://github.com/encode/django-rest-framework/issues/5479 [gh5295]: https://github.com/encode/django-rest-framework/issues/5295 [gh5464]: https://github.com/encode/django-rest-framework/issues/5464 [gh5478]: https://github.com/encode/django-rest-framework/issues/5478 [gh5476]: https://github.com/encode/django-rest-framework/issues/5476 [gh5466]: https://github.com/encode/django-rest-framework/issues/5466 [gh5472]: https://github.com/encode/django-rest-framework/issues/5472 [gh5462]: https://github.com/encode/django-rest-framework/issues/5462 [gh5470]: https://github.com/encode/django-rest-framework/issues/5470 [gh5469]: https://github.com/encode/django-rest-framework/issues/5469 [gh5435]: https://github.com/encode/django-rest-framework/issues/5435 [gh5434]: https://github.com/encode/django-rest-framework/issues/5434 [gh5426]: https://github.com/encode/django-rest-framework/issues/5426 [gh5421]: https://github.com/encode/django-rest-framework/issues/5421 [gh5415]: https://github.com/encode/django-rest-framework/issues/5415 [gh5401]: https://github.com/encode/django-rest-framework/issues/5401 [gh5398]: https://github.com/encode/django-rest-framework/issues/5398 [gh5388]: https://github.com/encode/django-rest-framework/issues/5388 [gh5387]: https://github.com/encode/django-rest-framework/issues/5387 [gh5372]: https://github.com/encode/django-rest-framework/issues/5372 [gh5380]: https://github.com/encode/django-rest-framework/issues/5380 [gh5351]: https://github.com/encode/django-rest-framework/issues/5351 [gh5375]: https://github.com/encode/django-rest-framework/issues/5375 [gh5373]: https://github.com/encode/django-rest-framework/issues/5373 [gh5361]: https://github.com/encode/django-rest-framework/issues/5361 [gh5348]: https://github.com/encode/django-rest-framework/issues/5348 [gh5058]: https://github.com/encode/django-rest-framework/issues/5058 [gh5457]: https://github.com/encode/django-rest-framework/issues/5457 [gh5376]: https://github.com/encode/django-rest-framework/issues/5376 [gh5422]: https://github.com/encode/django-rest-framework/issues/5422 [gh3732]: https://github.com/encode/django-rest-framework/issues/3732 [djangodocs-set-timezone]: https://docs.djangoproject.com/en/1.11/topics/i18n/timezones/#default-time-zone-and-current-time-zone [gh5273]: https://github.com/encode/django-rest-framework/issues/5273 [gh5440]: https://github.com/encode/django-rest-framework/issues/5440 [gh5265]: https://github.com/encode/django-rest-framework/issues/5265 [gh5250]: https://github.com/encode/django-rest-framework/issues/5250 [gh5170]: https://github.com/encode/django-rest-framework/issues/5170 [gh5443]: https://github.com/encode/django-rest-framework/issues/5443 [gh5448]: https://github.com/encode/django-rest-framework/issues/5448 [gh5452]: https://github.com/encode/django-rest-framework/issues/5452 [gh5342]: https://github.com/encode/django-rest-framework/issues/5342 [gh5454]: https://github.com/encode/django-rest-framework/issues/5454 [gh5482]: https://github.com/encode/django-rest-framework/issues/5482 [gh5489]: https://github.com/encode/django-rest-framework/issues/5489 [gh5486]: https://github.com/encode/django-rest-framework/issues/5486 [gh5503]: https://github.com/encode/django-rest-framework/issues/5503 [gh5500]: https://github.com/encode/django-rest-framework/issues/5500 [gh5492]: https://github.com/encode/django-rest-framework/issues/5492 [gh5552]: https://github.com/encode/django-rest-framework/issues/5552 [gh5539]: https://github.com/encode/django-rest-framework/issues/5539 [gh5559]: https://github.com/encode/django-rest-framework/issues/5559 [gh5561]: https://github.com/encode/django-rest-framework/issues/5561 [gh5562]: https://github.com/encode/django-rest-framework/issues/5562 [gh5548]: https://github.com/encode/django-rest-framework/issues/5548 [gh5560]: https://github.com/encode/django-rest-framework/issues/5560 [gh5557]: https://github.com/encode/django-rest-framework/issues/5557 [gh5556]: https://github.com/encode/django-rest-framework/issues/5556 [gh5555]: https://github.com/encode/django-rest-framework/issues/5555 [gh5550]: https://github.com/encode/django-rest-framework/issues/5550 [gh5549]: https://github.com/encode/django-rest-framework/issues/5549 [gh5546]: https://github.com/encode/django-rest-framework/issues/5546 [gh5547]: https://github.com/encode/django-rest-framework/issues/5547 [gh5544]: https://github.com/encode/django-rest-framework/issues/5544 [gh5518]: https://github.com/encode/django-rest-framework/issues/5518 [gh5533]: https://github.com/encode/django-rest-framework/issues/5533 [gh5532]: https://github.com/encode/django-rest-framework/issues/5532 [gh5530]: https://github.com/encode/django-rest-framework/issues/5530 [gh5527]: https://github.com/encode/django-rest-framework/issues/5527 [gh5524]: https://github.com/encode/django-rest-framework/issues/5524 [gh5516]: https://github.com/encode/django-rest-framework/issues/5516 [gh5513]: https://github.com/encode/django-rest-framework/issues/5513 [gh5511]: https://github.com/encode/django-rest-framework/issues/5511 [gh5514]: https://github.com/encode/django-rest-framework/issues/5514 [gh5512]: https://github.com/encode/django-rest-framework/issues/5512 [gh5510]: https://github.com/encode/django-rest-framework/issues/5510 [gh5567]: https://github.com/encode/django-rest-framework/issues/5567 [gh5691]: https://github.com/encode/django-rest-framework/issues/5691 [gh5688]: https://github.com/encode/django-rest-framework/issues/5688 [gh5689]: https://github.com/encode/django-rest-framework/issues/5689 [gh5687]: https://github.com/encode/django-rest-framework/issues/5687 [gh5685]: https://github.com/encode/django-rest-framework/issues/5685 [gh5683]: https://github.com/encode/django-rest-framework/issues/5683 [gh5682]: https://github.com/encode/django-rest-framework/issues/5682 [gh5681]: https://github.com/encode/django-rest-framework/issues/5681 [gh5680]: https://github.com/encode/django-rest-framework/issues/5680 [gh5679]: https://github.com/encode/django-rest-framework/issues/5679 [gh5678]: https://github.com/encode/django-rest-framework/issues/5678 [gh5656]: https://github.com/encode/django-rest-framework/issues/5656 [gh5665]: https://github.com/encode/django-rest-framework/issues/5665 [gh5658]: https://github.com/encode/django-rest-framework/issues/5658 [gh5668]: https://github.com/encode/django-rest-framework/issues/5668 [gh5652]: https://github.com/encode/django-rest-framework/issues/5652 [gh5648]: https://github.com/encode/django-rest-framework/issues/5648 [gh5649]: https://github.com/encode/django-rest-framework/issues/5649 [gh5646]: https://github.com/encode/django-rest-framework/issues/5646 [gh5645]: https://github.com/encode/django-rest-framework/issues/5645 [gh5641]: https://github.com/encode/django-rest-framework/issues/5641 [gh5639]: https://github.com/encode/django-rest-framework/issues/5639 [gh5622]: https://github.com/encode/django-rest-framework/issues/5622 [gh5625]: https://github.com/encode/django-rest-framework/issues/5625 [gh5624]: https://github.com/encode/django-rest-framework/issues/5624 [gh5629]: https://github.com/encode/django-rest-framework/issues/5629 [gh5626]: https://github.com/encode/django-rest-framework/issues/5626 [gh5600]: https://github.com/encode/django-rest-framework/issues/5600 [gh5618]: https://github.com/encode/django-rest-framework/issues/5618 [gh5619]: https://github.com/encode/django-rest-framework/issues/5619 [gh5607]: https://github.com/encode/django-rest-framework/issues/5607 [gh5617]: https://github.com/encode/django-rest-framework/issues/5617 [gh5598]: https://github.com/encode/django-rest-framework/issues/5598 [gh5613]: https://github.com/encode/django-rest-framework/issues/5613 [gh5599]: https://github.com/encode/django-rest-framework/issues/5599 [gh5602]: https://github.com/encode/django-rest-framework/issues/5602 [gh5612]: https://github.com/encode/django-rest-framework/issues/5612 [gh5611]: https://github.com/encode/django-rest-framework/issues/5611 [gh5610]: https://github.com/encode/django-rest-framework/issues/5610 [gh5590]: https://github.com/encode/django-rest-framework/issues/5590 [gh5591]: https://github.com/encode/django-rest-framework/issues/5591 [gh5587]: https://github.com/encode/django-rest-framework/issues/5587 [gh5584]: https://github.com/encode/django-rest-framework/issues/5584 [gh5581]: https://github.com/encode/django-rest-framework/issues/5581 [gh5578]: https://github.com/encode/django-rest-framework/issues/5578 [gh5577]: https://github.com/encode/django-rest-framework/issues/5577 [gh5579]: https://github.com/encode/django-rest-framework/issues/5579 [gh5633]: https://github.com/encode/django-rest-framework/issues/5633 [gh5692]: https://github.com/encode/django-rest-framework/issues/5692 [gh5695]: https://github.com/encode/django-rest-framework/issues/5695 [gh5696]: https://github.com/encode/django-rest-framework/issues/5696 [gh5697]: https://github.com/encode/django-rest-framework/issues/5697 [gh5886]: https://github.com/encode/django-rest-framework/issues/5886 [gh5888]: https://github.com/encode/django-rest-framework/issues/5888 [gh5705]: https://github.com/encode/django-rest-framework/issues/5705 [gh5796]: https://github.com/encode/django-rest-framework/issues/5796 [gh5763]: https://github.com/encode/django-rest-framework/issues/5763 [gh5777]: https://github.com/encode/django-rest-framework/issues/5777 [gh5787]: https://github.com/encode/django-rest-framework/issues/5787 [gh5754]: https://github.com/encode/django-rest-framework/issues/5754 [gh5783]: https://github.com/encode/django-rest-framework/issues/5783 [gh5773]: https://github.com/encode/django-rest-framework/issues/5773 [gh5757]: https://github.com/encode/django-rest-framework/issues/5757 [gh5752]: https://github.com/encode/django-rest-framework/issues/5752 [gh5766]: https://github.com/encode/django-rest-framework/issues/5766 [gh5751]: https://github.com/encode/django-rest-framework/issues/5751 [gh5654]: https://github.com/encode/django-rest-framework/issues/5654 [gh5729]: https://github.com/encode/django-rest-framework/issues/5729 [gh5735]: https://github.com/encode/django-rest-framework/issues/5735 [gh5739]: https://github.com/encode/django-rest-framework/issues/5739 [gh5736]: https://github.com/encode/django-rest-framework/issues/5736 [gh5734]: https://github.com/encode/django-rest-framework/issues/5734 [gh5733]: https://github.com/encode/django-rest-framework/issues/5733 [gh5720]: https://github.com/encode/django-rest-framework/issues/5720 [gh5701]: https://github.com/encode/django-rest-framework/issues/5701 [gh5700]: https://github.com/encode/django-rest-framework/issues/5700 [gh5703]: https://github.com/encode/django-rest-framework/issues/5703 [gh5712]: https://github.com/encode/django-rest-framework/issues/5712 [gh5709]: https://github.com/encode/django-rest-framework/issues/5709 [gh5702]: https://github.com/encode/django-rest-framework/issues/5702 [gh5655]: https://github.com/encode/django-rest-framework/issues/5655 [gh5713]: https://github.com/encode/django-rest-framework/issues/5713 [gh5711]: https://github.com/encode/django-rest-framework/issues/5711 [gh5704]: https://github.com/encode/django-rest-framework/issues/5704 [gh5854]: https://github.com/encode/django-rest-framework/issues/5854 [gh5846]: https://github.com/encode/django-rest-framework/issues/5846 [gh5891]: https://github.com/encode/django-rest-framework/issues/5891 [gh5849]: https://github.com/encode/django-rest-framework/issues/5849 [gh5880]: https://github.com/encode/django-rest-framework/issues/5880 [gh5843]: https://github.com/encode/django-rest-framework/issues/5843 [gh5872]: https://github.com/encode/django-rest-framework/issues/5872 [gh5870]: https://github.com/encode/django-rest-framework/issues/5870 [gh5844]: https://github.com/encode/django-rest-framework/issues/5844 [gh5837]: https://github.com/encode/django-rest-framework/issues/5837 [gh5827]: https://github.com/encode/django-rest-framework/issues/5827 [gh5823]: https://github.com/encode/django-rest-framework/issues/5823 [gh5809]: https://github.com/encode/django-rest-framework/issues/5809 [gh5835]: https://github.com/encode/django-rest-framework/issues/5835 [gh5834]: https://github.com/encode/django-rest-framework/issues/5834 [gh5833]: https://github.com/encode/django-rest-framework/issues/5833 [gh5894]: https://github.com/encode/django-rest-framework/issues/5894 [gh5817]: https://github.com/encode/django-rest-framework/issues/5817 [gh5815]: https://github.com/encode/django-rest-framework/issues/5815 [gh5818]: https://github.com/encode/django-rest-framework/issues/5818 [gh5800]: https://github.com/encode/django-rest-framework/issues/5800 [gh5676]: https://github.com/encode/django-rest-framework/issues/5676 [gh5802]: https://github.com/encode/django-rest-framework/issues/5802 [gh5765]: https://github.com/encode/django-rest-framework/issues/5765 [gh5764]: https://github.com/encode/django-rest-framework/issues/5764 [gh5904]: https://github.com/encode/django-rest-framework/issues/5904 [gh5899]: https://github.com/encode/django-rest-framework/issues/5899 [gh5915]: https://github.com/encode/django-rest-framework/issues/5915 [gh5922]: https://github.com/encode/django-rest-framework/issues/5922 [gh5921]: https://github.com/encode/django-rest-framework/issues/5921 [gh5920]: https://github.com/encode/django-rest-framework/issues/5920 [gh6109]: https://github.com/encode/django-rest-framework/issues/6109 [gh6141]: https://github.com/encode/django-rest-framework/issues/6141 [gh6113]: https://github.com/encode/django-rest-framework/issues/6113 [gh6112]: https://github.com/encode/django-rest-framework/issues/6112 [gh6111]: https://github.com/encode/django-rest-framework/issues/6111 [gh6028]: https://github.com/encode/django-rest-framework/issues/6028 [gh5657]: https://github.com/encode/django-rest-framework/issues/5657 [gh6054]: https://github.com/encode/django-rest-framework/issues/6054 [gh5993]: https://github.com/encode/django-rest-framework/issues/5993 [gh5990]: https://github.com/encode/django-rest-framework/issues/5990 [gh5988]: https://github.com/encode/django-rest-framework/issues/5988 [gh5785]: https://github.com/encode/django-rest-framework/issues/5785 [gh5992]: https://github.com/encode/django-rest-framework/issues/5992 [gh5605]: https://github.com/encode/django-rest-framework/issues/5605 [gh5982]: https://github.com/encode/django-rest-framework/issues/5982 [gh5981]: https://github.com/encode/django-rest-framework/issues/5981 [gh5747]: https://github.com/encode/django-rest-framework/issues/5747 [gh5643]: https://github.com/encode/django-rest-framework/issues/5643 [gh5881]: https://github.com/encode/django-rest-framework/issues/5881 [gh5869]: https://github.com/encode/django-rest-framework/issues/5869 [gh5878]: https://github.com/encode/django-rest-framework/issues/5878 [gh5932]: https://github.com/encode/django-rest-framework/issues/5932 [gh5927]: https://github.com/encode/django-rest-framework/issues/5927 [gh5942]: https://github.com/encode/django-rest-framework/issues/5942 [gh5936]: https://github.com/encode/django-rest-framework/issues/5936 [gh5931]: https://github.com/encode/django-rest-framework/issues/5931 [gh6183]: https://github.com/encode/django-rest-framework/issues/6183 [gh6075]: https://github.com/encode/django-rest-framework/issues/6075 [gh6138]: https://github.com/encode/django-rest-framework/issues/6138 [gh6081]: https://github.com/encode/django-rest-framework/issues/6081 [gh6073]: https://github.com/encode/django-rest-framework/issues/6073 [gh6191]: https://github.com/encode/django-rest-framework/issues/6191 [gh6060]: https://github.com/encode/django-rest-framework/issues/6060 [gh6233]: https://github.com/encode/django-rest-framework/issues/6233 [gh5753]: https://github.com/encode/django-rest-framework/issues/5753 [gh6229]: https://github.com/encode/django-rest-framework/issues/6229 [gh6330]: https://github.com/encode/django-rest-framework/issues/6330 [gh6299]: https://github.com/encode/django-rest-framework/issues/6299 [gh6371]: https://github.com/encode/django-rest-framework/issues/6371 [gh6480]: https://github.com/encode/django-rest-framework/issues/6480 [gh6240]: https://github.com/encode/django-rest-framework/issues/6240 [gh6361]: https://github.com/encode/django-rest-framework/issues/6361 [gh6463]: https://github.com/encode/django-rest-framework/issues/6463 [gh6472]: https://github.com/encode/django-rest-framework/issues/6472 [gh6268]: https://github.com/encode/django-rest-framework/issues/6268 [gh6279]: https://github.com/encode/django-rest-framework/issues/6279 [gh6282]: https://github.com/encode/django-rest-framework/issues/6282 [gh6207]: https://github.com/encode/django-rest-framework/issues/6207 [gh6455]: https://github.com/encode/django-rest-framework/issues/6455 [gh6422]: https://github.com/encode/django-rest-framework/issues/6422 [gh6430]: https://github.com/encode/django-rest-framework/issues/6430 [gh6429]: https://github.com/encode/django-rest-framework/issues/6429 [gh6340]: https://github.com/encode/django-rest-framework/issues/6340 [gh6416]: https://github.com/encode/django-rest-framework/issues/6416 [gh6407]: https://github.com/encode/django-rest-framework/issues/6407 [gh6613]: https://github.com/encode/django-rest-framework/issues/6613 [gh6680]: https://github.com/encode/django-rest-framework/issues/6680 [gh6317]: https://github.com/encode/django-rest-framework/issues/6317 [gh6687]: https://github.com/encode/django-rest-framework/issues/6687 [gh6892]: https://github.com/encode/django-rest-framework/issues/6892 [gh6916]: https://github.com/encode/django-rest-framework/issues/6916 [gh6865]: https://github.com/encode/django-rest-framework/issues/6865 [gh6898]: https://github.com/encode/django-rest-framework/issues/6898 [gh6941]: https://github.com/encode/django-rest-framework/issues/6941 [gh6944]: https://github.com/encode/django-rest-framework/issues/6944 [gh6914]: https://github.com/encode/django-rest-framework/issues/6914 [gh6912]: https://github.com/encode/django-rest-framework/issues/6912 [gh7018]: https://github.com/encode/django-rest-framework/issues/7018 [gh6996]: https://github.com/encode/django-rest-framework/issues/6996 [gh6980]: https://github.com/encode/django-rest-framework/issues/6980 [gh7059]: https://github.com/encode/django-rest-framework/issues/7059 [gh6923]: https://github.com/encode/django-rest-framework/issues/6923 ================================================ FILE: docs/community/third-party-packages.md ================================================ # Third Party Packages > Software ecosystems […] establish a community that further accelerates the sharing of knowledge, content, issues, expertise and skills. > > — [Jan Bosch][cite]. ## About Third Party Packages Third Party Packages allow developers to share code that extends the functionality of Django REST framework, in order to support additional use-cases. We **support**, **encourage** and **strongly favor** the creation of Third Party Packages to encapsulate new behavior rather than adding additional functionality directly to Django REST Framework. We aim to make creating third party packages as easy as possible, whilst keeping a **simple** and **well maintained** core API. By promoting third party packages we ensure that the responsibility for a package remains with its author. If a package proves suitably popular it can always be considered for inclusion into the core REST framework. If you have an idea for a new feature please consider how it may be packaged as a Third Party Package. We're always happy to discuss ideas on the [Mailing List][discussion-group]. ## Creating a Third Party Package ### Version compatibility Sometimes, in order to ensure your code works on various different versions of Django, Python or third party libraries, you'll need to run slightly different code depending on the environment. Any code that branches in this way should be isolated into a `compat.py` module, and should provide a single common interface that the rest of the codebase can use. Check out Django REST framework's [compat.py][drf-compat] for an example. ### Once your package is available Once your package is decently documented and available on PyPI, you might want share it with others that might find it useful. #### Adding to the Django REST framework grid We suggest adding your package to the [REST Framework][rest-framework-grid] grid on Django Packages. #### Adding to the Django REST framework docs Create a [Pull Request][drf-create-pr] 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. You can also let others know about your package through the [discussion group][discussion-group]. ## Existing Third Party Packages Django REST Framework has a growing community of developers, packages, and resources. Check out a grid detailing all the packages and ecosystem around Django REST Framework at [Django Packages][rest-framework-grid]. To submit new content, [create a pull request][drf-create-pr]. ### Async Support * [adrf](https://github.com/em1208/adrf) - Async support, provides async Views, ViewSets, and Serializers. ### Authentication * [djangorestframework-digestauth][djangorestframework-digestauth] - Provides Digest Access Authentication support. * [django-oauth-toolkit][django-oauth-toolkit] - Provides OAuth 2.0 support. * [djangorestframework-simplejwt][djangorestframework-simplejwt] - Provides JSON Web Token Authentication support. * [hawkrest][hawkrest] - Provides Hawk HTTP Authorization. * [djangorestframework-httpsignature][djangorestframework-httpsignature] - Provides an easy to use HTTP Signature Authentication mechanism. * [djoser][djoser] - Provides a set of views to handle basic actions such as registration, login, logout, password reset and account activation. * [DRF Auth Kit][drf-auth-kit] - Provides complete REST authentication with JWT cookies, social login, MFA, and user management. Features full type safety and automatic OpenAPI schema generation. * [dj-rest-auth][dj-rest-auth] - Provides a set of REST API endpoints for registration, authentication (including social media authentication), password reset, retrieve and update user details, etc. * [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 * [drf-any-permissions][drf-any-permissions] - Provides alternative permission handling. * [djangorestframework-composed-permissions][djangorestframework-composed-permissions] - Provides a simple way to define complex permissions. * [rest_condition][rest-condition] - Another extension for building complex permissions in a simple and convenient way. * [dry-rest-permissions][dry-rest-permissions] - Provides a simple way to define permissions for individual api actions. * [drf-access-policy][drf-access-policy] - Declarative and flexible permissions inspired by AWS' IAM policies. * [drf-psq][drf-psq] - An extension that gives support for having action-based **permission_classes**, **serializer_class**, and **queryset** dependent on permission-based rules. * [axioms-drf-py][axioms-drf-py] - Supports authentication and claim-based fine-grained authorization (**scopes**, **roles**, **groups**, **permissions**, etc. including object-level checks) using JWT tokens issued by an OAuth2/OIDC Authorization Server. ### Serializers * [django-rest-framework-mongoengine][django-rest-framework-mongoengine] - Serializer class that supports using MongoDB as the storage layer for Django REST framework. * [djangorestframework-gis][djangorestframework-gis] - Geographic add-ons * [django-pydantic-field][django-pydantic-field] - Provides a way to use Pydantic models as schemas for Django's JSONField with full support for Pydantic v1 and v2, type safety and integration with Django REST Framework. * [drf-pydantic][drf-pydantic] - Use Pydantic with Django REST framework for data validation and (de)serialization. * [djangorestframework-hstore][djangorestframework-hstore] - Serializer class to support django-hstore DictionaryField model field and its schema-mode feature. * [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. * [html-json-forms][html-json-forms] - Provides an algorithm and serializer to process HTML JSON Form submissions per the (inactive) spec. * [django-rest-framework-serializer-extensions][drf-serializer-extensions] - Enables black/whitelisting fields, and conditionally expanding child serializers on a per-view/request basis. * [djangorestframework-queryfields][djangorestframework-queryfields] - Serializer mixin allowing clients to control which fields will be sent in the API response. * [drf-flex-fields][drf-flex-fields] - Serializer providing dynamic field expansion and sparse field sets via URL parameters. * [drf-action-serializer][drf-action-serializer] - Serializer providing per-action fields config for use with ViewSets to prevent having to write multiple serializers. * [djangorestframework-dataclasses][djangorestframework-dataclasses] - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models. * [django-restql][django-restql] - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields). * [graphwrap][graphwrap] - Transform your REST API into a fully compliant GraphQL API with just two lines of code. Leverages [Graphene-Django](https://docs.graphene-python.org/projects/django/en/latest/) to dynamically build, at runtime, a GraphQL ObjectType for each view in your API. * [drf-shapeless-serializers][drf-shapeless-serializers] - Dynamically assemble, configure, and shape your Django Rest Framework serializers at runtime, much like connecting Lego bricks. ### Serializer fields * [drf-compound-fields][drf-compound-fields] - Provides "compound" serializer fields, such as lists of simple values. * [drf-extra-fields][drf-extra-fields] - Provides extra serializer fields. * [django-versatileimagefield][django-versatileimagefield] - Provides a drop-in replacement for Django's stock `ImageField` that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, [click here][django-versatileimagefield-drf-docs]. ### Views * [django-rest-multiple-models][django-rest-multiple-models] - Provides a generic view (and mixin) for sending multiple serialized models and/or querysets via a single API request. * [drf-typed-views][drf-typed-views] - Use Python type annotations to validate/deserialize request parameters. Inspired by API Star, Hug and FastAPI. * [rest-framework-actions][rest-framework-actions] - Provides control over each action in ViewSets. Serializers per action, method. ### Routers * [drf-nested-routers][drf-nested-routers] - Provides routers and relationship fields for working with nested resources. * [wq.db.rest][wq.db.rest] - Provides an admin-style model registration API with reasonable default URLs and viewsets. ### Parsers * [djangorestframework-msgpack][djangorestframework-msgpack] - Provides MessagePack renderer and parser support. * [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. * [djangorestframework-camel-case][djangorestframework-camel-case] - Provides camel case JSON renderers and parsers. * [nested-multipart-parser][nested-multipart-parser] - Provides nested parser for http multipart request ### Renderers * [djangorestframework-csv][djangorestframework-csv] - Provides CSV renderer support. * [djangorestframework-jsonapi][djangorestframework-jsonapi] - Provides a parser, renderer, serializers, and other tools to help build an API that is compliant with the jsonapi.org spec. * [drf_ujson2][drf_ujson2] - Implements JSON rendering using the UJSON package. * [rest-pandas][rest-pandas] - Pandas DataFrame-powered renderers including Excel, CSV, and SVG formats. * [djangorestframework-rapidjson][djangorestframework-rapidjson] - Provides rapidjson support with parser and renderer. ### Filtering * [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. ### 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. * [gaiarestframework][gaiarestframework] - Utils for django-rest-framework * [drf-extensions][drf-extensions] - A collection of custom extensions * [ember-django-adapter][ember-django-adapter] - An adapter for working with Ember.js * [django-versatileimagefield][django-versatileimagefield] - Provides a drop-in replacement for Django's stock `ImageField` that makes it easy to serve images in multiple sizes/renditions from a single field. For DRF-specific implementation docs, [click here][django-versatileimagefield-drf-docs]. * [drf-tracking][drf-tracking] - Utilities to track requests to DRF API views. * [drf_tweaks][drf_tweaks] - Serializers with one-step validation (and more), pagination without counts and other tweaks. * [django-rest-framework-braces][django-rest-framework-braces] - Collection of utilities for working with Django Rest Framework. The most notable ones are [FormSerializer](https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#formserializer) and [SerializerForm](https://django-rest-framework-braces.readthedocs.io/en/latest/overview.html#serializerform), which are adapters between DRF serializers and Django forms. * [drf-haystack][drf-haystack] - Haystack search for Django Rest Framework * [django-rest-framework-version-transforms][django-rest-framework-version-transforms] - Enables the use of delta transformations for versioning of DRF resource representations. * [django-rest-messaging][django-rest-messaging], [django-rest-messaging-centrifugo][django-rest-messaging-centrifugo] and [django-rest-messaging-js][django-rest-messaging-js] - A real-time pluggable messaging service using DRM. * [djangorest-alchemy][djangorest-alchemy] - SQLAlchemy support for REST framework. * [djangorestframework-datatables][djangorestframework-datatables] - Seamless integration between Django REST framework and [Datatables](https://datatables.net). * [django-rest-framework-condition][django-rest-framework-condition] - Decorators for managing HTTP cache headers for Django REST framework (ETag and Last-modified). * [django-rest-witchcraft][django-rest-witchcraft] - Provides DRF integration with SQLAlchemy with SQLAlchemy model serializers/viewsets and a bunch of other goodies * [djangorestframework-mvt][djangorestframework-mvt] - An extension for creating views that serve Postgres data as Map Box Vector Tiles. * [drf-viewset-profiler][drf-viewset-profiler] - Lib to profile all methods from a viewset line by line. * [djangorestframework-features][djangorestframework-features] - Advanced schema generation and more based on named features. * [django-elasticsearch-dsl-drf][django-elasticsearch-dsl-drf] - Integrate Elasticsearch DSL with Django REST framework. Package provides views, serializers, filter backends, pagination and other handy add-ons. * [django-lisan][django-lisan] - A lightweight translation and localization framework for Django REST Framework APIs. * [django-api-client][django-api-client] - DRF client that groups the Endpoint response, for use in CBVs and FBV as if you were working with Django's Native Models.. * [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 * [apitally] - A simple API monitoring, analytics, and request logging tool using middleware. For DRF-specific setup guide, [click here](https://docs.apitally.io/frameworks/django-rest-framework). * [wireup][wireup] - Dependency injection container with Django integration support. For integration docs, [click here][wireup-django-docs]. ### 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 [create-a-repo]: https://help.github.com/articles/create-a-repo/ [pypi-register]: https://pypi.org/account/register/ [semver]: https://semver.org/ [tox-docs]: https://tox.readthedocs.io/en/latest/ [drf-compat]: https://github.com/encode/django-rest-framework/blob/main/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 [authentication]: ../api-guide/authentication.md [permissions]: ../api-guide/permissions.md [third-party-packages]: #existing-third-party-packages [discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework [drf-auth-kit]: https://github.com/huynguyengl99/drf-auth-kit [djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth [django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit [djangorestframework-jwt]: https://github.com/GetBlimp/django-rest-framework-jwt [djangorestframework-simplejwt]: https://github.com/davesque/django-rest-framework-simplejwt [hawkrest]: https://github.com/kumar303/hawkrest [djangorestframework-httpsignature]: https://github.com/etoccalino/django-rest-framework-httpsignature [djoser]: https://github.com/sunscrapers/djoser [drf-any-permissions]: https://github.com/kevin-brown/drf-any-permissions [djangorestframework-composed-permissions]: https://github.com/niwibe/djangorestframework-composed-permissions [rest-condition]: https://github.com/caxap/rest_condition [django-rest-framework-mongoengine]: https://github.com/umutbozkurt/django-rest-framework-mongoengine [djangorestframework-gis]: https://github.com/djangonauts/django-rest-framework-gis [djangorestframework-hstore]: https://github.com/djangonauts/django-rest-framework-hstore [drf-compound-fields]: https://github.com/estebistec/drf-compound-fields [drf-extra-fields]: https://github.com/Hipo/drf-extra-fields [django-rest-multiple-models]: https://github.com/MattBroach/DjangoRestMultipleModels [drf-nested-routers]: https://github.com/alanjds/drf-nested-routers [wq.db.rest]: https://wq.io/docs/about-rest [djangorestframework-msgpack]: https://github.com/juanriaza/django-rest-framework-msgpack [djangorestframework-camel-case]: https://github.com/vbabiy/djangorestframework-camel-case [nested-multipart-parser]: https://github.com/remigermain/nested-multipart-parser [djangorestframework-csv]: https://github.com/mjumbewu/django-rest-framework-csv [drf_ujson2]: https://github.com/Amertz08/drf_ujson2 [rest-pandas]: https://github.com/wq/django-rest-pandas [djangorestframework-rapidjson]: https://github.com/allisson/django-rest-framework-rapidjson [djangorestframework-chain]: https://github.com/philipn/django-rest-framework-chain [djangorestrelationalhyperlink]: https://github.com/fredkingham/django_rest_model_hyperlink_serializers_project [django-rest-framework-proxy]: https://github.com/eofs/django-rest-framework-proxy [gaiarestframework]: https://github.com/AppsFuel/gaiarestframework [drf-extensions]: https://github.com/chibisov/drf-extensions [ember-django-adapter]: https://github.com/dustinfarris/ember-django-adapter [dj-rest-auth]: https://github.com/iMerica/dj-rest-auth [django-versatileimagefield]: https://github.com/WGBH/django-versatileimagefield [django-versatileimagefield-drf-docs]:https://django-versatileimagefield.readthedocs.io/en/latest/drf_integration.html [drf-tracking]: https://github.com/aschn/drf-tracking [django-rest-framework-braces]: https://github.com/dealertrack/django-rest-framework-braces [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 [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 [html-json-forms]: https://github.com/wq/html-json-forms [django-rest-messaging]: https://github.com/raphaelgyory/django-rest-messaging [django-rest-messaging-centrifugo]: https://github.com/raphaelgyory/django-rest-messaging-centrifugo [django-rest-messaging-js]: https://github.com/raphaelgyory/django-rest-messaging-js [drf_tweaks]: https://github.com/ArabellaTech/drf_tweaks [drf-oidc-auth]: https://github.com/ByteInternet/drf-oidc-auth [drf-serializer-extensions]: https://github.com/evenicoulddoit/django-rest-framework-serializer-extensions [djangorestframework-queryfields]: https://github.com/wimglenn/djangorestframework-queryfields [drfpasswordless]: https://github.com/aaronn/django-rest-framework-passwordless [djangorest-alchemy]: https://github.com/dealertrack/djangorest-alchemy [djangorestframework-datatables]: https://github.com/izimobil/django-rest-framework-datatables [django-rest-framework-condition]: https://github.com/jozo/django-rest-framework-condition [django-rest-witchcraft]: https://github.com/shosca/django-rest-witchcraft [drf-access-policy]: https://github.com/rsinger86/drf-access-policy [drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields [drf-typed-views]: https://github.com/rsinger86/drf-typed-views [drf-action-serializer]: https://github.com/gregschmit/drf-action-serializer [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 [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 [django-api-client]: https://github.com/rhenter/django-api-client [drf-psq]: https://github.com/drf-psq/drf-psq [django-rest-authemail]: https://github.com/celiao/django-rest-authemail [graphwrap]: https://github.com/PaulGilmartin/graph_wrap [rest-framework-actions]: https://github.com/AlexisMunera98/rest-framework-actions [fast-drf]: https://github.com/iashraful/fast-drf [wireup]: https://github.com/maldoinc/wireup [wireup-django-docs]: https://maldoinc.github.io/wireup/latest/integrations/django/ [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 [apitally]: https://github.com/apitally/apitally-py [drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers [django-lisan]: https://github.com/Nabute/django-lisan [axioms-drf-py]: https://github.com/abhishektiwari/axioms-drf-py [django-pydantic-field]: https://github.com/surenkov/django-pydantic-field [drf-pydantic]: https://github.com/georgebv/drf-pydantic ================================================ FILE: docs/community/tutorials-and-resources.md ================================================ # Tutorials and Resources There are a wide range of resources available for learning and using Django REST framework. We try to keep a comprehensive list available here. ## Books ## 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] * [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] * [Start Your API - Django REST Framework Part 1][start-your-api-django-rest-framework-part-1] * [Permissions & Authentication - Django REST Framework Part 2][permissions-authentication-django-rest-framework-part-2] * [ViewSets and Routers - Django REST Framework Part 3][viewsets-and-routers-django-rest-framework-part-3] * [Django REST Framework User Endpoint][django-rest-framework-user-endpoint] * [Check Credentials Using Django REST Framework][check-credentials-using-django-rest-framework] * [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] * [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] * [Building APIs with Django and Django REST framework](https://books.agiliq.com/projects/django-api-polls-tutorial/en/latest/) ## Videos ### 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-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 * [Django REST Framework Part 1][django-rest-framework-part-1-video] * [Django REST Framework in Your PJ's!][drf-in-your-pjs] * [Building a REST API Using Django & Django REST Framework][building-a-rest-api-using-django-and-drf] * [Blog API with Django REST Framework][blog-api-with-drf] * [Ember and Django Part 1][ember-and-django-part 1-video] * [Django REST Framework Image Upload Tutorial (with AngularJS)][drf-image-upload-tutorial-with-angularjs] * [Django REST Framework Tutorials][drf-tutorials] ## Articles * [Web API performance: Profiling Django REST Framework][web-api-performance-profiling-django-rest-framework] * [API Development with Django and Django REST Framework][api-development-with-django-and-django-rest-framework] * [Integrating Pandas, Django REST Framework and Bokeh][integrating-pandas-drf-and-bokeh] * [Controlling Uncertainty on Web Applications and APIs][controlling-uncertainty-on-web-apps-and-apis] * [Full Text Search in Django REST Framework with Database Backends][full-text-search-in-drf] * [OAuth2 Authentication with Django REST Framework and Custom Third-Party OAuth2 Backends][oauth2-authentication-with-drf] * [Nested Resources with Django REST Framework][nested-resources-with-drf] * [Image Fields with Django REST Framework][image-fields-with-drf] * [Chatbot Using Django REST Framework + api.ai + Slack - Part 1/3][chatbot-using-drf-part1] * [New Django Admin with DRF and EmberJS... What are the News?][new-django-admin-with-drf-and-emberjs] * [Blog posts about Django REST Framework][medium-django-rest-framework] * [Implementing Rest APIs With Embedded Privacy][doordash-implementing-rest-apis] ## Documentations * [Classy Django REST Framework][cdrf.co] * [DRF-schema-adapter][drf-schema] Want your Django REST Framework talk/tutorial/article to be added to our website? Or know of a resource that's not yet included here? Please [submit a pull request][submit-pr] or [email us][anna-email]! [beginners-guide-to-the-django-rest-framework]: https://code.tutsplus.com/tutorials/beginners-guide-to-the-django-rest-framework--cms-19786 [getting-started-with-django-rest-framework-and-angularjs]: https://blog.kevinastone.com/django-rest-framework-and-angular-js [end-to-end-web-app-with-django-rest-framework-angularjs]: https://mourafiq.com/2013/07/01/end-to-end-web-app-with-django-angular-1.html [start-your-api-django-rest-framework-part-1]: https://www.youtube.com/watch?v=hqo2kk91WpE [permissions-authentication-django-rest-framework-part-2]: https://www.youtube.com/watch?v=R3xvUDUZxGU [viewsets-and-routers-django-rest-framework-part-3]: https://www.youtube.com/watch?v=2d6w4DGQ4OU [django-rest-framework-user-endpoint]: https://richardtier.com/2014/02/25/django-rest-framework-user-endpoint/ [check-credentials-using-django-rest-framework]: https://richardtier.com/2014/03/06/110/ [ember-and-django-part 1-video]: http://www.neckbeardrepublic.com/screencasts/ember-and-django-part-1 [django-rest-framework-part-1-video]: http://www.neckbeardrepublic.com/screencasts/django-rest-framework-part-1 [web-api-performance-profiling-django-rest-framework]: https://www.dabapps.com/blog/api-performance-profiling-django-rest-framework/ [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 [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/ [controlling-uncertainty-on-web-apps-and-apis]: https://web.archive.org/web/20180104205043/https://machinalis.com/blog/controlling-uncertainty-on-web-applications-and-apis/ [full-text-search-in-drf]: https://web.archive.org/web/20180104205059/http://machinalis.com/blog/full-text-search-on-django-rest-framework/ [oauth2-authentication-with-drf]: https://web.archive.org/web/20180104205054/http://machinalis.com/blog/oauth2-authentication/ [nested-resources-with-drf]: https://web.archive.org/web/20180104205109/http://machinalis.com/blog/nested-resources-with-django/ [image-fields-with-drf]: https://web.archive.org/web/20180104205048/http://machinalis.com/blog/image-fields-with-django-rest-framework/ [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/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-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 [drf-image-upload-tutorial-with-angularjs]: https://www.youtube.com/watch?v=hMiNTCIY7dw&list=PLUe5s-xycYk_X0vDjYBmKuIya2a2myF8O [blog-api-with-drf]: https://www.youtube.com/watch?v=XMu0T6L2KRQ&list=PLEsfXFp6DpzTOcOVdZF-th7BS_GYGguAS [drf-an-intro]: https://realpython.com/blog/python/django-rest-framework-quick-start/ [drf-tutorial]: https://tests4geeks.com/django-rest-framework-tutorial/ [building-a-restful-api-with-drf]: https://agiliq.com/blog/2014/12/building-a-restful-api-with-django-rest-framework/ [submit-pr]: https://github.com/encode/django-rest-framework [anna-email]: mailto:anna@django-rest-framework.org [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 ================================================ FILE: docs/index.md ================================================ --- hide: - navigation --- ---

Django REST Framework

![Django REST Framework](img/logo-light.png#only-light) ![Django REST Framework](img/logo-dark.png#only-dark) 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 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]. * Extensive documentation, and [great community support][group]. * Used and trusted by internationally recognized companies including [Mozilla][mozilla], [Red Hat][redhat], [Heroku][heroku], and [Eventbrite][eventbrite]. --- ## Requirements REST framework requires the following: * Django (4.2, 5.0, 5.1, 5.2, 6.0) * Python (3.10, 3.11, 3.12, 3.13, 3.14) We **highly recommend** and only officially support the latest patch release of each Python and Django series. The following packages are optional: * [PyYAML][pyyaml], [uritemplate][uritemplate] (5.1+, 3.0.0+) - Schema generation support. * [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. ## Installation Install using `pip`, including any optional packages you want... ```bash pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support ``` ...or clone the project from github. ```bash git clone https://github.com/encode/django-rest-framework ``` Add `'rest_framework'` to your `INSTALLED_APPS` setting. ```python INSTALLED_APPS = [ # ... "rest_framework", ] ``` If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root `urls.py` file. ```python urlpatterns = [ # ... path("api-auth/", include("rest_framework.urls")) ] ``` Note that the URL path can be whatever you want. ## Example Let's take a look at a quick example of using REST framework to build a simple model-backed API. We'll create a read-write API for accessing information on the users of our project. Any global settings for a REST framework API are kept in a single configuration dictionary named `REST_FRAMEWORK`. Start off by adding the following to your `settings.py` module: ```python REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly" ] } ``` Don't forget to make sure you've also added `rest_framework` to your `INSTALLED_APPS`. We're ready to create our API now. Here's our project's root `urls.py` module: ```python from django.urls import path, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email", "is_staff"] # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r"users", UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("", include(router.urls)), path("api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] ``` You can now open the API in your browser at [http://127.0.0.1:8000/](http://127.0.0.1:8000/), and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system. ## Quickstart Can't wait to get started? The [quickstart guide][quickstart] is the fastest way to get up and running, and building APIs with REST framework. ## Development See the [Contribution guidelines][contributing] for information on how to clone 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. ## Security **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. ## License Copyright © 2011-present, [Encode OSS Ltd](https://www.encode.io/). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. [mozilla]: https://www.mozilla.org/en-US/about/ [redhat]: https://www.redhat.com/ [heroku]: https://www.heroku.com/ [eventbrite]: https://www.eventbrite.co.uk/about/ [pyyaml]: https://pypi.org/project/PyYAML/ [uritemplate]: https://pypi.org/project/uritemplate/ [markdown]: https://pypi.org/project/Markdown/ [pygments]: https://pypi.org/project/Pygments/ [django-filter]: https://pypi.org/project/django-filter/ [django-guardian]: https://github.com/django-guardian/django-guardian [index]: . [oauth1-section]: api-guide/authentication/#django-rest-framework-oauth [oauth2-section]: api-guide/authentication/#django-oauth-toolkit [serializer-section]: api-guide/serializers#serializers [modelserializer-section]: api-guide/serializers#modelserializer [functionview-section]: api-guide/views#function-based-views [quickstart]: tutorial/quickstart.md [generic-views]: api-guide/generic-views.md [viewsets]: api-guide/viewsets.md [routers]: api-guide/routers.md [serializers]: api-guide/serializers.md [authentication]: api-guide/authentication.md [contributing]: community/contributing.md [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework [stack-overflow]: https://stackoverflow.com/ [django-rest-framework-tag]: https://stackoverflow.com/questions/tagged/django-rest-framework [security-mail]: mailto:rest-framework-security@googlegroups.com ================================================ FILE: docs/theme/js/prettify-1.0.js ================================================ var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p document$.subscribe(function() { document.querySelectorAll('pre code').forEach(code => { code.parentElement.classList.add('prettyprint', 'well'); }); prettyPrint(); }); {% endblock %} ================================================ FILE: docs/theme/src/README.md ================================================ # DRF logos This folder contains the source file for the DRF logos as Figma file. ================================================ FILE: docs/theme/src/drf-logos.fig ================================================ version https://git-lfs.github.com/spec/v1 oid sha256:762ff0dcedaa80a0ba95b9b8fc656d0c5fd2514a70d08335afe0eb06c9e14658 size 1303581 ================================================ FILE: docs/theme/stylesheets/extra.css ================================================ :root > * { /* primary */ --md-primary-fg-color: #2c2c2c; --md-primary-fg-color--light: #a8a8a8; --md-primary-fg-color--dark: #181818; /* accent */ --md-accent-fg-color: #c50d0d; --md-accent-fg-color--light: #ff8f8f; --md-accent-fg-color--dark: #A30000; /* Style links */ --md-typeset-a-color: var(--md-typeset-color); } /* Dark theme customisation */ [data-md-color-scheme="slate"] { --md-accent-fg-color--dark: #F25757; } .md-header { border-top: 5px solid #A30000; } body hr { border-top: 1px dotted var(--md-accent-fg-color--dark); } .badges { display: flex; justify-content: end; gap: 8px; } /* Cutesy quote styling */ [dir="ltr"] .md-typeset blockquote { font-family: Georgia, serif; font-size: 18px; font-style: italic; margin: 0.25em 0; padding: 0.25em 40px; line-height: 1.45; position: relative; color: var(--md-typeset-color); border-left: none; } [dir="ltr"] .md-typeset blockquote:before { display: block; content: "\201C"; font-size: 80px; position: absolute; left: -10px; top: -20px; color: #7a7a7a; } [dir="ltr"] .md-typeset blockquote p:last-child { color: #999999; font-size: 14px; display: block; margin-top: 5px; } .md-typeset a { color: var(--md-accent-fg-color--dark); } /* Replacement for `body { background-attachment: fixed; }`, which has performance issues when scrolling on large displays. */ body::before { content: ' '; position: fixed; width: 100%; height: 100%; top: 0; left: 0; background-color: #f8f8f8; background: url(../img/grid.png) repeat-x; will-change: transform; z-index: -1; } ================================================ FILE: docs/theme/stylesheets/prettify.css ================================================ .com { color: #93a1a1; } .lit { color: #195f91; } .pun, .opn, .clo { color: #93a1a1; } .fun { color: #dc322f; } .str, .atv { color: #D14; } .kwd, .prettyprint .tag { color: #1e347b; } .typ, .atn, .dec, .var { color: teal; } .pln { color: #48484c; } [data-md-color-scheme="slate"] { .com { color: #687272; } .lit { color: #2481c7; } .str, .atv { color: #e37e8e;; } .kwd, .prettyprint .tag { color: #6e8ee1; } .typ, .atn, .dec, .var { color: #05abab; } .pln { color: #d3d3dc; } } .prettyprint.linenums { -webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; -moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; } /* Specify class=linenums on a pre to get line numbering */ ol.linenums { margin: 0 0 0 33px; /* IE indents via margin-left */ } ol.linenums li { padding-left: 12px; color: #bebec5; line-height: 20px; text-shadow: 0 1px 0 #fff; } ================================================ FILE: docs/topics/ajax-csrf-cors.md ================================================ # Working with AJAX, CSRF & CORS > "Take a close look at possible CSRF / XSRF vulnerabilities on your own websites. They're the worst kind of vulnerability — very easy to exploit by attackers, yet not so intuitively easy to understand for software developers, at least until you've been bitten by one." > > — [Jeff Atwood][cite] ## Javascript clients If you’re building a JavaScript client to interface with your Web API, you'll need to consider if the client can use the same authentication policy that is used by the rest of the website, and also determine if you need to use CSRF tokens or CORS headers. AJAX requests that are made within the same context as the API they are interacting with will typically use `SessionAuthentication`. This ensures that once a user has logged in, any AJAX requests made can be authenticated using the same session-based authentication that is used for the rest of the website. AJAX requests that are made on a different site from the API they are communicating with will typically need to use a non-session-based authentication scheme, such as `TokenAuthentication`. ## CSRF protection [Cross Site Request Forgery][csrf] protection is a mechanism of guarding against a particular type of attack, which can occur when a user has not logged out of a web site, and continues to have a valid session. In this circumstance a malicious site may be able to perform actions against the target site, within the context of the logged-in session. To guard against these type of attacks, you need to do two things: 1. Ensure that the 'safe' HTTP operations, such as `GET`, `HEAD` and `OPTIONS` cannot be used to alter any server-side state. 2. Ensure that any 'unsafe' HTTP operations, such as `POST`, `PUT`, `PATCH` and `DELETE`, always require a valid CSRF token. If you're using `SessionAuthentication` you'll need to include valid CSRF tokens for any `POST`, `PUT`, `PATCH` or `DELETE` operations. In order to make AJAX requests, you need to include CSRF token in the HTTP header, as [described in the Django documentation][csrf-ajax]. ## CORS [Cross-Origin Resource Sharing][cors] is a mechanism for allowing clients to interact with APIs that are hosted on a different domain. CORS works by requiring the server to include a specific set of headers that allow a browser to determine if and when cross-domain requests should be allowed. The best way to deal with CORS in REST framework is to add the required response headers in middleware. This ensures that CORS is supported transparently, without having to change any behavior in your views. [Adam Johnson][adamchainz] maintains the [django-cors-headers] package, which is known to work correctly with REST framework APIs. [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/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 ================================================ FILE: docs/topics/browsable-api.md ================================================ # The Browsable API > It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we are doing. The precise opposite is the case. Civilization advances by extending the number of important operations which we can perform without thinking about them. > > — [Alfred North Whitehead][cite], An Introduction to Mathematics (1911) API may stand for Application *Programming* Interface, but humans have to be able to read the APIs, too; someone has to do the programming. Django REST Framework supports generating human-friendly HTML output for each resource when the `HTML` format is requested. These pages allow for easy browsing of resources, as well as forms for submitting data to the resources using `POST`, `PUT`, and `DELETE`. ## URLs If you include fully-qualified URLs in your resource output, they will be 'urlized' and made clickable for easy browsing by humans. The `rest_framework` package includes a [`reverse`][drfreverse] helper for this purpose. ## Formats By default, the API will return the format specified by the headers, which in the case of the browser is HTML. The format can be specified using `?format=` in the request, so you can look at the raw JSON response in a browser by adding `?format=json` to the URL. There are helpful extensions for viewing JSON in [Firefox][ffjsonview] and [Chrome][chromejsonview]. ## 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.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: **templates/rest_framework/api.html** {% extends "rest_framework/base.html" %} ... # Override blocks with required customizations ### Overriding the default theme To replace the default theme, add a `bootstrap_theme` block to your `api.html` and insert a `link` to the desired Bootstrap theme css file. This will completely replace the included theme. {% block bootstrap_theme %} {% endblock %} Suitable pre-made replacement themes are available at [Bootswatch][bswatch]. To use any of the Bootswatch themes, simply download the theme's `bootstrap.min.css` file, add it to your project, and replace the default one as described above. 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. Full example: {% extends "rest_framework/base.html" %} {% block bootstrap_theme %} {% endblock %} {% block bootstrap_navbar_variant %}{% endblock %} For more specific CSS tweaks than simply overriding the default bootstrap theme you can override the `style` block. --- ![Cerulean theme][cerulean] *Screenshot of the bootswatch 'Cerulean' theme* --- ![Slate theme][slate] *Screenshot of the bootswatch 'Slate' 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`. * `body` - The entire html ``. * `bodyclass` - Class attribute for the `` tag, empty by default. * `bootstrap_theme` - CSS for the Bootstrap theme. * `bootstrap_navbar_variant` - CSS class for the navbar. * `branding` - Branding section of the navbar, see [Bootstrap components][bcomponentsnav]. * `breadcrumbs` - Links showing resource nesting, allowing the user to go back up the resources. It's recommended to preserve these, but they can be overridden using the breadcrumbs block. * `script` - JavaScript files for the page. * `style` - CSS stylesheets for the page. * `title` - Title of the page. * `userlinks` - This is a list of links on the right of the header, by default containing login/logout links. To add links instead of replace, use `{{ block.super }}` to preserve the authentication links. #### Components All of the standard [Bootstrap components][bcomponents] are available. #### Tooltips The browsable API makes use of the Bootstrap tooltips component. Any element with the `js-tooltip` class and a `title` attribute has that title content will display a tooltip on hover events. ### Login Template To add branding and customize the look-and-feel of the login template, create a template called `login.html` and add it to your project, eg: `templates/rest_framework/login.html`. The template should extend from `rest_framework/login_base.html`. You can add your site name or branding by including the branding block: {% extends "rest_framework/login_base.html" %} {% block branding %}

My Site Name

{% endblock %} You can also customize the style by adding the `bootstrap_theme` or `style` block similar to `api.html`. ### Advanced Customization #### Context The context that's available to the template: * `allowed_methods` : A list of methods allowed by the resource * `api_settings` : The API settings * `available_formats` : A list of formats allowed by the resource * `breadcrumblist` : The list of links following the chain of nested resources * `content` : The content of the API response * `description` : The description of the resource, generated from its docstring * `name` : The name of the resource * `post_form` : A form instance for use by the POST form (if allowed) * `put_form` : A form instance for use by the PUT form (if allowed) * `display_edit_forms` : A boolean indicating whether or not POST, PUT and PATCH forms will be displayed * `request` : The request object * `response` : The response object * `version` : The version of Django REST Framework * `view` : The view handling the request * `FORMAT_PARAM` : The view can accept a format override * `METHOD_PARAM` : The view can accept a method override You can override the `BrowsableAPIRenderer.get_context()` method to customize the context that gets passed to the template. #### Not using base.html For more advanced customization, such as not having a Bootstrap basis or tighter integration with the rest of your site, you can simply choose not to have `api.html` extend `base.html`. Then the page content and capabilities are entirely up to you. #### Handling `ChoiceField` with large numbers of items. When a relationship or `ChoiceField` has too many items, rendering the widget containing all the options can become very slow, and cause the browsable API rendering to perform poorly. The simplest option in this case is to replace the select input with a standard text input. For example: author = serializers.HyperlinkedRelatedField( queryset=User.objects.all(), style={'base_template': 'input.html'} ) #### Autocomplete An alternative, but more complex option would be to replace the input with an autocomplete widget, that only loads and renders a subset of the available options as needed. If you need to do this you'll need to do some work to build a custom autocomplete HTML template yourself. There are [a variety of packages for autocomplete widgets][autocomplete-packages], such as [django-autocomplete-light][django-autocomplete-light], that you may want to refer to. Note that you will not be able to simply include these components as standard widgets, but will need to write the HTML template explicitly. This is because REST framework 3.0 no longer supports the `widget` keyword argument since it now uses templated HTML generation. --- [cite]: https://en.wikiquote.org/wiki/Alfred_North_Whitehead [drfreverse]: ../api-guide/reverse.md [ffjsonview]: https://addons.mozilla.org/en-US/firefox/addon/jsonview/ [chromejsonview]: https://chrome.google.com/webstore/detail/chklaanhfefbnpoihckbnefhakgolnmc [bootstrap]: https://getbootstrap.com/ [cerulean]: ../img/cerulean.png [slate]: ../img/slate.png [bswatch]: https://bootswatch.com/ [bcomponents]: https://getbootstrap.com/2.3.2/components.html [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 ================================================ FILE: docs/topics/browser-enhancements.md ================================================ # Browser enhancements > "There are two noncontroversial uses for overloaded POST. The first is to *simulate* HTTP's uniform interface for clients like web browsers that don't support PUT or DELETE" > > — [RESTful Web Services][cite], Leonard Richardson & Sam Ruby. In order to allow the browsable API to function, there are a couple of browser enhancements that REST framework needs to provide. As of version 3.3.0 onwards these are enabled with javascript, using the [ajax-form][ajax-form] library. ## Browser based PUT, DELETE, etc... The [AJAX form library][ajax-form] supports browser-based `PUT`, `DELETE` and other methods on HTML forms. After including the library, use the `data-method` attribute on the form, like so:
...
Note that prior to 3.3.0, this support was server-side rather than javascript based. The method overloading style (as used in [Ruby on Rails][rails]) is no longer supported due to subtle issues that it introduces in request parsing. ## Browser based submission of non-form content Browser-based submission of content types such as JSON are supported by the [AJAX form library][ajax-form], using form fields with `data-override='content-type'` and `data-override='content'` attributes. For example:
Note that prior to 3.3.0, this support was server-side rather than javascript based. ## URL based format suffixes REST framework can take `?format=json` style URL parameters, which can be a useful shortcut for determining which content type should be returned from the view. This behavior is controlled using the `URL_FORMAT_OVERRIDE` setting. ## HTTP header based method overriding Prior to version 3.3.0 the semi extension header `X-HTTP-Method-Override` was supported for overriding the request method. This behavior is no longer in core, but can be adding if needed using middleware. For example: METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' class MethodOverrideMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if request.method == 'POST' and METHOD_OVERRIDE_HEADER in request.META: request.method = request.META[METHOD_OVERRIDE_HEADER] return self.get_response(request) ## URL based accept headers Until version 3.3.0 REST framework included built-in support for `?accept=application/json` style URL parameters, which would allow the `Accept` header to be overridden. Since the introduction of the content negotiation API this behavior is no longer included in core, but may be added using a custom content negotiation class, if needed. For example: class AcceptQueryParamOverride() def get_accept_list(self, request): header = request.META.get('HTTP_ACCEPT', '*/*') header = request.query_params.get('_accept', header) return [token.strip() for token in header.split(',')] ## Doesn't HTML5 support PUT and DELETE forms? Nope. It was at one point intended to support `PUT` and `DELETE` forms, but was later [dropped from the spec][html5]. There remains [ongoing discussion][put_delete] about adding support for `PUT` and `DELETE`, as well as how to support content types other than form-encoded data. [cite]: https://www.amazon.com/RESTful-Web-Services-Leonard-Richardson/dp/0596529260 [ajax-form]: https://github.com/tomchristie/ajax-form [rails]: https://guides.rubyonrails.org/form_helpers.html#how-do-forms-with-put-or-delete-methods-work [html5]: https://www.w3.org/TR/html5-diff/#changes-2010-06-24 [put_delete]: http://amundsen.com/examples/put-delete-forms/ ================================================ FILE: docs/topics/documenting-your-api.md ================================================ # Documenting your API > A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state. > > — Roy Fielding, [REST APIs must be hypertext driven][cite] REST framework provides a range of different choices for documenting your API. The following is a non-exhaustive list of some of the most popular options. ## Third-party packages for OpenAPI support REST framework recommends using third-party packages for generating and presenting OpenAPI schemas, as they provide more features and flexibility than the built-in (deprecated) implementation. ### 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) !!! warning **Deprecation notice:** REST framework's built-in support for generating OpenAPI schemas is deprecated in favor of third-party packages that provide this functionality instead. As a replacement, we recommend using **drf-spectacular**. There are a number of packages available that allow you to generate HTML documentation pages from OpenAPI schemas. Two popular options are [Swagger UI][swagger-ui] and [ReDoc][redoc]. Both require little more than the location of your static schema file or dynamic `SchemaView` endpoint. ### A minimal example with Swagger UI Assuming you've followed the example from the schemas documentation for routing a dynamic `SchemaView`, a minimal Django template for using Swagger UI might be this: ```html Swagger
``` Save this in your templates folder as `swagger-ui.html`. Then route a `TemplateView` in your project's URL conf: ```python from django.views.generic import TemplateView 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", ), ] ``` See the [Swagger UI documentation][swagger-ui] for advanced usage. ### A minimal example with ReDoc. Assuming you've followed the example from the schemas documentation for routing a dynamic `SchemaView`, a minimal Django template for using ReDoc might be this: ```html ReDoc ``` Save this in your templates folder as `redoc.html`. Then route a `TemplateView` in your project's URL conf: ```python from django.views.generic import TemplateView 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", ), ] ``` See the [ReDoc documentation][redoc] for advanced usage. ## Self describing APIs The browsable API that REST framework provides makes it possible for your API to be entirely self describing. The documentation for each API endpoint can be provided simply by visiting the URL in your browser. ![Screenshot - Self describing API][image-self-describing-api] --- #### Setting the title The title that is used in the browsable API is generated from the view class name or function name. Any trailing `View` or `ViewSet` suffix is stripped, and the string is whitespace separated on uppercase/lowercase boundaries or underscores. For example, the view `UserListView`, will be named `User List` when presented in the browsable API. When working with viewsets, an appropriate suffix is appended to each generated view. For example, the view set `UserViewSet` will generate views named `User List` and `User Instance`. #### Setting the description The description in the browsable API is generated from the docstring of the view or viewset. If the python `Markdown` library is installed, then [markdown syntax][markdown] may be used in the docstring, and will be converted to HTML in the browsable API. For example: class AccountListView(views.APIView): """ Returns a list of all **active** accounts in the system. For more details on how accounts are activated please [see here][ref]. [ref]: http://example.com/activating-accounts """ Note that when using viewsets the basic docstring is used for all generated views. To provide descriptions for each view, such as for the list and retrieve views, use docstring sections as described in [Schemas as documentation: Examples][schemas-examples]. #### The `OPTIONS` method REST framework APIs also support programmatically accessible descriptions, using the `OPTIONS` HTTP method. A view will respond to an `OPTIONS` request with metadata including the name, description, and the various media types it accepts and responds with. When using the generic views, any `OPTIONS` requests will additionally respond with metadata regarding any `POST` or `PUT` actions available, describing which fields are on the serializer. You can modify the response behavior to `OPTIONS` requests by overriding the `options` view method and/or by providing a custom Metadata class. For example: def options(self, request, *args, **kwargs): """ Don't include the view description in OPTIONS responses. """ meta = self.metadata_class() data = meta.determine_metadata(request, self) data.pop('description') return Response(data=data, status=status.HTTP_200_OK) See [the Metadata docs][metadata-docs] for more details. --- ## The hypermedia approach To be fully RESTful an API should present its available actions as hypermedia controls in the responses that it sends. In this approach, rather than documenting the available API endpoints up front, the description instead concentrates on the *media types* that are used. The available actions that may be taken on any given URL are not strictly fixed, but are instead made available by the presence of link and form controls in the returned document. To implement a hypermedia API you'll need to decide on an appropriate media type for the API, and implement a custom renderer and parser for that media type. The [REST, Hypermedia & HATEOAS][hypermedia-docs] section of the documentation includes pointers to background reading, as well as links to various hypermedia formats. [cite]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven [hypermedia-docs]: rest-hypermedia-hateoas.md [metadata-docs]: ../api-guide/metadata.md [schemas-examples]: ../api-guide/schemas.md#examples [image-drf-yasg]: ../img/drf-yasg.png [image-self-describing-api]: ../img/self-describing.png [drf-yasg]: https://github.com/axnsan12/drf-yasg/ [drf-spectacular]: https://github.com/tfranzel/drf-spectacular/ [markdown]: https://daringfireball.net/projects/markdown/syntax [open-api]: https://openapis.org/ [redoc]: https://github.com/Rebilly/ReDoc [swagger]: https://swagger.io/ [swagger-ui]: https://swagger.io/tools/swagger-ui/ ================================================ FILE: docs/topics/html-and-forms.md ================================================ # 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 ================================================ FILE: docs/topics/internationalization.md ================================================ # Internationalization > Supporting internationalization is not optional. It must be a core feature. > > — [Jannis Leidel, speaking at Django Under the Hood, 2015][cite]. REST framework ships with translatable error messages. You can make these appear in your language enabling [Django's standard translation mechanisms][django-translation]. Doing so will allow you to: * Select a language other than English as the default, using the standard `LANGUAGE_CODE` Django setting. * Allow clients to choose a language themselves, using the `LocaleMiddleware` included with Django. A typical usage for API clients would be to include an `Accept-Language` request header. ## Enabling internationalized APIs You can change the default language by using the standard Django `LANGUAGE_CODE` setting: LANGUAGE_CODE = "es-es" You can turn on per-request language requests by adding `LocalMiddleware` to your `MIDDLEWARE` setting: MIDDLEWARE = [ ... 'django.middleware.locale.LocaleMiddleware' ] When per-request internationalization is enabled, client requests will respect the `Accept-Language` header where possible. For example, let's make a request for an unsupported media type: **Request** GET /api/users HTTP/1.1 Accept: application/xml Accept-Language: es-es Host: example.org **Response** HTTP/1.0 406 NOT ACCEPTABLE {"detail": "No se ha podido satisfacer la solicitud de cabecera de Accept."} REST framework includes these built-in translations both for standard exception cases, and for serializer validation errors. Note that the translations only apply to the error strings themselves. The format of error messages, and the keys of field names will remain the same. An example `400 Bad Request` response body might look like this: {"detail": {"username": ["Esse campo deve ser único."]}} If you want to use different string for parts of the response such as `detail` and `non_field_errors` then you can modify this behavior by using a [custom exception handler][custom-exception-handler]. #### Specifying the set of supported languages. By default all available languages will be supported. If you only wish to support a subset of the available languages, use Django's standard `LANGUAGES` setting: LANGUAGES = [ ('de', _('German')), ('en', _('English')), ] ## Adding new translations REST framework translations are managed on GitHub. You can contribute new translation languages or update existing ones by following the guidelines in the [Contributing to REST Framework] section and submitting a pull request. Sometimes you may need to add translation strings to your project locally. You may need to do this if: * You want to use REST Framework in a language which is not supported by the project. * Your project includes custom error messages, which are not part of REST framework's default translation strings. #### Translating a new language locally This guide assumes you are already familiar with how to translate a Django app. If you're not, start by reading [Django's translation docs][django-translation]. If you're translating a new language you'll need to translate the existing REST framework error messages: 1. Make a new folder where you want to store the internationalization resources. Add this path to your [`LOCALE_PATHS`][django-locale-paths] setting. 2. Now create a subfolder for the language you want to translate. The folder should be named using [locale name][django-locale-name] notation. For example: `de`, `pt_BR`, `es_AR`. 3. Now copy the [base translations file][django-po-source] from the REST framework source code into your translations folder. 4. Edit the `django.po` file you've just copied, translating all the error messages. 5. Run `manage.py compilemessages -l pt_BR` to make the translations available for Django to use. You should see a message like `processing file django.po in <...>/locale/pt_BR/LC_MESSAGES`. 6. Restart your development server to see the changes take effect. If you're only translating custom error messages that exist inside your project codebase you don't need to copy the REST framework source `django.po` file into a `LOCALE_PATHS` folder, and can instead simply run Django's standard `makemessages` process. ## How the language is determined If you want to allow per-request language preferences you'll need to include `django.middleware.locale.LocaleMiddleware` in your `MIDDLEWARE` setting. You can find more information on how the language preference is determined in the [Django documentation][django-language-preference]. For reference, the method is: 1. First, it looks for the language prefix in the requested URL. 2. Failing that, it looks for the `LANGUAGE_SESSION_KEY` key in the current user’s session. 3. Failing that, it looks for a cookie. 4. Failing that, it looks at the `Accept-Language` HTTP header. 5. Failing that, it uses the global `LANGUAGE_CODE` setting. For API clients the most appropriate of these will typically be to use the `Accept-Language` header; Sessions and cookies will not be available unless using session authentication, and generally better practice to prefer an `Accept-Language` header for API clients rather than using language URL prefixes. [cite]: https://youtu.be/Wa0VfS2q94Y [Contributing to REST Framework]: ../community/contributing.md#development [django-translation]: https://docs.djangoproject.com/en/stable/topics/i18n/translation [custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling [django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/main/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 [django-locale-name]: https://docs.djangoproject.com/en/stable/topics/i18n/#term-locale-name ================================================ FILE: docs/topics/rest-hypermedia-hateoas.md ================================================ # REST, Hypermedia & HATEOAS > You keep using that word "REST". I do not think it means what you think it means. > > — 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 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. The following fall into the "required reading" category. * Roy Fielding's dissertation - [Architectural Styles and the Design of Network-based Software Architectures][dissertation]. * Roy Fielding's "[REST APIs must be hypertext-driven][hypertext-driven]" blog post. * Leonard Richardson & Mike Amundsen's [RESTful Web APIs][restful-web-apis]. * Mike Amundsen's [Building Hypermedia APIs with HTML5 and Node][building-hypermedia-apis]. * Steve Klabnik's [Designing Hypermedia APIs][designing-hypermedia-apis]. * The [Richardson Maturity Model][maturitymodel]. For a more thorough background, check out Klabnik's [Hypermedia API reading list][readinglist]. ## Building Hypermedia APIs with REST framework REST framework is an agnostic Web API toolkit. It does help guide you towards building well-connected APIs, and makes it easy to design appropriate media types, but it does not strictly enforce any particular design style. ## What REST framework provides. It is self evident that REST framework makes it possible to build Hypermedia APIs. The browsable API that it offers is built on HTML - the hypermedia language of the web. REST framework also includes [serialization] and [parser]/[renderer] components that make it easy to build appropriate media types, [hyperlinked relations][fields] for building well-connected systems, and great support for [content negotiation][conneg]. ## What REST framework doesn't provide. What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labeled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope. [cite]: https://vimeo.com/channels/restfest/49503453 [dissertation]: https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm [hypertext-driven]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven [restful-web-apis]: http://restfulwebapis.org/ [building-hypermedia-apis]: https://www.amazon.com/Building-Hypermedia-APIs-HTML5-Node/dp/1449306578 [designing-hypermedia-apis]: http://designinghypermediaapis.com/ [readinglist]: http://blog.steveklabnik.com/posts/2012-02-27-hypermedia-api-reading-list [maturitymodel]: https://martinfowler.com/articles/richardsonMaturityModel.html [hal]: http://stateless.co/hal_specification.html [collection]: http://www.amundsen.com/media-types/collection/ [json-api]: http://jsonapi.org/ [microformats]: http://microformats.org/wiki/Main_Page [serialization]: ../api-guide/serializers.md [parser]: ../api-guide/parsers.md [renderer]: ../api-guide/renderers.md [fields]: ../api-guide/fields.md [conneg]: ../api-guide/content-negotiation.md ================================================ FILE: docs/topics/writable-nested-serializers.md ================================================ > To save HTTP requests, it may be convenient to send related documents along with the request. > > — [JSON API specification for Ember Data][cite]. # Writable nested serializers Although flat data structures serve to properly delineate between the individual entities in your service, there are cases where it may be more appropriate or convenient to use nested data structures. Nested data structures are easy enough to work with if they're read-only - simply nest your serializer classes and you're good to go. However, there are a few more subtleties to using writable nested serializers, due to the dependencies between the various model instances, and the need to save or delete multiple instances in a single action. ## One-to-many data structures *Example of a **read-only** nested serializer. Nothing complex to worry about here.* class ToDoItemSerializer(serializers.ModelSerializer): class Meta: model = ToDoItem fields = ['text', 'is_completed'] class ToDoListSerializer(serializers.ModelSerializer): items = ToDoItemSerializer(many=True, read_only=True) class Meta: model = ToDoList fields = ['title', 'items'] Some example output from our serializer. { 'title': 'Leaving party preparations', 'items': [ {'text': 'Compile playlist', 'is_completed': True}, {'text': 'Send invites', 'is_completed': False}, {'text': 'Clean house', 'is_completed': False} ] } Let's take a look at updating our nested one-to-many data structure. ### Validation errors ### Adding and removing items ### Making PATCH requests [cite]: http://jsonapi.org/format/#url-based-json-api ================================================ FILE: docs/tutorial/1-serialization.md ================================================ # Tutorial 1: Serialization ## Introduction This tutorial will cover creating a simple pastebin code highlighting Web API. Along the way it will introduce the various components that make up REST framework, and give you a comprehensive understanding of how everything fits together. The tutorial is fairly in-depth, so you should probably get a cookie and a cup of your favorite brew before getting started. If you just want a quick overview, you should head over to the [quickstart] documentation instead. !!! 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. ## Setting up a new environment Before we do anything else we'll create a new virtual environment called `.venv`, using [venv]. This will make sure our package configuration is kept nicely isolated from any other projects we're working on. === ":fontawesome-brands-linux: Linux, :fontawesome-brands-apple: macOS" ```bash python3 -m venv .venv source .venv/bin/activate ``` === ":fontawesome-brands-windows: Windows" If you use Bash for Windows ```bash python3 -m venv .venv source .venv\Scripts\activate ``` Now that we're inside a virtual environment, we can install our package requirements. ```bash pip install django pip install djangorestframework pip install pygments # We'll be using this for the code highlighting ``` !!! tip To exit the virtual environment at any time, just type `deactivate`. For more information see the [venv documentation][venv]. ## Getting started Okay, we're ready to get coding. To get started, let's create a new project to work with. ```bash cd ~ django-admin startproject tutorial cd tutorial ``` Once that's done we can create an app that we'll use to create a simple Web API. ```bash python manage.py startapp snippets ``` We'll need to add our new `snippets` app and the `rest_framework` app to `INSTALLED_APPS`. Let's edit the `tutorial/settings.py` file: ```text INSTALLED_APPS = [ ... 'rest_framework', 'snippets', ] ``` Okay, we're ready to roll. ## Creating a model to work with For the purposes of this tutorial we're going to start by creating a simple `Snippet` model that is used to store code snippets. Go ahead and edit the `snippets/models.py` file. Note: Good programming practices include comments. Although you will find them in our repository version of this tutorial code, we have omitted them here to focus on the code itself. ```python from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default="") code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField( choices=LANGUAGE_CHOICES, default="python", max_length=100 ) style = models.CharField(choices=STYLE_CHOICES, default="friendly", max_length=100) class Meta: ordering = ["created"] ``` We'll also need to create an initial migration for our snippet model, and sync the database for the first time. ```bash python manage.py makemigrations snippets python manage.py migrate snippets ``` ## Creating a Serializer class The first thing we need to get started on our Web API is to provide a way of serializing and deserializing the snippet instances into representations such as `json`. We can do this by declaring serializers that work very similar to Django's forms. Create a file in the `snippets` directory named `serializers.py` and add the following. ```python from rest_framework import serializers from snippets.models import Snippet, LANGUAGE_CHOICES, STYLE_CHOICES class SnippetSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) code = serializers.CharField(style={"base_template": "textarea.html"}) linenos = serializers.BooleanField(required=False) language = serializers.ChoiceField(choices=LANGUAGE_CHOICES, default="python") style = serializers.ChoiceField(choices=STYLE_CHOICES, default="friendly") def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Snippet.objects.create(**validated_data) def update(self, instance, validated_data): """ Update and return an existing `Snippet` instance, given the validated data. """ instance.title = validated_data.get("title", instance.title) instance.code = validated_data.get("code", instance.code) instance.linenos = validated_data.get("linenos", instance.linenos) instance.language = validated_data.get("language", instance.language) instance.style = validated_data.get("style", instance.style) instance.save() return instance ``` The first part of the serializer class defines the fields that get serialized/deserialized. The `create()` and `update()` methods define how fully fledged instances are created or modified when calling `serializer.save()` A serializer class is very similar to a Django `Form` class, and includes similar validation flags on the various fields, such as `required`, `max_length` and `default`. The field flags can also control how the serializer should be displayed in certain circumstances, such as when rendering to HTML. The `{'base_template': 'textarea.html'}` flag above is equivalent to using `widget=widgets.Textarea` on a Django `Form` class. This is particularly useful for controlling how the browsable API should be displayed, as we'll see later in the tutorial. We can actually also save ourselves some time by using the `ModelSerializer` class, as we'll see later, but for now we'll keep our serializer definition explicit. ## Working with Serializers Before we go any further we'll familiarize ourselves with using our new Serializer class. Let's drop into the Django shell. ```bash python manage.py shell ``` Okay, once we've got a few imports out of the way, let's create a couple of code snippets to work with. ```pycon >>> from snippets.models import Snippet >>> from snippets.serializers import SnippetSerializer >>> from rest_framework.renderers import JSONRenderer >>> from rest_framework.parsers import JSONParser >>> snippet = Snippet(code='foo = "bar"\n') >>> snippet.save() >>> snippet = Snippet(code='print("hello, world")\n') >>> snippet.save() ``` We've now got a few snippet instances to play with. Let's take a look at serializing one of those instances. ```pycon >>> serializer = SnippetSerializer(snippet) >>> serializer.data {'id': 2, 'title': '', 'code': 'print("hello, world")\n', 'linenos': False, 'language': 'python', 'style': 'friendly'} ``` At this point we've translated the model instance into Python native datatypes. To finalize the serialization process we render the data into `json`. ```pycon >>> content = JSONRenderer().render(serializer.data) >>> content 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... ```pycon >>> import io >>> stream = io.BytesIO(content) >>> data = JSONParser().parse(stream) ``` ...then we restore those native datatypes into a fully populated object instance. ```pycon >>> serializer = SnippetSerializer(data=data) >>> serializer.is_valid() True >>> serializer.validated_data {'title': '', 'code': 'print("hello, world")', 'linenos': False, 'language': 'python', 'style': 'friendly'} >>> serializer.save() ``` Notice how similar the API is to working with forms. The similarity should become even more apparent when we start writing views that use our serializer. We can also serialize querysets instead of model instances. To do so we simply add a `many=True` flag to the serializer arguments. ```pycon >>> serializer = SnippetSerializer(Snippet.objects.all(), many=True) >>> serializer.data [{'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. In the same way that Django provides both `Form` classes and `ModelForm` classes, REST framework includes both `Serializer` classes, and `ModelSerializer` classes. Let's look at refactoring our serializer using the `ModelSerializer` class. Open the file `snippets/serializers.py` again, and replace the `SnippetSerializer` class with the following. ```python from rest_framework import serializers from snippets.models import Snippet class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = ["id", "title", "code", "linenos", "language", "style"] ``` One nice property that serializers have is that you can inspect all the fields in a serializer instance, by printing its representation. Open the Django shell with `python manage.py shell`, then try the following: ```pycon >>> from snippets.serializers import SnippetSerializer >>> serializer = SnippetSerializer() >>> print(repr(serializer)) SnippetSerializer(): id = IntegerField(label='ID', read_only=True) title = CharField(allow_blank=True, max_length=100, required=False) code = CharField(style={'base_template': 'textarea.html'}) linenos = BooleanField(required=False) language = ChoiceField(choices=[('Clipper', 'FoxPro'), ('Cucumber', 'Gherkin'), ('RobotFramework', 'RobotFramework'), ('abap', 'ABAP'), ('ada', 'Ada')... style = ChoiceField(choices=[('autumn', 'autumn'), ('borland', 'borland'), ('bw', 'bw'), ('colorful', 'colorful')... ``` It's important to remember that `ModelSerializer` classes don't do anything particularly magical, they are simply a shortcut for creating serializer classes: * An automatically determined set of fields. * Simple default implementations for the `create()` and `update()` methods. ## Writing regular Django views using our Serializer Let's see how we can write some API views using our new Serializer class. For the moment we won't use any of REST framework's other features, we'll just write the views as regular Django views. Edit the `snippets/views.py` file, and add the following. ```python from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer ``` The root of our API is going to be a view that supports listing all the existing snippets, or creating a new snippet. ```python @csrf_exempt def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == "GET": snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == "POST": data = JSONParser().parse(request) serializer = SnippetSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) ``` Note that because we want to be able to POST to this view from clients that won't have a CSRF token we need to mark the view as `csrf_exempt`. This isn't something that you'd normally want to do, and REST framework views actually use more sensible behavior than this, but it'll do for our purposes right now. We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet. ```python @csrf_exempt def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": serializer = SnippetSerializer(snippet) return JsonResponse(serializer.data) elif request.method == "PUT": data = JSONParser().parse(request) serializer = SnippetSerializer(snippet, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == "DELETE": snippet.delete() return HttpResponse(status=204) ``` Finally we need to wire these views up. Create the `snippets/urls.py` file: ```python from django.urls import path from snippets import views urlpatterns = [ path("snippets/", views.snippet_list), path("snippets//", views.snippet_detail), ] ``` We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs. ```python from django.urls import path, include urlpatterns = [ path("", include("snippets.urls")), ] ``` It's worth noting that there are a couple of edge cases we're not dealing with properly at the moment. If we send malformed `json`, or if a request is made with a method that the view doesn't handle, then we'll end up with a 500 "server error" response. Still, this'll do for now. ## Testing our first attempt at a Web API Now we can start up a sample server that serves our snippets. Quit out of the shell... ```pycon >>> quit() ``` ...and start up Django's development server. ```bash python manage.py runserver Validating models... 0 errors found Django version 5.0, using settings 'tutorial.settings' Starting Development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ``` In another terminal window, we can test the server. We can test our API using [curl][curl] or [HTTPie][HTTPie]. HTTPie is a user-friendly http client that's written in Python. Let's install that. You can install HTTPie using pip: ```bash pip install httpie ``` Finally, we can get a list of all of the snippets: ```bash 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": 3, "title": "", "code": "print(\"hello, world\")", "linenos": false, "language": "python", "style": "friendly" } ] ``` Or we can get a particular snippet by referencing its id: ```bash 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" } ``` Similarly, you can have the same json displayed by visiting these URLs in a web browser. ## Where are we now We're doing okay so far, we've got a serialization API that feels pretty similar to Django's Forms API, and some regular Django views. Our API views don't do anything particularly special at the moment, beyond serving `json` responses, and there are some error handling edge cases we'd still like to clean up, but it's a functioning Web API. 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 [venv]: https://docs.python.org/3/library/venv.html [tut-2]: 2-requests-and-responses.md [HTTPie]: https://github.com/httpie/httpie#installation [curl]: https://curl.haxx.se/ ================================================ FILE: docs/tutorial/2-requests-and-responses.md ================================================ # Tutorial 2: Requests and Responses From this point we're going to really start covering the core of REST framework. Let's introduce a couple of essential building blocks. ## Request objects REST framework introduces a `Request` object that extends the regular `HttpRequest`, and provides more flexible request parsing. The core functionality of the `Request` object is the `request.data` attribute, which is similar to `request.POST`, but more useful for working with Web APIs. ```python request.POST # Only handles form data. Only works for 'POST' method. request.data # Handles arbitrary data. Works for 'POST', 'PUT' and 'PATCH' methods. ``` ## Response objects REST framework also introduces a `Response` object, which is a type of `TemplateResponse` that takes unrendered content and uses content negotiation to determine the correct content type to return to the client. ```python return Response(data) # Renders to content type as requested by the client. ``` ## Status codes Using numeric HTTP status codes in your views doesn't always make for obvious reading, and it's easy to not notice if you get an error code wrong. REST framework provides more explicit identifiers for each status code, such as `HTTP_400_BAD_REQUEST` in the `status` module. It's a good idea to use these throughout rather than using numeric identifiers. ## Wrapping API views REST framework provides two wrappers you can use to write API views. 1. The `@api_view` decorator for working with function based views. 2. The `APIView` class for working with class-based 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 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 Okay, let's go ahead and start using these new components to refactor our views slightly. ```python from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from snippets.models import Snippet from snippets.serializers import SnippetSerializer @api_view(["GET", "POST"]) def snippet_list(request): """ List all code snippets, or create a new snippet. """ if request.method == "GET": snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) elif request.method == "POST": serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ``` Our instance view is an improvement over the previous example. It's a little more concise, and the code now feels very similar to if we were working with the Forms API. We're also using named status codes, which makes the response meanings more obvious. Here is the view for an individual snippet, in the `views.py` module. ```python @api_view(["GET", "PUT", "DELETE"]) def snippet_detail(request, pk): """ Retrieve, update or delete a code snippet. """ try: snippet = Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == "GET": serializer = SnippetSerializer(snippet) return Response(serializer.data) elif request.method == "PUT": serializer = SnippetSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == "DELETE": snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT) ``` This should all feel very familiar - it is not a lot different from working with regular Django views. Notice that we're no longer explicitly tying our requests or responses to a given content type. `request.data` can handle incoming `json` requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us. ## Adding optional format suffixes to our URLs To take advantage of the fact that our responses are no longer hardwired to a single content type let's add support for format suffixes to our API endpoints. Using format suffixes gives us URLs that explicitly refer to a given format, and means our API will be able to handle URLs such as [][json-url]. Start by adding a `format` keyword argument to both of the views, like so. `def snippet_list(request, format=None):` and `def snippet_detail(request, pk, format=None):` Now update the `snippets/urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs. ```python from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path("snippets/", views.snippet_list), path("snippets//", views.snippet_detail), ] urlpatterns = format_suffix_patterns(urlpatterns) ``` We don't necessarily need to add these extra url patterns in, but it gives us a simple, clean way of referring to a specific format. ## How's it looking? Go ahead and test the API from the command line, as we did in [tutorial part 1][tut-1]. Everything is working pretty similarly, although we've got some nicer error handling if we send invalid requests. We can get a list of all of the snippets, as before. ```bash http http://127.0.0.1:8000/snippets/ 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" } ] ``` We can control the format of the response that we get back, either by using the `Accept` header: ```bash http http://127.0.0.1:8000/snippets/ Accept:application/json # Request JSON http http://127.0.0.1:8000/snippets/ Accept:text/html # Request HTML ``` Or by appending a format suffix: ```bash http http://127.0.0.1:8000/snippets.json # JSON suffix http http://127.0.0.1:8000/snippets.api # Browsable API suffix ``` Similarly, we can control the format of the request that we send, using the `Content-Type` header. ```bash # POST using form data http --form POST http://127.0.0.1:8000/snippets/ code="print(123)" { "id": 3, "title": "", "code": "print(123)", "linenos": false, "language": "python", "style": "friendly" } # POST using JSON http --json POST http://127.0.0.1:8000/snippets/ code="print(456)" { "id": 4, "title": "", "code": "print(456)", "linenos": false, "language": "python", "style": "friendly" } ``` If you add a `--debug` switch to the `http` requests above, you will be able to see the request type in request headers. Now go and open the API in a web browser, by visiting [][devserver]. ### Browsability Because the API chooses the content type of the response based on the client request, it will, by default, return an HTML-formatted representation of the resource when that resource is requested by a web browser. This allows for the API to return a fully web-browsable HTML representation. Having a web-browsable API is a huge usability win, and makes developing and using your API much easier. It also dramatically lowers the barrier-to-entry for other developers wanting to inspect and work with your API. See the [browsable api][browsable-api] topic for more information about the browsable API feature and how to customize it. ## What's next? In [tutorial part 3][tut-3], we'll start using class-based views, and see how generic views reduce the amount of code we need to write. [json-url]: http://example.com/api/items/4.json [devserver]: http://127.0.0.1:8000/snippets/ [browsable-api]: ../topics/browsable-api.md [tut-1]: 1-serialization.md [tut-3]: 3-class-based-views.md ================================================ FILE: docs/tutorial/3-class-based-views.md ================================================ # Tutorial 3: Class-based Views We can also write our API views using class-based views, rather than function based views. As we'll see this is a powerful pattern that allows us to reuse common functionality, and helps us keep our code [DRY][dry]. ## Rewriting our API using class-based views We'll start by rewriting the root view as a class-based view. All this involves is a little bit of refactoring of `views.py`. ```python from snippets.models import Snippet from snippets.serializers import SnippetSerializer from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status class SnippetList(APIView): """ List all snippets, or create a new snippet. """ def get(self, request, format=None): snippets = Snippet.objects.all() serializer = SnippetSerializer(snippets, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = SnippetSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ``` So far, so good. It looks pretty similar to the previous case, but we've got better separation between the different HTTP methods. We'll also need to update the instance view in `views.py`. ```python class SnippetDetail(APIView): """ Retrieve, update or delete a snippet instance. """ def get_object(self, pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http404 def get(self, request, pk, format=None): snippet = self.get_object(pk) serializer = SnippetSerializer(snippet) return Response(serializer.data) def put(self, request, pk, format=None): snippet = self.get_object(pk) serializer = SnippetSerializer(snippet, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): snippet = self.get_object(pk) snippet.delete() return Response(status=status.HTTP_204_NO_CONTENT) ``` That's looking good. Again, it's still pretty similar to the function based view right now. We'll also need to refactor our `snippets/urls.py` slightly now that we're using class-based views. ```python from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views urlpatterns = [ path("snippets/", views.SnippetList.as_view()), path("snippets//", views.SnippetDetail.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns) ``` Okay, we're done. If you run the development server everything should be working just as before. ## Using mixins 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 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. ```python from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework import mixins from rest_framework import generics class SnippetList( mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView ): queryset = Snippet.objects.all() serializer_class = SnippetSerializer def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) ``` We'll take a moment to examine exactly what's happening here. We're building our view using `GenericAPIView`, and adding in `ListModelMixin` and `CreateModelMixin`. The base class provides the core functionality, and the mixin classes provide the `.list()` and `.create()` actions. We're then explicitly binding the `get` and `post` methods to the appropriate actions. Simple enough stuff so far. ```python class SnippetDetail( mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView, ): queryset = Snippet.objects.all() serializer_class = SnippetSerializer def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) ``` Pretty similar. Again we're using the `GenericAPIView` class to provide the core functionality, and adding in mixins to provide the `.retrieve()`, `.update()` and `.destroy()` actions. ## Using generic class-based views Using the mixin classes we've rewritten the views to use slightly less code than before, but we can go one step further. REST framework provides a set of already mixed-in generic views that we can use to trim down our `views.py` module even more. ```python from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework import generics class SnippetList(generics.ListCreateAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer class SnippetDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer ``` Wow, that's pretty concise. We've gotten a huge amount for free, and our code looks like good, clean, idiomatic Django. Next we'll move onto [part 4 of the tutorial][tut-4], where we'll take a look at how we can deal with authentication and permissions for our API. [dry]: https://en.wikipedia.org/wiki/Don't_repeat_yourself [tut-4]: 4-authentication-and-permissions.md ================================================ FILE: docs/tutorial/4-authentication-and-permissions.md ================================================ # Tutorial 4: Authentication & Permissions Currently our API doesn't have any restrictions on who can edit or delete code snippets. We'd like to have some more advanced behavior in order to make sure that: * Code snippets are always associated with a creator. * Only authenticated users may create snippets. * Only the creator of a snippet may update or delete it. * Unauthenticated requests should have full read-only access. ## Adding information to our model We're going to make a couple of changes to our `Snippet` model class. First, let's add a couple of fields. One of those fields will be used to represent the user who created the code snippet. The other field will be used to store the highlighted HTML representation of the code. Add the following two fields to the `Snippet` model in `models.py`. ```python owner = models.ForeignKey( "auth.User", related_name="snippets", on_delete=models.CASCADE ) highlighted = models.TextField() ``` We'd also need to make sure that when the model is saved, that we populate the highlighted field, using the `pygments` code highlighting library. We'll need some extra imports: ```python from pygments.lexers import get_lexer_by_name from pygments.formatters.html import HtmlFormatter from pygments import highlight ``` And now we can add a `.save()` method to our model class: ```python def save(self, *args, **kwargs): """ Use the `pygments` library to create a highlighted HTML representation of the code snippet. """ lexer = get_lexer_by_name(self.language) linenos = "table" if self.linenos else False options = {"title": self.title} if self.title else {} formatter = HtmlFormatter(style=self.style, linenos=linenos, full=True, **options) self.highlighted = highlight(self.code, lexer, formatter) super().save(*args, **kwargs) ``` When that's all done we'll need to update our database tables. Normally we'd create a database migration in order to do that, but for the purposes of this tutorial, let's just delete the database and start again. ```bash rm -f db.sqlite3 rm -r snippets/migrations python manage.py makemigrations snippets python manage.py migrate ``` You might also want to create a few different users, to use for testing the API. The quickest way to do this will be with the `createsuperuser` command. ```bash python manage.py createsuperuser ``` ## Adding endpoints for our User models Now that we've got some users to work with, we'd better add representations of those users to our API. Creating a new serializer is easy. In `serializers.py` add: ```python from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField( many=True, queryset=Snippet.objects.all() ) class Meta: model = User fields = ["id", "username", "snippets"] ``` Because `'snippets'` is a *reverse* relationship on the User model, it will not be included by default when using the `ModelSerializer` class, so we needed to add an explicit field for it. We'll also add a couple of views to `views.py`. We'd like to just use read-only views for the user representations, so we'll use the `ListAPIView` and `RetrieveAPIView` generic class-based views. ```python from django.contrib.auth.models import User class UserList(generics.ListAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetail(generics.RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer ``` Make sure to also import the `UserSerializer` class ```python from snippets.serializers import UserSerializer ``` Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `snippets/urls.py`. ```python path("users/", views.UserList.as_view()), path("users//", views.UserDetail.as_view()), ``` ## Associating Snippets with Users Right now, if we created a code snippet, there'd be no way of associating the user that created the snippet, with the snippet instance. The user isn't sent as part of the serialized representation, but is instead a property of the incoming request. The way we deal with that is by overriding a `.perform_create()` method on our snippet views, that allows us to modify how the instance save is managed, and handle any information that is implicit in the incoming request or requested URL. On the `SnippetList` view class, add the following method: ```python def perform_create(self, serializer): serializer.save(owner=self.request.user) ``` The `create()` method of our serializer will now be passed an additional `'owner'` field, along with the validated data from the request. ## Updating our serializer Now that snippets are associated with the user that created them, let's update our `SnippetSerializer` to reflect that. Add the following field to the serializer definition in `serializers.py`: ```python owner = serializers.ReadOnlyField(source="owner.username") ``` !!! note Make sure you also add `'owner',` to the list of fields in the inner `Meta` class. This field is doing something quite interesting. The `source` argument controls which attribute is used to populate a field, and can point at any attribute on the serialized instance. It can also take the dotted notation shown above, in which case it will traverse the given attributes, in a similar way as it is used with Django's template language. The field we've added is the untyped `ReadOnlyField` class, in contrast to the other typed fields, such as `CharField`, `BooleanField` etc... The untyped `ReadOnlyField` is always read-only, and will be used for serialized representations, but will not be used for updating model instances when they are deserialized. We could have also used `CharField(read_only=True)` here. ## Adding required permissions to views Now that code snippets are associated with users, we want to make sure that only authenticated users are able to create, update and delete code snippets. REST framework includes a number of permission classes that we can use to restrict who can access a given view. In this case the one we're looking for is `IsAuthenticatedOrReadOnly`, which will ensure that authenticated requests get read-write access, and unauthenticated requests get read-only access. First add the following import in the views module ```python from rest_framework import permissions ``` Then, add the following property to **both** the `SnippetList` and `SnippetDetail` view classes. ```python permission_classes = [permissions.IsAuthenticatedOrReadOnly] ``` ## Adding login to the Browsable API If you open a browser and navigate to the browsable API at the moment, you'll find that you're no longer able to create new code snippets. In order to do so we'd need to be able to login as a user. We can add a login view for use with the browsable API, by editing the URLconf in our project-level `urls.py` file. Add the following import at the top of the file: ```python from django.urls import path, include ``` And, at the end of the file, add a pattern to include the login and logout views for the browsable API. ```python urlpatterns += [ path("api-auth/", include("rest_framework.urls")), ] ``` The `'api-auth/'` part of pattern can actually be whatever URL you want to use. Now if you open up the browser again and refresh the page you'll see a 'Login' link in the top right of the page. If you log in as one of the users you created earlier, you'll be able to create code snippets again. Once you've created a few code snippets, navigate to the '/users/' endpoint, and notice that the representation includes a list of the snippet ids that are associated with each user, in each user's 'snippets' field. ## Object level permissions Really we'd like all code snippets to be visible to anyone, but also make sure that only the user that created a code snippet is able to update or delete it. To do that we're going to need to create a custom permission. In the snippets app, create a new file, `permissions.py` ```python from rest_framework import permissions class IsOwnerOrReadOnly(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): # Read permissions are allowed to any request, # so we'll always allow GET, HEAD or OPTIONS requests. if request.method in permissions.SAFE_METHODS: return True # Write permissions are only allowed to the owner of the snippet. return obj.owner == request.user ``` Now we can add that custom permission to our snippet instance endpoint, by editing the `permission_classes` property on the `SnippetDetail` view class: ```python permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] ``` Make sure to also import the `IsOwnerOrReadOnly` class. ```python from snippets.permissions import IsOwnerOrReadOnly ``` Now, if you open a browser again, you find that the 'DELETE' and 'PUT' actions only appear on a snippet instance endpoint if you're logged in as the same user that created the code snippet. ## Authenticating with the API Because we now have a set of permissions on the API, we need to authenticate our requests to it if we want to edit any snippets. We haven't set up any [authentication classes][authentication], so the defaults are currently applied, which are `SessionAuthentication` and `BasicAuthentication`. When we interact with the API through the web browser, we can login, and the browser session will then provide the required authentication for the requests. If we're interacting with the API programmatically we need to explicitly provide the authentication credentials on each request. If we try to create a snippet without authenticating, we'll get an error: ```bash http POST http://127.0.0.1:8000/snippets/ code="print(123)" { "detail": "Authentication credentials were not provided." } ``` We can make a successful request by including the username and password of one of the users we created earlier. ```bash http -a admin:password123 POST http://127.0.0.1:8000/snippets/ code="print(789)" { "id": 1, "owner": "admin", "title": "foo", "code": "print(789)", "linenos": false, "language": "python", "style": "friendly" } ``` ## Summary We've now got a fairly fine-grained set of permissions on our Web API, and end points for users of the system and for the code snippets that they have created. In [part 5][tut-5] of the tutorial we'll look at how we can tie everything together by creating an HTML endpoint for our highlighted snippets, and improve the cohesion of our API by using hyperlinking for the relationships within the system. [authentication]: ../api-guide/authentication.md [tut-5]: 5-relationships-and-hyperlinked-apis.md ================================================ FILE: docs/tutorial/5-relationships-and-hyperlinked-apis.md ================================================ # Tutorial 5: Relationships & Hyperlinked APIs At the moment relationships within our API are represented by using primary keys. In this part of the tutorial we'll improve the cohesion and discoverability of our API, by instead using hyperlinking for relationships. ## Creating an endpoint for the root of our API Right now we have endpoints for 'snippets' and 'users', but we don't have a single entry point to our API. To create one, we'll use a regular function-based view and the `@api_view` decorator we introduced earlier. In your `snippets/views.py` add: ```python from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework.reverse import reverse @api_view(["GET"]) def api_root(request, format=None): return Response( { "users": reverse("user-list", request=request, format=format), "snippets": reverse("snippet-list", request=request, format=format), } ) ``` Two things should be noticed here. First, we're using REST framework's `reverse` function in order to return fully-qualified URLs; second, URL patterns are identified by convenience names that we will declare later on in our `snippets/urls.py`. ## Creating an endpoint for the highlighted snippets The other obvious thing that's still missing from our pastebin API is the code highlighting endpoints. Unlike all our other API endpoints, we don't want to use JSON, but instead just present an HTML representation. There are two styles of HTML renderer provided by REST framework, one for dealing with HTML rendered using templates, the other for dealing with pre-rendered HTML. The second renderer is the one we'd like to use for this endpoint. The other thing we need to consider when creating the code highlight view is that there's no existing concrete generic view that we can use. We're not returning an object instance, but instead a property of an object instance. Instead of using a concrete generic view, we'll use the base class for representing instances, and create our own `.get()` method. In your `snippets/views.py` add: ```python from rest_framework import renderers class SnippetHighlight(generics.GenericAPIView): queryset = Snippet.objects.all() renderer_classes = [renderers.StaticHTMLRenderer] def get(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) ``` As usual we need to add the new views that we've created in to our URLconf. We'll add a url pattern for our new API root in `snippets/urls.py`: ```python path("", views.api_root), ``` And then add a url pattern for the snippet highlights: ```python path("snippets//highlight/", views.SnippetHighlight.as_view()), ``` ## Hyperlinking our API Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship: * Using primary keys. * Using hyperlinking between entities. * Using a unique identifying slug field on the related entity. * Using the default string representation of the related entity. * Nesting the related entity inside the parent representation. * Some other custom representation. REST framework supports all of these styles, and can apply them across forward or reverse relationships, or apply them across custom managers such as generic foreign keys. In this case we'd like to use a hyperlinked style between entities. In order to do so, we'll modify our serializers to extend `HyperlinkedModelSerializer` instead of the existing `ModelSerializer`. The `HyperlinkedModelSerializer` has the following differences from `ModelSerializer`: * It does not include the `id` field by default. * It includes a `url` field, using `HyperlinkedIdentityField`. * Relationships use `HyperlinkedRelatedField`, instead of `PrimaryKeyRelatedField`. We can easily re-write our existing serializers to use hyperlinking. In your `snippets/serializers.py` add: ```python class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source="owner.username") highlight = serializers.HyperlinkedIdentityField( view_name="snippet-highlight", format="html" ) class Meta: model = Snippet fields = [ "url", "id", "highlight", "owner", "title", "code", "linenos", "language", "style", ] class UserSerializer(serializers.HyperlinkedModelSerializer): snippets = serializers.HyperlinkedRelatedField( many=True, view_name="snippet-detail", read_only=True ) class Meta: model = User fields = ["url", "id", "username", "snippets"] ``` Notice that we've also added a new `'highlight'` field. This field is of the same type as the `url` field, except that it points to the `'snippet-highlight'` url pattern, instead of the `'snippet-detail'` url pattern. Because we've included format suffixed URLs such as `'.json'`, we also need to indicate on the `highlight` field that any format suffixed hyperlinks it returns should use the `'.html'` suffix. !!! note When you are manually instantiating these serializers inside your views (e.g., in `SnippetDetail` or `SnippetList`), you **must** pass `context={'request': request}` so the serializer knows how to build absolute URLs. For example, instead of: serializer = SnippetSerializer(snippet) You must write: serializer = SnippetSerializer(snippet, context={"request": request}) If your view is a subclass of `GenericAPIView`, you may use the `get_serializer_context()` as a convenience method. ## Making sure our URL patterns are named If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name. * The root of our API refers to `'user-list'` and `'snippet-list'`. * Our snippet serializer includes a field that refers to `'snippet-highlight'`. * Our user serializer includes a field that refers to `'snippet-detail'`. * Our snippet and user serializers include `'url'` fields that by default will refer to `'{model_name}-detail'`, which in this case will be `'snippet-detail'` and `'user-detail'`. After adding all those names into our URLconf, our final `snippets/urls.py` file should look like this: ```python from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from snippets import views # API endpoints urlpatterns = format_suffix_patterns( [ path("", views.api_root), path("snippets/", views.SnippetList.as_view(), name="snippet-list"), path( "snippets//", views.SnippetDetail.as_view(), name="snippet-detail" ), path( "snippets//highlight/", views.SnippetHighlight.as_view(), name="snippet-highlight", ), path("users/", views.UserList.as_view(), name="user-list"), path("users//", views.UserDetail.as_view(), name="user-detail"), ] ) ``` ## Adding pagination The list views for users and code snippets could end up returning quite a lot of instances, so really we'd like to make sure we paginate the results, and allow the API client to step through each of the individual pages. We can change the default list style to use pagination, by modifying our `tutorial/settings.py` file slightly. Add the following setting: ```python REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10, } ``` Note that settings in REST framework are all namespaced into a single dictionary setting, named `REST_FRAMEWORK`, which helps keep them well separated from your other project settings. We could also customize the pagination style if we needed to, but in this case we'll just stick with the default. ## Browsing the API If we open a browser and navigate to the browsable API, you'll find that you can now work your way around the API simply by following links. You'll also be able to see the 'highlight' links on the snippet instances, that will take you to the highlighted code HTML representations. In [part 6][tut-6] of the tutorial we'll look at how we can use ViewSets and Routers to reduce the amount of code we need to build our API. [tut-6]: 6-viewsets-and-routers.md ================================================ FILE: docs/tutorial/6-viewsets-and-routers.md ================================================ # Tutorial 6: ViewSets & Routers REST framework includes an abstraction for dealing with `ViewSets`, that allows the developer to concentrate on modeling the state and interactions of the API, and leave the URL construction to be handled automatically, based on common conventions. `ViewSet` classes are almost the same thing as `View` classes, except that they provide operations such as `retrieve`, or `update`, and not method handlers such as `get` or `put`. A `ViewSet` class is only bound to a set of method handlers at the last moment, when it is instantiated into a set of views, typically by using a `Router` class which handles the complexities of defining the URL conf for you. ## Refactoring to use ViewSets Let's take our current set of views, and refactor them into view sets. 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: ```python from rest_framework import viewsets class UserViewSet(viewsets.ReadOnlyModelViewSet): """ This viewset automatically provides `list` and `retrieve` actions. """ queryset = User.objects.all() serializer_class = UserSerializer ``` Here we've used the `ReadOnlyModelViewSet` class to automatically provide the default 'read-only' operations. We're still setting the `queryset` and `serializer_class` attributes exactly as we did when we were using regular views, but we no longer need to provide the same information to two separate classes. 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. ```python from rest_framework import permissions from rest_framework import renderers from rest_framework.decorators import action from rest_framework.response import Response class SnippetViewSet(viewsets.ModelViewSet): """ This ViewSet automatically provides `list`, `create`, `retrieve`, `update` and `destroy` actions. Additionally we also provide an extra `highlight` action. """ queryset = Snippet.objects.all() serializer_class = SnippetSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly] @action(detail=True, renderer_classes=[renderers.StaticHTMLRenderer]) def highlight(self, request, *args, **kwargs): snippet = self.get_object() return Response(snippet.highlighted) def perform_create(self, serializer): serializer.save(owner=self.request.user) ``` This time we've used the `ModelViewSet` class in order to get the complete set of default read and write operations. Notice that we've also used the `@action` decorator to create a custom action, named `highlight`. This decorator can be used to add any custom endpoints that don't fit into the standard `create`/`update`/`delete` style. Custom actions which use the `@action` decorator will respond to `GET` requests by default. We can use the `methods` argument if we wanted an action that responded to `POST` requests. The URLs for custom actions by default depend on the method name itself. If you want to change the way url should be constructed, you can include `url_path` as a decorator keyword argument. ## Binding ViewSets to URLs explicitly The handler methods only get bound to the actions when we define the URLConf. To see what's going on under the hood let's first explicitly create a set of views from our ViewSets. In the `snippets/urls.py` file we bind our `ViewSet` classes into a set of concrete views. ```python from rest_framework import renderers from snippets.views import api_root, SnippetViewSet, UserViewSet snippet_list = SnippetViewSet.as_view({"get": "list", "post": "create"}) snippet_detail = SnippetViewSet.as_view( {"get": "retrieve", "put": "update", "patch": "partial_update", "delete": "destroy"} ) snippet_highlight = SnippetViewSet.as_view( {"get": "highlight"}, renderer_classes=[renderers.StaticHTMLRenderer] ) user_list = UserViewSet.as_view({"get": "list"}) user_detail = UserViewSet.as_view({"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. Now that we've bound our resources into concrete views, we can register the views with the URL conf as usual. ```python urlpatterns = format_suffix_patterns( [ path("", api_root), path("snippets/", snippet_list, name="snippet-list"), path("snippets//", snippet_detail, name="snippet-detail"), path( "snippets//highlight/", snippet_highlight, name="snippet-highlight" ), path("users/", user_list, name="user-list"), path("users//", user_detail, name="user-detail"), ] ) ``` ## Using Routers Because we're using `ViewSet` classes rather than `View` classes, we actually don't need to design the URL conf ourselves. The conventions for wiring up resources into views and urls can be handled automatically, using a `Router` class. All we need to do is register the appropriate view sets with a router, and let it do the rest. Here's our re-wired `snippets/urls.py` file. ```python 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. router = DefaultRouter() 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 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` function from our `views` module. ## 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. 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. ================================================ FILE: docs/tutorial/quickstart.md ================================================ # Quickstart We're going to create a simple API to allow admin users to view and edit the users and groups in the system. ## Project setup Create a new Django project named `tutorial`, then start a new app called `quickstart`. === ":fontawesome-brands-linux: Linux, :fontawesome-brands-apple: macOS" ```bash # Create the project directory mkdir tutorial cd tutorial # Create a virtual environment to isolate our package dependencies locally python3 -m venv .venv source .venv/bin/activate # Install Django and Django REST framework into the virtual environment pip install djangorestframework # Set up a new project with a single application django-admin startproject tutorial . # Note the trailing '.' character cd tutorial django-admin startapp quickstart cd .. ``` === ":fontawesome-brands-windows: Windows" If you use Bash for Windows ```bash # Create the project directory mkdir tutorial cd tutorial # Create a virtual environment to isolate our package dependencies locally python3 -m venv .venv source .venv\Scripts\activate # Install Django and Django REST framework into the virtual environment pip install djangorestframework # Set up a new project with a single application django-admin startproject tutorial . # Note the trailing '.' character cd tutorial django-admin startapp quickstart cd .. ``` The project layout should look like: ```bash $ pwd /tutorial $ find . . ./tutorial ./tutorial/asgi.py ./tutorial/__init__.py ./tutorial/quickstart ./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/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). Now sync your database for the first time: ```bash python manage.py migrate ``` We'll also create an initial user named `admin` with a password. We'll authenticate as that user later in our example. ```bash 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... ## Serializers 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. ```python from django.contrib.auth.models import Group, User from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ["url", "username", "email", "groups"] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ["url", "name"] ``` Notice that we're using hyperlinked relations in this case with `HyperlinkedModelSerializer`. You can also use primary key and various other relationships, but hyperlinking is good RESTful design. ## Views Right, we'd better write some views then. Open `tutorial/quickstart/views.py` and get typing. ```python 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): """ API endpoint that allows users to be viewed or edited. """ queryset = User.objects.all().order_by("-date_joined") serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated] class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ queryset = Group.objects.all().order_by("name") serializer_class = GroupSerializer permission_classes = [permissions.IsAuthenticated] ``` Rather than write multiple views we're grouping together all the common behavior into classes called `ViewSets`. We can easily break these down into individual views if we need to, but using viewsets keeps the view logic nicely organized as well as being very concise. ## URLs Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... ```python from django.urls import include, path from rest_framework import routers from tutorial.quickstart import views router = routers.DefaultRouter() router.register(r"users", views.UserViewSet) router.register(r"groups", views.GroupViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ path("", include(router.urls)), path("api-auth/", include("rest_framework.urls", namespace="rest_framework")), ] ``` Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. Again, if we need more control over the API URLs we can simply drop down to using regular class-based views, and writing the URL conf explicitly. Finally, we're including default login and logout views for use with the browsable API. That's optional, but useful if your API requires authentication and you want to use the browsable API. ## Pagination Pagination allows you to control how many objects per page are returned. To enable it add the following lines to `tutorial/settings.py` ```python REST_FRAMEWORK = { "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.PageNumberPagination", "PAGE_SIZE": 10, } ``` ## Settings Add `'rest_framework'` to `INSTALLED_APPS`. The settings module will be in `tutorial/settings.py` ```text INSTALLED_APPS = [ ... 'rest_framework', ] ``` Okay, we're done. --- ## Testing our API We're now ready to test the API we've built. Let's fire up the server from the command line. ```bash python manage.py runserver ``` We can now access our API, both from the command-line, using tools like `curl`... ```bash bash: curl -u admin -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/users/ Enter host password for user 'admin': { "count": 1, "next": null, "previous": null, "results": [ { "url": "http://127.0.0.1:8000/users/1/", "username": "admin", "email": "admin@example.com", "groups": [] } ] } ``` Or using the [httpie][httpie], command line tool... ```bash 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": 1, "next": null, "previous": null, "results": [ { "email": "admin@example.com", "groups": [], "url": "http://127.0.0.1:8000/users/1/", "username": "admin" } ] } ``` Or directly through the browser, by going to the URL `http://127.0.0.1:8000/users/`... ![Quick start image][image] If you're working through the browser, make sure to login using the control in the top right corner. Great, that was easy! If you want to get a more in depth understanding of how REST framework fits together head on over to [the tutorial][tutorial], or start browsing the [API guide][guide]. [image]: ../img/quickstart.png [tutorial]: 1-serialization.md [guide]: ../api-guide/requests.md [httpie]: https://httpie.io/docs#installation ================================================ FILE: licenses/bootstrap.md ================================================ https://github.com/twbs/bootstrap/ The MIT License (MIT) Copyright (c) 2011-2016 Twitter, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ================================================ FILE: licenses/jquery.json-view.md ================================================ https://github.com/bazh/jquery.json-view/ The MIT License (MIT) Copyright (c) 2014 bazh. (https://github.com/bazh) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: mkdocs.yml ================================================ site_name: Django REST framework site_url: https://www.django-rest-framework.org/ site_description: Django REST framework - Web APIs for Django repo_url: https://github.com/encode/django-rest-framework theme: name: material custom_dir: docs/theme favicon: theme/img/favicon.ico logo: theme/img/logo.png palette: - media: "(prefers-color-scheme)" primary: custom accent: custom toggle: icon: material/brightness-auto name: "Switch to light mode" - media: "(prefers-color-scheme: light)" scheme: default primary: custom accent: custom toggle: icon: material/brightness-7 name: "Switch to dark mode" - media: "(prefers-color-scheme: dark)" scheme: slate primary: custom accent: custom toggle: icon: material/brightness-4 name: "Switch to system preference" features: - content.tabs.link - content.code.annotate - content.code.copy - navigation.tabs - navigation.tabs.sticky - navigation.instant - navigation.instant.prefetch - navigation.instant.progress - navigation.path - navigation.sections - navigation.top - navigation.tracking - search.suggest - toc.follow extra_css: - theme/stylesheets/extra.css - theme/stylesheets/prettify.css extra_javascript: - theme/js/prettify-1.0.js markdown_extensions: - admonition - attr_list - toc: permalink: true - pymdownx.highlight: pygments_lang_class: true - pymdownx.inlinehilite - pymdownx.snippets - pymdownx.superfences - pymdownx.tabbed: alternate_style: true - pymdownx.emoji: emoji_index: !!python/name:material.extensions.emoji.twemoji emoji_generator: !!python/name:material.extensions.emoji.to_svg nav: - Home: 'index.md' - Tutorial: - 'Quickstart': 'tutorial/quickstart.md' - '1 - Serialization': 'tutorial/1-serialization.md' - '2 - Requests and responses': 'tutorial/2-requests-and-responses.md' - '3 - Class based views': 'tutorial/3-class-based-views.md' - '4 - Authentication and permissions': 'tutorial/4-authentication-and-permissions.md' - '5 - Relationships and hyperlinked APIs': 'tutorial/5-relationships-and-hyperlinked-apis.md' - '6 - Viewsets and routers': 'tutorial/6-viewsets-and-routers.md' - API Guide: - 'Requests': 'api-guide/requests.md' - 'Responses': 'api-guide/responses.md' - 'Views': 'api-guide/views.md' - 'Generic views': 'api-guide/generic-views.md' - 'Viewsets': 'api-guide/viewsets.md' - 'Routers': 'api-guide/routers.md' - 'Parsers': 'api-guide/parsers.md' - 'Renderers': 'api-guide/renderers.md' - 'Serializers': 'api-guide/serializers.md' - 'Serializer fields': 'api-guide/fields.md' - 'Serializer relations': 'api-guide/relations.md' - 'Validators': 'api-guide/validators.md' - 'Authentication': 'api-guide/authentication.md' - 'Permissions': 'api-guide/permissions.md' - 'Caching': 'api-guide/caching.md' - 'Throttling': 'api-guide/throttling.md' - 'Filtering': 'api-guide/filtering.md' - 'Pagination': 'api-guide/pagination.md' - 'Versioning': 'api-guide/versioning.md' - 'Content negotiation': 'api-guide/content-negotiation.md' - 'Metadata': 'api-guide/metadata.md' - 'Schemas': 'api-guide/schemas.md' - 'Format suffixes': 'api-guide/format-suffixes.md' - 'Returning URLs': 'api-guide/reverse.md' - 'Exceptions': 'api-guide/exceptions.md' - 'Status codes': 'api-guide/status-codes.md' - 'Testing': 'api-guide/testing.md' - 'Settings': 'api-guide/settings.md' - Topics: - 'Documenting your API': 'topics/documenting-your-api.md' - 'Internationalization': 'topics/internationalization.md' - 'AJAX, CSRF & CORS': 'topics/ajax-csrf-cors.md' - 'HTML & Forms': 'topics/html-and-forms.md' - 'Browser Enhancements': 'topics/browser-enhancements.md' - 'The Browsable API': 'topics/browsable-api.md' - 'REST, Hypermedia & HATEOAS': 'topics/rest-hypermedia-hateoas.md' - Community: - 'Tutorials and Resources': 'community/tutorials-and-resources.md' - 'Third Party Packages': 'community/third-party-packages.md' - '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' - '3.11 Announcement': 'community/3.11-announcement.md' - '3.10 Announcement': 'community/3.10-announcement.md' - '3.9 Announcement': 'community/3.9-announcement.md' - '3.8 Announcement': 'community/3.8-announcement.md' - '3.7 Announcement': 'community/3.7-announcement.md' - '3.6 Announcement': 'community/3.6-announcement.md' - '3.5 Announcement': 'community/3.5-announcement.md' - '3.4 Announcement': 'community/3.4-announcement.md' - '3.3 Announcement': 'community/3.3-announcement.md' - '3.2 Announcement': 'community/3.2-announcement.md' - '3.1 Announcement': 'community/3.1-announcement.md' - '3.0 Announcement': 'community/3.0-announcement.md' - 'Kickstarter Announcement': 'community/kickstarter-announcement.md' - 'Mozilla Grant': 'community/mozilla-grant.md' - 'Jobs': 'community/jobs.md' ================================================ FILE: pyproject.toml ================================================ [build-system] build-backend = "setuptools.build_meta" requires = [ "setuptools>=77.0.3" ] [project] name = "djangorestframework" description = "Web APIs for Django, made easy." readme = "README.md" license = "BSD-3-Clause" license-files = [ "LICENSE.md" ] authors = [ { name = "Tom Christie", email = "tom@tomchristie.com" } ] requires-python = ">=3.10" classifiers = [ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Framework :: Django", "Framework :: Django :: 4.2", "Framework :: Django :: 5.0", "Framework :: Django :: 5.1", "Framework :: Django :: 5.2", "Framework :: Django :: 6.0", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", "Topic :: Internet :: WWW/HTTP", ] dynamic = [ "version" ] dependencies = [ "django>=4.2" ] urls.Changelog = "https://www.django-rest-framework.org/community/release-notes/" urls.Funding = "https://fund.django-rest-framework.org/topics/funding/" urls.Homepage = "https://www.django-rest-framework.org" urls.Source = "https://github.com/encode/django-rest-framework" [dependency-groups] dev = [ { include-group = "docs" }, { include-group = "optional" }, { include-group = "test" }, ] test = [ "importlib-metadata<9.0", # Pytest for running the tests. "pytest==9.*", "pytest-cov==7.*", "pytest-django>=4.5.2,<5", # Remove when dropping support for Django<5.0 "pytz", ] docs = [ # MkDocs to build our documentation. "mkdocs==1.6.1", "mkdocs-material[imaging]==9.7.5", # pylinkvalidator to check for broken links in documentation. "pylinkvalidator==0.3", ] optional = [ # Optional packages which may be used with REST framework. "django-filter", "django-guardian>=2.4.0,<3.4", "inflection==0.5.1", "legacy-cgi; python_version>='3.13'", "markdown>=3.3.7", "psycopg[binary]>=3.1.8", "pygments>=2.17,<2.20", "pyyaml>=5.3.1,<6.1", "requests", "uritemplate", ] django42 = [ "django>=4.2,<5.0" ] django50 = [ "django>=5.0,<5.1" ] django51 = [ "django>=5.1,<5.2" ] django52 = [ "django>=5.2,<6.0" ] django60 = [ "django>=6.0,<6.1" ] djangomain = [ "django @ https://github.com/django/django/archive/main.tar.gz" ] [tool.setuptools] [tool.setuptools.dynamic] version = { attr = "rest_framework.__version__" } [tool.setuptools.packages.find] include = [ "rest_framework*" ] [tool.setuptools.package-data] "rest_framework" = [ "templates/**/*", "static/**/*", "locale/**/*.mo", ] [tool.isort] skip = [ ".tox" ] atomic = true multi_line_output = 5 extra_standard_library = [ "types" ] known_third_party = [ "pytest", "_pytest", "django", "pytz", "uritemplate" ] known_first_party = [ "rest_framework", "tests" ] [tool.codespell] # Ref: https://github.com/codespell-project/codespell#using-a-config-file skip = "*/kickstarter-announcement.md,*.js,*.map,*.po,*.css,locale" ignore-words = "codespell-ignore-words.txt" builtin = "clear,rare,code,names,en-GB_to_en-US" [tool.pyproject-fmt] max_supported_python = "3.14" keep_full_version = true [tool.pytest.ini_options] addopts = "--tb=short --strict-markers -ra" testpaths = [ "tests" ] filterwarnings = [ "ignore:'cgi' is deprecated:DeprecationWarning", ] [tool.coverage.run] # NOTE: source is ignored with pytest-cov (but uses the same). source = [ "." ] include = [ "rest_framework/*", "tests/*" ] branch = true [tool.coverage.report] include = [ "rest_framework/*", "tests/*" ] exclude_lines = [ "pragma: no cover", "raise NotImplementedError", ] ================================================ FILE: rest_framework/__init__.py ================================================ r""" ______ _____ _____ _____ __ | ___ \ ___/ ___|_ _| / _| | | | |_/ / |__ \ `--. | | | |_ _ __ __ _ _ __ ___ _____ _____ _ __| |__ | /| __| `--. \ | | | _| '__/ _` | '_ ` _ \ / _ \ \ /\ / / _ \| '__| |/ / | |\ \| |___/\__/ / | | | | | | | (_| | | | | | | __/\ V V / (_) | | | < \_| \_\____/\____/ \_/ |_| |_| \__,_|_| |_| |_|\___| \_/\_/ \___/|_| |_|\_| """ __title__ = 'Django REST framework' __version__ = '3.17.0' __author__ = 'Tom Christie' __license__ = 'BSD-3-Clause' __copyright__ = 'Copyright 2011-2023 Encode OSS Ltd' # Version synonym VERSION = __version__ # Header encoding (see RFC5987) HTTP_HEADER_ENCODING = 'iso-8859-1' # Default datetime input and output formats ISO_8601 = 'iso-8601' DJANGO_DURATION_FORMAT = 'django' ================================================ FILE: rest_framework/apps.py ================================================ from django.apps import AppConfig class RestFrameworkConfig(AppConfig): name = 'rest_framework' verbose_name = "Django REST framework" def ready(self): # Add System checks from .checks import pagination_system_check # NOQA ================================================ FILE: rest_framework/authentication.py ================================================ """ Provides various authentication policies. """ import base64 import binascii from django.contrib.auth import authenticate, get_user_model from django.middleware.csrf import CsrfViewMiddleware from django.utils.translation import gettext_lazy as _ from rest_framework import HTTP_HEADER_ENCODING, exceptions def get_authorization_header(request): """ Return request's 'Authorization:' header, as a bytestring. Hide some test client ickyness where the header can be unicode. """ auth = request.META.get('HTTP_AUTHORIZATION', b'') if isinstance(auth, str): # Work around django test client oddness auth = auth.encode(HTTP_HEADER_ENCODING) return auth class CSRFCheck(CsrfViewMiddleware): def _reject(self, request, reason): # Return the failure reason instead of an HttpResponse return reason class BaseAuthentication: """ All authentication classes should extend BaseAuthentication. """ def authenticate(self, request): """ Authenticate the request and return a two-tuple of (user, token). """ raise NotImplementedError(".authenticate() must be overridden.") def authenticate_header(self, request): """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ pass class BasicAuthentication(BaseAuthentication): """ HTTP Basic authentication against username/password. """ www_authenticate_realm = 'api' def authenticate(self, request): """ Returns a `User` if a correct username and password have been supplied using HTTP Basic authentication. Otherwise returns `None`. """ auth = get_authorization_header(request).split() if not auth or auth[0].lower() != b'basic': return None if len(auth) == 1: msg = _('Invalid basic header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid basic header. Credentials string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: try: auth_decoded = base64.b64decode(auth[1]).decode('utf-8') except UnicodeDecodeError: auth_decoded = base64.b64decode(auth[1]).decode('latin-1') 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) return self.authenticate_credentials(userid, password, request) def authenticate_credentials(self, userid, password, request=None): """ Authenticate the userid and password against username and password with optional request for context. """ credentials = { get_user_model().USERNAME_FIELD: userid, 'password': password } user = authenticate(request=request, **credentials) if user is None: raise exceptions.AuthenticationFailed(_('Invalid username/password.')) if not user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) return (user, None) def authenticate_header(self, request): return 'Basic realm="%s"' % self.www_authenticate_realm class SessionAuthentication(BaseAuthentication): """ Use Django's session framework for authentication. """ def authenticate(self, request): """ Returns a `User` if the request session currently has a logged in user. Otherwise returns `None`. """ # Get the session-based user from the underlying HttpRequest object user = getattr(request._request, 'user', None) # Unauthenticated, CSRF validation not required if not user or not user.is_active: return None self.enforce_csrf(request) # CSRF passed with authenticated user return (user, None) def enforce_csrf(self, request): """ Enforce CSRF validation for session based authentication. """ def dummy_get_response(request): # pragma: no cover return None check = CSRFCheck(dummy_get_response) # populates request.META['CSRF_COOKIE'], which is used in process_view() check.process_request(request) reason = check.process_view(request, None, (), {}) if reason: # CSRF failed, bail with explicit error message raise exceptions.PermissionDenied('CSRF Failed: %s' % reason) class TokenAuthentication(BaseAuthentication): """ Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Token ". For example: Authorization: Token 401f7ac837da42b97f613d789819ff93537bee6a """ keyword = 'Token' model = None def get_model(self): if self.model is not None: return self.model from rest_framework.authtoken.models import Token return Token """ A custom token model may be used, but must have the following properties. * key -- The string identifying the token * user -- The user to which the token belongs """ def authenticate(self, request): auth = get_authorization_header(request).split() if not auth or auth[0].lower() != self.keyword.lower().encode(): return None if len(auth) == 1: msg = _('Invalid token header. No credentials provided.') raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = _('Invalid token header. Token string should not contain spaces.') raise exceptions.AuthenticationFailed(msg) try: token = auth[1].decode() except UnicodeError: msg = _('Invalid token header. Token string should not contain invalid characters.') raise exceptions.AuthenticationFailed(msg) return self.authenticate_credentials(token) def authenticate_credentials(self, key): model = self.get_model() try: token = model.objects.select_related('user').get(key=key) except model.DoesNotExist: raise exceptions.AuthenticationFailed(_('Invalid token.')) if not token.user.is_active: raise exceptions.AuthenticationFailed(_('User inactive or deleted.')) return (token.user, token) def authenticate_header(self, request): return self.keyword class RemoteUserAuthentication(BaseAuthentication): """ REMOTE_USER authentication. To use this, set up your web server to perform authentication, which will set the REMOTE_USER environment variable. You will need to have 'django.contrib.auth.backends.RemoteUserBackend in your AUTHENTICATION_BACKENDS setting """ # Name of request header to grab username from. This will be the key as # used in the request.META dictionary, i.e. the normalization of headers to # all uppercase and the addition of "HTTP_" prefix apply. header = "REMOTE_USER" def authenticate(self, request): user = authenticate(request=request, remote_user=request.META.get(self.header)) if user and user.is_active: return (user, None) ================================================ FILE: rest_framework/authtoken/__init__.py ================================================ ================================================ FILE: rest_framework/authtoken/admin.py ================================================ from django.contrib import admin from django.contrib.admin.utils import quote from django.contrib.admin.views.main import ChangeList 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 User = get_user_model() class TokenChangeList(ChangeList): """Map to matching User id""" def url_for_result(self, result): pk = result.user.pk return reverse('admin:%s_%s_change' % (self.opts.app_label, self.opts.model_name), args=(quote(pk),), current_app=self.model_admin.admin_site.name) class TokenAdmin(admin.ModelAdmin): list_display = ('key', 'user', 'created') list_filter = ('created',) fields = ('user',) search_fields = ('user__%s' % User.USERNAME_FIELD,) search_help_text = _('Username') ordering = ('user__%s' % User.USERNAME_FIELD,) actions = None # Actions not compatible with mapped IDs. def get_changelist(self, request, **kwargs): return TokenChangeList def get_object(self, request, object_id, from_field=None): """ Map from User ID to matching Token. """ queryset = self.get_queryset(request) field = User._meta.pk try: object_id = field.to_python(object_id) user = User.objects.get(**{field.name: object_id}) return queryset.get(user=user) except (queryset.model.DoesNotExist, User.DoesNotExist, ValidationError, ValueError): return None def delete_model(self, request, obj): # Map back to actual Token, since delete() uses pk. token = Token.objects.get(key=obj.key) return super().delete_model(request, token) admin.site.register(TokenProxy, TokenAdmin) ================================================ FILE: rest_framework/authtoken/apps.py ================================================ from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class AuthTokenConfig(AppConfig): name = 'rest_framework.authtoken' verbose_name = _("Auth Token") ================================================ FILE: rest_framework/authtoken/management/__init__.py ================================================ ================================================ FILE: rest_framework/authtoken/management/commands/__init__.py ================================================ ================================================ FILE: rest_framework/authtoken/management/commands/drf_create_token.py ================================================ from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from rest_framework.authtoken.models import Token UserModel = get_user_model() class Command(BaseCommand): help = 'Create DRF Token for a given user' def create_user_token(self, username, reset_token): user = UserModel._default_manager.get_by_natural_key(username) if reset_token: Token.objects.filter(user=user).delete() token = Token.objects.get_or_create(user=user) return token[0] def add_arguments(self, parser): parser.add_argument('username', type=str) parser.add_argument( '-r', '--reset', action='store_true', dest='reset_token', default=False, help='Reset existing User token and create a new one', ) def handle(self, *args, **options): username = options['username'] reset_token = options['reset_token'] try: token = self.create_user_token(username, reset_token) except UserModel.DoesNotExist: raise CommandError( 'Cannot create the Token: user {} does not exist'.format( username) ) self.stdout.write( f'Generated token {token.key} for user {username}') ================================================ FILE: rest_framework/authtoken/migrations/0001_initial.py ================================================ from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Token', fields=[ ('key', models.CharField(primary_key=True, serialize=False, max_length=40)), ('created', models.DateTimeField(auto_now_add=True)), ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL, related_name='auth_token', on_delete=models.CASCADE)), ], options={ }, bases=(models.Model,), ), ] ================================================ FILE: rest_framework/authtoken/migrations/0002_auto_20160226_1747.py ================================================ from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authtoken', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='token', options={'verbose_name_plural': 'Tokens', 'verbose_name': 'Token'}, ), migrations.AlterField( model_name='token', name='created', field=models.DateTimeField(verbose_name='Created', auto_now_add=True), ), migrations.AlterField( model_name='token', name='key', field=models.CharField(verbose_name='Key', max_length=40, primary_key=True, serialize=False), ), migrations.AlterField( model_name='token', name='user', field=models.OneToOneField(to=settings.AUTH_USER_MODEL, verbose_name='User', related_name='auth_token', on_delete=models.CASCADE), ), ] ================================================ FILE: rest_framework/authtoken/migrations/0003_tokenproxy.py ================================================ # Generated by Django 3.1.1 on 2020-09-28 09:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('authtoken', '0002_auto_20160226_1747'), ] operations = [ migrations.CreateModel( name='TokenProxy', fields=[ ], options={ 'verbose_name': 'token', 'proxy': True, 'indexes': [], 'constraints': [], }, bases=('authtoken.token',), ), ] ================================================ FILE: rest_framework/authtoken/migrations/0004_alter_tokenproxy_options.py ================================================ # 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'}, ), ] ================================================ FILE: rest_framework/authtoken/migrations/__init__.py ================================================ ================================================ FILE: rest_framework/authtoken/models.py ================================================ import secrets from django.conf import settings from django.db import models from django.utils.translation import gettext_lazy as _ class Token(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) user = models.OneToOneField( settings.AUTH_USER_MODEL, related_name='auth_token', on_delete=models.CASCADE, verbose_name=_("User") ) created = models.DateTimeField(_("Created"), auto_now_add=True) class Meta: # Work around for a bug in Django: # https://code.djangoproject.com/ticket/19422 # # Also see corresponding ticket: # https://github.com/encode/django-rest-framework/issues/705 abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): """ Save the token instance. If no key is provided, generates a cryptographically secure key. For new tokens, ensures they are inserted as new (not updated). """ if not self.key: self.key = self.generate_key() # For new objects, force INSERT to prevent overwriting existing tokens if self._state.adding: kwargs['force_insert'] = True return super().save(*args, **kwargs) @classmethod def generate_key(cls): return secrets.token_hex(20) def __str__(self): return self.key class TokenProxy(Token): """ Proxy mapping pk to user pk for use in admin. """ @property def pk(self): return self.user_id class Meta: proxy = 'rest_framework.authtoken' in settings.INSTALLED_APPS abstract = 'rest_framework.authtoken' not in settings.INSTALLED_APPS verbose_name = _("Token") verbose_name_plural = _("Tokens") ================================================ FILE: rest_framework/authtoken/serializers.py ================================================ from django.contrib.auth import authenticate from django.utils.translation import gettext_lazy as _ from rest_framework import serializers class AuthTokenSerializer(serializers.Serializer): username = serializers.CharField( label=_("Username"), write_only=True ) password = serializers.CharField( label=_("Password"), style={'input_type': 'password'}, trim_whitespace=False, write_only=True ) token = serializers.CharField( label=_("Token"), read_only=True ) def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if username and password: user = authenticate(request=self.context.get('request'), username=username, password=password) # The authenticate call simply returns None for is_active=False # users. (Assuming the default ModelBackend authentication # backend.) if not user: msg = _('Unable to log in with provided credentials.') raise serializers.ValidationError(msg, code='authorization') else: msg = _('Must include "username" and "password".') raise serializers.ValidationError(msg, code='authorization') attrs['user'] = user return attrs ================================================ FILE: rest_framework/authtoken/views.py ================================================ from rest_framework import parsers, renderers from rest_framework.authtoken.models import Token from rest_framework.authtoken.serializers import AuthTokenSerializer from rest_framework.response import Response from rest_framework.views import APIView class ObtainAuthToken(APIView): throttle_classes = () permission_classes = () parser_classes = (parsers.FormParser, parsers.MultiPartParser, parsers.JSONParser,) renderer_classes = (renderers.JSONRenderer,) serializer_class = AuthTokenSerializer def get_serializer_context(self): return { 'request': self.request, 'format': self.format_kwarg, 'view': self } def get_serializer(self, *args, **kwargs): kwargs['context'] = self.get_serializer_context() return self.serializer_class(*args, **kwargs) def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.validated_data['user'] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key}) obtain_auth_token = ObtainAuthToken.as_view() ================================================ FILE: rest_framework/checks.py ================================================ from django.core.checks import Tags, Warning, register @register(Tags.compatibility) def pagination_system_check(app_configs, **kwargs): errors = [] # Use of default page size setting requires a default Paginator class from rest_framework.settings import api_settings if api_settings.PAGE_SIZE and not api_settings.DEFAULT_PAGINATION_CLASS: errors.append( Warning( "You have specified a default PAGE_SIZE pagination rest_framework setting, " "without specifying also a DEFAULT_PAGINATION_CLASS.", hint="The default for DEFAULT_PAGINATION_CLASS is None. " "In previous versions this was PageNumberPagination. " "If you wish to define PAGE_SIZE globally whilst defining " "pagination_class on a per-view basis you may silence this check.", id="rest_framework.W001" ) ) return errors ================================================ FILE: rest_framework/compat.py ================================================ """ The `compat` module provides support for backwards compatibility with older versions of Django/Python, and compatibility wrappers around optional packages. """ import django 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 def unicode_http_header(value): # Coerce HTTP header value to unicode. if isinstance(value, bytes): return value.decode('iso-8859-1') return value # django.contrib.postgres requires psycopg try: from django.contrib.postgres import fields as postgres_fields except ImportError: postgres_fields = None # uritemplate is required for OpenAPI schema generation try: import uritemplate except ImportError: uritemplate = None # pyyaml is optional try: import yaml except ImportError: yaml = None # inflection is optional try: import inflection except ImportError: inflection = None # requests is optional try: import requests except ImportError: requests = None # PATCH method is not implemented by Django if 'patch' not in View.http_method_names: View.http_method_names = View.http_method_names + ['patch'] # Markdown is optional (version 3.0+ required) try: import markdown HEADERID_EXT_PATH = 'markdown.extensions.toc' LEVEL_PARAM = 'baselevel' def apply_markdown(text): """ Simple wrapper around :func:`markdown.markdown` to set the base level of '#' style headers to

. """ extensions = [HEADERID_EXT_PATH] extension_configs = { HEADERID_EXT_PATH: { LEVEL_PARAM: '2' } } md = markdown.Markdown( extensions=extensions, extension_configs=extension_configs ) md_filter_add_syntax_highlight(md) return md.convert(text) except ImportError: apply_markdown = None markdown = None try: import pygments from pygments.formatters import HtmlFormatter from pygments.lexers import TextLexer, get_lexer_by_name def pygments_highlight(text, lang, style): lexer = get_lexer_by_name(lang, stripall=False) formatter = HtmlFormatter(nowrap=True, style=style) return pygments.highlight(text, lexer, formatter) def pygments_css(style): formatter = HtmlFormatter(style=style) return formatter.get_style_defs('.highlight') except ImportError: pygments = None def pygments_highlight(text, lang, style): return text def pygments_css(style): return None if markdown is not None and pygments is not None: # starting from this blogpost and modified to support current markdown extensions API # https://zerokspot.com/weblog/2008/06/18/syntax-highlighting-in-markdown-with-pygments/ import re from markdown.preprocessors import Preprocessor class CodeBlockPreprocessor(Preprocessor): pattern = re.compile( r'^\s*``` *([^\n]+)\n(.+?)^\s*```', re.M | re.S) formatter = HtmlFormatter() def run(self, lines): def repl(m): try: lexer = get_lexer_by_name(m.group(1)) except (ValueError, NameError): lexer = TextLexer() code = m.group(2).replace('\t', ' ') code = pygments.highlight(code, lexer, self.formatter) code = code.replace('\n\n', '\n \n').replace('\n', '
').replace('\\@', '@') return '\n\n%s\n\n' % code ret = self.pattern.sub(repl, "\n".join(lines)) return ret.split("\n") def md_filter_add_syntax_highlight(md): md.preprocessors.register(CodeBlockPreprocessor(), 'highlight', 40) return True else: def md_filter_add_syntax_highlight(md): return False 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 <= 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) } # `separators` argument to `json.dumps()` differs between 2.x and 3.x # See: https://bugs.python.org/issue22767 SHORT_SEPARATORS = (',', ':') LONG_SEPARATORS = (', ', ': ') INDENT_SEPARATORS = (',', ': ') ================================================ FILE: rest_framework/decorators.py ================================================ """ The most important decorator in this module is `@api_view`, which is used for writing function-based views with REST framework. There are also various decorators for setting the API policies on function based views, as well as the `@action` decorator, which is used to annotate methods on viewsets that should be included by routers. """ import types from django.forms.utils import pretty_name from rest_framework.views import APIView def api_view(http_method_names=None): """ Decorator that converts a function-based view into an APIView subclass. Takes a list of allowed methods for the view as an argument. """ http_method_names = ['GET'] if (http_method_names is None) else http_method_names def decorator(func): WrappedAPIView = type( 'WrappedAPIView', (APIView,), {'__doc__': func.__doc__} ) # Note, the above allows us to set the docstring. # It is the equivalent of: # # class WrappedAPIView(APIView): # pass # WrappedAPIView.__doc__ = func.doc <--- Not possible to do this # api_view applied without (method_names) 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 assert isinstance(http_method_names, (list, tuple)), \ '@api_view expected a list of strings, received %s' % type(http_method_names).__name__ allowed_methods = set(http_method_names) | {'options'} WrappedAPIView.http_method_names = [method.lower() for method in allowed_methods] def handler(self, *args, **kwargs): return func(*args, **kwargs) for method in http_method_names: setattr(WrappedAPIView, method.lower(), handler) WrappedAPIView.__name__ = func.__name__ WrappedAPIView.__module__ = func.__module__ WrappedAPIView.renderer_classes = getattr(func, 'renderer_classes', APIView.renderer_classes) WrappedAPIView.parser_classes = getattr(func, 'parser_classes', APIView.parser_classes) WrappedAPIView.authentication_classes = getattr(func, 'authentication_classes', APIView.authentication_classes) WrappedAPIView.throttle_classes = getattr(func, 'throttle_classes', APIView.throttle_classes) WrappedAPIView.permission_classes = getattr(func, 'permission_classes', APIView.permission_classes) WrappedAPIView.content_negotiation_class = getattr(func, 'content_negotiation_class', APIView.content_negotiation_class) WrappedAPIView.metadata_class = getattr(func, 'metadata_class', APIView.metadata_class) WrappedAPIView.versioning_class = getattr(func, "versioning_class", APIView.versioning_class) WrappedAPIView.schema = getattr(func, 'schema', APIView.schema) return WrappedAPIView.as_view() return decorator def _check_decorator_order(func, decorator_name): """ Check if an API policy decorator is being applied after @api_view. """ # Check if func is actually a view function (result of APIView.as_view()) if hasattr(func, 'cls') and issubclass(func.cls, APIView): raise TypeError( f"@{decorator_name} must come after (below) the @api_view decorator. " "The correct order is:\n\n" " @api_view(['GET'])\n" f" @{decorator_name}(...)\n" " def my_view(request):\n" " ...\n\n" "See https://www.django-rest-framework.org/api-guide/views/#api-policy-decorators" ) def renderer_classes(renderer_classes): def decorator(func): _check_decorator_order(func, 'renderer_classes') func.renderer_classes = renderer_classes return func return decorator def parser_classes(parser_classes): def decorator(func): _check_decorator_order(func, 'parser_classes') func.parser_classes = parser_classes return func return decorator def authentication_classes(authentication_classes): def decorator(func): _check_decorator_order(func, 'authentication_classes') func.authentication_classes = authentication_classes return func return decorator def throttle_classes(throttle_classes): def decorator(func): _check_decorator_order(func, 'throttle_classes') func.throttle_classes = throttle_classes return func return decorator def permission_classes(permission_classes): def decorator(func): _check_decorator_order(func, 'permission_classes') func.permission_classes = permission_classes return func return decorator def content_negotiation_class(content_negotiation_class): def decorator(func): _check_decorator_order(func, 'content_negotiation_class') func.content_negotiation_class = content_negotiation_class return func return decorator def metadata_class(metadata_class): def decorator(func): _check_decorator_order(func, 'metadata_class') func.metadata_class = metadata_class return func return decorator def versioning_class(versioning_class): def decorator(func): _check_decorator_order(func, 'versioning_class') func.versioning_class = versioning_class return func return decorator def schema(view_inspector): def decorator(func): _check_decorator_order(func, 'schema') func.schema = view_inspector return func return decorator def action(methods=None, detail=None, url_path=None, url_name=None, **kwargs): """ Mark a ViewSet method as a routable action. `@action`-decorated functions will be endowed with a `mapping` property, a `MethodMapper` that can be used to add additional method-based behaviors on the routed action. :param methods: A list of HTTP method names this action responds to. Defaults to GET only. :param detail: Required. Determines whether this action applies to instance/detail requests or collection/list requests. :param url_path: Define the URL segment for this action. Defaults to the name of the method decorated. :param url_name: Define the internal (`reverse`) URL name for this action. Defaults to the name of the method decorated with underscores replaced with dashes. :param kwargs: Additional properties to set on the view. This can be used to override viewset-level *_classes settings, equivalent to how the `@renderer_classes` etc. decorators work for function- based API views. """ methods = ['get'] if methods is None else methods methods = [method.lower() for method in methods] assert detail is not None, ( "@action() missing required argument: 'detail'" ) # name and suffix are mutually exclusive if 'name' in kwargs and 'suffix' in kwargs: raise TypeError("`name` and `suffix` are mutually exclusive arguments.") def decorator(func): func.mapping = MethodMapper(func, methods) func.detail = detail func.url_path = url_path if url_path else func.__name__ func.url_name = url_name if url_name else func.__name__.replace('_', '-') # These kwargs will end up being passed to `ViewSet.as_view()` within # the router, which eventually delegates to Django's CBV `View`, # which assigns them as instance attributes for each request. func.kwargs = kwargs # Set descriptive arguments for viewsets if 'name' not in kwargs and 'suffix' not in kwargs: func.kwargs['name'] = pretty_name(func.__name__) func.kwargs['description'] = func.__doc__ or None return func return decorator class MethodMapper(dict): """ Enables mapping HTTP methods to different ViewSet methods for a single, logical action. Example usage: class MyViewSet(ViewSet): @action(detail=False) def example(self, request, **kwargs): ... @example.mapping.post def create_example(self, request, **kwargs): ... """ def __init__(self, action, methods): self.action = action for method in methods: self[method] = self.action.__name__ def _map(self, method, func): assert method not in self, ( "Method '%s' has already been mapped to '.%s'." % (method, self[method])) assert func.__name__ != self.action.__name__, ( "Method mapping does not behave like the property decorator. You " "cannot use the same method name for each mapping declaration.") self[method] = func.__name__ return func def get(self, func): return self._map('get', func) def post(self, func): return self._map('post', func) def put(self, func): return self._map('put', func) def patch(self, func): return self._map('patch', func) def delete(self, func): return self._map('delete', func) def head(self, func): return self._map('head', func) def options(self, func): return self._map('options', func) def trace(self, func): return self._map('trace', func) ================================================ FILE: rest_framework/exceptions.py ================================================ """ Handled exceptions raised by REST framework. In addition, Django's built in 403 and 404 exceptions are handled. (`django.http.Http404` and `django.core.exceptions.PermissionDenied`) """ import math from django.http import JsonResponse from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext from rest_framework import status from rest_framework.utils.serializer_helpers import ReturnDict, ReturnList def _get_error_details(data, default_code=None): """ Descend into a nested data structure, forcing any lazy translation strings or strings into `ErrorDetail`. """ if isinstance(data, (list, tuple)): ret = [ _get_error_details(item, default_code) for item in data ] if isinstance(data, ReturnList): return ReturnList(ret, serializer=data.serializer) return ret elif isinstance(data, dict): ret = { key: _get_error_details(value, default_code) for key, value in data.items() } if isinstance(data, ReturnDict): return ReturnDict(ret, serializer=data.serializer) return ret text = force_str(data) code = getattr(data, 'code', default_code) return ErrorDetail(text, code) def _get_codes(detail): if isinstance(detail, list): return [_get_codes(item) for item in detail] elif isinstance(detail, dict): return {key: _get_codes(value) for key, value in detail.items()} return detail.code def _get_full_details(detail): if isinstance(detail, list): return [_get_full_details(item) for item in detail] elif isinstance(detail, dict): return {key: _get_full_details(value) for key, value in detail.items()} return { 'message': detail, 'code': detail.code } class ErrorDetail(str): """ A string-like object that can additionally have a code. """ code = None def __new__(cls, string, code=None): self = super().__new__(cls, string) self.code = code return self def __eq__(self, other): result = super().__eq__(other) if result is NotImplemented: return NotImplemented try: return result and self.code == other.code except AttributeError: return result def __ne__(self, other): result = self.__eq__(other) if result is NotImplemented: return NotImplemented return not result def __repr__(self): return 'ErrorDetail(string=%r, code=%r)' % ( str(self), self.code, ) def __hash__(self): return hash(str(self)) class APIException(Exception): """ Base class for REST framework exceptions. Subclasses should provide `.status_code` and `.default_detail` properties. """ status_code = status.HTTP_500_INTERNAL_SERVER_ERROR default_detail = _('A server error occurred.') default_code = 'error' def __init__(self, detail=None, code=None): if detail is None: detail = self.default_detail if code is None: code = self.default_code self.detail = _get_error_details(detail, code) def __str__(self): return str(self.detail) def get_codes(self): """ Return only the code part of the error details. Eg. {"name": ["required"]} """ return _get_codes(self.detail) def get_full_details(self): """ Return both the message & code parts of the error details. Eg. {"name": [{"message": "This field is required.", "code": "required"}]} """ return _get_full_details(self.detail) # The recommended style for using `ValidationError` is to keep it namespaced # under `serializers`, in order to minimize potential confusion with Django's # built in `ValidationError`. For example: # # from rest_framework import serializers # raise serializers.ValidationError('Value was invalid') class ValidationError(APIException): status_code = status.HTTP_400_BAD_REQUEST default_detail = _('Invalid input.') default_code = 'invalid' def __init__(self, detail=None, code=None): if detail is None: detail = self.default_detail if code is None: code = self.default_code # For validation failures, we may collect many errors together, # so the details should always be coerced to a list if not already. if isinstance(detail, tuple): detail = list(detail) elif not isinstance(detail, dict) and not isinstance(detail, list): detail = [detail] self.detail = _get_error_details(detail, code) class ParseError(APIException): status_code = status.HTTP_400_BAD_REQUEST default_detail = _('Malformed request.') default_code = 'parse_error' class AuthenticationFailed(APIException): status_code = status.HTTP_401_UNAUTHORIZED default_detail = _('Incorrect authentication credentials.') default_code = 'authentication_failed' class NotAuthenticated(APIException): status_code = status.HTTP_401_UNAUTHORIZED default_detail = _('Authentication credentials were not provided.') default_code = 'not_authenticated' class PermissionDenied(APIException): status_code = status.HTTP_403_FORBIDDEN default_detail = _('You do not have permission to perform this action.') default_code = 'permission_denied' class NotFound(APIException): status_code = status.HTTP_404_NOT_FOUND default_detail = _('Not found.') default_code = 'not_found' class MethodNotAllowed(APIException): status_code = status.HTTP_405_METHOD_NOT_ALLOWED default_detail = _('Method "{method}" not allowed.') default_code = 'method_not_allowed' def __init__(self, method, detail=None, code=None): if detail is None: detail = force_str(self.default_detail).format(method=method) super().__init__(detail, code) class NotAcceptable(APIException): status_code = status.HTTP_406_NOT_ACCEPTABLE default_detail = _('Could not satisfy the request Accept header.') default_code = 'not_acceptable' def __init__(self, detail=None, code=None, available_renderers=None): self.available_renderers = available_renderers super().__init__(detail, code) class UnsupportedMediaType(APIException): status_code = status.HTTP_415_UNSUPPORTED_MEDIA_TYPE default_detail = _('Unsupported media type "{media_type}" in request.') default_code = 'unsupported_media_type' def __init__(self, media_type, detail=None, code=None): if detail is None: detail = force_str(self.default_detail).format(media_type=media_type) super().__init__(detail, code) class Throttled(APIException): status_code = status.HTTP_429_TOO_MANY_REQUESTS default_detail = _('Request was throttled.') extra_detail_singular = _('Expected available in {wait} second.') extra_detail_plural = _('Expected available in {wait} seconds.') default_code = 'throttled' def __init__(self, wait=None, detail=None, code=None): if detail is None: detail = force_str(self.default_detail) if wait is not None: wait = math.ceil(wait) detail = ' '.join(( detail, force_str(ngettext(self.extra_detail_singular.format(wait=wait), self.extra_detail_plural.format(wait=wait), wait)))) self.wait = wait super().__init__(detail, code) def server_error(request, *args, **kwargs): """ Generic 500 error handler. """ data = { 'error': 'Server Error (500)' } return JsonResponse(data, status=status.HTTP_500_INTERNAL_SERVER_ERROR) def bad_request(request, exception, *args, **kwargs): """ Generic 400 error handler. """ data = { 'error': 'Bad Request (400)' } return JsonResponse(data, status=status.HTTP_400_BAD_REQUEST) ================================================ FILE: rest_framework/fields.py ================================================ import contextlib import copy import datetime import decimal import functools import inspect import re import uuid import warnings from collections.abc import Mapping from enum import Enum from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ValidationError as DjangoValidationError from django.core.validators import ( EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, ProhibitNullCharactersValidator, RegexValidator, URLValidator ) from django.forms import FilePathField as DjangoFilePathField from django.forms import ImageField as DjangoImageField from django.utils import timezone from django.utils.dateparse import ( parse_date, parse_datetime, parse_duration, parse_time ) from django.utils.duration import duration_iso_string, duration_string from django.utils.encoding import is_protected_type, smart_str 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 _ try: import pytz except ImportError: pytz = None from rest_framework import DJANGO_DURATION_FORMAT, 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 class empty: """ This class is used to represent no data being provided for a given input or output value. It is required because `None` may be a valid input or output value. """ pass class BuiltinSignatureError(Exception): """ Built-in function signatures are not inspectable. This exception is raised so the serializer can raise a helpful error message. """ pass def is_simple_callable(obj): """ True if the object is a callable that takes no arguments. """ if not callable(obj): return False # Bail early since we cannot inspect built-in function signatures. if inspect.isbuiltin(obj): raise BuiltinSignatureError( 'Built-in function signatures are not inspectable. ' 'Wrap the function call in a simple, pure Python function.') if not (inspect.isfunction(obj) or inspect.ismethod(obj) or isinstance(obj, functools.partial)): return False sig = inspect.signature(obj) params = sig.parameters.values() return all( param.kind == param.VAR_POSITIONAL or param.kind == param.VAR_KEYWORD or param.default != param.empty for param in params ) def get_attribute(instance, attrs): """ Similar to Python's built in `getattr(instance, attr)`, but takes a list of nested attributes, instead of a single attribute. Also accepts either attribute lookup on objects or dictionary lookups. """ for attr in attrs: try: if isinstance(instance, Mapping): instance = instance[attr] else: instance = getattr(instance, attr) except ObjectDoesNotExist: return None if is_simple_callable(instance): try: instance = instance() except (AttributeError, KeyError) as exc: # 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(f'Exception raised in callable attribute "{attr}"; original exception was: {exc}') return instance def to_choices_dict(choices): """ Convert choices into key/value dicts. to_choices_dict([1]) -> {1: 1} to_choices_dict([(1, '1st'), (2, '2nd')]) -> {1: '1st', 2: '2nd'} to_choices_dict([('Group', ((1, '1st'), 2))]) -> {'Group': {1: '1st', 2: '2'}} """ # Allow single, paired or grouped choices style: # choices = [1, 2, 3] # choices = [(1, 'First'), (2, 'Second'), (3, 'Third')] # choices = [('Category', ((1, 'First'), (2, 'Second'))), (3, 'Third')] ret = {} for choice in choices: if not isinstance(choice, (list, tuple)): # single choice ret[choice] = choice else: key, value = choice if isinstance(value, (list, tuple)): # grouped choices (category, sub choices) ret[key] = to_choices_dict(value) else: # paired choice (key, display value) ret[key] = value return ret def flatten_choices_dict(choices): """ Convert a group choices dict into a flat dict of 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 = {} for key, value in choices.items(): if isinstance(value, dict): # grouped choices (category, sub choices) for sub_key, sub_value in value.items(): ret[sub_key] = sub_value else: # choice (key, display value) ret[key] = value return ret def iter_options(grouped_choices, cutoff=None, cutoff_text=None): """ Helper function for options and option groups in templates. """ class StartOptionGroup: start_option_group = True end_option_group = False def __init__(self, label): self.label = label class EndOptionGroup: start_option_group = False end_option_group = True class Option: start_option_group = False end_option_group = False def __init__(self, value, display_text, disabled=False): self.value = value self.display_text = display_text self.disabled = disabled count = 0 for key, value in grouped_choices.items(): if cutoff and count >= cutoff: break if isinstance(value, dict): yield StartOptionGroup(label=key) for sub_key, sub_value in value.items(): if cutoff and count >= cutoff: break yield Option(value=sub_key, display_text=sub_value) count += 1 yield EndOptionGroup() else: yield Option(value=key, display_text=value) count += 1 if cutoff and count >= cutoff and cutoff_text: cutoff_text = cutoff_text.format(count=cutoff) yield Option(value='n/a', display_text=cutoff_text, disabled=True) def get_error_detail(exc_info): """ Given a Django ValidationError, return a list of ErrorDetail, with the `code` populated. """ code = getattr(exc_info, 'code', None) or 'invalid' try: error_dict = exc_info.error_dict except AttributeError: return [ ErrorDetail((error.message % error.params) if error.params else error.message, code=error.code if error.code else code) for error in exc_info.error_list] return { k: [ ErrorDetail((error.message % error.params) if error.params else error.message, code=error.code if error.code else code) for error in errors ] for k, errors in error_dict.items() } class CreateOnlyDefault: """ This class may be used to provide default values that are only used for create operations, but that do not return any value for update operations. """ requires_context = True def __init__(self, default): self.default = default def __call__(self, serializer_field): is_update = serializer_field.parent.instance is not None if is_update: raise SkipField() if callable(self.default): if getattr(self.default, 'requires_context', False): return self.default(serializer_field) else: return self.default() return self.default def __repr__(self): return '%s(%s)' % (self.__class__.__name__, repr(self.default)) class CurrentUserDefault: requires_context = True def __call__(self, serializer_field): return serializer_field.context['request'].user def __repr__(self): return '%s()' % self.__class__.__name__ class SkipField(Exception): pass REGEX_TYPE = type(re.compile('')) NOT_READ_ONLY_WRITE_ONLY = 'May not set both `read_only` and `write_only`' NOT_READ_ONLY_REQUIRED = 'May not set both `read_only` and `required`' NOT_REQUIRED_DEFAULT = 'May not set both `required` and `default`' USE_READONLYFIELD = 'Field(read_only=True) should be ReadOnlyField' MISSING_ERROR_MESSAGE = ( 'ValidationError raised by `{class_name}`, but error key `{key}` does ' 'not exist in the `error_messages` dictionary.' ) class Field: _creation_counter = 0 default_error_messages = { 'required': _('This field is required.'), 'null': _('This field may not be null.') } default_validators = [] default_empty_html = empty initial = None def __init__(self, *, read_only=False, write_only=False, required=None, default=empty, initial=empty, source=None, label=None, help_text=None, style=None, error_messages=None, validators=None, allow_null=False): self._creation_counter = Field._creation_counter Field._creation_counter += 1 # If `required` is unset, then use `True` unless a default is provided. if required is None: required = default is empty and not read_only # Some combinations of keyword arguments do not make sense. assert not (read_only and write_only), NOT_READ_ONLY_WRITE_ONLY assert not (read_only and required), NOT_READ_ONLY_REQUIRED assert not (required and default is not empty), NOT_REQUIRED_DEFAULT assert not (read_only and self.__class__ == Field), USE_READONLYFIELD self.read_only = read_only self.write_only = write_only self.required = required self.default = default self.source = source self.initial = self.initial if (initial is empty) else initial self.label = label self.help_text = help_text self.style = {} if style is None else style self.allow_null = allow_null if self.default_empty_html is not empty: if default is not empty: self.default_empty_html = default if validators is not None: self.validators = list(validators) # These are set up by `.bind()` when the field is added to a serializer. self.field_name = None self.parent = None # Collect default error message from self and parent classes messages = {} for cls in reversed(self.__class__.__mro__): messages.update(getattr(cls, 'default_error_messages', {})) 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. Called when a field is added to the parent serializer instance. """ # In order to enforce a consistent style, we error if a redundant # 'source' argument has been used. For example: # my_field = serializer.CharField(source='my_field') assert self.source != field_name, ( "It is redundant to specify `source='%s'` on field '%s' in " "serializer '%s', because it is the same as the field name. " "Remove the `source` keyword argument." % (field_name, self.__class__.__name__, parent.__class__.__name__) ) self.field_name = field_name self.parent = parent # `self.label` should default to being based on the field name. if self.label is None: self.label = field_name.replace('_', ' ').capitalize() # self.source should default to being the same as the field name. if self.source is None: self.source = field_name # self.source_attrs is a list of attributes that need to be looked up # when serializing the instance, or populating the validated data. if self.source == '*': self.source_attrs = [] else: self.source_attrs = self.source.split('.') # .validators is a lazily loaded property, that gets its default # value from `get_validators`. @property def validators(self): if not hasattr(self, '_validators'): self._validators = self.get_validators() return self._validators @validators.setter def validators(self, validators): self._validators = validators def get_validators(self): return list(self.default_validators) def get_initial(self): """ Return a value to use when the field is being returned as a primitive value, without any object instance. """ if callable(self.initial): return self.initial() return self.initial def get_value(self, dictionary): """ Given the *incoming* primitive data, return the value for this field that should be validated and transformed to a native value. """ if html.is_html_input(dictionary): # HTML forms will represent empty fields as '', and cannot # represent None or False values directly. if self.field_name not in dictionary: if getattr(self.root, 'partial', False): return empty return self.default_empty_html ret = dictionary[self.field_name] if ret == '' and self.allow_null: # If the field is blank, and null is a valid value then # determine if we should use null instead. return '' if getattr(self, 'allow_blank', False) else None elif ret == '' and not self.required: # If the field is blank, and emptiness is valid then # determine if we should use emptiness instead. return '' if getattr(self, 'allow_blank', False) else empty return ret return dictionary.get(self.field_name, empty) def get_attribute(self, instance): """ Given the *outgoing* object instance, return the primitive value that should be used for this field. """ try: return get_attribute(instance, self.source_attrs) except BuiltinSignatureError as exc: msg = ( 'Field source for `{serializer}.{field}` maps to a built-in ' 'function type and is invalid. Define a property or method on ' 'the `{instance}` instance that wraps the call to the built-in ' 'function.'.format( serializer=self.parent.__class__.__name__, field=self.field_name, instance=instance.__class__.__name__, ) ) raise type(exc)(msg) except (KeyError, AttributeError) as exc: if self.default is not empty: return self.get_default() if self.allow_null: return None if not self.required: raise SkipField() msg = ( 'Got {exc_type} when attempting to get a value for field ' '`{field}` on serializer `{serializer}`.\nThe serializer ' 'field might be named incorrectly and not match ' 'any attribute or key on the `{instance}` instance.\n' 'Original exception text was: {exc}.'.format( exc_type=type(exc).__name__, field=self.field_name, serializer=self.parent.__class__.__name__, instance=instance.__class__.__name__, exc=exc ) ) raise type(exc)(msg) def get_default(self): """ Return the default value to use when validating data if no input is provided for this field. If a default has not been set for this field then this will simply raise `SkipField`, indicating that no value should be set in the validated data for this field. """ if self.default is empty or getattr(self.root, 'partial', False): # No default, or this is a partial update. raise SkipField() if callable(self.default): if getattr(self.default, 'requires_context', False): return self.default(self) else: return self.default() return self.default def validate_empty_values(self, data): """ Validate empty values, and either: * Raise `ValidationError`, indicating invalid data. * Raise `SkipField`, indicating that the field should be ignored. * Return (True, data), indicating an empty value that should be returned without any further validation being applied. * Return (False, data), indicating a non-empty value, that should have validation applied as normal. """ if self.read_only: return (True, self.get_default()) if data is empty: if getattr(self.root, 'partial', False): raise SkipField() if self.required: self.fail('required') return (True, self.get_default()) if data is None: if not self.allow_null: self.fail('null') # Nullable `source='*'` fields should not be skipped when its named # field is given a null value. This is because `source='*'` means # the field is passed the entire object, which is not null. elif self.source == '*': return (False, None) return (True, None) return (False, data) def run_validation(self, data=empty): """ Validate a simple representation and return the internal value. The provided data may be `empty` if no representation was included in the input. May raise `SkipField` if the field should not be included in the validated data. """ (is_empty_value, data) = self.validate_empty_values(data) if is_empty_value: return data value = self.to_internal_value(data) self.run_validators(value) return value def run_validators(self, value): """ Test the given value against all the validators on the field, and either raise a `ValidationError` or simply return. """ errors = [] for validator in self.validators: try: if getattr(validator, 'requires_context', False): validator(value, self) else: validator(value) except ValidationError as exc: # If the validation error contains a mapping of fields to # errors then simply raise it immediately rather than # attempting to accumulate a list of errors. if isinstance(exc.detail, dict): raise errors.extend(exc.detail) except DjangoValidationError as exc: errors.extend(get_error_detail(exc)) if errors: raise ValidationError(errors) def to_internal_value(self, data): """ Transform the *incoming* primitive data into a native value. """ raise NotImplementedError( '{cls}.to_internal_value() must be implemented for field ' '{field_name}. If you do not need to support write operations ' 'you probably want to subclass `ReadOnlyField` instead.'.format( cls=self.__class__.__name__, field_name=self.field_name, ) ) def to_representation(self, value): """ Transform the *outgoing* native value into primitive data. """ raise NotImplementedError( '{cls}.to_representation() must be implemented for field {field_name}.'.format( cls=self.__class__.__name__, field_name=self.field_name, ) ) def fail(self, key, **kwargs): """ A helper method that simply raises a validation error. """ try: msg = self.error_messages[key] except KeyError: class_name = self.__class__.__name__ msg = MISSING_ERROR_MESSAGE.format(class_name=class_name, key=key) raise AssertionError(msg) message_string = msg.format(**kwargs) raise ValidationError(message_string, code=key) @property def root(self): """ Returns the top-level serializer for this field. """ root = self while root.parent is not None: root = root.parent return root @property def context(self): """ Returns the context as passed to the root serializer on initialization. """ return getattr(self.root, '_context', {}) def __new__(cls, *args, **kwargs): """ When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object. """ instance = super().__new__(cls) instance._args = args instance._kwargs = kwargs return instance def __deepcopy__(self, memo): """ When cloning fields we instantiate using the arguments it was originally created with, rather than copying the complete state. """ # Treat regexes and validators as immutable. # See https://github.com/encode/django-rest-framework/issues/1954 # and https://github.com/encode/django-rest-framework/pull/4489 args = [ copy.deepcopy(item) if not isinstance(item, REGEX_TYPE) else item for item in self._args ] kwargs = { key: (copy.deepcopy(value, memo) if (key not in ('validators', 'regex')) else value) for key, value in self._kwargs.items() } return self.__class__(*args, **kwargs) def __repr__(self): """ Fields are represented using their initial calling arguments. This allows us to create descriptive representations for serializer instances that show all the declared fields on the serializer. """ return representation.field_repr(self) # Boolean types... class BooleanField(Field): default_error_messages = { 'invalid': _('Must be a valid boolean.') } default_empty_html = False initial = False TRUE_VALUES = { 't', 'y', 'yes', 'true', 'on', '1', 1, True, } FALSE_VALUES = { 'f', 'n', 'no', 'false', 'off', '0', 0, 0.0, False, } 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): with contextlib.suppress(TypeError): if self._lower_if_str(data) in self.TRUE_VALUES: return True elif self._lower_if_str(data) in self.FALSE_VALUES: return False elif self._lower_if_str(data) in self.NULL_VALUES and self.allow_null: return None self.fail("invalid", input=data) def to_representation(self, value): if self._lower_if_str(value) in self.TRUE_VALUES: return True elif self._lower_if_str(value) in self.FALSE_VALUES: return False if self._lower_if_str(value) in self.NULL_VALUES and self.allow_null: return None return bool(value) # String types... class CharField(Field): default_error_messages = { 'invalid': _('Not a valid string.'), 'blank': _('This field may not be blank.'), 'max_length': _('Ensure this field has no more than {max_length} characters.'), 'min_length': _('Ensure this field has at least {min_length} characters.'), } initial = '' def __init__(self, **kwargs): self.allow_blank = kwargs.pop('allow_blank', False) self.trim_whitespace = kwargs.pop('trim_whitespace', True) self.max_length = kwargs.pop('max_length', None) self.min_length = kwargs.pop('min_length', None) super().__init__(**kwargs) if self.max_length is not None: message = lazy_format(self.error_messages['max_length'], max_length=self.max_length) self.validators.append( MaxLengthValidator(self.max_length, message=message)) if self.min_length is not None: message = lazy_format(self.error_messages['min_length'], min_length=self.min_length) self.validators.append( MinLengthValidator(self.min_length, message=message)) self.validators.append(ProhibitNullCharactersValidator()) self.validators.append(ProhibitSurrogateCharactersValidator()) def run_validation(self, data=empty): # Test for the empty string here so that it does not get validated, # and so that subclasses do not need to handle it explicitly # inside the `to_internal_value()` method. if data == '' or (self.trim_whitespace and str(data).strip() == ''): if not self.allow_blank: self.fail('blank') return '' return super().run_validation(data) def to_internal_value(self, data): # We're lenient with allowing basic numerics to be coerced into strings, # but other types should fail. Eg. unclear if booleans should represent as `true` or `True`, # and composites such as lists are likely user error. if isinstance(data, bool) or not isinstance(data, (str, int, float,)): self.fail('invalid') value = str(data) return value.strip() if self.trim_whitespace else value def to_representation(self, value): return str(value) class EmailField(CharField): default_error_messages = { 'invalid': _('Enter a valid email address.') } def __init__(self, **kwargs): super().__init__(**kwargs) validator = EmailValidator(message=self.error_messages['invalid']) self.validators.append(validator) class RegexField(CharField): default_error_messages = { 'invalid': _('This value does not match the required pattern.') } def __init__(self, regex, **kwargs): super().__init__(**kwargs) validator = RegexValidator(regex, message=self.error_messages['invalid']) self.validators.append(validator) class SlugField(CharField): default_error_messages = { 'invalid': _('Enter a valid "slug" consisting of letters, numbers, underscores or hyphens.'), 'invalid_unicode': _('Enter a valid "slug" consisting of Unicode letters, numbers, underscores, or hyphens.') } def __init__(self, allow_unicode=False, **kwargs): super().__init__(**kwargs) self.allow_unicode = allow_unicode if self.allow_unicode: validator = RegexValidator(re.compile(r'^[-\w]+\Z', re.UNICODE), message=self.error_messages['invalid_unicode']) else: validator = RegexValidator(re.compile(r'^[-a-zA-Z0-9_]+$'), message=self.error_messages['invalid']) self.validators.append(validator) class URLField(CharField): default_error_messages = { 'invalid': _('Enter a valid URL.') } def __init__(self, **kwargs): super().__init__(**kwargs) validator = URLValidator(message=self.error_messages['invalid']) self.validators.append(validator) class UUIDField(Field): valid_formats = ('hex_verbose', 'hex', 'int', 'urn') default_error_messages = { 'invalid': _('Must be a valid UUID.'), } def __init__(self, **kwargs): self.uuid_format = kwargs.pop('format', 'hex_verbose') if self.uuid_format not in self.valid_formats: raise ValueError( 'Invalid format for uuid representation. ' 'Must be one of "{}"'.format('", "'.join(self.valid_formats)) ) super().__init__(**kwargs) def to_internal_value(self, data): if not isinstance(data, uuid.UUID): try: if isinstance(data, int): return uuid.UUID(int=data) elif isinstance(data, str): return uuid.UUID(hex=data) else: self.fail('invalid', value=data) except (ValueError): self.fail('invalid', value=data) return data def to_representation(self, value): if self.uuid_format == 'hex_verbose': return str(value) else: return getattr(value, self.uuid_format) class IPAddressField(CharField): """Support both IPAddressField and GenericIPAddressField""" default_error_messages = { 'invalid': _('Enter a valid IPv4 or IPv6 address.'), } def __init__(self, protocol='both', **kwargs): self.protocol = protocol.lower() self.unpack_ipv4 = (self.protocol == 'both') super().__init__(**kwargs) validators = ip_address_validators(protocol, self.unpack_ipv4) self.validators.extend(validators) def to_internal_value(self, data): if not isinstance(data, str): self.fail('invalid', value=data) if ':' in data: try: if self.protocol in ('both', 'ipv6'): return clean_ipv6_address(data, self.unpack_ipv4) except DjangoValidationError: self.fail('invalid', value=data) return super().to_internal_value(data) # Number types... class IntegerField(Field): default_error_messages = { 'invalid': _('A valid integer is required.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'max_string_length': _('String value too large.') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. re_decimal = re.compile(r'\.0*\s*$') # allow e.g. '1.0' as an int, but not '1.2' def __init__(self, **kwargs): self.max_value = kwargs.pop('max_value', None) self.min_value = kwargs.pop('min_value', None) super().__init__(**kwargs) if self.max_value is not None: message = lazy_format(self.error_messages['max_value'], max_value=self.max_value) self.validators.append( MaxValueValidator(self.max_value, message=message)) if self.min_value is not None: message = lazy_format(self.error_messages['min_value'], min_value=self.min_value) self.validators.append( MinValueValidator(self.min_value, message=message)) def to_internal_value(self, data): if isinstance(data, str) and len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: data = int(self.re_decimal.sub('', str(data))) except (ValueError, TypeError): self.fail('invalid') return data def to_representation(self, value): return int(value) class BigIntegerField(IntegerField): default_error_messages = { 'invalid': _('A valid biginteger 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.') } def __init__(self, coerce_to_string=None, **kwargs): super().__init__(**kwargs) if coerce_to_string is not None: self.coerce_to_string = coerce_to_string def to_representation(self, value): if getattr(self, 'coerce_to_string', api_settings.COERCE_BIGINT_TO_STRING): return '' if value is None else str(value) return super().to_representation(value) class FloatField(Field): default_error_messages = { '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.'), 'overflow': _('Integer value too large to convert to float') } MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. def __init__(self, **kwargs): self.max_value = kwargs.pop('max_value', None) self.min_value = kwargs.pop('min_value', None) super().__init__(**kwargs) if self.max_value is not None: message = lazy_format(self.error_messages['max_value'], max_value=self.max_value) self.validators.append( MaxValueValidator(self.max_value, message=message)) if self.min_value is not None: message = lazy_format(self.error_messages['min_value'], min_value=self.min_value) self.validators.append( MinValueValidator(self.min_value, message=message)) def to_internal_value(self, data): if isinstance(data, str) and len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: return float(data) except (TypeError, ValueError): self.fail('invalid') except OverflowError: self.fail('overflow') def to_representation(self, value): return float(value) class DecimalField(Field): default_error_messages = { 'invalid': _('A valid number is required.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'max_digits': _('Ensure that there are no more than {max_digits} digits in total.'), 'max_decimal_places': _('Ensure that there are no more than {max_decimal_places} decimal places.'), 'max_whole_digits': _('Ensure that there are no more than {max_whole_digits} digits before the decimal point.'), 'max_string_length': _('String value too large.') } 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, 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: self.coerce_to_string = True 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: self.max_whole_digits = None super().__init__(**kwargs) if self.max_value is not None: message = lazy_format(self.error_messages['max_value'], max_value=self.max_value) self.validators.append( MaxValueValidator(self.max_value, message=message)) if self.min_value is not None: message = lazy_format(self.error_messages['min_value'], min_value=self.min_value) self.validators.append( MinValueValidator(self.min_value, message=message)) if rounding is not None: valid_roundings = [v for k, v in vars(decimal).items() if k.startswith('ROUND_')] assert rounding in valid_roundings, ( 'Invalid rounding option %s. Valid values for rounding are: %s' % (rounding, valid_roundings)) self.rounding = rounding def validate_empty_values(self, data): if smart_str(data).strip() == '' and self.allow_null: return (True, None) return super().validate_empty_values(data) def to_internal_value(self, data): """ Validate that the input is a decimal number and return a Decimal instance. """ data = smart_str(data).strip() if self.localize: data = sanitize_separators(data) if len(data) > self.MAX_STRING_LENGTH: self.fail('max_string_length') try: value = decimal.Decimal(data) except decimal.DecimalException: self.fail('invalid') if value.is_nan(): self.fail('invalid') # Check for infinity and negative infinity. if value in (decimal.Decimal('Inf'), decimal.Decimal('-Inf')): self.fail('invalid') return self.quantize(self.validate_precision(value)) def validate_precision(self, value): """ Ensure that there are no more than max_digits in the number, and no more than decimal_places digits after the decimal point. Override this method to disable the precision validation for input values or to enhance it in any way you need to. """ sign, digittuple, exponent = value.as_tuple() if exponent >= 0: # 1234500.0 total_digits = len(digittuple) + exponent whole_digits = total_digits decimal_places = 0 elif len(digittuple) > abs(exponent): # 123.45 total_digits = len(digittuple) whole_digits = total_digits - abs(exponent) decimal_places = abs(exponent) else: # 0.001234 total_digits = abs(exponent) whole_digits = 0 decimal_places = total_digits if self.max_digits is not None and total_digits > self.max_digits: self.fail('max_digits', max_digits=self.max_digits) if self.decimal_places is not None and decimal_places > self.decimal_places: self.fail('max_decimal_places', max_decimal_places=self.decimal_places) if self.max_whole_digits is not None and whole_digits > self.max_whole_digits: self.fail('max_whole_digits', max_whole_digits=self.max_whole_digits) return value def to_representation(self, value): coerce_to_string = getattr(self, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING) if value is None: if coerce_to_string: return '' else: return None if not isinstance(value, decimal.Decimal): value = decimal.Decimal(str(value).strip()) 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'{quantized:f}' def quantize(self, value): """ Quantize the decimal value to the configured precision. """ if self.decimal_places is None: return value context = decimal.getcontext().copy() if self.max_digits is not None: context.prec = self.max_digits return value.quantize( decimal.Decimal('.1') ** self.decimal_places, rounding=self.rounding, context=context ) # Date & time fields... class DateTimeField(Field): default_error_messages = { 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}.'), 'date': _('Expected a datetime but got a date.'), 'make_aware': _('Invalid datetime for the timezone "{timezone}".'), 'overflow': _('Datetime value out of range.') } datetime_parser = datetime.datetime.strptime def __init__(self, format=empty, input_formats=None, default_timezone=None, **kwargs): if format is not empty: self.format = format if input_formats is not None: self.input_formats = input_formats if default_timezone is not None: self.timezone = default_timezone super().__init__(**kwargs) def enforce_timezone(self, value): """ When `self.default_timezone` is `None`, always return naive datetimes. When `self.default_timezone` is not `None`, always return aware datetimes. """ field_timezone = self.timezone if hasattr(self, 'timezone') else self.default_timezone() if field_timezone is not None: if timezone.is_aware(value): try: return value.astimezone(field_timezone) except OverflowError: self.fail('overflow') try: 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 def default_timezone(self): return timezone.get_current_timezone() if settings.USE_TZ else None def to_internal_value(self, value): input_formats = getattr(self, 'input_formats', api_settings.DATETIME_INPUT_FORMATS) if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): self.fail('date') if isinstance(value, datetime.datetime): return self.enforce_timezone(value) for input_format in input_formats: 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) 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) def to_representation(self, value): if not value: return None output_format = getattr(self, 'format', api_settings.DATETIME_FORMAT) if output_format is None or isinstance(value, str): return value value = self.enforce_timezone(value) if output_format.lower() == ISO_8601: value = value.isoformat() if value.endswith('+00:00'): value = value[:-6] + 'Z' return value return value.strftime(output_format) class DateField(Field): default_error_messages = { 'invalid': _('Date has wrong format. Use one of these formats instead: {format}.'), 'datetime': _('Expected a date but got a datetime.'), } datetime_parser = datetime.datetime.strptime def __init__(self, format=empty, input_formats=None, **kwargs): if format is not empty: self.format = format if input_formats is not None: self.input_formats = input_formats super().__init__(**kwargs) def to_internal_value(self, value): input_formats = getattr(self, 'input_formats', api_settings.DATE_INPUT_FORMATS) if isinstance(value, datetime.datetime): self.fail('datetime') if isinstance(value, datetime.date): return value for input_format in input_formats: if input_format.lower() == ISO_8601: try: parsed = parse_date(value) except (ValueError, TypeError): pass else: if parsed is not None: return parsed else: try: parsed = self.datetime_parser(value, input_format) except (ValueError, TypeError): pass else: return parsed.date() humanized_format = humanize_datetime.date_formats(input_formats) self.fail('invalid', format=humanized_format) def to_representation(self, value): if not value: return None output_format = getattr(self, 'format', api_settings.DATE_FORMAT) if output_format is None or isinstance(value, str): return value # Applying a `DateField` to a datetime value is almost always # not a sensible thing to do, as it means naively dropping # any explicit or implicit timezone info. assert not isinstance(value, datetime.datetime), ( 'Expected a `date`, but got a `datetime`. Refusing to coerce, ' 'as this may mean losing timezone information. Use a custom ' 'read-only field and deal with timezone issues explicitly.' ) if output_format.lower() == ISO_8601: return value.isoformat() return value.strftime(output_format) class TimeField(Field): default_error_messages = { 'invalid': _('Time has wrong format. Use one of these formats instead: {format}.'), } datetime_parser = datetime.datetime.strptime def __init__(self, format=empty, input_formats=None, **kwargs): if format is not empty: self.format = format if input_formats is not None: self.input_formats = input_formats super().__init__(**kwargs) def to_internal_value(self, value): input_formats = getattr(self, 'input_formats', api_settings.TIME_INPUT_FORMATS) if isinstance(value, datetime.time): return value for input_format in input_formats: if input_format.lower() == ISO_8601: try: parsed = parse_time(value) except (ValueError, TypeError): pass else: if parsed is not None: return parsed else: try: parsed = self.datetime_parser(value, input_format) except (ValueError, TypeError): pass else: return parsed.time() humanized_format = humanize_datetime.time_formats(input_formats) self.fail('invalid', format=humanized_format) def to_representation(self, value): if value in (None, ''): return None output_format = getattr(self, 'format', api_settings.TIME_FORMAT) if output_format is None or isinstance(value, str): return value # Applying a `TimeField` to a datetime value is almost always # not a sensible thing to do, as it means naively dropping # any explicit or implicit timezone info. assert not isinstance(value, datetime.datetime), ( 'Expected a `time`, but got a `datetime`. Refusing to coerce, ' 'as this may mean losing timezone information. Use a custom ' 'read-only field and deal with timezone issues explicitly.' ) if output_format.lower() == ISO_8601: return value.isoformat() return value.strftime(output_format) class DurationField(Field): default_error_messages = { '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, *, format=empty, **kwargs): self.max_value = kwargs.pop('max_value', None) self.min_value = kwargs.pop('min_value', None) if format is not empty: if format is None or (isinstance(format, str) and format.lower() in (ISO_8601, DJANGO_DURATION_FORMAT)): self.format = format elif isinstance(format, str): raise ValueError( f"Unknown duration format provided, got '{format}'" " while expecting 'django', 'iso-8601' or `None`." ) else: raise TypeError( "duration format must be either str or `None`," f" not {type(format).__name__}" ) super().__init__(**kwargs) if self.max_value is not None: message = lazy_format(self.error_messages['max_value'], max_value=self.max_value) self.validators.append( MaxValueValidator(self.max_value, message=message)) if self.min_value is not None: message = lazy_format(self.error_messages['min_value'], min_value=self.min_value) self.validators.append( MinValueValidator(self.min_value, message=message)) def to_internal_value(self, value): if isinstance(value, datetime.timedelta): return 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]') def to_representation(self, value): output_format = getattr(self, 'format', api_settings.DURATION_FORMAT) if output_format is None: return value if isinstance(output_format, str): if output_format.lower() == ISO_8601: return duration_iso_string(value) if output_format.lower() == DJANGO_DURATION_FORMAT: return duration_string(value) raise ValueError( f"Unknown duration format provided, got '{output_format}'" " while expecting 'django', 'iso-8601' or `None`." ) raise TypeError( "duration format must be either str or `None`," f" not {type(output_format).__name__}" ) # Choice types... class ChoiceField(Field): default_error_messages = { 'invalid_choice': _('"{input}" is not a valid choice.') } html_cutoff = None html_cutoff_text = _('More than {count} items...') def __init__(self, choices, **kwargs): self.choices = choices self.html_cutoff = kwargs.pop('html_cutoff', self.html_cutoff) self.html_cutoff_text = kwargs.pop('html_cutoff_text', self.html_cutoff_text) self.allow_blank = kwargs.pop('allow_blank', False) super().__init__(**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: self.fail('invalid_choice', input=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): """ Helper method for use with templates rendering select widgets. """ return iter_options( self.grouped_choices, cutoff=self.html_cutoff, cutoff_text=self.html_cutoff_text ) def _get_choices(self): return self._choices def _set_choices(self, choices): self.grouped_choices = to_choices_dict(choices) self._choices = flatten_choices_dict(self.grouped_choices) # Map the string representation of choices to the underlying value. # Allows us to deal with eg. integer choices while supporting either # integer or string input, but still get the correct datatype out. self.choice_strings_to_values = { 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) class MultipleChoiceField(ChoiceField): default_error_messages = { 'invalid_choice': _('"{input}" is not a valid choice.'), 'not_a_list': _('Expected a list of items but got type "{input_type}".'), 'empty': _('This selection may not be empty.') } default_empty_html = [] def __init__(self, **kwargs): self.allow_empty = kwargs.pop('allow_empty', True) super().__init__(**kwargs) def get_value(self, dictionary): if self.field_name not in dictionary: if getattr(self.root, 'partial', False): return empty # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): return dictionary.getlist(self.field_name) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): if isinstance(data, str) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) if not self.allow_empty and len(data) == 0: self.fail('empty') # Arguments for super() are needed because of scoping inside # comprehensions. return list( dict.fromkeys( super(MultipleChoiceField, self).to_internal_value(item) for item in data ) ) def to_representation(self, value): return list( dict.fromkeys( self.choice_strings_to_values.get(str(item), item) for item in value ) ) class FilePathField(ChoiceField): default_error_messages = { 'invalid_choice': _('"{input}" is not a valid path choice.') } def __init__(self, path, match=None, recursive=False, allow_files=True, allow_folders=False, required=None, **kwargs): # Defer to Django's FilePathField implementation to get the # valid set of choices. field = DjangoFilePathField( path, match=match, recursive=recursive, allow_files=allow_files, allow_folders=allow_folders, required=required ) kwargs['choices'] = field.choices kwargs['required'] = required super().__init__(**kwargs) # File types... class FileField(Field): default_error_messages = { 'required': _('No file was submitted.'), 'invalid': _('The submitted data was not a file. Check the encoding type on the form.'), 'no_name': _('No filename could be determined.'), 'empty': _('The submitted file is empty.'), 'max_length': _('Ensure this filename has at most {max_length} characters (it has {length}).'), } def __init__(self, **kwargs): self.max_length = kwargs.pop('max_length', None) self.allow_empty_file = kwargs.pop('allow_empty_file', False) if 'use_url' in kwargs: self.use_url = kwargs.pop('use_url') super().__init__(**kwargs) def to_internal_value(self, data): try: # `UploadedFile` objects should have name and size attributes. file_name = data.name file_size = data.size except AttributeError: self.fail('invalid') if not file_name: self.fail('no_name') if not self.allow_empty_file and not file_size: self.fail('empty') if self.max_length and len(file_name) > self.max_length: self.fail('max_length', max_length=self.max_length, length=len(file_name)) return data def to_representation(self, value): if not value: return None use_url = getattr(self, 'use_url', api_settings.UPLOADED_FILES_USE_URL) if use_url: try: url = value.url except AttributeError: return None request = self.context.get('request', None) if request is not None: return request.build_absolute_uri(url) return url return value.name class ImageField(FileField): default_error_messages = { 'invalid_image': _( 'Upload a valid image. The file you uploaded was either not an image or a corrupted image.' ), } def __init__(self, **kwargs): self._DjangoImageField = kwargs.pop('_DjangoImageField', DjangoImageField) super().__init__(**kwargs) def to_internal_value(self, data): # Image validation is a bit grungy, so we'll just outright # defer to Django's implementation so we don't need to # consider it, or treat PIL as a test dependency. file_object = super().to_internal_value(data) django_field = self._DjangoImageField() django_field.error_messages = self.error_messages return django_field.clean(file_object) # Composite field types... class _UnvalidatedField(Field): def __init__(self, **kwargs): super().__init__(**kwargs) self.allow_blank = True self.allow_null = True def to_internal_value(self, data): return data def to_representation(self, value): return value class ListField(Field): child = _UnvalidatedField() initial = [] default_error_messages = { 'not_a_list': _('Expected a list of items but got type "{input_type}".'), 'empty': _('This list may not be empty.'), 'min_length': _('Ensure this field has at least {min_length} elements.'), 'max_length': _('Ensure this field has no more than {max_length} elements.') } def __init__(self, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.allow_empty = kwargs.pop('allow_empty', True) self.max_length = kwargs.pop('max_length', None) self.min_length = kwargs.pop('min_length', None) assert not inspect.isclass(self.child), '`child` has not been instantiated.' assert self.child.source is None, ( "The `source` argument is not meaningful when applied to a `child=` field. " "Remove `source=` from the field declaration." ) super().__init__(**kwargs) self.child.bind(field_name='', parent=self) if self.max_length is not None: message = lazy_format(self.error_messages['max_length'], max_length=self.max_length) self.validators.append(MaxLengthValidator(self.max_length, message=message)) if self.min_length is not None: message = lazy_format(self.error_messages['min_length'], min_length=self.min_length) self.validators.append(MinLengthValidator(self.min_length, message=message)) def get_value(self, dictionary): if self.field_name not in dictionary: if getattr(self.root, 'partial', False): return empty # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): val = dictionary.getlist(self.field_name, []) if len(val) > 0: # Support QueryDict lists in HTML input. return val return html.parse_html_list(dictionary, prefix=self.field_name, default=empty) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): """ List of dicts of native values <- List of dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_list(data, default=[]) if isinstance(data, (str, Mapping)) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) if not self.allow_empty and len(data) == 0: self.fail('empty') return self.run_child_validation(data) def to_representation(self, data): """ List of object instances -> List of dicts of primitive datatypes. """ return [self.child.to_representation(item) if item is not None else None for item in data] def run_child_validation(self, data): result = [] 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 raise ValidationError(errors) class DictField(Field): child = _UnvalidatedField() initial = {} default_error_messages = { 'not_a_dict': _('Expected a dictionary of items but got type "{input_type}".'), 'empty': _('This dictionary may not be empty.'), } def __init__(self, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.allow_empty = kwargs.pop('allow_empty', True) assert not inspect.isclass(self.child), '`child` has not been instantiated.' assert self.child.source is None, ( "The `source` argument is not meaningful when applied to a `child=` field. " "Remove `source=` from the field declaration." ) super().__init__(**kwargs) self.child.bind(field_name='', parent=self) def get_value(self, dictionary): # We override the default field access in order to support # dictionaries in HTML forms. if html.is_html_input(dictionary): return html.parse_html_dict(dictionary, prefix=self.field_name) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): """ Dicts of native values <- Dicts of primitive datatypes. """ if html.is_html_input(data): data = html.parse_html_dict(data) if not isinstance(data, dict): self.fail('not_a_dict', input_type=type(data).__name__) if not self.allow_empty and len(data) == 0: self.fail('empty') return self.run_child_validation(data) def to_representation(self, value): return { str(key): self.child.to_representation(val) if val is not None else None for key, val in value.items() } def run_child_validation(self, data): result = {} errors = {} for key, value in data.items(): key = str(key) try: result[key] = self.child.run_validation(value) except ValidationError as e: errors[key] = e.detail if not errors: return result raise ValidationError(errors) class HStoreField(DictField): child = CharField(allow_blank=True, allow_null=True) def __init__(self, **kwargs): super().__init__(**kwargs) assert isinstance(self.child, CharField), ( "The `child` argument must be an instance of `CharField`, " "as the hstore extension stores values as strings." ) class JSONField(Field): default_error_messages = { 'invalid': _('Value must be valid JSON.') } # Workaround for isinstance calls when importing the field isn't possible _is_jsonfield = True def __init__(self, **kwargs): self.binary = kwargs.pop('binary', False) self.encoder = kwargs.pop('encoder', None) self.decoder = kwargs.pop('decoder', None) super().__init__(**kwargs) def get_value(self, dictionary): if html.is_html_input(dictionary) and self.field_name in dictionary: # When HTML form input is used, mark up the input # as being a JSON string, rather than a JSON primitive. class JSONString(str): def __new__(cls, value): ret = str.__new__(cls, value) ret.is_json_string = True return ret return JSONString(dictionary[self.field_name]) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): try: if self.binary or getattr(data, 'is_json_string', False): if isinstance(data, bytes): data = data.decode() return json.loads(data, cls=self.decoder) else: json.dumps(data, cls=self.encoder) except (TypeError, ValueError): self.fail('invalid') return data def to_representation(self, value): if self.binary: value = json.dumps(value, cls=self.encoder) value = value.encode() return value # Miscellaneous field types... class ReadOnlyField(Field): """ A read-only field that simply returns the field value. If the field is a method with no parameters, the method will be called and its return value used as the representation. For example, the following would call `get_expiry_date()` on the object: class ExampleSerializer(Serializer): expiry_date = ReadOnlyField(source='get_expiry_date') """ def __init__(self, **kwargs): kwargs['read_only'] = True super().__init__(**kwargs) def to_representation(self, value): return value class HiddenField(Field): """ A hidden field does not take input from the user, or present any output, but it does populate a field in `validated_data`, based on its default value. This is particularly useful when we have a `unique_for_date` constraint on a pair of fields, as we need some way to include the date in the validated data. """ def __init__(self, **kwargs): assert 'default' in kwargs, 'default is a required argument.' kwargs['write_only'] = True super().__init__(**kwargs) def get_value(self, dictionary): # We always use the default value for `HiddenField`. # User input is never provided or accepted. return empty def to_internal_value(self, data): return data class SerializerMethodField(Field): """ A read-only field that get its representation from calling a method on the parent serializer class. The method called will be of the form "get_{field_name}", and should take a single argument, which is the object being serialized. For example: 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'] = '*' kwargs['read_only'] = True super().__init__(**kwargs) def bind(self, field_name, parent): # The method name defaults to `get_{field_name}`. if self.method_name is None: self.method_name = f'get_{field_name}' super().bind(field_name, parent) def to_representation(self, value): method = getattr(self.parent, self.method_name) return method(value) class ModelField(Field): """ A generic field that can be used against an arbitrary model field. This is used by `ModelSerializer` when dealing with custom model fields, that do not have a serializer field to be mapped to. """ default_error_messages = { 'max_length': _('Ensure this field has no more than {max_length} characters.'), } def __init__(self, model_field, **kwargs): self.model_field = model_field # The `max_length` option is supported by Django's base `Field` class, # so we'd better support it here. self.max_length = kwargs.pop('max_length', None) super().__init__(**kwargs) if self.max_length is not None: message = lazy_format(self.error_messages['max_length'], max_length=self.max_length) self.validators.append( MaxLengthValidator(self.max_length, message=message)) def to_internal_value(self, data): rel = self.model_field.remote_field if rel is not None: return rel.model._meta.get_field(rel.field_name).to_python(data) return self.model_field.to_python(data) def get_attribute(self, obj): # We pass the object instance onto `to_representation`, # not just the field attribute. return obj def to_representation(self, obj): value = self.model_field.value_from_object(obj) if is_protected_type(value): return value return self.model_field.value_to_string(obj) ================================================ FILE: rest_framework/filters.py ================================================ """ Provides generic filtering backends that can be used to filter the results returned by list views. """ import operator from functools import reduce 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.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. """ def filter_queryset(self, request, queryset, view): """ Return a filtered queryset. """ raise NotImplementedError(".filter_queryset() must be overridden.") def get_schema_operation_parameters(self, view): return [] class SearchFilter(BaseFilterBackend): # The URL query parameter used for the search. search_param = api_settings.SEARCH_PARAM template = 'rest_framework/filters/search.html' lookup_prefixes = { '^': 'istartswith', '=': 'iexact', '@': 'search', '$': 'iregex', } search_title = _('Search') search_description = _('A search term.') def get_search_fields(self, view, request): """ Search fields are obtained from the view, but the request is always passed to this method. Sub-classes can override this method to dynamically change the search fields based on request content. """ return getattr(view, 'search_fields', None) def get_search_terms(self, request): """ Search terms are set by a ?search=... query parameter, and may be whitespace delimited. """ 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, 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]) def must_call_distinct(self, queryset, search_fields): """ Return True if 'distinct()' should be used to query the given lookups. """ for search_field in search_fields: opts = queryset.model._meta if search_field[0] in self.lookup_prefixes: search_field = search_field[1:] # Annotated fields do not need to be distinct if isinstance(queryset, models.QuerySet) and search_field in queryset.query.annotations: continue parts = search_field.split(LOOKUP_SEP) for part in parts: field = opts.get_field(part) if hasattr(field, 'get_path_info'): # This field is a relation, update opts to follow the relation path_info = field.get_path_info() opts = path_info[-1].to_opts if any(path.m2m for path in path_info): # This field is a m2m relation so we know we need to call distinct return True else: # This field has a custom __ query transform but is not a relational field. break return False def filter_queryset(self, request, queryset, view): search_fields = self.get_search_fields(view, request) search_terms = self.get_search_terms(request) if not search_fields or not search_terms: return queryset orm_lookups = [ self.construct_search(str(search_field), queryset) for search_field in search_fields ] base = queryset # 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): # 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 '' context = { 'param': self.search_param, 'term': request.query_params.get(self.search_param, ''), } template = loader.get_template(self.template) return template.render(context) def get_schema_operation_parameters(self, view): return [ { 'name': self.search_param, 'required': False, 'in': 'query', 'description': force_str(self.search_description), 'schema': { 'type': 'string', }, }, ] class OrderingFilter(BaseFilterBackend): # The URL query parameter used for the ordering. ordering_param = api_settings.ORDERING_PARAM ordering_fields = None ordering_title = _('Ordering') ordering_description = _('Which field to use when ordering the results.') template = 'rest_framework/filters/ordering.html' def get_ordering(self, request, queryset, view): """ Ordering is set by a comma delimited ?ordering=... query parameter. The `ordering` query parameter can be overridden by setting the `ordering_param` value on the OrderingFilter or by specifying an `ORDERING_PARAM` value in the API settings. """ params = request.query_params.get(self.ordering_param) if params: fields = [param.strip() for param in params.split(',')] ordering = self.remove_invalid_fields(queryset, fields, view, request) if ordering: return ordering # No ordering was included, or all the ordering fields were invalid return self.get_default_ordering(view) def get_default_ordering(self, view): ordering = getattr(view, 'ordering', None) if isinstance(ordering, str): return (ordering,) return ordering def get_default_valid_fields(self, queryset, view, context=None): if context is None: context = {} # If `ordering_fields` is not specified, then we determine a default # based on the serializer class, if one exists on the view. if hasattr(view, 'get_serializer_class'): try: serializer_class = view.get_serializer_class() except AssertionError: # Raised by the default implementation if # no serializer_class was found serializer_class = None else: serializer_class = getattr(view, 'serializer_class', None) if serializer_class is None: msg = ( "Cannot use %s on a view which does not have either a " "'serializer_class', an overriding 'get_serializer_class' " "or 'ordering_fields' attribute." ) raise ImproperlyConfigured(msg % self.__class__.__name__) model_class = queryset.model model_property_names = [ # 'pk' is a property added in Django's Model class, however it is valid for ordering. attr for attr in dir(model_class) if isinstance(getattr(model_class, attr), property) and attr != 'pk' ] return [ (field.source.replace('.', '__') or field_name, field.label) for field_name, field in serializer_class(context=context).fields.items() if ( not getattr(field, 'write_only', False) and not field.source == '*' and field.source not in model_property_names ) ] def get_valid_fields(self, queryset, view, context=None): if context is None: context = {} valid_fields = getattr(view, 'ordering_fields', self.ordering_fields) if valid_fields is None: # Default to allowing filtering on serializer fields return self.get_default_valid_fields(queryset, view, context) elif valid_fields == '__all__': # View explicitly allows filtering on any model field valid_fields = [ (field.name, field.verbose_name) for field in queryset.model._meta.fields ] valid_fields += [ (key, key.title().split('__')) for key in queryset.query.annotations ] else: valid_fields = [ (item, item) if isinstance(item, str) else item for item in valid_fields ] return valid_fields def remove_invalid_fields(self, queryset, fields, view, request): valid_fields = [item[0] for item in self.get_valid_fields(queryset, view, {'request': request})] def term_valid(term): if term.startswith("-"): term = term[1:] return term in valid_fields return [term for term in fields if term_valid(term)] def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) if ordering: return queryset.order_by(*ordering) return queryset def get_template_context(self, request, queryset, view): current = self.get_ordering(request, queryset, view) current = None if not current else current[0] options = [] context = { 'request': request, 'current': current, 'param': self.ordering_param, } for key, label in self.get_valid_fields(queryset, view, context): options.append((key, '%s - %s' % (label, _('ascending')))) options.append(('-' + key, '%s - %s' % (label, _('descending')))) context['options'] = options return context def to_html(self, request, queryset, view): template = loader.get_template(self.template) context = self.get_template_context(request, queryset, view) return template.render(context) def get_schema_operation_parameters(self, view): return [ { 'name': self.ordering_param, 'required': False, 'in': 'query', 'description': force_str(self.ordering_description), 'schema': { 'type': 'string', }, }, ] ================================================ FILE: rest_framework/generics.py ================================================ """ Generic views that provide commonly needed behavior. """ from django.core.exceptions import ValidationError from django.db.models.query import QuerySet from django.http import Http404 from django.shortcuts import get_object_or_404 as _get_object_or_404 from rest_framework import mixins, views from rest_framework.settings import api_settings def get_object_or_404(queryset, *filter_args, **filter_kwargs): """ Same as Django's standard shortcut, but make sure to also raise 404 if the filter_kwargs don't match the required types. """ try: return _get_object_or_404(queryset, *filter_args, **filter_kwargs) except (TypeError, ValueError, ValidationError): raise Http404 class GenericAPIView(views.APIView): """ Base class for all other generic views. """ # You'll need to either set these attributes, # or override `get_queryset()`/`get_serializer_class()`. # If you are overriding a view method, it is important that you call # `get_queryset()` instead of accessing the `queryset` property directly, # as `queryset` will get evaluated only once, and those results are cached # for all subsequent requests. queryset = None serializer_class = None # If you want to use object lookups other than pk, set 'lookup_field'. # For more complex lookup requirements override `get_object()`. lookup_field = 'pk' lookup_url_kwarg = None # The filter backend classes to use for queryset filtering filter_backends = api_settings.DEFAULT_FILTER_BACKENDS # 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. This must be an iterable, and may be a queryset. Defaults to using `self.queryset`. This method should always be used rather than accessing `self.queryset` directly, as `self.queryset` gets evaluated only once, and those results are cached for all subsequent requests. You may want to override this if you need to provide different querysets depending on the incoming request. (Eg. return a list of items that is specific to the user) """ assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) queryset = self.queryset if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset def get_object(self): """ Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. """ queryset = self.filter_queryset(self.get_queryset()) # Perform the lookup filtering. lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field assert lookup_url_kwarg in self.kwargs, ( 'Expected view %s to be called with a URL keyword argument ' 'named "%s". Fix your URL conf, or set the `.lookup_field` ' 'attribute on the view correctly.' % (self.__class__.__name__, lookup_url_kwarg) ) filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]} obj = get_object_or_404(queryset, **filter_kwargs) # May raise a permission denied self.check_object_permissions(self.request, obj) return obj def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() kwargs.setdefault('context', self.get_serializer_context()) return serializer_class(*args, **kwargs) def get_serializer_class(self): """ Return the class to use for the serializer. Defaults to using `self.serializer_class`. You may want to override this if you need to provide different serializations depending on the incoming request. (Eg. admins get full serialization, others get basic serialization) """ assert self.serializer_class is not None, ( "'%s' should either include a `serializer_class` attribute, " "or override the `get_serializer_class()` method." % self.__class__.__name__ ) return self.serializer_class def get_serializer_context(self): """ Extra context provided to the serializer class. """ return { 'request': self.request, 'format': self.format_kwarg, 'view': self } def filter_queryset(self, queryset): """ Given a queryset, filter it with whichever filter backend is in use. You are unlikely to want to override this method, although you may need to call it either from a list view, or from a custom `get_object` method if you want to apply the configured filtering backend to the default queryset. """ for backend in list(self.filter_backends): queryset = backend().filter_queryset(self.request, queryset, self) return queryset @property def paginator(self): """ The paginator instance associated with the view, or `None`. """ if not hasattr(self, '_paginator'): if self.pagination_class is None: self._paginator = None else: self._paginator = self.pagination_class() return self._paginator def paginate_queryset(self, queryset): """ Return a single page of results, or `None` if pagination is disabled. """ if self.paginator is None: return None return self.paginator.paginate_queryset(queryset, self.request, view=self) def get_paginated_response(self, data): """ Return a paginated style `Response` object for the given output data. """ assert self.paginator is not None return self.paginator.get_paginated_response(data) # Concrete view classes that provide method handlers # by composing the mixin classes with the base view. class CreateAPIView(mixins.CreateModelMixin, GenericAPIView): """ Concrete view for creating a model instance. """ def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class ListAPIView(mixins.ListModelMixin, GenericAPIView): """ Concrete view for listing a queryset. """ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) class RetrieveAPIView(mixins.RetrieveModelMixin, GenericAPIView): """ Concrete view for retrieving a model instance. """ def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) class DestroyAPIView(mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for deleting a model instance. """ def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) class UpdateAPIView(mixins.UpdateModelMixin, GenericAPIView): """ Concrete view for updating a model instance. """ def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) class ListCreateAPIView(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView): """ Concrete view for listing a queryset or creating a model instance. """ def get(self, request, *args, **kwargs): return self.list(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) class RetrieveUpdateAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, GenericAPIView): """ Concrete view for retrieving, updating a model instance. """ def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) class RetrieveDestroyAPIView(mixins.RetrieveModelMixin, mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for retrieving or deleting a model instance. """ def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, GenericAPIView): """ Concrete view for retrieving, updating or deleting a model instance. """ def get(self, request, *args, **kwargs): return self.retrieve(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs) ================================================ FILE: rest_framework/locale/ach/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Acoli (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ach/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ach\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/ar/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Andrew Ayoub , 2017 # aymen chaieb , 2017 # 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" "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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Arabic (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ar/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ar\n" "Plural-Forms: nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "ترويسة أساسية غير صالحة. لم تقدم أي بيانات تفويض." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "ترويسة أساسية غير صالحة. يجب أن لا تحتوي سلسلة بيانات التفويض على مسافات." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "ترويسة أساسية غير صالحة. بيانات التفويض لم تُشفر بشكل صحيح بنظام أساس64." #: authentication.py:101 msgid "Invalid username/password." msgstr "اسم المستخدم/كلمة المرور غير صحيحة." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "المستخدم غير مفعل او تم حذفه." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "رمز الراْس المميّز غير صالح, لم تقدم أي بيانات." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "رمز الراْس المميّز غير صالح, سلسلة الرمز المميّز لا يجب أن تحتوي على أي أحرف مسافات." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "رمز الراْس المميّز غير صالح, سلسلة الرمز المميّز لا يجب أن تحتوي على أي أحرف غير صالحة." #: authentication.py:203 msgid "Invalid token." msgstr "رمز غير صحيح." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "رمز التفويض" #: authtoken/models.py:13 msgid "Key" msgstr "المفتاح" #: authtoken/models.py:16 msgid "User" msgstr "المستخدم" #: authtoken/models.py:18 msgid "Created" msgstr "أنشئ" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "الرمز" #: authtoken/models.py:28 msgid "Tokens" msgstr "الرموز" #: authtoken/serializers.py:9 msgid "Username" msgstr "اسم المستخدم" #: authtoken/serializers.py:13 msgid "Password" msgstr "كلمة المرور" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "تعذر تسجيل الدخول بالبيانات المدخلة." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "يجب أن تتضمن \"اسم المستخدم\" و \"كلمة المرور\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "حدث خطأ في الخادم." #: exceptions.py:142 msgid "Invalid input." msgstr "مدخل غير صالح." #: exceptions.py:161 msgid "Malformed request." msgstr "الطلب صيغ بشكل سيء." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "بيانات الدخول غير صحيحة." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "لم يتم تزويد بيانات الدخول." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "ليس لديك صلاحية للقيام بهذا الإجراء." #: exceptions.py:185 msgid "Not found." msgstr "غير موجود." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "طريقة \"{method}\" غير مسموح بها." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "تعذر تلبية ترويسة Accept في الطلب." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "الوسيط \"{media_type}\" الموجود في الطلب غير معتمد." #: exceptions.py:223 msgid "Request was throttled." msgstr "تم حد الطلب." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "متوقع التوفر خلال {wait} ثانية." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "متوقع التوفر خلال {wait} ثواني." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "هذا الحقل مطلوب." #: fields.py:317 msgid "This field may not be null." msgstr "لا يمكن لهذا الحقل ان يكون فارغاً null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "يجب أن يكون قيمة منطقية صالحة." #: fields.py:766 msgid "Not a valid string." msgstr "ليس نصاً صالحاً." #: fields.py:767 msgid "This field may not be blank." msgstr "لا يمكن لهذا الحقل ان يكون فارغاً." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "تأكد ان عدد الحروف في هذا الحقل لا تتجاوز {max_length}." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "تأكد ان عدد الحروف في هذا الحقل لا يقل عن {min_length}." #: fields.py:816 msgid "Enter a valid email address." msgstr "يرجى إدخال عنوان بريد إلكتروني صحيح." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "هذه القيمة لا تطابق النمط المطلوب." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "أدخل \"slug\" صالح يحتوي على حروف، أرقام، شُرط سفلية أو واصلات." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "أدخل \"slug\" صالح يحتوي على حروف يونيكود، أرقام، شُرط سفلية أو واصلات." #: fields.py:854 msgid "Enter a valid URL." msgstr "الرجاء إدخال رابط إلكتروني صالح." #: fields.py:867 msgid "Must be a valid UUID." msgstr "يجب أن يكون معرف UUID صالح." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "أدخِل عنوان IPV4 أو IPV6 صحيح." #: fields.py:931 msgid "A valid integer is required." 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}." #: 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}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "النص طويل جداً." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "الرجاء إدخال رقم صالح." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "تأكد ان القيمة لا تحوي أكثر من {max_digits} رقم." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "تأكد انه لا يوجد اكثر من {max_decimal_places} أرقام عشرية." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "تأكد انه لا يوجد اكثر من {max_whole_digits} أرقام قبل النقطة العشرية." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "صيغة التاريخ و الوقت غير صحيحة. عليك أن تستخدم احد الصيغ التالية: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "متوقع تاريخ و وقت و وجد تاريخ فقط" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "تاريخ و وقت غير صالح للمنطقة الزمنية \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." msgstr "قيمة التاريخ و الوقت خارج النطاق." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "صيغة التاريخ غير صحيحة. عليك أن تستخدم واحدة من هذه الصيغ التالية: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "متوقع تاريخ فقط و وجد تاريخ ووقت" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "صيغة الوقت غير صحيحة. عليك أن تستخدم واحدة من هذه الصيغ التالية: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "صيغة المدة غير صحيحة. يرجى استخدام احد الصيغ التالية: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" ليس خياراً صالحاً." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "أكثر من {count} عنصر..." #: 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 "المتوقع وجود قائمة عناصر لكن وجد النوع \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "هذا التحديد لا يجب أن يكون فارغا." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "{input} ليس خيار مسار صالح." #: fields.py:1514 msgid "No file was submitted." msgstr "لم يتم إرسال أي ملف." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "البيانات المرسلة ليست ملف. تأكد من نوع الترميز في النموذج." #: fields.py:1516 msgid "No filename could be determined." msgstr "تعذر تحديد اسم الملف." #: fields.py:1517 msgid "The submitted file is empty." msgstr "الملف المرسل فارغ." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "يرجى رفع صورة صالحة. الملف الذي قمت برفعه ليس صورة أو أنه ملف تالف." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "يجب أن لا تكون القائمة فارغة." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "تأكد ان عدد العناصر في هذا الحقل لا يقل عن {min_length}." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "تأكد ان عدد العناصر في هذا الحقل لا يتجاوز {max_length}." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "المتوقع كان قاموس عناصر و لكن النوع المتحصل عليه هو \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "يجب أن لا يكون القاموس فارغاً." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "القيمة يجب أن تكون JSON صالح." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "بحث" #: filters.py:50 msgid "A search term." msgstr "مصطلح البحث." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "الترتيب" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "أي حقل يجب استخدامه عند ترتيب النتائج." #: filters.py:287 msgid "ascending" msgstr "تصاعدي" #: filters.py:288 msgid "descending" msgstr "تنازلي" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "رقم الصفحة ضمن النتائج المقسمة." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "عدد النتائج التي يجب إرجاعها في كل صفحة." #: pagination.py:189 msgid "Invalid page." msgstr "صفحة غير صحيحة." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "الفهرس الأولي الذي يجب البدء منه لإرجاع النتائج." #: pagination.py:581 msgid "The pagination cursor value." msgstr "قيمة المؤشر للتقسيم." #: pagination.py:583 msgid "Invalid cursor" msgstr "مؤشر غير صالح" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "معرف العنصر \"{pk_value}\" غير صالح - العنصر غير موجود." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "نوع غير صحيح. يتوقع قيمة معرف العنصر، بينما حصل على {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "رابط تشعبي غير صالح - لا يوجد تطابق URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "رابط تشعبي غير صالح - تطابق URL غير صحيح." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "رابط تشعبي غير صالح - العنصر غير موجود." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "نوع غير صحيح. المتوقع هو رابط URL، ولكن تم الحصول على {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "عنصر ب {slug_name}={value} غير موجود." #: relations.py:449 msgid "Invalid value." msgstr "قيمة غير صالحة." #: schemas/utils.py:32 msgid "unique integer value" msgstr "رقم صحيح فريد" #: schemas/utils.py:34 msgid "UUID string" msgstr "نص UUID" #: schemas/utils.py:36 msgid "unique value" msgstr "قيمة فريدة" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "نوع {value_type} يحدد هذا {name}." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "معطيات غير صالحة. المتوقع هو قاموس، لكن المتحصل عليه {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "إجراءات إضافية" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "مرشحات" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "شريط التنقل" #: templates/rest_framework/base.html:75 msgid "content" msgstr "المحتوى" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "نموذج الطلب" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "المحتوى الرئيسي" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "معلومات الطلب" #: templates/rest_framework/base.html:177 msgid "response info" 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 "لا شيء" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "لا يوجد عناصر لتحديدها." #: validators.py:39 msgid "This field must be unique." msgstr "هذا الحقل يجب أن يكون فريد" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "الحقول {field_names} يجب أن تشكل مجموعة فريدة." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "لا يُسمح بالحروف البديلة: U+{code_point:X}." #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "الحقل يجب ان يكون فريد للتاريخ {date_field}." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "الحقل يجب ان يكون فريد للشهر {date_field}." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "الحقل يجب ان يكون فريد للعام {date_field}." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "إصدار غير صالح في ترويسة \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "نسخة غير صالحة في مسار URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr " إصدار غير صالح في المسار URL. لا يطابق أي إصدار من مساحة الإسم." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "إصدار غير صالح في اسم المضيف." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "إصدار غير صالح في معلمة الإستعلام." ================================================ FILE: rest_framework/locale/az/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Emin Mastizada , 2020 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Azerbaijani (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/az/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: az\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Xətalı sadə başlıq. İstifadəçi məlumatları təchiz edilməyib." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Xətalı sadə başlıq. İstifadəçi məlumatlarında boşluq olmamalıdır." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Xətalı sadə başlıq. İstifadəçi məlumatları base64 ilə düzgün şifrələnməyib." #: authentication.py:101 msgid "Invalid username/password." msgstr "Xətalı istifadəçi adı/parol." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "İstifadəçi aktiv deyil və ya silinib." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Xətalı token başlığı. İstifadəçi məlumatları təchiz edilməyib." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Xətalı token başlığı. Token mətnində boşluqlar olmamalıdır." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Xətalı token başlığı. Token mətnində xətalı simvollar olmamalıdır." #: authentication.py:203 msgid "Invalid token." msgstr "Xətalı token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Təsdiqləmə Tokeni" #: authtoken/models.py:13 msgid "Key" msgstr "Açar" #: authtoken/models.py:16 msgid "User" msgstr "İstifadəçi" #: authtoken/models.py:18 msgid "Created" msgstr "Yaradılıb" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokenlər" #: authtoken/serializers.py:9 msgid "Username" msgstr "İstifadəçi adı" #: authtoken/serializers.py:13 msgid "Password" msgstr "Parol" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Təchiz edilən istifadəçi məlumatları ilə daxil olmaq mümkün olmadı." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Mütləq \"username\" və \"password\" olmalıdır." #: exceptions.py:102 msgid "A server error occurred." msgstr "Server xətası yaşandı." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Qüsurlu istək." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Səhv təsdiqləmə məlumatları." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Təsdiqləmə məlumatları təchiz edilməyib." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Bu əməliyyat üçün icazəniz yoxdur." #: exceptions.py:185 msgid "Not found." msgstr "Tapılmadı." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "\"{method}\" yöntəminə icazə verilmir." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "İstəyin Accept başlığını qane etmək mümkün olmadı." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "İstəkdə dəstəklənməyən \"{media_type}\" mediya növü." #: exceptions.py:223 msgid "Request was throttled." msgstr "İstək nəzərə alınmadı." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Bu sahə tələb edilir." #: fields.py:317 msgid "This field may not be null." msgstr "Bu sahə null ola bilməz." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Bu sahə boş ola bilməz." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Bu sahənin ən çox {max_length} simvolu olduğuna əmin olun." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Bu sahənin ən az {min_length} simvolu olduğuna əmin olun." #: fields.py:816 msgid "Enter a valid email address." msgstr "Keçərli e-poçt ünvanı daxil edin." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Bu dəyər tələb edilən formaya uyğun gəlmir." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Hərf, rəqəm, alt xətt və defislərdən ibarət keçərli \"slug\" daxil edin." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Keçərli URL daxil edin." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Keçərli IPv4 və ya IPv6 ünvanı daxil edin." #: fields.py:931 msgid "A valid integer is required." msgstr "Keçərli tam ədəd tələb edilir." #: 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 "Bu dəyərin uzunluğunun ən çox {max_value} olduğuna əmin olun." #: 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 "Bu dəyərin uzunluğunun ən az {min_value} olduğuna əmin olun." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Yazı dəyəri çox uzundur." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Keçərli rəqəm tələb edilir." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Ən çox {max_digits} rəqəm olduğuna əmin olun." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Ən çox {max_decimal_places} onluq kəsr hissəsi olduğuna əmin olun." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Onluq kərsdən əvvəl ən çox {max_whole_digits} rəqəm olduğuna əmin olun." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime dəyəri səhvdir. Əvəzinə bu formatlardan birini işlədin: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Datetime gözlənirdi amma date gəldi." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Date dəyəri səhvdir. Əvəzinə bu formatlardan birini işlədin: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Date gözlənirdi amma datetime gəldi." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Vaxt formatı səhvdir. Əvəzinə bu formatlardan birini işlədin: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Müddət formatı səhvdir. Əvəzinə bu formatlardan birini işlədin: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" keçərli seçim deyil." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "{count} elementdən daha çoxdur..." #: 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 "Elementlər siyahısı gözlənirdi, amma \"{input_type}\" növü gəldi." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Bu seçim boş ola bilməz." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" keçərli yol seçimi deyil." #: fields.py:1514 msgid "No file was submitted." msgstr "Heç bir fayl göndərilmədi." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Göndərilən məlumat fayl deyildi. Anketin şifrələmə (encoding) növünü yoxlayın." #: fields.py:1516 msgid "No filename could be determined." msgstr "Faylın adı təyin edilə bilmədi." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Göndərilən fayl boşdur." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Fayl adının ən çox {max_length} simvoldan ibarət olduğuna əmin olun (hazırki: {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Keçərli şəkil yükləyin. Yüklədiyiniz fayl ya şəkil deyil, ya da ola bilsin zədələnib." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Bu siyahı boş ola bilməz." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Elementlərin kitabçası (dictionary) gözlənirdi amma \"{input_type}\" növü gəldi." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Dəyər keçərli JSON olmalıdır." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Axtarış" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sıralama" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "artan" #: filters.py:288 msgid "descending" msgstr "azalan" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Xətalı səhifə." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Xətalı kursor" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Xətalı pk \"{pk_value}\" - obyekt mövcud deyil." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Xətalı növ. PK dəyəri gözlənirdi, {data_type} alındı." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Xətalı hiperkeçid - Heç bir URL uyğun gəlmir." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Xətalı hiperkeçid - Xətalı URL uyğunluğu." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Xətalı hiperkeçid - Obyekt mövcud deyil." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Xətalı növ. URL yazısı gözlənirdi, {data_type} gəldi." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} üçün uyğun obyekt mövcud deyil." #: relations.py:449 msgid "Invalid value." msgstr "Xətalı dəyər." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Xətalı məlumat. Kitabça (dictionary) gözlənirdi, {datatype} gəldi." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filterlər" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Heç nə" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Seçiləcək element yoxdur." #: validators.py:39 msgid "This field must be unique." msgstr "Bu sahə unikal olmalıdır." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "{field_names} sahələri birlikdə unikal dəst olmalıdırlar." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Bu sahə \"{date_field}\" günü üçün unikal olmalıdır." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Bu sahə \"{date_field}\" ayı üçün unikal olmalıdır." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Bu sahə \"{date_field}\" ili üçün unikal olmalıdır." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Accept\" başlığında xətalı versiya." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URL yolunda xətalı versiya." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "URL yolunda xətalı versiya. Heç bir versiya namespace-inə uyğun gəlmir." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Hostname-də xətalı versiya." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Sorğu parametrində xətalı versiya." ================================================ FILE: rest_framework/locale/be/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Belarusian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/be/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: be\n" "Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/bg/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Bulgarian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/bg/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: bg\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Невалиден header за базово удостоверение (basic authentication). Не се предоставени удостоверения." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Невалиден header за базово удостоверение (basic authentication). Носителите на удостоверение не трябва да съдържат интервали." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Невалиден header за базово удостоверение (basic authentication). Носителите на удостоверение не са кодирани в base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Невалидни потребителско име/парола." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Потребителят е неактивен или изтрит." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Невалиден token header. Не са предоставени носители на удостоверение." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Невалиден token header. Жетона (token-a) не трябва да съдържа интервали." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Невалиден token header. Жетона (token-a) не трябва да съдържа невалидни символи." #: authentication.py:203 msgid "Invalid token." msgstr "Невалиден жетон." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Жетон за удостоверение" #: authtoken/models.py:13 msgid "Key" msgstr "Ключ" #: authtoken/models.py:16 msgid "User" msgstr "Потребител" #: authtoken/models.py:18 msgid "Created" msgstr "Създаден" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Жетон" #: authtoken/models.py:28 msgid "Tokens" msgstr "Жетони" #: authtoken/serializers.py:9 msgid "Username" msgstr "Потребителско име" #: authtoken/serializers.py:13 msgid "Password" msgstr "Парола" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Не е възможен вход с предоставените удостоверения." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Трябва да съдържа \"username\" (потребителско име) и \"password\" (парола)." #: exceptions.py:102 msgid "A server error occurred." msgstr "Сървърна грешка." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Неправилно оформена заявка." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Невалидни носители на удостоверение." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Носители на удостоверение не са предоставени." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Нямате права да се направи това действие." #: exceptions.py:185 msgid "Not found." msgstr "Обектът не е намерен." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Метод \"{method}\" не е позволен." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Не може да бъде удовлетворен Accept header." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Неподдържан тип на документа \"{media_type}\" в заявката." #: exceptions.py:223 msgid "Request was throttled." msgstr "Заявката е ограничена." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Това поле е задължително." #: fields.py:317 msgid "This field may not be null." msgstr "Това поле не може да има празна стойност." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Това поле не може да е празно." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Това поле не трябва да съдържа повече от {max_length} символа." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Това поле трябва да съдържа поде {min_length} символа." #: fields.py:816 msgid "Enter a valid email address." msgstr "Въведете валиден имейл адрес." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Тази стойност не съответства на изисквания шаблон." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Въведете валиден \"slug\" съдържащ латински букви, цифри, долни черти или тирета." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Въведете валиден URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Въведете валиден IPv4 или IPv6 адрес." #: fields.py:931 msgid "A valid integer is required." 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}." #: 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}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Низът е прекалено голям." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Необходимо е валидно число." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Допустими са не повече от {max_digits} цифри." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Допустими са не повече от {max_decimal_places} цифри след десетичната запетая." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Допустими са не повече от {max_whole_digits} цифри преди десетичната запетая." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Датата и часът са в невалиден формат. Валидни са следните формати: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Очаква се дата и час, но е намерена само дата." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Дата е в невалиден формат. Валидни са следните формати: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Очаква се дата, но са подадени дата и час." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Времето е в невалиден формат. Валидни са следните формати: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Отрязъкът от време е в невалиден формат. Валидни са следните формати: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" не е валиден избор." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Повече от {count} неща..." #: 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 "Очаква се списък от неща, но е получен тип \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Този избор не може да е празен." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" не е валиден избор за път." #: fields.py:1514 msgid "No file was submitted." msgstr "Не е подаден файл." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Подадените данни не са файл. Проверете кодировката на формата." #: fields.py:1516 msgid "No filename could be determined." msgstr "Не може да бъде определено името на файла." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Подадения файл е празен." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "Невалидно изображение. Подадения файл не е изображение или е повредено изображение." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Този списък не може да е празен." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Очаква се асоциативен масив, но е получен \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Стойността трябва да е валиден JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Търсене" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Подредба" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "в нарастващ ред" #: filters.py:288 msgid "descending" msgstr "в намаляващ ред" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Невалидна страница." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Невалиден курсор" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Невалиден идентификатор \"{pk_value}\" - обектът не съществува." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Неправилен тип. Очакван е тип за основен ключ, получен е {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Невалидна връзка (hyperlink) - няма намерен URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Невалидна връзка (hyperlink) - неправилно съвпадение на URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Невалидна връзка (hyperlink) - обектът не съществува." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Невалиден тип. Очаква се URL низ, получен е {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Обект с {slug_name}={value} не съществува." #: relations.py:449 msgid "Invalid value." msgstr "Невалидна стойност." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Невалидни данни. Очаква се асоциативен масив, но е получен {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Филтри" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Нищо" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Няма неща за избиране." #: validators.py:39 msgid "This field must be unique." msgstr "Това поле трябва да е уникално." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Полетата {field_names} трябва да образуват уникална комбинация." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Това поле трябва да е уникално за \"{date_field}\" дата." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Това поле трябва да е уникално за \"{date_field}\" месец." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Това поле трябва да е уникално за \"{date_field}\" година." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Невалидна версия в \"Accept\" header." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Невалидна версия в URL пътя." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Невалидна версия в URL пътя. Няма съвпадение с пространството от имена на версии." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Невалидна версия в името на сървъра (hostname)." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Невалидна версия в GET параметър." ================================================ FILE: rest_framework/locale/ca/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Catalan (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ca/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ca\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Header Basic invàlid. No hi ha disponibles les credencials." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Header Basic invàlid. Les credencials no poden contenir espais." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Header Basic invàlid. Les credencials no estan codificades correctament en base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Usuari/Contrasenya incorrectes." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Usuari inactiu o esborrat." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Token header invàlid. No s'han indicat les credencials." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Token header invàlid. El token no ha de contenir espais." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Token header invàlid. El token no pot contenir caràcters invàlids." #: authentication.py:203 msgid "Invalid token." msgstr "Token invàlid." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:13 msgid "Key" msgstr "" #: authtoken/models.py:16 msgid "User" msgstr "" #: authtoken/models.py:18 msgid "Created" msgstr "" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "" #: authtoken/models.py:28 msgid "Tokens" msgstr "" #: authtoken/serializers.py:9 msgid "Username" msgstr "" #: authtoken/serializers.py:13 msgid "Password" msgstr "" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "No es possible loguejar-se amb les credencials introduïdes." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "S'ha d'incloure \"username\" i \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "S'ha produït un error en el servidor." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Request amb format incorrecte." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Credencials d'autenticació incorrectes." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Credencials d'autenticació no disponibles." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "No té permisos per realitzar aquesta acció." #: exceptions.py:185 msgid "Not found." msgstr "No trobat." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Mètode \"{method}\" no permès." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "No s'ha pogut satisfer l'Accept header de la petició." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Media type \"{media_type}\" no suportat." #: exceptions.py:223 msgid "Request was throttled." msgstr "La petició ha estat limitada pel número màxim de peticions definit." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Aquest camp és obligatori." #: fields.py:317 msgid "This field may not be null." msgstr "Aquest camp no pot ser nul." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Aquest camp no pot estar en blanc." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Aquest camp no pot tenir més de {max_length} caràcters." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Aquest camp ha de tenir un mínim de {min_length} caràcters." #: fields.py:816 msgid "Enter a valid email address." msgstr "Introdueixi una adreça de correu vàlida." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Aquest valor no compleix el patró requerit." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Introdueix un \"slug\" vàlid consistent en lletres, números, guions o guions baixos." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Introdueixi una URL vàlida." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Introdueixi una adreça IPv4 o IPv6 vàlida." #: fields.py:931 msgid "A valid integer is required." msgstr "Es requereix un nombre enter vàlid." #: 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 "Aquest valor ha de ser menor o igual a {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 "Aquest valor ha de ser més gran o igual a {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Valor del text massa gran." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Es requereix un nombre vàlid." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "No pot haver-hi més de {max_digits} dígits en total." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "No pot haver-hi més de {max_decimal_places} decimals." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "No pot haver-hi més de {max_whole_digits} dígits abans del punt decimal." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "El Datetime té un format incorrecte. Utilitzi un d'aquests formats: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "S'espera un Datetime però s'ha rebut un Date." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "El Date té un format incorrecte. Utilitzi un d'aquests formats: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "S'espera un Date però s'ha rebut un Datetime." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "El Time té un format incorrecte. Utilitzi un d'aquests formats: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "La durada té un format incorrecte. Utilitzi un d'aquests formats: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" no és una opció vàlida." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "" #: 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 "S'espera una llista d'ítems però s'ha rebut el tipus \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Aquesta selecció no pot estar buida." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" no és un path vàlid." #: fields.py:1514 msgid "No file was submitted." msgstr "No s'ha enviat cap fitxer." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Les dades enviades no són un fitxer. Comproveu l'encoding type del formulari." #: fields.py:1516 msgid "No filename could be determined." msgstr "No s'ha pogut determinar el nom del fitxer." #: fields.py:1517 msgid "The submitted file is empty." msgstr "El fitxer enviat està buit." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "El nom del fitxer ha de tenir com a màxim {max_length} caràcters (en té {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Envieu una imatge vàlida. El fitxer enviat no és una imatge o és una imatge corrompuda." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Aquesta llista no pot estar buida." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "S'espera un diccionari però s'ha rebut el tipus \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "" #: filters.py:288 msgid "descending" msgstr "" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Cursor invàlid." #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "PK invàlida \"{pk_value}\" - l'objecte no existeix." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Tipus incorrecte. S'espera el valor d'una PK, s'ha rebut {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Hyperlink invàlid - Cap match d'URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Hyperlink invàlid - Match d'URL incorrecta." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Hyperlink invàlid - L'objecte no existeix." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Tipus incorrecte. S'espera una URL, s'ha rebut {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "L'objecte amb {slug_name}={value} no existeix." #: relations.py:449 msgid "Invalid value." msgstr "Valor invàlid." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Dades invàlides. S'espera un diccionari però s'ha rebut {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Cap" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Cap opció seleccionada." #: validators.py:39 msgid "This field must be unique." msgstr "Aquest camp ha de ser únic." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Aquests camps {field_names} han de constituir un conjunt únic." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Aquest camp ha de ser únic per a la data \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Aquest camp ha de ser únic per al mes \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Aquest camp ha de ser únic per a l'any \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Versió invàlida al header \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Versió invàlida a la URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Versió invàlida al hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Versió invàlida al paràmetre de consulta." ================================================ FILE: rest_framework/locale/ca_ES/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Catalan (Spain) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ca_ES/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ca_ES\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/cs/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Jirka Vejrazka , 2015 # Tomáš Ehrlich , 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" "PO-Revision-Date: 2020-10-13 19:45+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Czech (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/cs/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: cs\n" "Plural-Forms: nplurals=4; plural=(n == 1 && n % 1 == 0) ? 0 : (n >= 2 && n <= 4 && n % 1 == 0) ? 1: (n % 1 != 0 ) ? 2 : 3;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Chybná hlavička. Nebyly poskytnuty přihlašovací údaje." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Chybná hlavička. Přihlašovací údaje by neměly obsahovat mezery." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Chybná hlavička. Přihlašovací údaje nebyly správně zakódovány pomocí base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Chybné uživatelské jméno nebo heslo." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Uživatelský účet je neaktivní nebo byl smazán." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Chybná hlavička tokenu. Nebyly zadány přihlašovací údaje." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Chybná hlavička tokenu. Přihlašovací údaje by neměly obsahovat mezery." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Chybná hlavička s tokenem. Token nesmí obsahovat nevalidní znaky." #: authentication.py:203 msgid "Invalid token." msgstr "Chybný token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Autentizační token" #: authtoken/models.py:13 msgid "Key" msgstr "Klíč" #: authtoken/models.py:16 msgid "User" msgstr "Uživatel" #: authtoken/models.py:18 msgid "Created" msgstr "Vytvořeno" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokeny" #: authtoken/serializers.py:9 msgid "Username" msgstr "Uživatelské jméno" #: authtoken/serializers.py:13 msgid "Password" msgstr "Heslo" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Zadanými údaji se nebylo možné přihlásit." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Musí obsahovat \"uživatelské jméno\" a \"heslo\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Chyba na straně serveru." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Neplatný formát požadavku." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Chybné přihlašovací údaje." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Nebyly zadány přihlašovací údaje." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "K této akci nemáte oprávnění." #: exceptions.py:185 msgid "Not found." msgstr "Nenalezeno." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metoda \"{method}\" není povolena." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Nelze vyhovět požadavku v hlavičce Accept." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Nepodporovaný media type \"{media_type}\" v požadavku." #: exceptions.py:223 msgid "Request was throttled." msgstr "Požadavek byl limitován kvůli omezení počtu požadavků za časovou periodu." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Toto pole je vyžadováno." #: fields.py:317 msgid "This field may not be null." msgstr "Toto pole nesmí být prázdné (null)." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Toto pole nesmí být prázdné." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Zkontrolujte, že toto pole není delší než {max_length} znaků." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Zkontrolujte, že toto pole obsahuje alespoň {min_length} znaků." #: fields.py:816 msgid "Enter a valid email address." msgstr "Vložte platnou e-mailovou adresu." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Hodnota v tomto poli neodpovídá požadovanému formátu." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Vložte platnou \"zkrácenou formu\" obsahující pouze malá písmena, čísla, spojovník nebo podtržítko." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Vložte platný odkaz." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Vložte platnou IPv4 nebo IPv6 adresu." #: fields.py:931 msgid "A valid integer is required." msgstr "Je vyžadováno celé číslo." #: 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 "Zkontrolujte, že hodnota je menší nebo rovna {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 "Zkontrolujte, že hodnota je větší nebo rovna {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Řetězec je příliš dlouhý." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Je vyžadováno číslo." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Zkontrolujte, že číslo neobsahuje více než {max_digits} čislic." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Zkontrolujte, že číslo nemá více než {max_decimal_places} desetinných míst." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Zkontrolujte, že číslo neobsahuje více než {max_whole_digits} čislic před desetinnou čárkou." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Chybný formát data a času. Použijte jeden z těchto formátů: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Bylo zadáno pouze datum bez času." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Chybný formát data. Použijte jeden z těchto formátů: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Bylo zadáno datum a čas, místo samotného data." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Chybný formát času. Použijte jeden z těchto formátů: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Trvání má nesprávný formát. Použijte jeden z následujících: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" není platnou možností." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Více než {count} položek..." #: 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 "Byl očekáván seznam položek ale nalezen \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Tento výběr by neměl být prázdný." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" není validní cesta k souboru." #: fields.py:1514 msgid "No file was submitted." msgstr "Nebyl zaslán žádný soubor." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Zaslaná data neobsahují soubor. Zkontrolujte typ kódování ve formuláři." #: fields.py:1516 msgid "No filename could be determined." msgstr "Nebylo možné zjistit jméno souboru." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Zaslaný soubor je prázdný." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Zajistěte, aby jméno souboru obsahovalo maximálně {max_length} znaků (teď má {length} znaků)." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Nahrajte platný obrázek. Nahraný soubor buď není obrázkem nebo je poškozen." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Tento list by neměl být prázdný." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Byl očekáván slovník položek ale nalezen \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Hodnota musí být platná hodnota JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Hledat" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Řazení" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "vzestupně" #: filters.py:288 msgid "descending" msgstr "sestupně" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Nevalidní strana." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Chybný kurzor" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Chybný primární klíč \"{pk_value}\" - objekt neexistuje." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Chybný typ. Byl přijat typ {data_type} místo hodnoty primárního klíče." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Chybný odkaz - nebyla nalezena žádní shoda." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Chybný odkaz - byla nalezena neplatná shoda." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Chybný odkaz - objekt neexistuje." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Chybný typ. Byl přijat typ {data_type} místo očekávaného odkazu." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekt s {slug_name}={value} neexistuje." #: relations.py:449 msgid "Invalid value." msgstr "Chybná hodnota." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Chybná data. Byl přijat typ {datatype} místo očekávaného slovníku." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtry" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Neuvedeno" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Žádné položky k výběru." #: validators.py:39 msgid "This field must be unique." msgstr "Tato položka musí být unikátní." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Položka {field_names} musí tvořit unikátní množinu." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Tato položka musí být pro datum \"{date_field}\" unikátní." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Tato položka musí být pro měsíc \"{date_field}\" unikátní." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Tato položka musí být pro rok \"{date_field}\" unikátní." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Chybné číslo verze v hlavičce Accept." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Chybné číslo verze v odkazu." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Nevalidní verze v URL cestě. Neodpovídá žádnému z jmenných prostorů pro verze." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Chybné číslo verze v hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Chybné čislo verze v URL parametru." ================================================ FILE: rest_framework/locale/da/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Mads Jensen , 2015-2017 # Mikkel Munch Mortensen <3xm@detfalskested.dk>, 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" "PO-Revision-Date: 2020-10-13 19:45+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Danish (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/da/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: da\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Ugyldig basic header. Ingen legitimation angivet." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Ugyldig basic header. Legitimationsstrenge må ikke indeholde mellemrum." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Ugyldig basic header. Legitimationen er ikke base64 encoded på korrekt vis." #: authentication.py:101 msgid "Invalid username/password." msgstr "Ugyldigt brugernavn/kodeord." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Inaktiv eller slettet bruger." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Ugyldig token header." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Ugyldig token header. Token-strenge må ikke indeholde mellemrum." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Ugyldig token header. Token streng bør ikke indeholde ugyldige karakterer." #: authentication.py:203 msgid "Invalid token." msgstr "Ugyldigt token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:13 msgid "Key" msgstr "Nøgle" #: authtoken/models.py:16 msgid "User" msgstr "Bruger" #: authtoken/models.py:18 msgid "Created" msgstr "Oprettet" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Brugernavn" #: authtoken/serializers.py:13 msgid "Password" msgstr "Kodeord" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Kunne ikke logge ind med den angivne legitimation." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Skal indeholde \"username\" og \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Der er sket en serverfejl." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Misdannet forespørgsel." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Ugyldig legitimation til autentificering." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Legitimation til autentificering blev ikke angivet." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Du har ikke lov til at udføre denne handling." #: exceptions.py:185 msgid "Not found." msgstr "Ikke fundet." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metoden \"{method}\" er ikke tilladt." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Kunne ikke efterkomme forespørgslens Accept header." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Forespørgslens media type, \"{media_type}\", er ikke understøttet." #: exceptions.py:223 msgid "Request was throttled." msgstr "Forespørgslen blev neddroslet." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Dette felt er påkrævet." #: fields.py:317 msgid "This field may not be null." msgstr "Dette felt må ikke være null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Dette felt må ikke være tomt." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Tjek at dette felt ikke indeholder flere end {max_length} tegn." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Tjek at dette felt indeholder mindst {min_length} tegn." #: fields.py:816 msgid "Enter a valid email address." msgstr "Angiv en gyldig e-mailadresse." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Denne værdi passer ikke med det påkrævede mønster." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Indtast en gyldig \"slug\", bestående af bogstaver, tal, bund- og bindestreger." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Indtast en gyldig URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Indtast en gyldig IPv4 eller IPv6 adresse." #: fields.py:931 msgid "A valid integer is required." msgstr "Et gyldigt heltal er påkrævet." #: 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 "Tjek at værdien er mindre end eller lig med {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 "Tjek at værdien er større end eller lig med {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Strengværdien er for stor." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Et gyldigt tal er påkrævet." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Tjek at der ikke er flere end {max_digits} cifre i alt." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Tjek at der ikke er flere end {max_decimal_places} cifre efter kommaet." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Tjek at der ikke er flere end {max_whole_digits} cifre før kommaet." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datotid har et forkert format. Brug i stedet et af disse formater: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Forventede en datotid, men fik en dato." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Dato har et forkert format. Brug i stedet et af disse formater: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Forventede en dato men fik en datotid." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Klokkeslæt har forkert format. Brug i stedet et af disse formater: {format}. " #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Varighed har forkert format. Brug istedet et af følgende formater: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" er ikke et gyldigt valg." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Flere end {count} objekter..." #: 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 "Forventede en liste, men fik noget af typen \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Dette valg kan være tomt." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" er ikke et gyldigt valg af adresse." #: fields.py:1514 msgid "No file was submitted." msgstr "Ingen medsendt fil." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Det medsendte data var ikke en fil. Tjek typen af indkodning på formularen." #: fields.py:1516 msgid "No filename could be determined." msgstr "Filnavnet kunne ikke afgøres." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Den medsendte fil er tom." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Sørg for at filnavnet er højst {max_length} langt (det er {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Medsend et gyldigt billede. Den medsendte fil var enten ikke et billede eller billedfilen var ødelagt." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Denne liste er muligvis ikke tom." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Forventede en dictionary, men fik noget af typen \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Værdi skal være gyldig JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Søg" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sortering" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "stigende" #: filters.py:288 msgid "descending" msgstr "faldende" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Ugyldig side" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Ugyldig cursor" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Ugyldig primærnøgle \"{pk_value}\" - objektet findes ikke." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Ugyldig type. Forventet værdi er primærnøgle, fik {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Ugyldigt hyperlink - intet URL match." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Ugyldigt hyperlink - forkert URL match." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Ugyldigt hyperlink - objektet findes ikke." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Forkert type. Forventede en URL-streng, fik {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Object med {slug_name}={value} findes ikke." #: relations.py:449 msgid "Invalid value." msgstr "Ugyldig værdi." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Ugyldig data. Forventede en dictionary, men fik {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtre" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ingen" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Intet at vælge." #: validators.py:39 msgid "This field must be unique." msgstr "Dette felt skal være unikt." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Felterne {field_names} skal udgøre et unikt sæt." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Dette felt skal være unikt for \"{date_field}\"-datoen." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Dette felt skal være unikt for \"{date_field}\"-måneden." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Dette felt skal være unikt for \"{date_field}\"-året." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Ugyldig version i \"Accept\" headeren." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Ugyldig version i URL-stien." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Ugyldig version in URLen. Den stemmer ikke overens med nogen versionsnumre." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Ugyldig version i hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Ugyldig version i forespørgselsparameteren." ================================================ FILE: rest_framework/locale/de/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Fabian Büchler , 2015 # 5a85a00218ad0559ac6870a4179f4dbc, 2017 # Lukas Bischofberger , 2017 # Mads Jensen , 2015 # Niklas P , 2015-2016 # Thomas Tanner, 2015 # Tom Jaster , 2015 # Xavier Ordoquy , 2015 # stefan6419846, 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: German (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/de/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: de\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." 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." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Ungültiger Basic Header. Zugangsdaten sind nicht korrekt mit base64 kodiert." #: authentication.py:101 msgid "Invalid username/password." msgstr "Ungültiger Benutzername/Passwort." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Benutzer inaktiv oder gelöscht." #: authentication.py:184 msgid "Invalid token header. No credentials provided." 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." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Ungültiger Token Header. Zugangsdaten dürfen keine ungültigen Zeichen enthalten." #: authentication.py:203 msgid "Invalid token." msgstr "Ungültiges Token" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Auth Token" #: authtoken/models.py:13 msgid "Key" msgstr "Schlüssel" #: authtoken/models.py:16 msgid "User" msgstr "Benutzer" #: authtoken/models.py:18 msgid "Created" msgstr "Erzeugt" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Benutzername" #: authtoken/serializers.py:13 msgid "Password" msgstr "Passwort" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Die angegebenen Zugangsdaten stimmen nicht." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"username\" und \"password\" sind erforderlich." #: exceptions.py:102 msgid "A server error occurred." msgstr "Ein Serverfehler ist aufgetreten." #: exceptions.py:142 msgid "Invalid input." msgstr "Ungültige Eingabe." #: exceptions.py:161 msgid "Malformed request." msgstr "Fehlerhafte Anfrage." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Falsche Anmeldedaten." #: exceptions.py:173 msgid "Authentication credentials were not provided." 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." #: exceptions.py:185 msgid "Not found." msgstr "Nicht gefunden." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Methode \"{method}\" nicht erlaubt." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Kann die Accept Kopfzeile der Anfrage nicht erfüllen." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Nicht unterstützter Medientyp \"{media_type}\" in der Anfrage." #: exceptions.py:223 msgid "Request was throttled." msgstr "Die Anfrage wurde gedrosselt." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "Erwarte Verfügbarkeit in {wait} Sekunde." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." 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 zwingend erforderlich." #: fields.py:317 msgid "This field may not be null." msgstr "Dieses Feld darf nicht null sein." #: fields.py:701 msgid "Must be a valid boolean." msgstr "Muss ein gültiger Wahrheitswert sein." #: fields.py:766 msgid "Not a valid string." msgstr "Kein gültiger String." #: fields.py:767 msgid "This field may not be blank." msgstr "Dieses Feld darf nicht leer sein." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Stelle sicher, dass dieses Feld nicht mehr als {max_length} Zeichen lang ist." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Stelle sicher, dass dieses Feld mindestens {min_length} Zeichen lang ist." #: fields.py:816 msgid "Enter a valid email address." msgstr "Gib eine gültige E-Mail Adresse an." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Dieser Wert passt nicht zu dem erforderlichen Muster." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Gib ein gültiges \"slug\" aus Buchstaben, Ziffern, Unterstrichen und Minuszeichen ein." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "Gib ein gültiges \"slug\" aus Unicode-Buchstaben, Ziffern, Unterstrichen und Minuszeichen ein." #: fields.py:854 msgid "Enter a valid URL." msgstr "Gib eine gültige URL ein." #: fields.py:867 msgid "Must be a valid UUID." 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." #: fields.py:931 msgid "A valid integer is required." msgstr "Eine gültige Ganzzahl ist erforderlich." #: 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 "Stelle sicher, dass dieser Wert kleiner oder gleich {max_value} ist." #: 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 "Stelle sicher, dass dieser Wert größer oder gleich {min_value} ist." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Zeichenkette zu lang." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Eine gültige Zahl ist erforderlich." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Stelle sicher, dass es insgesamt nicht mehr als {max_digits} Ziffern lang ist." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Stelle sicher, dass es nicht mehr als {max_decimal_places} Nachkommastellen lang ist." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Stelle sicher, dass es nicht mehr als {max_whole_digits} Stellen vor dem Komma lang ist." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datums- und Zeitangabe hat das falsche Format. Nutze stattdessen eines dieser Formate: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Erwarte eine Datums- und Zeitangabe, erhielt aber ein Datum." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "Ungültige Datumsangabe für die Zeitzone \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." msgstr "Datumsangabe außerhalb des Bereichs." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Datum hat das falsche Format. Nutze stattdessen eines dieser Formate: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Erwarte ein Datum, erhielt aber eine Datums- und Zeitangabe." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Zeitangabe hat das falsche Format. Nutze stattdessen eines dieser Formate: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Laufzeit hat das falsche Format. Benutze stattdessen eines dieser Formate {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" ist keine gültige Option." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Mehr als {count} Ergebnisse" #: 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 "Erwarte eine Liste von Elementen, erhielt aber den Typ \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Diese Auswahl darf nicht leer sein" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" ist ein ungültiger Pfad." #: fields.py:1514 msgid "No file was submitted." msgstr "Es wurde keine Datei übermittelt." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Die übermittelten Daten stellen keine Datei dar. Prüfe den Kodierungstyp im Formular." #: fields.py:1516 msgid "No filename could be determined." msgstr "Der Dateiname konnte nicht ermittelt werden." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Die übermittelte Datei ist leer." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Stelle sicher, dass dieser Dateiname höchstens {max_length} Zeichen lang ist (er hat {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Lade ein gültiges Bild hoch. Die hochgeladene Datei ist entweder kein Bild oder ein beschädigtes Bild." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Diese Liste darf nicht leer sein." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." 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 "Dieses Feld darf nicht mehr als {max_length} Einträge enthalten." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Erwartete ein Dictionary mit Elementen, erhielt aber den Typ \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "Dieses Dictionary darf nicht leer sein." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Wert muss gültiges JSON sein." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Suche" #: filters.py:50 msgid "A search term." msgstr "Ein Suchbegriff." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sortierung" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "Feld, das zum Sortieren der Ergebnisse verwendet werden soll." #: filters.py:287 msgid "ascending" msgstr "Aufsteigend" #: filters.py:288 msgid "descending" msgstr "Absteigend" #: pagination.py:174 msgid "A page number within the paginated result set." 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 "Anzahl der pro Seite zurückzugebenden Ergebnisse." #: pagination.py:189 msgid "Invalid page." msgstr "Ungültige Seite." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "Der initiale Index, von dem die Ergebnisse zurückgegeben werden sollen." #: pagination.py:581 msgid "The pagination cursor value." msgstr "Der Zeigerwert für die Paginierung" #: pagination.py:583 msgid "Invalid cursor" msgstr "Ungültiger Zeiger" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." 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}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Ungültiger Hyperlink - entspricht keiner URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Ungültiger Hyperlink - URL stimmt nicht überein." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." 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}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekt mit {slug_name}={value} existiert nicht." #: relations.py:449 msgid "Invalid value." msgstr "Ungültiger Wert." #: schemas/utils.py:32 msgid "unique integer value" msgstr "eindeutiger Ganzzahl-Wert" #: schemas/utils.py:34 msgid "UUID string" msgstr "UUID-String" #: schemas/utils.py:36 msgid "unique value" msgstr "eindeutiger Wert" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "Ein {value_type}, der {name} identifiziert." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." 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 "Zusätzliche Aktionen" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filter" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "Navigation" #: templates/rest_framework/base.html:75 msgid "content" msgstr "Inhalt" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "Anfrage-Formular" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "Hauptteil" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "Anfrage-Informationen" #: templates/rest_framework/base.html:177 msgid "response info" msgstr "Antwort-Informationen" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 #: templates/rest_framework/vertical/radio.html:3 msgid "None" msgstr "Nichts" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Keine Elemente zum Auswählen." #: validators.py:39 msgid "This field must be unique." msgstr "Dieses Feld muss eindeutig sein." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." 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 "Ersatzzeichen sind nicht erlaubt: U+{code_point:X}." #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Dieses Feld muss bezüglich des \"{date_field}\" Datums eindeutig sein." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Dieses Feld muss bezüglich des \"{date_field}\" Monats eindeutig sein." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Dieses Feld muss bezüglich des \"{date_field}\" Jahrs eindeutig sein." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Ungültige Version in der \"Accept\" Kopfzeile." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Ungültige Version im URL-Pfad." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Ungültige Version im URL-Pfad. Entspricht keinem Versions-Namensraum." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Ungültige Version im Hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Ungültige Version im Anfrageparameter." ================================================ FILE: rest_framework/locale/el/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Christos Barkonikos , 2020 # Panagiotis Pavlidis , 2019 # Serafeim Papastefanos , 2016 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Greek (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/el/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: el\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Λανθασμένη επικεφαλίδα basic. Δεν υπάρχουν διαπιστευτήρια." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Λανθασμένη επικεφαλίδα basic. Τα διαπιστευτήρια δεν πρέπει να περιέχουν κενά." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Λανθασμένη επικεφαλίδα basic. Τα διαπιστευτήρια δεν είναι κωδικοποιημένα κατά base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Λανθασμένο όνομα χρήστη/κωδικός." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Ο χρήστης είναι ανενεργός ή διεγραμμένος." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Λανθασμένη επικεφαλίδα token. Δεν υπάρχουν διαπιστευτήρια." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Λανθασμένη επικεφαλίδα token. Το token δεν πρέπει να περιέχει κενά." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Λανθασμένη επικεφαλίδα token. Το token περιέχει μη επιτρεπτούς χαρακτήρες." #: authentication.py:203 msgid "Invalid token." msgstr "Λανθασμένο token" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Token πιστοποίησης" #: authtoken/models.py:13 msgid "Key" msgstr "Κλειδί" #: authtoken/models.py:16 msgid "User" msgstr "Χρήστης" #: authtoken/models.py:18 msgid "Created" msgstr "Δημιουργήθηκε" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Όνομα χρήστη" #: authtoken/serializers.py:13 msgid "Password" msgstr "Κωδικός" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Δεν είναι δυνατή η σύνδεση με τα διαπιστευτήρια." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Πρέπει να περιέχει \"όνομα χρήστη\" και \"κωδικό\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Σφάλμα διακομιστή." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Λανθασμένο αίτημα." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Λάθος διαπιστευτήρια." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Δεν δόθηκαν διαπιστευτήρια." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Δεν έχετε δικαίωματα για αυτή την ενέργεια." #: exceptions.py:185 msgid "Not found." msgstr "Δε βρέθηκε." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Η μέθοδος \"{method}\" δεν επιτρέπεται." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Δεν ήταν δυνατή η ικανοποίηση της επικεφαλίδας Accept της αίτησης." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Δεν υποστηρίζεται το media type \"{media_type}\" της αίτησης." #: exceptions.py:223 msgid "Request was throttled." msgstr "Το αίτημα έγινε throttle." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Το πεδίο είναι απαραίτητο." #: fields.py:317 msgid "This field may not be null." msgstr "Το πεδίο δε μπορεί να είναι null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Το πεδίο δε μπορεί να είναι κενό." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Επιβεβαιώσατε ότι το πεδίο δεν έχει περισσότερους από {max_length} χαρακτήρες." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Επιβεβαιώσατε ότι το πεδίο έχει τουλάχιστον {min_length} χαρακτήρες." #: fields.py:816 msgid "Enter a valid email address." msgstr "Συμπληρώσατε μια έγκυρη διεύθυνση e-mail." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Η τιμή δε ταιριάζει με το pattern." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Εισάγετε ένα έγκυρο \"slug\" που αποτελείται από γράμματα, αριθμούς παύλες και κάτω παύλες." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Εισάγετε έγκυρο URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Εισάγετε μια έγκυρη διεύθυνση IPv4 ή IPv6." #: fields.py:931 msgid "A valid integer is required." 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}." #: 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}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Το κείμενο είναι πολύ μεγάλο." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Ένας έγκυρος αριθμός είναι απαραίτητος." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Επιβεβαιώσατε ότι δεν υπάρχουν παραπάνω από {max_digits} ψηφία." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Επιβεβαιώσατε ότι δεν υπάρχουν παραπάνω από {max_decimal_places} δεκαδικά ψηφία." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Επιβεβαιώσατε ότι δεν υπάρχουν παραπάνω από {max_whole_digits} ακέραια ψηφία." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Η ημερομηνία έχεi λάθος μορφή. Χρησιμοποιήστε μια από τις ακόλουθες μορφές: {format}" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Αναμένεται ημερομηνία και ώρα αλλά δόθηκε μόνο ημερομηνία." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Η ημερομηνία έχεi λάθος μορφή. Χρησιμοποιήστε μια από τις ακόλουθες μορφές: {format}" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Αναμένεται ημερομηνία αλλά δόθηκε ημερομηνία και ώρα." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Η ώρα έχει λάθος μορφή. Χρησιμοποιήστε μια από τις ακόλουθες μορφές: {format}" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Η διάρκεια έχει λάθος μορφή. Χρησιμοποιήστε μια από τις ακόλουθες μορφές: {format}" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "Το \"{input}\" δεν είναι έγκυρη επιλογή." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Περισσότερα από {count} αντικείμενα..." #: 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 "Αναμένεται μια λίστα αντικειμένον αλλά δόθηκε ο τύπος \"{input_type}\"" #: fields.py:1458 msgid "This selection may not be empty." msgstr "Η επιλογή δε μπορεί να είναι κενή." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "Το \"{input}\" δεν είναι έγκυρη επιλογή διαδρομής." #: fields.py:1514 msgid "No file was submitted." msgstr "Δεν υποβλήθηκε αρχείο." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Τα δεδομένα που υποβλήθηκαν δεν ήταν αρχείο. Ελέγξατε την κωδικοποίηση της φόρμας." #: fields.py:1516 msgid "No filename could be determined." msgstr "Δε βρέθηκε όνομα αρχείου." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Το αρχείο που υποβλήθηκε είναι κενό." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "Ανεβάστε μια έγκυρη εικόνα. Το αρχείο που ανεβάσατε είτε δεν είναι εικόνα είτε έχει καταστραφεί." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Η λίστα δε μπορεί να είναι κενή." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Αναμένεται ένα λεξικό αντικείμενων αλλά δόθηκε ο τύπος \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Η τιμή πρέπει να είναι μορφής JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Αναζήτηση" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ταξινόμηση" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "" #: filters.py:288 msgid "descending" msgstr "" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Λάθος σελίδα." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Λάθος cursor." #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Λάθος κλειδί \"{pk_value}\" - το αντικείμενο δεν υπάρχει." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Λάθος τύπος. Αναμένεται τιμή κλειδιού, δόθηκε {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Λάθος σύνδεση - δε ταιριάζει κάποιο URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Λάθος σύνδεση - δε ταιριάζει κάποιο URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Λάθος σύνδεση - το αντικείμενο δεν υπάρχει." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Λάθος τύπος. Αναμένεται URL, δόθηκε {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Το αντικείμενο {slug_name}={value} δεν υπάρχει." #: relations.py:449 msgid "Invalid value." msgstr "Λάθος τιμή." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Λάθος δεδομένα. Αναμένεται λεξικό αλλά δόθηκε {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Φίλτρα" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "None" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Δεν υπάρχουν αντικείμενα προς επιλογή." #: validators.py:39 msgid "This field must be unique." msgstr "Το πεδίο πρέπει να είναι μοναδικό" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Τα πεδία {field_names} πρέπει να αποτελούν ένα μοναδικό σύνολο." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Το πεδίο πρέπει να είναι μοναδικό για την ημερομηνία \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Το πεδίο πρέπει να είναι μοναδικό για το μήνα \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Το πεδίο πρέπει να είναι μοναδικό για το έτος \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Λάθος έκδοση στην επικεφαλίδα \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Λάθος έκδοση στη διαδρομή URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Λάθος έκδοση στο hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Λάθος έκδοση στην παράμετρο" ================================================ FILE: rest_framework/locale/el_GR/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Greek (Greece) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/el_GR/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: el_GR\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/en/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: English (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/en/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: en\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Invalid basic header. No credentials provided." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Invalid basic header. Credentials string should not contain spaces." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Invalid basic header. Credentials not correctly base64 encoded." #: authentication.py:101 msgid "Invalid username/password." msgstr "Invalid username/password." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "User inactive or deleted." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Invalid token header. No credentials provided." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Invalid token header. Token string should not contain spaces." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Invalid token header. Token string should not contain invalid characters." #: authentication.py:203 msgid "Invalid token." msgstr "Invalid token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Auth Token" #: authtoken/models.py:13 msgid "Key" msgstr "Key" #: authtoken/models.py:16 msgid "User" msgstr "User" #: authtoken/models.py:18 msgid "Created" msgstr "Created" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Username" #: authtoken/serializers.py:13 msgid "Password" msgstr "Password" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Unable to log in with provided credentials." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Must include \"username\" and \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "A server error occurred." #: exceptions.py:142 msgid "Invalid input." msgstr "Invalid input." #: exceptions.py:161 msgid "Malformed request." msgstr "Malformed request." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Incorrect authentication credentials." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Authentication credentials were not provided." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "You do not have permission to perform this action." #: exceptions.py:185 msgid "Not found." msgstr "Not found." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Method \"{method}\" not allowed." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Could not satisfy the request Accept header." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Unsupported media type \"{media_type}\" in request." #: exceptions.py:223 msgid "Request was throttled." msgstr "Request was throttled." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "Expected available in {wait} second." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "Expected available in {wait} seconds." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "This field is required." #: fields.py:317 msgid "This field may not be null." msgstr "This field may not be null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "Must be a valid boolean." #: fields.py:766 msgid "Not a valid string." msgstr "Not a valid string." #: fields.py:767 msgid "This field may not be blank." msgstr "This field may not be blank." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Ensure this field has no more than {max_length} characters." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Ensure this field has at least {min_length} characters." #: fields.py:816 msgid "Enter a valid email address." msgstr "Enter a valid email address." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "This value does not match the required pattern." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Enter a valid \"slug\" consisting of letters, numbers, underscores or hyphens." #: 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." #: fields.py:854 msgid "Enter a valid URL." msgstr "Enter a valid URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "Must be a valid UUID." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Enter a valid IPv4 or IPv6 address." #: fields.py:931 msgid "A valid integer is required." msgstr "A valid integer is required." #: 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 "Ensure this value is less than or equal to {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 "Ensure this value is greater than or equal to {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "String value too large." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "A valid number is required." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Ensure that there are no more than {max_digits} digits in total." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Ensure that there are no more than {max_decimal_places} decimal places." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Ensure that there are no more than {max_whole_digits} digits before the decimal point." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime has wrong format. Use one of these formats instead: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Expected a datetime but got a date." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "Invalid datetime for the timezone \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." msgstr "Datetime value out of range." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Date has wrong format. Use one of these formats instead: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Expected a date but got a datetime." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Time has wrong format. Use one of these formats instead: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Duration has wrong format. Use one of these formats instead: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" is not a valid choice." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "More than {count} items..." #: 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 "Expected a list of items but got type \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "This selection may not be empty." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" is not a valid path choice." #: fields.py:1514 msgid "No file was submitted." msgstr "No file was submitted." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "The submitted data was not a file. Check the encoding type on the form." #: fields.py:1516 msgid "No filename could be determined." msgstr "No filename could be determined." #: fields.py:1517 msgid "The submitted file is empty." msgstr "The submitted file is empty." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Ensure this filename has at most {max_length} characters (it has {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Upload a valid image. The file you uploaded was either not an image or a corrupted image." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "This list may not be empty." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "Ensure this field has at least {min_length} elements." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "Ensure this field has no more than {max_length} elements." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Expected a dictionary of items but got type \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "This dictionary may not be empty." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Value must be valid JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Search" #: filters.py:50 msgid "A search term." msgstr "A search term." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordering" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "Which field to use when ordering the results." #: filters.py:287 msgid "ascending" msgstr "ascending" #: filters.py:288 msgid "descending" msgstr "descending" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "A page number within the paginated result set." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "Number of results to return per page." #: pagination.py:189 msgid "Invalid page." msgstr "Invalid page." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "The initial index from which to return the results." #: pagination.py:581 msgid "The pagination cursor value." msgstr "The pagination cursor value." #: pagination.py:583 msgid "Invalid cursor" msgstr "Invalid cursor" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Invalid pk \"{pk_value}\" - object does not exist." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Incorrect type. Expected pk value, received {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Invalid hyperlink - No URL match." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Invalid hyperlink - Incorrect URL match." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Invalid hyperlink - Object does not exist." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Incorrect type. Expected URL string, received {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Object with {slug_name}={value} does not exist." #: relations.py:449 msgid "Invalid value." msgstr "Invalid value." #: schemas/utils.py:32 msgid "unique integer value" msgstr "unique integer value" #: schemas/utils.py:34 msgid "UUID string" msgstr "UUID string" #: schemas/utils.py:36 msgid "unique value" msgstr "unique value" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "A {value_type} identifying this {name}." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Invalid data. Expected a dictionary, but got {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "Extra Actions" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filters" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "navbar" #: templates/rest_framework/base.html:75 msgid "content" msgstr "content" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "request form" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "main content" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "request info" #: templates/rest_framework/base.html:177 msgid "response info" msgstr "response info" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 #: templates/rest_framework/vertical/radio.html:3 msgid "None" msgstr "None" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "No items to select." #: validators.py:39 msgid "This field must be unique." msgstr "This field must be unique." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "The fields {field_names} must make a unique set." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "Surrogate characters are not allowed: U+{code_point:X}." #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "This field must be unique for the \"{date_field}\" date." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "This field must be unique for the \"{date_field}\" month." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "This field must be unique for the \"{date_field}\" year." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Invalid version in \"Accept\" header." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Invalid version in URL path." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Invalid version in URL path. Does not match any version namespace." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Invalid version in hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Invalid version in query parameter." ================================================ FILE: rest_framework/locale/en_AU/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: English (Australia) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/en_AU/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: en_AU\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/en_CA/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: English (Canada) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/en_CA/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: en_CA\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/en_US/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # FIRST AUTHOR , YEAR. # #, fuzzy msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2020-10-13 21:45+0200\n" "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" "Last-Translator: FULL NAME \n" "Language-Team: LANGUAGE \n" "Language: \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:101 msgid "Invalid username/password." msgstr "" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:13 msgid "Key" msgstr "" #: authtoken/models.py:16 msgid "User" msgstr "" #: authtoken/models.py:18 msgid "Created" msgstr "" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "" #: authtoken/models.py:28 msgid "Tokens" msgstr "" #: authtoken/serializers.py:9 msgid "Username" msgstr "" #: authtoken/serializers.py:13 msgid "Password" msgstr "" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:102 msgid "A server error occurred." msgstr "" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:185 msgid "Not found." msgstr "" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:223 msgid "Request was throttled." msgstr "" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "" #: fields.py:317 msgid "This field may not be null." msgstr "" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:816 msgid "Enter a valid email address." msgstr "" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:931 msgid "A valid integer is required." 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 "" #: 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 "" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:1008 #, python-brace-format msgid "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "" #: 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 "" #: fields.py:1458 msgid "This selection may not be empty." msgstr "" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "" #: fields.py:1515 msgid "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1516 msgid "No filename could be determined." msgstr "" #: fields.py:1517 msgid "The submitted file is empty." msgstr "" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "" #: filters.py:288 msgid "descending" msgstr "" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:449 msgid "Invalid value." msgstr "" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "" #: validators.py:39 msgid "This field must be unique." msgstr "" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "" ================================================ FILE: rest_framework/locale/es/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Ernesto Rico Schmidt , 2015 # José Padilla , 2015 # Leo Prada , 2019 # Miguel Gonzalez , 2015 # 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: 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" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: es\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Cabecera básica inválida. Las credenciales no fueron suministradas." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Cabecera básica inválida. La cadena con las credenciales no debe contener espacios." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Cabecera básica inválida. Las credenciales no fueron codificadas correctamente en base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Nombre de usuario/contraseña inválidos." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Usuario inactivo o borrado." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Cabecera token inválida. Las credenciales no fueron suministradas." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Cabecera token inválida. La cadena token no debe contener espacios." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Cabecera token inválida. La cadena token no debe contener caracteres inválidos." #: authentication.py:203 msgid "Invalid token." msgstr "Token inválido." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Token de autenticación" #: authtoken/models.py:13 msgid "Key" msgstr "Clave" #: authtoken/models.py:16 msgid "User" msgstr "Usuario" #: authtoken/models.py:18 msgid "Created" msgstr "Fecha de creación" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Nombre de usuario" #: authtoken/serializers.py:13 msgid "Password" msgstr "Contraseña" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "No puede iniciar sesión con las credenciales proporcionadas." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Debe incluir \"username\" y \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Se ha producido un error en el servidor." #: exceptions.py:142 msgid "Invalid input." msgstr "Entrada inválida." #: exceptions.py:161 msgid "Malformed request." msgstr "Solicitud con formato incorrecto." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Credenciales de autenticación incorrectas." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Las credenciales de autenticación no se proveyeron." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Usted no tiene permiso para realizar esta acción." #: exceptions.py:185 msgid "Not found." msgstr "No encontrado." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Método \"{method}\" no permitido." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "No se ha podido satisfacer la solicitud de cabecera de Accept." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Tipo de medio \"{media_type}\" incompatible en la solicitud." #: exceptions.py:223 msgid "Request was throttled." msgstr "Solicitud fue regulada (throttled)." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "Se espera que esté disponible en {wait} segundo." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "Se espera que esté disponible en {wait} segundos." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Este campo es requerido." #: fields.py:317 msgid "This field may not be null." msgstr "Este campo no puede ser nulo." #: fields.py:701 msgid "Must be a valid boolean." msgstr "Debe ser un booleano válido." #: fields.py:766 msgid "Not a valid string." msgstr "No es una cadena válida." #: fields.py:767 msgid "This field may not be blank." msgstr "Este campo no puede estar en blanco." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Asegúrese de que este campo no tenga más de {max_length} caracteres." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Asegúrese de que este campo tenga al menos {min_length} caracteres." #: fields.py:816 msgid "Enter a valid email address." msgstr "Introduzca una dirección de correo electrónico válida." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Este valor no coincide con el patrón requerido." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Introduzca un \"slug\" válido consistente en letras, números, guiones o guiones bajos." #: fields.py:839 msgid "" "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." msgstr "Introduzca una URL válida." #: fields.py:867 msgid "Must be a valid UUID." msgstr "Debe ser un UUID válido." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Introduzca una dirección IPv4 o IPv6 válida." #: fields.py:931 msgid "A valid integer is required." msgstr "Introduzca un número entero válido." #: 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 "Asegúrese de que este valor es menor o igual a {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 "Asegúrese de que este valor es mayor o igual a {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Cadena demasiado larga." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Se requiere un número válido." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Asegúrese de que no haya más de {max_digits} dígitos en total." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Asegúrese de que no haya más de {max_decimal_places} decimales." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Asegúrese de que no haya más de {max_whole_digits} dígitos en la parte entera." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Fecha/hora con formato erróneo. Use uno de los siguientes formatos en su lugar: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." 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 "Fecha y hora inválida para la zona horaria \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." msgstr "Valor de fecha y hora fuera de rango." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Fecha con formato erróneo. Use uno de los siguientes formatos en su lugar: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Se esperaba una fecha en vez de una fecha/hora." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Hora con formato erróneo. Use uno de los siguientes formatos en su lugar: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Duración con formato erróneo. Use uno de los siguientes formatos en su lugar: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" no es una elección válida." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Más de {count} elementos..." #: 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 "Se esperaba una lista de elementos en vez del tipo \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Esta selección no puede estar vacía." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" no es una elección de ruta válida." #: fields.py:1514 msgid "No file was submitted." msgstr "No se envió ningún archivo." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "La información enviada no era un archivo. Compruebe el tipo de codificación del formulario." #: fields.py:1516 msgid "No filename could be determined." msgstr "No se pudo determinar un nombre de archivo." #: fields.py:1517 msgid "The submitted file is empty." msgstr "El archivo enviado está vació." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Asegúrese de que el nombre de archivo no tenga más de {max_length} caracteres (tiene {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Adjunte una imagen válida. El archivo adjunto o bien no es una imagen o bien está dañado." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." 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 "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 "Asegúrese de que este campo no tiene más de {max_length} elementos." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Se esperaba un diccionario de elementos en vez del tipo \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "Este diccionario no debe estar vacío." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "El valor debe ser JSON válido." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Buscar" #: filters.py:50 msgid "A search term." msgstr "Un término de búsqueda." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordenamiento" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "Qué campo usar para ordenar los resultados." #: filters.py:287 msgid "ascending" msgstr "ascendiente" #: filters.py:288 msgid "descending" msgstr "descendiente" #: pagination.py:174 msgid "A page number within the paginated result set." 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 "Número de resultados a devolver por página." #: pagination.py:189 msgid "Invalid page." msgstr "Página inválida." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "El índice inicial a partir del cual devolver los resultados." #: pagination.py:581 msgid "The pagination cursor value." msgstr "El valor del cursor de paginación." #: pagination.py:583 msgid "Invalid cursor" msgstr "Cursor inválido" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Clave primaria \"{pk_value}\" inválida - objeto no existe." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Tipo incorrecto. Se esperaba valor de clave primaria y se recibió {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Hiperenlace inválido - No hay URL coincidentes." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Hiperenlace inválido - Coincidencia incorrecta de la URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Hiperenlace inválido - Objeto no existe." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Tipo incorrecto. Se esperaba una URL y se recibió {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objeto con {slug_name}={value} no existe." #: relations.py:449 msgid "Invalid value." msgstr "Valor inválido." #: schemas/utils.py:32 msgid "unique integer value" msgstr "valor de entero único" #: schemas/utils.py:34 msgid "UUID string" msgstr "Cadena UUID" #: schemas/utils.py:36 msgid "unique value" msgstr "valor único" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "Un {value_type} que identifique este {name}." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." 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 "Acciones extras" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtros" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ninguno" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "No hay elementos para seleccionar." #: validators.py:39 msgid "This field must be unique." msgstr "Este campo debe ser único." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Los campos {field_names} deben formar un conjunto único." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Este campo debe ser único para el día \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Este campo debe ser único para el mes \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Este campo debe ser único para el año \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Versión inválida en la cabecera \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Versión inválida en la ruta de la URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "La versión especificada en la ruta de la URL no es válida. No coincide con ninguna del espacio de nombres de versiones." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Versión inválida en el nombre de host." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Versión inválida en el parámetro de consulta." ================================================ FILE: rest_framework/locale/et/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Erlend Eelmets , 2020 # Tõnis Kärdi , 2015,2019 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Estonian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/et/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: et\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Sobimatu lihtpäis. Kasutajatunnus on esitamata." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Sobimatu lihtpäis. Kasutajatunnus ei tohi sisaldada tühikuid." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Sobimatu lihtpäis. Kasutajatunnus pole korrektselt base64-kodeeritud." #: authentication.py:101 msgid "Invalid username/password." msgstr "Sobimatu kasutajatunnus/salasõna." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Kasutaja on inaktiivne või kustutatud." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Sobimatu lubakaardi päis. Kasutajatunnus on esitamata." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Sobimatu lubakaardi päis. Loa sõne ei tohi sisaldada tühikuid." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Sobimatu lubakaardi päis. Loa sõne ei tohi sisaldada sobimatuid märke." #: authentication.py:203 msgid "Invalid token." msgstr "Sobimatu lubakaart." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Autentimistähis" #: authtoken/models.py:13 msgid "Key" msgstr "Võti" #: authtoken/models.py:16 msgid "User" msgstr "Kasutaja" #: authtoken/models.py:18 msgid "Created" msgstr "Loodud" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Tähis" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tähised" #: authtoken/serializers.py:9 msgid "Username" msgstr "Kasutajanimi" #: authtoken/serializers.py:13 msgid "Password" msgstr "Salasõna" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Sisselogimine antud tunnusega ebaõnnestus." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Peab sisaldama \"kasutajatunnust\" ja \"slasõna\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Viga serveril." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Väändunud päring." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Ebakorrektne autentimistunnus." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Autentimistunnus on esitamata." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Teil puuduvad piisavad õigused selle tegevuse teostamiseks." #: exceptions.py:185 msgid "Not found." msgstr "Ei leidnud." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Meetod \"{method}\" pole lubatud." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Päringu Accept-päist ei suutnud täita." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Meedia tüüpi {media_type} päringus ei toetata." #: exceptions.py:223 msgid "Request was throttled." msgstr "Liiga palju päringuid." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Väli on kohustuslik." #: fields.py:317 msgid "This field may not be null." msgstr "Väli ei tohi olla tühi." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "See väli ei tohi olla tühi." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Veendu, et see väli poleks pikem kui {max_length} tähemärki." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Veendu, et see väli oleks vähemalt {min_length} tähemärki pikk." #: fields.py:816 msgid "Enter a valid email address." msgstr "Sisestage kehtiv e-posti aadress." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Väärtus ei ühti etteantud mustriga." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Sisestage kehtiv \"slug\", mis koosneks tähtedest, numbritest, ala- või sidekriipsudest." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Sisestage korrektne URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Sisesta valiidne IPv4 või IPv6 aadress" #: fields.py:931 msgid "A valid integer is required." msgstr "Sisendiks peab olema täisarv." #: 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 "Veenduge, et väärtus on väiksem kui või võrdne väärtusega {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 "Veenduge, et väärtus on suurem kui või võrdne väärtusega {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Sõne on liiga pikk." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Sisendiks peab olema arv." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Veenduge, et kokku pole rohkem kui {max_digits} numbit." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Veenduge, et komakohti pole rohkem kui {max_decimal_places}. " #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Veenduge, et täiskohti poleks rohkem kui {max_whole_digits}." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Valesti formaaditud kuupäev-kellaaeg. Kasutage mõnda neist: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Ootasin kuupäev-kellaaeg andmetüüpi, kuid sain hoopis kuupäeva." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Valesti formaaditud kuupäev. Kasutage mõnda neist: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Ootasin kuupäeva andmetüüpi, kuid sain hoopis kuupäev-kellaaja." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Valesti formaaditud kellaaeg. Kasutage mõnda neist: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Valesti formaaditud kestvus. Kasutage mõnda neist: {format}" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" on sobimatu valik." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Kirjeid on rohkem kui {count} ... " #: 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 "Ootasin kirjete järjendit, kuid sain \"{input_type}\" - tüübi." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Valik ei tohi olla määramata." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" on sobimatu valik." #: fields.py:1514 msgid "No file was submitted." msgstr "Ühtegi faili ei esitatud." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Esitatud andmetes ei olnud faili. Kontrollige vormi kodeeringut." #: fields.py:1516 msgid "No filename could be determined." msgstr "Ei suutnud tuvastada failinime." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Esitatud fail oli tühi." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Veenduge, et failinimi oleks maksimaalselt {max_length} tähemärki pikk (praegu on {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Laadige üles kehtiv pildifail. Üles laetud fail ei olnud pilt või oli see katki." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Loetelu ei tohi olla määramata." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Ootasin kirjete sõnastikku, kuid sain \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Väärtus peab olema valiidne JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Otsing" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Järjestus" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "kasvav" #: filters.py:288 msgid "descending" msgstr "kahanev" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Sobimatu lehekülg." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Sobimatu kursor" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Sobimatu primaarvõti \"{pk_value}\" - objekti pole olemas." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Sobimatu andmetüüp. Ootasin primaarvõtit, sain {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Sobimatu hüperlink - ei leidnud URLi vastet." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Sobimatu hüperlink - vale URLi vaste." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Sobimatu hüperlink - objekti ei eksisteeri." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Sobimatu andmetüüp. Ootasin URLi sõne, sain {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekti {slug_name}={value} ei eksisteeri." #: relations.py:449 msgid "Invalid value." msgstr "Sobimatu väärtus." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Sobimatud andmed. Ootasin sõnastikku, kuid sain {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtrid" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Puudub" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Pole midagi valida." #: validators.py:39 msgid "This field must be unique." msgstr "Selle välja väärtus peab olema unikaalne." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Veerud {field_names} peavad moodustama unikaalse hulga." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Selle välja väärtus peab olema unikaalne veerus \"{date_field}\" märgitud kuupäeval." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Selle välja väärtus peab olema unikaalneveerus \"{date_field}\" märgitud kuul." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Selle välja väärtus peab olema unikaalneveerus \"{date_field}\" märgitud aastal." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Sobimatu versioon \"Accept\" päises." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Sobimatu versioon URLi rajas." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Sobimatu versioon URLis - see ei vasta ühelegi teadaolevale." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Sobimatu versioon hostinimes." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Sobimatu versioon päringu parameetris." ================================================ FILE: rest_framework/locale/fa/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Ali Mahdiyar , 2020 # Aryan Baghi , 2020 # Omid Zarin , 2019 # Xavier Ordoquy , 2020 # Sina Amini , 2024 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:58+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Persian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/fa/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: fa\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "هدر اولیه نامعتبر است. اطلاعات هویتی ارائه نشده است." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "هدر اولیه نامعتبر است. رشته ی اطلاعات هویتی نباید شامل فاصله باشد." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "هدر اولیه نامعتبر است. اطلاعات هویتی با متد base64 به درستی رمزنگاری نشده است." #: authentication.py:101 msgid "Invalid username/password." msgstr "نام کاربری/رمز‌عبور نامعتبر است." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "کاربر غیر فعال یا حذف شده است." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "توکن هدر نامعتبر است. اطلاعات هویتی ارائه نشده است. " #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "توکن هدر نامعتبر است. توکن نباید شامل فضای خالی باشد." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "توکن هدر نامعتبر است. توکن شامل کاراکتر‌های نامعتبر است." #: authentication.py:203 msgid "Invalid token." msgstr "توکن هدر نامعتبر است. " #: authtoken/apps.py:7 msgid "Auth Token" msgstr "توکن اعتبار‌سنجی" #: authtoken/models.py:13 msgid "Key" msgstr "کلید" #: authtoken/models.py:16 msgid "User" msgstr "کاربر" #: authtoken/models.py:18 msgid "Created" msgstr "ایجاد‌شد" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "توکن" #: authtoken/models.py:28 msgid "Tokens" msgstr "توکن‌ها" #: authtoken/serializers.py:9 msgid "Username" msgstr "نام‌کاربری" #: authtoken/serializers.py:13 msgid "Password" msgstr "رمز‌عبور" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "با اطلاعات ارسال شده نمیتوان وارد شد." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "باید شامل نام‌کاربری و رمز‌عبود باشد." #: exceptions.py:102 msgid "A server error occurred." msgstr "خطای سمت سرور رخ داده است." #: exceptions.py:142 msgid "Invalid input." msgstr "ورودی نامعتبر" #: exceptions.py:161 msgid "Malformed request." msgstr "درخواست ناقص." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "اطلاعات احراز هویت صحیح نیست." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "اطلاعات برای اعتبارسنجی ارسال نشده است." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "شما اجازه انجام این دستور را ندارید." #: exceptions.py:185 msgid "Not found." msgstr "یافت نشد." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "متد {method} مجاز نیست." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "نوع محتوای درخواستی در هدر قابل قبول نیست." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "نوع رسانه {media_type} در درخواست پشتیبانی نمیشود." #: exceptions.py:223 msgid "Request was throttled." msgstr "تعداد درخواست‌های شما محدود شده است." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "انتظار می‌رود در {wait} ثانیه در دسترس باشد." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "انتظار می‌رود در {wait} ثانیه در دسترس باشد." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "این مقدار لازم است." #: fields.py:317 msgid "This field may not be null." msgstr "این مقدار نباید توهی باشد." #: fields.py:701 msgid "Must be a valid boolean." msgstr "باید یک مقدار منطقی(بولی) معتبر باشد." #: fields.py:766 msgid "Not a valid string." msgstr "یک رشته معتبر نیست." #: fields.py:767 msgid "This field may not be blank." msgstr "این مقدار نباید خالی باشد." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "مطمعن شوید طول این مقدار بیشتر از {max_length} نیست." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "مطمعن شوید طول این مقدار حداقل {min_length} است." #: fields.py:816 msgid "Enter a valid email address." msgstr "پست الکترونیکی صحیح وارد کنید." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "مقدار وارد شده با الگو مطابقت ندارد." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "یک \"slug\" معتبر شامل حروف، اعداد، آندرلاین یا خط فاصله وارد کنید" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "یک URL معتبر وارد کنید" #: fields.py:867 msgid "Must be a valid UUID." msgstr "باید یک UUID معتبر باشد." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "یک آدرس IPv4 یا IPv6 معتبر وارد کنید." #: fields.py:931 msgid "A valid integer is required." 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} باشد." #: 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} باشد." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "رشته بسیار طولانی است." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "یک عدد معتبر نیاز است." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "بیشتر از {max_digits} رقم نباید وجود داشته باشد." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "بیشتر از {max_decimal_places} ممیز اعشار نباید وجود داشته باشد" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "بیشتر از {max_whole_digits} رقم نباید قبل از ممیز اعشار باشد." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "فرمت Datetime اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "باید datetime باشد اما date دریافت شد." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "تاریخ و زمان برای منطقه زمانی \"{timezone}\" نامعتبر است." #: fields.py:1151 msgid "Datetime value out of range." msgstr "مقدار تاریخ و زمان خارج از محدوده است." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "فرمت تاریخ اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "باید date باشد اما datetime دریافت شد." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "فرمت Time اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "فرمت Duration اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" یک انتخاب معتبر نیست." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "بیشتر از {count} آیتم..." #: 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 "باید یک لیست از مقادیر ارسال شود اما یک «{input_type}» دریافت شد." #: fields.py:1458 msgid "This selection may not be empty." msgstr "این بخش نمی‌تواند خالی باشد." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" یک مسیر انتخاب معتبر نیست." #: fields.py:1514 msgid "No file was submitted." msgstr "فایلی ارسال نشده است." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "دیتای ارسال شده فایل نیست. encoding type فرم را چک کنید." #: fields.py:1516 msgid "No filename could be determined." msgstr "اسم فایل مشخص نیست." #: fields.py:1517 msgid "The submitted file is empty." msgstr "فایل ارسال شده خالی است." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "یک عکس معتبر آپلود کنید. فایلی که ارسال کردید عکس یا عکس خراب شده نیست" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "این لیست نمی تواند خالی باشد" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "اطمینان حاصل کنید که این فیلد حداقل {min_length} عنصر دارد." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "اطمینان حاصل کنید که این فیلد بیش از {max_length} عنصر ندارد." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "باید دیکشنری از آیتم ها ارسال می شد، اما \"{input_type}\" ارسال شده است." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "این دیکشنری نمی‌تواند خالی باشد." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "مقدار باید JSON معتبر باشد." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "جستجو" #: filters.py:50 msgid "A search term." msgstr "یک عبارت جستجو." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "ترتیب" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "کدام فیلد باید هنگام مرتب‌سازی نتایج استفاده شود." #: filters.py:287 msgid "ascending" msgstr "صعودی" #: filters.py:288 msgid "descending" msgstr "نزولی" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "یک شماره صفحه‌ در مجموعه نتایج صفحه‌بندی شده." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "تعداد نتایج برای نمایش در هر صفحه." #: pagination.py:189 msgid "Invalid page." msgstr "صفحه نامعتبر" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "ایندکس اولیه‌ای که از آن نتایج بازگردانده می‌شود." #: pagination.py:581 msgid "The pagination cursor value." msgstr "مقدار نشانگر صفحه‌بندی." #: pagination.py:583 msgid "Invalid cursor" msgstr "مکان نمای نامعتبر" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "pk نامعتبر \"{pk_value}\" - این Object وجود ندارد" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "تایپ نامعتبر. باید pk ارسال می شد اما {data_type} ارسال شده است." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "هایپرلینک نامعتبر - URL مطابق وجود ندارد" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "هایپرلینک نامعتبر - خطا در تطابق URL" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "هایپرلینک نامعبتر - Object وجود ندارد." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "داده نامعتبر. باید رشته ی URL باشد، اما {data_type} دریافت شد." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Object با {slug_name}={value} وجود ندارد." #: relations.py:449 msgid "Invalid value." msgstr "مقدار نامعتبر." #: schemas/utils.py:32 msgid "unique integer value" msgstr "مقداد عدد یکتا" #: schemas/utils.py:34 msgid "UUID string" msgstr "رشته UUID" #: schemas/utils.py:36 msgid "unique value" msgstr "مقدار یکتا" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "یک {value_type} که این {name} را شناسایی میکند." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "داده نامعتبر. باید دیکشنری ارسال می شد، اما {datatype} ارسال شده است." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "اقدامات اضافی" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "فیلترها" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "نوار ناوبری" #: templates/rest_framework/base.html:75 msgid "content" msgstr "محتوا" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "فرم درخواست" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "محتوای اصلی" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "اطلاعات درخواست" #: templates/rest_framework/base.html:177 msgid "response info" 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 "None" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "آیتمی برای انتخاب وجود ندارد" #: validators.py:39 msgid "This field must be unique." msgstr "این فیلد باید یکتا باشد" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "فیلدهای {field_names} باید یک مجموعه یکتا باشند." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "کاراکترهای جایگزین مجاز نیستند: U+{code_point:X}." #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "این فیلد باید برای تاریخ \"{date_field}\" یکتا باشد." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "این فیلد باید برای ماه \"{date_field}\" یکتا باشد." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "این فیلد باید برای سال \"{date_field}\" یکتا باشد." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "ورژن نامعتبر در هدر \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "ورژن نامعتبر در مسیر URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "ورژن نامعتبر در مسیر URL. با هیچ نام گذاری ورژنی تطابق ندارد." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "نسخه نامعتبر در نام هاست" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "ورژن نامعتبر در پارامتر کوئری." ================================================ FILE: rest_framework/locale/fa_IR/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Ali Mahdiyar , 2020 # Aryan Baghi , 2020 # Omid Zarin , 2019 # Xavier Ordoquy , 2020 # Sina Amini , 2024 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:59+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Persian (Iran) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/fa_IR/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: fa_IR\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "هدر اولیه نامعتبر است. اطلاعات هویتی ارائه نشده است." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "هدر اولیه نامعتبر است. رشته ی اطلاعات هویتی نباید شامل فاصله باشد." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "هدر اولیه نامعتبر است. اطلاعات هویتی با متد base64 به درستی رمزنگاری نشده است." #: authentication.py:101 msgid "Invalid username/password." msgstr "نام کاربری/رمز‌عبور نامعتبر است." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "کاربر غیر فعال یا حذف شده است." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "توکن هدر نامعتبر است. اطلاعات هویتی ارائه نشده است. " #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "توکن هدر نامعتبر است. توکن نباید شامل فضای خالی باشد." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "توکن هدر نامعتبر است. توکن شامل کاراکتر‌های نامعتبر است." #: authentication.py:203 msgid "Invalid token." msgstr "توکن هدر نامعتبر است. " #: authtoken/apps.py:7 msgid "Auth Token" msgstr "توکن اعتبار‌سنجی" #: authtoken/models.py:13 msgid "Key" msgstr "کلید" #: authtoken/models.py:16 msgid "User" msgstr "کاربر" #: authtoken/models.py:18 msgid "Created" msgstr "ایجاد‌شد" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "توکن" #: authtoken/models.py:28 msgid "Tokens" msgstr "توکن‌ها" #: authtoken/serializers.py:9 msgid "Username" msgstr "نام‌کاربری" #: authtoken/serializers.py:13 msgid "Password" msgstr "رمز‌عبور" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "با اطلاعات ارسال شده نمیتوان وارد شد." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "باید شامل نام‌کاربری و رمز‌عبود باشد." #: exceptions.py:102 msgid "A server error occurred." msgstr "خطای سمت سرور رخ داده است." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "درخواست ناقص." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "اطلاعات احراز هویت صحیح نیست." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "اطلاعات برای اعتبارسنجی ارسال نشده است." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "شما اجازه انجام این دستور را ندارید." #: exceptions.py:185 msgid "Not found." msgstr "یافت نشد." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "متد {method} مجاز نیست." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "نوع محتوای درخواستی در هدر قابل قبول نیست." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "نوع رسانه {media_type} در درخواست پشتیبانی نمیشود." #: exceptions.py:223 msgid "Request was throttled." msgstr "تعداد درخواست‌های شما محدود شده است." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "این مقدار لازم است." #: fields.py:317 msgid "This field may not be null." msgstr "این مقدار نباید توهی باشد." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "این مقدار نباید خالی باشد." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "مطمعن شوید طول این مقدار بیشتر از {max_length} نیست." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "مطمعن شوید طول این مقدار حداقل {min_length} است." #: fields.py:816 msgid "Enter a valid email address." msgstr "پست الکترونیکی صحیح وارد کنید." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "مقدار وارد شده با الگو مطابقت ندارد." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "یک \"slug\" معتبر شامل حروف، اعداد، آندرلاین یا خط فاصله وارد کنید" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "یک URL معتبر وارد کنید" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "یک آدرس IPv4 یا IPv6 معتبر وارد کنید." #: fields.py:931 msgid "A valid integer is required." 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} باشد." #: 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} باشد." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "رشته بسیار طولانی است." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "یک عدد معتبر نیاز است." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "بیشتر از {max_digits} رقم نباید وجود داشته باشد." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "بیشتر از {max_decimal_places} ممیز اعشار نباید وجود داشته باشد" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "بیشتر از {max_whole_digits} رقم نباید قبل از ممیز اعشار باشد." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "فرمت Datetime اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "باید datetime باشد اما date دریافت شد." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "فرمت تاریخ اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "باید date باشد اما datetime دریافت شد." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "فرمت Time اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "فرمت Duration اشتباه است. از یکی از این فرمت ها استفاده کنید: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" یک انتخاب معتبر نیست." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "بیشتر از {count} آیتم..." #: 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 "باید یک لیست از مقادیر ارسال شود اما یک «{input_type}» دریافت شد." #: fields.py:1458 msgid "This selection may not be empty." msgstr "این بخش نمی‌تواند خالی باشد." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" یک مسیر انتخاب معتبر نیست." #: fields.py:1514 msgid "No file was submitted." msgstr "فایلی ارسال نشده است." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "دیتای ارسال شده فایل نیست. encoding type فرم را چک کنید." #: fields.py:1516 msgid "No filename could be determined." msgstr "اسم فایل مشخص نیست." #: fields.py:1517 msgid "The submitted file is empty." msgstr "فایل ارسال شده خالی است." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "یک عکس معتبر آپلود کنید. فایلی که ارسال کردید عکس یا عکس خراب شده نیست" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "این لیست نمی تواند خالی باشد" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "باید دیکشنری از آیتم ها ارسال می شد، اما \"{input_type}\" ارسال شده است." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "مقدار باید JSON معتبر باشد." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "جستجو" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "ترتیب" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "صعودی" #: filters.py:288 msgid "descending" msgstr "نزولی" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "صفحه نامعتبر" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "مکان نمای نامعتبر" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "pk نامعتبر \"{pk_value}\" - این Object وجود ندارد" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "تایپ نامعتبر. باید pk ارسال می شد اما {data_type} ارسال شده است." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "هایپرلینک نامعتبر - URL مطابق وجود ندارد" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "هایپرلینک نامعتبر - خطا در تطابق URL" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "هایپرلینک نامعبتر - Object وجود ندارد." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "داده نامعتبر. باید رشته ی URL باشد، اما {data_type} دریافت شد." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Object با {slug_name}={value} وجود ندارد." #: relations.py:449 msgid "Invalid value." msgstr "مقدار نامعتبر." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "داده نامعتبر. باید دیکشنری ارسال می شد، اما {datatype} ارسال شده است." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "فیلترها" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "None" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "آیتمی برای انتخاب وجود ندارد" #: validators.py:39 msgid "This field must be unique." msgstr "این فیلد باید یکتا باشد" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "فیلدهای {field_names} باید یک مجموعه یکتا باشند." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "این فیلد باید برای تاریخ \"{date_field}\" یکتا باشد." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "این فیلد باید برای ماه \"{date_field}\" یکتا باشد." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "این فیلد باید برای سال \"{date_field}\" یکتا باشد." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "ورژن نامعتبر در هدر \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "ورژن نامعتبر در مسیر URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "ورژن نامعتبر در مسیر URL. با هیچ نام گذاری ورژنی تطابق ندارد." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "نسخه نامعتبر در نام هاست" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "ورژن نامعتبر در پارامتر کوئری." ================================================ FILE: rest_framework/locale/fi/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Aarni Koskela, 2015 # Aarni Koskela, 2015-2016 # Kimmo Huoman , 2020 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Finnish (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/fi/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: fi\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Epäkelpo \"basic\" -otsake. Ei annettuja tunnuksia." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Epäkelpo \"basic\" -otsake. Tunnusmerkkijono ei saa sisältää välilyöntejä." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Epäkelpo \"basic\" -otsake. Tunnukset eivät ole base64-koodattu." #: authentication.py:101 msgid "Invalid username/password." msgstr "Epäkelpo käyttäjänimi tai salasana." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Käyttäjä ei-aktiivinen tai poistettu." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Epäkelpo \"token\" -otsake. Ei annettuja tunnuksia." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Epäkelpo \"token\" -otsake. Tunnusmerkkijono ei saa sisältää välilyöntejä." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Epäkelpo \"token\" -otsake. Tunnusmerkkijono ei saa sisältää epäkelpoja merkkejä." #: authentication.py:203 msgid "Invalid token." msgstr "Epäkelpo token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Autentikaatiotunniste" #: authtoken/models.py:13 msgid "Key" msgstr "Avain" #: authtoken/models.py:16 msgid "User" msgstr "Käyttäjä" #: authtoken/models.py:18 msgid "Created" msgstr "Luotu" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Tunniste" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tunnisteet" #: authtoken/serializers.py:9 msgid "Username" msgstr "Käyttäjänimi" #: authtoken/serializers.py:13 msgid "Password" msgstr "Salasana" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Kirjautuminen epäonnistui annetuilla tunnuksilla." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Pitää sisältää \"username\" ja \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Sattui palvelinvirhe." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Pyyntö on virheellisen muotoinen." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Väärät autentikaatiotunnukset." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Autentikaatiotunnuksia ei annettu." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Sinulla ei ole oikeutta suorittaa tätä toimintoa." #: exceptions.py:185 msgid "Not found." msgstr "Ei löydy." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metodi \"{method}\" ei ole sallittu." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Ei voitu vastata pyynnön Accept-otsakkeen mukaisesti." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Pyynnön mediatyyppiä \"{media_type}\" ei tueta." #: exceptions.py:223 msgid "Request was throttled." msgstr "Pyyntö hidastettu." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Tämä kenttä vaaditaan." #: fields.py:317 msgid "This field may not be null." msgstr "Tämän kentän arvo ei voi olla \"null\"." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Tämä kenttä ei voi olla tyhjä." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Arvo saa olla enintään {max_length} merkkiä pitkä." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Arvo tulee olla vähintään {min_length} merkkiä pitkä." #: fields.py:816 msgid "Enter a valid email address." msgstr "Syötä kelvollinen sähköpostiosoite." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Arvo ei täsmää vaadittuun kuvioon." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Tässä voidaan käyttää vain kirjaimia (a-z), numeroita (0-9) sekä ala- ja tavuviivoja (_ -)." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Syötä oikea URL-osoite." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Syötä kelvollinen IPv4- tai IPv6-osoite." #: fields.py:931 msgid "A valid integer is required." msgstr "Syötä kelvollinen kokonaisluku." #: 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 "Tämän arvon on oltava pienempi tai yhtä suuri kuin {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 "Tämän luvun on oltava suurempi tai yhtä suuri kuin {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Liian suuri merkkijonoarvo." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Kelvollinen luku vaaditaan." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Tässä luvussa voi olla yhteensä enintään {max_digits} numeroa." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Tässä luvussa voi olla enintään {max_decimal_places} desimaalia." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Tässä luvussa voi olla enintään {max_whole_digits} numeroa ennen desimaalipilkkua." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Virheellinen päivämäärän/ajan muotoilu. Käytä jotain näistä muodoista: {format}" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Odotettiin päivämäärää ja aikaa, saatiin vain päivämäärä." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Virheellinen päivämäärän muotoilu. Käytä jotain näistä muodoista: {format}" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Odotettiin päivämäärää, saatiin päivämäärä ja aika." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Virheellinen kellonajan muotoilu. Käytä jotain näistä muodoista: {format}" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Virheellinen keston muotoilu. Käytä jotain näistä muodoista: {format}" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" ei ole kelvollinen valinta." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Enemmän kuin {count} kappaletta..." #: 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 "Odotettiin listaa, saatiin tyyppi {input_type}." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Valinta ei saa olla tyhjä." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" ei ole kelvollinen polku." #: fields.py:1514 msgid "No file was submitted." msgstr "Yhtään tiedostoa ei ole lähetetty." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Tiedostoa ei lähetetty. Tarkista lomakkeen koodaus (encoding)." #: fields.py:1516 msgid "No filename could be determined." msgstr "Tiedostonimeä ei voitu päätellä." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Lähetetty tiedosto on tyhjä." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Varmista että tiedostonimi on enintään {max_length} merkkiä pitkä (nyt {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Kuva ei kelpaa. Lähettämäsi tiedosto ei ole kuva, tai tiedosto on vioittunut." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Lista ei saa olla tyhjä." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Odotettiin sanakirjaa, saatiin tyyppi {input_type}." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Arvon pitää olla kelvollista JSONia." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Haku" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Järjestys" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "nouseva" #: filters.py:288 msgid "descending" msgstr "laskeva" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Epäkelpo sivu." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Epäkelpo kursori" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Epäkelpo pääavain {pk_value} - objektia ei ole olemassa." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Väärä tyyppi. Odotettiin pääavainarvoa, saatiin {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Epäkelpo linkki - URL ei täsmää." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Epäkelpo linkki - epäkelpo URL-osuma." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Epäkelpo linkki - objektia ei ole." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Epäkelpo tyyppi. Odotettiin URL-merkkijonoa, saatiin {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objektia ({slug_name}={value}) ei ole." #: relations.py:449 msgid "Invalid value." msgstr "Epäkelpo arvo." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Odotettiin sanakirjaa, saatiin tyyppi {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Suotimet" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ei mitään" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Ei valittavia kohteita." #: validators.py:39 msgid "This field must be unique." msgstr "Arvon tulee olla uniikki." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Kenttien {field_names} tulee muodostaa uniikki joukko." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Kentän tulee olla uniikki päivämäärän {date_field} suhteen." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Kentän tulee olla uniikki kuukauden {date_field} suhteen." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Kentän tulee olla uniikki vuoden {date_field} suhteen." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Epäkelpo versio Accept-otsakkeessa." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Epäkelpo versio URL-polussa." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "URL-polun versio ei täsmää mihinkään versionimiavaruuteen." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Epäkelpo versio palvelinosoitteessa." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Epäkelpo versio kyselyparametrissa." ================================================ FILE: rest_framework/locale/fr/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Erwann Mest , 2019 # Etienne Desgagné , 2015 # Martin Maillard , 2015 # Stéphane Raimbault , 2019 # Xavier Ordoquy , 2015-2016 # Sébastien Corbin , 2025 # Mathieu Dupuy , 2026 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: 2025-08-17 20:30+0200\n" "Last-Translator: Mathieu Dupuy \n" "Language-Team: French (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/fr/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: fr\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "En-tête « basic » non valide. Informations d'identification non fournies." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "En-tête « basic » non valide. Les informations d'identification ne doivent pas contenir d'espaces." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "En-tête « basic » non valide. Encodage base64 des informations d'identification incorrect." #: authentication.py:101 msgid "Invalid username/password." msgstr "Nom d'utilisateur et/ou mot de passe non valide(s)." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Utilisateur inactif ou supprimé." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "En-tête « token » non valide. Informations d'identification non fournies." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "En-tête « token » non valide. Un token ne doit pas contenir d'espaces." #: authentication.py:193 msgid "Invalid token header. Token string should not contain invalid characters." msgstr "En-tête « token » non valide. Un token ne doit pas contenir de caractères invalides." #: authentication.py:203 msgid "Invalid token." msgstr "Token non valide." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Jeton d'authentification" #: authtoken/models.py:13 msgid "Key" msgstr "Clef" #: authtoken/models.py:16 msgid "User" msgstr "Utilisateur" #: authtoken/models.py:18 msgid "Created" msgstr "Création" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Jeton" #: authtoken/models.py:28 msgid "Tokens" msgstr "Jetons" #: authtoken/serializers.py:9 msgid "Username" msgstr "Nom de l'utilisateur" #: authtoken/serializers.py:13 msgid "Password" msgstr "Mot de passe" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Impossible de se connecter avec les informations d'identification fournies." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "« username » et « password » doivent être inclus." #: exceptions.py:102 msgid "A server error occurred." msgstr "Une erreur du serveur est survenue." #: exceptions.py:142 msgid "Invalid input." msgstr "Saisie invalide." #: exceptions.py:161 msgid "Malformed request." msgstr "Requête malformée." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Informations d'authentification incorrectes." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Informations d'authentification non fournies." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Vous n'avez pas la permission d'effectuer cette action." #: exceptions.py:185 msgid "Not found." msgstr "Non trouvé." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Méthode « {method} » non autorisée." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "L'en-tête « Accept » n'a pas pu être satisfaite." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Type de média « {media_type} » non supporté." #: exceptions.py:223 msgid "Request was throttled." msgstr "Requête ralentie." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "Disponible à nouveau dans {wait} seconde." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "Disponible à nouveau dans {wait} secondes." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Ce champ est obligatoire." #: fields.py:317 msgid "This field may not be null." msgstr "Ce champ ne peut être nul." #: fields.py:701 msgid "Must be a valid boolean." msgstr "Doit être un booléen valide." #: fields.py:766 msgid "Not a valid string." msgstr "Chaîne de caractère invalide." #: fields.py:767 msgid "This field may not be blank." msgstr "Ce champ ne peut être vide." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Assurez-vous que ce champ comporte au plus {max_length} caractères." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Assurez-vous que ce champ comporte au moins {min_length} caractères." #: fields.py:816 msgid "Enter a valid email address." msgstr "Saisissez une adresse e-mail valide." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Cette valeur ne satisfait pas le motif imposé." #: fields.py:838 msgid "Enter a valid \"slug\" consisting of letters, numbers, underscores or hyphens." msgstr "Ce champ ne doit contenir que des lettres, des nombres, des tirets bas _ et des traits d'union." #: fields.py:839 msgid "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, or hyphens." msgstr "Ce champ ne doit contenir que des lettres Unicode, des nombres, des tirets bas _ et des traits d'union." #: fields.py:854 msgid "Enter a valid URL." msgstr "Saisissez une URL valide." #: fields.py:867 msgid "Must be a valid UUID." msgstr "Doit être un UUID valide." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Saisissez une adresse IPv4 ou IPv6 valide." #: fields.py:931 msgid "A valid integer is required." msgstr "Un nombre entier valide est requis." #: 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 "Assurez-vous que cette valeur est inférieure ou égale à {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 "Assurez-vous que cette valeur est supérieure ou égale à {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Chaîne de caractères trop longue." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Un nombre valide est requis." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Assurez-vous qu'il n'y a pas plus de {max_digits} chiffres au total." #: fields.py:1008 #, python-brace-format msgid "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Assurez-vous qu'il n'y a pas plus de {max_decimal_places} chiffres après la virgule." #: fields.py:1009 #, python-brace-format msgid "Ensure that there are no more than {max_whole_digits} digits before the decimal point." msgstr "Assurez-vous qu'il n'y a pas plus de {max_whole_digits} chiffres avant la virgule." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "La date + heure n'a pas le bon format. Utilisez un des formats suivants : {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Attendait une date + heure mais a reçu une date." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "Date et heure non valides pour le fuseau horaire \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." msgstr "Valeur de date et heure hors de l'intervalle." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "La date n'a pas le bon format. Utilisez un des formats suivants : {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Attendait une date mais a reçu une date + heure." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "L'heure n'a pas le bon format. Utilisez un des formats suivants : {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "La durée n'a pas le bon format. Utilisez l'un des formats suivants : {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "« {input} » n'est pas un choix valide." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Plus de {count} éléments..." #: 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 "Attendait une liste d'éléments mais a reçu « {input_type} »." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Cette sélection ne peut être vide." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "« {input} » n'est pas un choix de chemin valide." #: fields.py:1514 msgid "No file was submitted." msgstr "Aucun fichier n'a été soumis." #: fields.py:1515 msgid "The submitted data was not a file. Check the encoding type on the form." msgstr "La donnée soumise n'est pas un fichier. Vérifiez le type d'encodage du formulaire." #: fields.py:1516 msgid "No filename could be determined." msgstr "Le nom de fichier n'a pu être déterminé." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Le fichier soumis est vide." #: fields.py:1518 #, python-brace-format msgid "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Assurez-vous que le nom de fichier comporte au plus {max_length} caractères (il en comporte {length})." #: fields.py:1566 msgid "Upload a valid image. The file you uploaded was either not an image or a corrupted image." msgstr "Transférez une image valide. Le fichier que vous avez transféré n'est pas une image, ou il est corrompu." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Cette liste ne peut pas être vide." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "Assurez-vous que ce champ a au moins {min_length} éléments." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "Assurez-vous que ce champ n'a pas plus de {max_length} éléments." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Attendait un dictionnaire d'éléments mais a reçu « {input_type} »." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "Ce dictionnaire ne peut être vide." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "La valeur doit être un JSON valide." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Recherche" #: filters.py:50 msgid "A search term." msgstr "Un terme de recherche." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordre" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "Quel champ utiliser pour classer les résultats." #: filters.py:287 msgid "ascending" msgstr "croissant" #: filters.py:288 msgid "descending" msgstr "décroissant" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "Un numéro de page de l'ensemble des résultats." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "Nombre de résultats à retourner par page." #: pagination.py:189 msgid "Invalid page." msgstr "Page non valide." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "L'index initial depuis lequel retourner les résultats." #: pagination.py:581 msgid "The pagination cursor value." msgstr "La valeur du curseur de pagination." #: pagination.py:583 msgid "Invalid cursor" msgstr "Curseur non valide" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Clé primaire « {pk_value} » non valide - l'objet n'existe pas." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Type incorrect. Attendait une clé primaire, a reçu {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Lien non valide : pas d'URL correspondante." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Lien non valide : URL correspondante incorrecte." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Lien non valide : l'objet n'existe pas." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Type incorrect. Attendait une URL, a reçu {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "L'objet avec {slug_name}={value} n'existe pas." #: relations.py:449 msgid "Invalid value." msgstr "Valeur non valide." #: schemas/utils.py:32 msgid "unique integer value" msgstr "valeur entière unique" #: schemas/utils.py:34 msgid "UUID string" msgstr "Chaîne UUID" #: schemas/utils.py:36 msgid "unique value" msgstr "valeur unique" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "Un(une) {value_type} identifiant ce(cette) {name}." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Donnée non valide. Attendait un dictionnaire, a reçu {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "Actions supplémentaires" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtres" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "barre de navigation" #: templates/rest_framework/base.html:75 msgid "content" msgstr "contenu" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "formulaire de requête" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "contenu principal" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "information de la requête" #: templates/rest_framework/base.html:177 msgid "response info" msgstr "information de la réponse" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 #: templates/rest_framework/vertical/radio.html:3 msgid "None" msgstr "Aucune" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Aucun élément à sélectionner." #: validators.py:39 msgid "This field must be unique." msgstr "Ce champ doit être unique." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Les champs {field_names} doivent former un ensemble unique." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "Les caractères de substitution ne sont pas autorisés : U+{code_point:X}." #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Ce champ doit être unique pour la date « {date_field} »." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Ce champ doit être unique pour le mois « {date_field} »." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Ce champ doit être unique pour l'année « {date_field} »." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Version non valide dans l'en-tête « Accept »." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Version non valide dans l'URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Version invalide dans l'URL. Ne correspond à aucune version de l'espace de nommage." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Version non valide dans le nom d'hôte." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Version non valide dans le paramètre de requête." ================================================ FILE: rest_framework/locale/fr_CA/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: French (Canada) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/fr_CA/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: fr_CA\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/gl/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Galician (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/gl/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: gl\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/gl_ES/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Carlos Goce , 2015 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Galician (Spain) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/gl_ES/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: gl_ES\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "Valor non válido." #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "Ningún" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "Permiso denegado." ================================================ FILE: rest_framework/locale/he_IL/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Hebrew (Israel) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/he_IL/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: he_IL\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/hu/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Zoltan Szalai , 2015,2018-2019 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Hungarian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/hu/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: hu\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Érvénytelen basic fejléc. Nem voltak megadva azonosítók." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Érvénytelen basic fejléc. Az azonosító karakterlánc nem tartalmazhat szóközöket." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Érvénytelen basic fejléc. Az azonosítók base64 kódolása nem megfelelő." #: authentication.py:101 msgid "Invalid username/password." msgstr "Érvénytelen felhasználónév/jelszó." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "A felhasználó nincs aktiválva vagy törölve lett." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Érvénytelen token fejléc. Nem voltak megadva azonosítók." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Érvénytelen token fejléc. A token karakterlánc nem tartalmazhat szóközöket." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Érvénytelen token fejléc. A token karakterlánc nem tartalmazhat érvénytelen karaktereket." #: authentication.py:203 msgid "Invalid token." msgstr "Érvénytelen token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Auth token" #: authtoken/models.py:13 msgid "Key" msgstr "Kulcs" #: authtoken/models.py:16 msgid "User" msgstr "Felhasználó" #: authtoken/models.py:18 msgid "Created" msgstr "Létrehozva" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokenek" #: authtoken/serializers.py:9 msgid "Username" msgstr "Felhasználónév" #: authtoken/serializers.py:13 msgid "Password" msgstr "Jelszó" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "A megadott azonosítókkal nem lehet bejelentkezni." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Tartalmaznia kell a \"felhasználónevet\" és a \"jelszót\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Szerver oldali hiba történt." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Hibás kérés." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Hibás azonosítók." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Nem voltak megadva azonosítók." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Nincs jogosultsága a művelet végrehajtásához." #: exceptions.py:185 msgid "Not found." msgstr "Nem található." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "A \"{method}\" metódus nem megengedett." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "A kérés Accept fejlécét nem lehetett teljesíteni." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Nem támogatott média típus \"{media_type}\" a kérésben." #: exceptions.py:223 msgid "Request was throttled." msgstr "A kérés korlátozva lett." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Ennek a mezőnek a megadása kötelező." #: fields.py:317 msgid "This field may not be null." msgstr "Ez a mező nem lehet null értékű." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Ez a mező nem lehet üres." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Bizonyosodjon meg arról, hogy ez a mező legfeljebb {max_length} karakterből áll." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Bizonyosodjon meg arról, hogy ez a mező legalább {min_length} karakterből áll." #: fields.py:816 msgid "Enter a valid email address." msgstr "Adjon meg egy érvényes e-mail címet!" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Ez az érték nem illeszkedik a szükséges mintázatra." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Az URL barát cím csak betűket, számokat, aláhúzásokat és kötőjeleket tartalmazhat." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Adjon meg egy érvényes URL-t!" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Adjon meg egy érvényes IPv4 vagy IPv6 címet!" #: fields.py:931 msgid "A valid integer is required." msgstr "Egy érvényes egész szám megadása szükséges." #: 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 "Bizonyosodjon meg arról, hogy ez az érték legfeljebb {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 "Bizonyosodjon meg arról, hogy ez az érték legalább {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "A karakterlánc túl hosszú." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Egy érvényes szám megadása szükséges." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Bizonyosodjon meg arról, hogy a számjegyek száma összesen legfeljebb {max_digits}." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Bizonyosodjon meg arról, hogy a tizedes tört törtrészében levő számjegyek száma összesen legfeljebb {max_decimal_places}." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Bizonyosodjon meg arról, hogy a tizedes tört egész részében levő számjegyek száma összesen legfeljebb {max_whole_digits}." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "A dátum formátuma hibás. Használja ezek valamelyikét helyette: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Időt is tartalmazó dátum helyett egy időt nem tartalmazó dátum lett elküldve." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "A dátum formátuma hibás. Használja ezek valamelyikét helyette: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Időt nem tartalmazó dátum helyett egy időt is tartalmazó dátum lett elküldve." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Az idő formátuma hibás. Használja ezek valamelyikét helyette: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Az időtartam formátuma hibás. Használja ezek valamelyikét helyette: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "Érvénytelen választási lehetőség: \"{input}\"" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Több, mint {count} elem ..." #: 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 "Elemek listája helyett \"{input_type}\" lett elküldve." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Választania kell egy elemet." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "Érvénytelen választási lehetőség: \"{input}\"" #: fields.py:1514 msgid "No file was submitted." msgstr "Semmilyen fájl sem került feltöltésre." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Az elküldött adat nem egy fájl volt. Ellenőrizze a kódolás típusát az űrlapon!" #: fields.py:1516 msgid "No filename could be determined." msgstr "A fájlnév nem megállapítható." #: fields.py:1517 msgid "The submitted file is empty." msgstr "A küldött fájl üres." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Bizonyosodjon meg arról, hogy a fájlnév legfeljebb {max_length} karakterből áll (jelenlegi hossza: {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Töltsön fel egy érvényes képfájlt! A feltöltött fájl nem kép volt, vagy megsérült." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Nem lehet üres a lista." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Dictionary elemek helyett \"{input_type}\" lett megadva." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Az értéknek érvényes JSON-nek lennie." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Keresés" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Rendezés" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "növekvő" #: filters.py:288 msgid "descending" msgstr "csökkenő" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Érvénytelen oldal." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Érvénytelen kurzor" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Érvénytelen pk \"{pk_value}\" - az objektum nem létezik." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Helytelen típus. pk érték helyett {data_type} lett elküldve." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Érvénytelen link - Nem illeszkedő URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Érvénytelen link. - Eltérő URL illeszkedés." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Érvénytelen link - Az objektum nem létezik." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Helytelen típus. URL karakterlánc helyett {data_type} lett elküldve." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Nem létezik olyan objektum, amelynél {slug_name}={value}." #: relations.py:449 msgid "Invalid value." msgstr "Érvénytelen érték." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Érvénytelen adat. Egy dictionary helyett {datatype} lett elküldve." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Szűrők" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Semmi" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Nincsenek kiválasztható elemek." #: validators.py:39 msgid "This field must be unique." msgstr "Ennek a mezőnek egyedinek kell lennie." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "A {field_names} mezőnevek nem tartalmazhatnak duplikátumot." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "A mezőnek egyedinek kell lennie a \"{date_field}\" dátumra." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "A mezőnek egyedinek kell lennie a \"{date_field}\" hónapra." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "A mezőnek egyedinek kell lennie a \"{date_field}\" évre." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Érvénytelen verzió az \"Accept\" fejlécben." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Érvénytelen verzió az URL elérési útban." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Érvénytelen verzió az URL elérési útban. Nem illeszkedik egyetlen verzió névtérre sem." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Érvénytelen verzió a hosztnévben." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Érvénytelen verzió a lekérdezési paraméterben." ================================================ FILE: rest_framework/locale/hy/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Arnak Melikyan , 2019 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Armenian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/hy/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: hy\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Անվավեր վերնագիր: Նույնականացման տվյալները տրամադրված չեն:" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Անվավեր վերնագիր: Նույնականացման տողը չպետք է պարունակի բացատներ:" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Անվավեր վերնագիր: Նույնականացման տվյալները սխալ են ձեւակերպված base64-ում:" #: authentication.py:101 msgid "Invalid username/password." msgstr "Անվավեր օգտանուն / գաղտնաբառ:" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Օգտատերը ջնջված է կամ ոչ ակտիվ:" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Անվավեր տոկենի վերնագիր: Նույնականացման տվյալները տրամադրված չեն:" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Անվավեր տոկենի վերնագիր: Տոկենի տողը չպետք է պարունակի բացատներ:" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Անվավեր տոկենի վերնագիր: Տոկենի տողը չպետք է պարունակի անթույլատրելի նիշեր:" #: authentication.py:203 msgid "Invalid token." msgstr "Անվավեր տոկեն։" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Վավերացման Տոկեն։" #: authtoken/models.py:13 msgid "Key" msgstr "Բանալի" #: authtoken/models.py:16 msgid "User" msgstr "Օգտատեր" #: authtoken/models.py:18 msgid "Created" msgstr "Ստեղծված է" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Տոկեն" #: authtoken/models.py:28 msgid "Tokens" msgstr "Տոկեններ" #: authtoken/serializers.py:9 msgid "Username" msgstr "Օգտանուն" #: authtoken/serializers.py:13 msgid "Password" msgstr "Գաղտնաբառ" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Անհնար է մուտք գործել տրամադրված նույնականացման տվյալներով:" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Պետք է ներառի «օգտանուն» եւ «գաղտնաբառ»:" #: exceptions.py:102 msgid "A server error occurred." msgstr "Տեղի ունեցել սերվերի սխալ:" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Սխալ հարցում:" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Սխալ նույնականացման տվյալներ։" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Նույնականացման տվյալները տրամադրված չեն:" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Այս գործողությունը կատարելու թույլտվություն չունեք:" #: exceptions.py:185 msgid "Not found." msgstr "Չի գտնվել։" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "\"{method}\" մեթոդը թույլատրված չէ:" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Չհաջողվեց բավարարել հարցման Ընդունել վերնագիրը:" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Անհամապատասխան մեդիա տիպ \"{media_type}\":" #: exceptions.py:223 msgid "Request was throttled." msgstr "Հարցումն ընդհատվել է:" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Այս դաշտը պարտադիր է:" #: fields.py:317 msgid "This field may not be null." msgstr "Այս դաշտը չի կարող զրոյական լինել:" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Այս դաշտը չի կարող դատարկ լինել:" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Համոզվեք, որ այս դաշտը լինի ոչ ավել, քան {max_length} նիշ:" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Համոզվեք, որ այս դաշտը ունի առնվազն {min_length} նիշ:" #: fields.py:816 msgid "Enter a valid email address." msgstr "Մուտքագրեք վավեր էլ.փոստի հասցե:" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Այս արժեքը չի համապատասխանում պահանջվող օրինակին:" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Մուտքագրեք վավեր \"slug\", որը բաղկացած է տառերից, թվերից, ընդգծումից կամ դեֆիսից:" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Մուտքագրեք վավեր հղում:" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Մուտքագրեք վավեր IPv4 կամ IPv6 հասցե:" #: fields.py:931 msgid "A valid integer is required." 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} -ին։" #: 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} -ին։" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Տողը ունի չափազանց մեծ արժեք:" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Պահանջվում է վավեր համար:" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Համոզվեք, որ {max_digits} -ից ավել թվանշան չկա:" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Համոզվեք, որ {max_decimal_places} -ից ավել տասնորդական նշան չկա:" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Համոզվեք, որ տասնորդական կետից առաջ չկա {max_whole_digits} -ից ավել թվանշան:" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime -ը սխալ ձեւաչափ ունի: Փոխարենը օգտագործեք այս ձեւաչափերից մեկը. {format} ։" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Ակնկալվում է օրվա ժամը, սակայն ամսաթիվ է ստացել:" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Ամսաթիվն ունի սխալ ձեւաչափ: Փոխարենը օգտագործեք այս ձեւաչափերից մեկը. {format} ։" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Ակնկալվում է ամսաթիվ, սակայն ստացել է օրվա ժամը:" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Ժամանակը սխալ ձեւաչափ ունի: Փոխարենը օգտագործեք այս ձեւաչափերից մեկը. {format} ։" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Տեւողությունը սխալ ձեւաչափ ունի: Փոխարենը օգտագործեք այս ձեւաչափերից մեկը. {format} ։" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" -ը վավեր ընտրություն չէ:" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Ավելի քան {count} առարկա..." #: 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 "Ակնկալվում է տարրերի ցանկ, բայց ստացել է \"{input_type}\" -ի տիպ:" #: fields.py:1458 msgid "This selection may not be empty." msgstr "Այս ընտրությունը չի կարող դատարկ լինել:" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" -ը վավեր ճանապարհի ընտրություն չէ:" #: fields.py:1514 msgid "No file was submitted." msgstr "Ոչ մի ֆայլ չի ուղարկվել:" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Ուղարկված տվյալը ֆայլ չէ: Ստուգեք կոդավորման տիպը:" #: fields.py:1516 msgid "No filename could be determined." msgstr "Ֆայլի անունը հնարավոր չէ որոշվել:" #: fields.py:1517 msgid "The submitted file is empty." msgstr "Ուղարկված ֆայլը դատարկ է:" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "Վերբեռնեք վավեր նկար: Ձեր բեռնած ֆայլը կամ նկար չէ կամ վնասված նկար է:" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Այս ցանկը չի կարող դատարկ լինել:" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Ակնկալվում է տարրերի բառարան, բայց ստացել է \"{input_type}\" տիպ։" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Արժեքը պետք է լինի JSON:" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Որոնում" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Պատվիրել" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "աճման կարգով" #: filters.py:288 msgid "descending" msgstr "նվազման կարգով" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Անվավեր էջ:" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Սխալ կուրսոր" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Անվավեր pk \"{pk_value}\" օբյեկտը գոյություն չունի:" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Անհայտ տիպ: Ակնկալվում է pk արժեք, ստացված է {data_type}։" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Անվավեր հղում - Ոչ մի հղման համընկնում:" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Անվավեր հղում - սխալ հղման համընկնում:" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Անվավեր հղում - տվյալ օբյեկտը գոյություն չունի:" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Անվավեր տիպ: Սպասվում է հղման տողը, ստացել է {data_type}։" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} տվյալ պարունակությամբ օբյեկտ գոյություն չունի:" #: relations.py:449 msgid "Invalid value." msgstr "Անվավեր արժեք:" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Անվավեր տվյալներ: Սպասվում է բառարան, բայց ստացվել է {datatype}։" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Ֆիլտրեր" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ոչ մեկը" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Ոչ մի տարր ընտրված չէ։" #: validators.py:39 msgid "This field must be unique." msgstr "Այս դաշտը պետք է լինի եզակի:" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "{field_names} դաշտերը պետք է կազմեն եզակի հավաքածու:" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Այս դաշտը պետք է եզակի լինի \"{date_field}\" ամսաթվի համար:" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Այս դաշտը պետք է եզակի լինի \"{date_field}\" ամսվա համար:" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Այս դաշտը պետք է եզակի լինի \"{date_field}\" տարվա համար:" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Accept\" վերնագրի անվավեր տարբերակ:" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Անվավեր տարբերակ հղման ճանապարհի մեջ:" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Անվավեր տարբերակ հղման ճանապարհի մեջ: Չի համապատասխանում որեւէ անվանման տարբերակի:" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Անվավեր տարբերակ անվանման մեջ:" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Անվավեր տարբերակ `հարցման պարամետրում:" ================================================ FILE: rest_framework/locale/id/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Aldiantoro Nugroho , 2017 # aslam hadi , 2017 # Joseph Aditya P G, 2019 # Xavier Ordoquy , 2020 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 20:03+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Indonesian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/id/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: id\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:101 msgid "Invalid username/password." msgstr "Nama pengguna atau kata sandi salah." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Pengguna tidak akfif atau telah dihapus." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Token Autentikasi" #: authtoken/models.py:13 msgid "Key" msgstr "" #: authtoken/models.py:16 msgid "User" msgstr "Pengguna" #: authtoken/models.py:18 msgid "Created" msgstr "" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Token" #: authtoken/serializers.py:9 msgid "Username" msgstr "Nama pengguna" #: authtoken/serializers.py:13 msgid "Password" msgstr "Kata sandi" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Tidak dapat masuk dengan data pengguna ini." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Nama pengguna dan password harus diisi." #: exceptions.py:102 msgid "A server error occurred." msgstr "Terjadi galat di server." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Data autentikasi salah." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Data autentikasi tidak diberikan." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Anda tidak memiliki izin untuk melakukan tindakan ini." #: exceptions.py:185 msgid "Not found." msgstr "Data tidak ditemukan." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Permintaan dengan header Accept ini tidak dapat dipenuhi." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Jenis media \"{media_type}\" dalam permintaan ini tidak didukung." #: exceptions.py:223 msgid "Request was throttled." msgstr "Permintaan ini telah dibatasi." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Bidang ini harus diisi." #: fields.py:317 msgid "This field may not be null." msgstr "Bidang ini tidak boleh diisi dengan \"null\"." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Bidang ini tidak boleh kosong." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Isi bidang ini tidak boleh melebihi {max_length} karakter." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Isi bidang ini minimal {min_length} karakter." #: fields.py:816 msgid "Enter a valid email address." msgstr "Masukkan alamat email dengan format yang benar." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Karakter \"slug\" hanya dapat terdiri dari huruf, angka, underscore dan tanda hubung." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Masukkan URL dengan format yang benar." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Masukkan alamat IPv4 atau IPv6 dengan format yang benar." #: fields.py:931 msgid "A valid integer is required." msgstr "Nilai bidang ini harus berupa bilangan bulat." #: 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 "Isi bidang ini harus kurang atau sama dengan {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 "Isi bidang ini harus lebih atau sama dengan {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Panjang angka tidak boleh lebih dari {max_digits}." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Panjang angka di belakang koma tidak boleh lebih dari {max_decimal_places}." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Panjang angka bulat tidak boleh lebih dari {max_whole_digits}." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Format tanggal dan waktu salah. Gunakan salah satu format berikut: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Format tanggal salah. Gunakan salah satu format berikut: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Format waktu salah. Gunakan salah satu format berikut: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Format durasi salah. Gunakan salah satu format berikut: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" tidak ada dalam daftar pilihan." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "" #: 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 "" #: fields.py:1458 msgid "This selection may not be empty." msgstr "Pilihan tidak boleh kosong." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "Pilih berkas terlebih dahulu." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1516 msgid "No filename could be determined." msgstr "" #: fields.py:1517 msgid "The submitted file is empty." msgstr "Berkas kosong." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Panjang nama berkas tidak boleh lebih dari {max_length}. Panjang nama berkas ini {length} karakter." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Isi bidang ini harus berupa dictionary, bukan \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Isi bidang ini harus berupa JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "" #: filters.py:288 msgid "descending" msgstr "" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Objek dengan primary key \"{pk_value}\" tidak ditemukan." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:449 msgid "Invalid value." msgstr "" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "" #: validators.py:39 msgid "This field must be unique." msgstr "" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "" ================================================ FILE: rest_framework/locale/it/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Antonio Mancina , 2015 # Marco Ventura, 2019 # Mattia Procopio , 2015 # Riccardo Magliocchetti , 2019 # Sergio Morstabilini , 2015 # Xavier Ordoquy , 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" "PO-Revision-Date: 2020-10-13 19:45+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Italian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/it/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: it\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Header di base invalido. Credenziali non fornite." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Header di base invalido. Le credenziali non dovrebbero contenere spazi." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Credenziali non correttamente codificate in base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Nome utente/password non validi" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Utente inattivo o eliminato." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Header del token non valido. Credenziali non fornite." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Header del token non valido. Il contenuto del token non dovrebbe contenere spazi." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Header del token invalido. La stringa del token non dovrebbe contenere caratteri illegali." #: authentication.py:203 msgid "Invalid token." msgstr "Token invalido." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Auth Token" #: authtoken/models.py:13 msgid "Key" msgstr "Key" #: authtoken/models.py:16 msgid "User" msgstr "User" #: authtoken/models.py:18 msgid "Created" msgstr "Creato" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "I Token" #: authtoken/serializers.py:9 msgid "Username" msgstr "Username" #: authtoken/serializers.py:13 msgid "Password" msgstr "Password" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Impossibile eseguire il login con le credenziali immesse." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Deve includere \"nome utente\" e \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Errore del server." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Richiesta malformata." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Credenziali di autenticazione incorrette." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Non sono state immesse le credenziali di autenticazione." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Non hai l'autorizzazione per eseguire questa azione." #: exceptions.py:185 msgid "Not found." msgstr "Non trovato." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metodo \"{method}\" non consentito" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Impossibile soddisfare l'header \"Accept\" presente nella richiesta." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Tipo di media \"{media_type}\"non supportato." #: exceptions.py:223 msgid "Request was throttled." msgstr "La richiesta è stata limitata (throttled)." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Campo obbligatorio." #: fields.py:317 msgid "This field may not be null." msgstr "Il campo non può essere nullo." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Questo campo non può essere omesso." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Assicurati che questo campo non abbia più di {max_length} caratteri." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Assicurati che questo campo abbia almeno {min_length} caratteri." #: fields.py:816 msgid "Enter a valid email address." msgstr "Inserisci un indirizzo email valido." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Questo valore non corrisponde alla sequenza richiesta." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Immetti uno \"slug\" valido che consista di lettere, numeri, underscore o trattini." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Inserisci un URL valido" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Inserisci un indirizzo IPv4 o IPv6 valido." #: fields.py:931 msgid "A valid integer is required." msgstr "È richiesto un numero intero valido." #: 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 "Assicurati che il valore sia minore o uguale a {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 "Assicurati che il valore sia maggiore o uguale a {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Stringa troppo lunga." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "È richiesto un numero valido." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Assicurati che non ci siano più di {max_digits} cifre in totale." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Assicurati che non ci siano più di {max_decimal_places} cifre decimali." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Assicurati che non ci siano più di {max_whole_digits} cifre prima del separatore decimale." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "L'oggetto di tipo datetime è in un formato errato. Usa uno dei seguenti formati: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Atteso un oggetto di tipo datetime ma l'oggetto ricevuto è di tipo date." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "La data è in un formato errato. Usa uno dei seguenti formati: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Atteso un oggetto di tipo date ma l'oggetto ricevuto è di tipo datetime." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "L'orario ha un formato errato. Usa uno dei seguenti formati: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "La durata è in un formato errato. Usa uno dei seguenti formati: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" non è una scelta valida." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Più di {count} oggetti..." #: 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 "Attesa una lista di oggetti ma l'oggetto ricevuto è di tipo \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Questa selezione non può essere vuota." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" non è un percorso valido." #: fields.py:1514 msgid "No file was submitted." msgstr "Non è stato inviato alcun file." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "I dati inviati non corrispondono ad un file. Si prega di controllare il tipo di codifica nel form." #: fields.py:1516 msgid "No filename could be determined." msgstr "Il nome del file non può essere determinato." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Il file inviato è vuoto." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Assicurati che il nome del file abbia, al più, {max_length} caratteri (attualmente ne ha {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Invia un'immagine valida. Il file che hai inviato non era un'immagine o era corrotto." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Questa lista non può essere vuota." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Era atteso un dizionario di oggetti ma il dato ricevuto è di tipo \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Il valore deve essere un JSON valido." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Cerca" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordinamento" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "ascendente" #: filters.py:288 msgid "descending" msgstr "discendente" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Pagina non valida." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Cursore non valido" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Pk \"{pk_value}\" non valido - l'oggetto non esiste." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Tipo non corretto. Era atteso un valore pk, ma è stato ricevuto {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Collegamento non valido - Nessuna corrispondenza di URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Collegamento non valido - Corrispondenza di URL non corretta." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Collegamento non valido - L'oggetto non esiste." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Tipo non corretto. Era attesa una stringa URL, ma è stato ricevuto {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "L'oggetto con {slug_name}={value} non esiste." #: relations.py:449 msgid "Invalid value." msgstr "Valore non valido." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Dati non validi. Era atteso un dizionario, ma si è ricevuto {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtri" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Nessuno" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Nessun elemento da selezionare." #: validators.py:39 msgid "This field must be unique." msgstr "Questo campo deve essere unico." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "I campi {field_names} devono costituire un insieme unico." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Questo campo deve essere unico per la data \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Questo campo deve essere unico per il mese \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Questo campo deve essere unico per l'anno \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Versione non valida nell'header \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Versione non valida nella sequenza URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Versione non valida nell'URL path. Non corrisponde con nessun namespace di versione." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Versione non valida nel nome dell'host." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Versione non valida nel parametro della query." ================================================ FILE: rest_framework/locale/ja/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Hiroaki Nakamura , 2016 # Kouichi Nishizawa , 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Japanese (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ja/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ja\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "不正な基本ヘッダです。認証情報が含まれていません。" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "不正な基本ヘッダです。認証情報文字列に空白を含めてはいけません。" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "不正な基本ヘッダです。認証情報がBASE64で正しくエンコードされていません。" #: authentication.py:101 msgid "Invalid username/password." msgstr "ユーザ名かパスワードが違います。" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "ユーザが無効か削除されています。" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "不正なトークンヘッダです。認証情報が含まれていません。" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "不正なトークンヘッダです。トークン文字列に空白を含めてはいけません。" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "不正なトークンヘッダです。トークン文字列に不正な文字を含めてはいけません。" #: authentication.py:203 msgid "Invalid token." msgstr "不正なトークンです。" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "認証トークン" #: authtoken/models.py:13 msgid "Key" msgstr "キー" #: authtoken/models.py:16 msgid "User" msgstr "ユーザ" #: authtoken/models.py:18 msgid "Created" msgstr "作成された" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "トークン" #: authtoken/models.py:28 msgid "Tokens" msgstr "トークン" #: authtoken/serializers.py:9 msgid "Username" msgstr "ユーザ名" #: authtoken/serializers.py:13 msgid "Password" msgstr "パスワード" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "提供された認証情報でログインできません。" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"username\"と\"password\"を含まなければなりません。" #: exceptions.py:102 msgid "A server error occurred." msgstr "サーバエラーが発生しました。" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "不正な形式のリクエストです。" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "認証情報が正しくありません。" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "認証情報が含まれていません。" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "このアクションを実行する権限がありません。" #: exceptions.py:185 msgid "Not found." msgstr "見つかりませんでした。" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "メソッド \"{method}\" は許されていません。" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "リクエストのAcceptヘッダを満たすことができませんでした。" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "リクエストのメディアタイプ \"{media_type}\" はサポートされていません。" #: exceptions.py:223 msgid "Request was throttled." msgstr "リクエストの処理は絞られました。" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "この項目は必須です。" #: fields.py:317 msgid "This field may not be null." msgstr "この項目はnullにできません。" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "この項目は空にできません。" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "この項目が{max_length}文字より長くならないようにしてください。" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "この項目は少なくとも{min_length}文字以上にしてください。" #: fields.py:816 msgid "Enter a valid email address." msgstr "有効なメールアドレスを入力してください。" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "この値は所要のパターンにマッチしません。" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "文字、数字、アンダースコア、またはハイフンから成る有効な \"slug\" を入力してください。" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "有効なURLを入力してください。" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "有効なIPv4またはIPv6アドレスを入力してください。" #: fields.py:931 msgid "A valid integer is required." 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}以下にしてください。" #: 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}以上にしてください。" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "文字列が長過ぎます。" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "有効な数値を入力してください。" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "合計で最大{max_digits}桁以下になるようにしてください。" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "小数点以下の桁数を{max_decimal_places}を超えないようにしてください。" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "整数部の桁数を{max_whole_digits}を超えないようにしてください。" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "日時の形式が違います。以下のどれかの形式にしてください: {format}。" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "日付ではなく日時を入力してください。" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "日付の形式が違います。以下のどれかの形式にしてください: {format}。" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "日時ではなく日付を入力してください。" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "時刻の形式が違います。以下のどれかの形式にしてください: {format}。" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "機関の形式が違います。以下のどれかの形式にしてください: {format}。" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\"は有効な選択肢ではありません。" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr " {count} 個より多い..." #: 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 "\"{input_type}\" 型のデータではなく項目のリストを入力してください。" #: fields.py:1458 msgid "This selection may not be empty." msgstr "空でない項目を選択してください。" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\"は有効なパスの選択肢ではありません。" #: fields.py:1514 msgid "No file was submitted." msgstr "ファイルが添付されていません。" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "添付されたデータはファイルではありません。フォームのエンコーディングタイプを確認してください。" #: fields.py:1516 msgid "No filename could be determined." msgstr "ファイル名が取得できませんでした。" #: fields.py:1517 msgid "The submitted file is empty." msgstr "添付ファイルの中身が空でした。" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "有効な画像をアップロードしてください。アップロードされたファイルは画像でないか壊れた画像です。" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "リストは空ではいけません。" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "\"{input_type}\" 型のデータではなく項目の辞書を入力してください。" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "値は有効なJSONでなければなりません。" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "検索" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "順序" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "昇順" #: filters.py:288 msgid "descending" msgstr "降順" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "不正なページです。" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "カーソルが不正です。" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "主キー \"{pk_value}\" は不正です - データが存在しません。" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "不正な型です。{data_type} 型ではなく主キーの値を入力してください。" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "ハイパーリンクが不正です - URLにマッチしません。" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "ハイパーリンクが不正です - 不正なURLにマッチします。" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "ハイパーリンクが不正です - リンク先が存在しません。" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "不正なデータ型です。{data_type} 型ではなくURL文字列を入力してください。" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} のデータが存在しません。" #: relations.py:449 msgid "Invalid value." msgstr "不正な値です。" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "不正なデータです。{datatype} 型ではなく辞書を入力してください。" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "フィルタ" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "なし" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "選択する項目がありません。" #: validators.py:39 msgid "This field must be unique." msgstr "この項目は一意でなければなりません。" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "項目 {field_names} は一意な組でなければなりません。" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "この項目は \"{date_field}\" の日に対して一意でなければなりません。" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "この項目は \"{date_field}\" の月に対して一意でなければなりません。" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "この項目は \"{date_field}\" の年に対して一意でなければなりません。" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Accept\" 内のバージョンが不正です。" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URLパス内のバージョンが不正です。" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "不正なバージョンのURLのパスです。どのバージョンの名前空間にも一致しません。" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "ホスト名内のバージョンが不正です。" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "クエリパラメータ内のバージョンが不正です。" ================================================ FILE: rest_framework/locale/kk/LC_MESSAGES/django.po ================================================ # This file is distributed under the same license as the Django REST framework package. # Translators: # Dulat Kushibayev , 2025 # msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-06-01 23:03+0300\n" "PO-Revision-Date: 2025-06-01 20:03+0000\n" "Last-Translator: Dulat Kushibayev \n" "Language-Team: \n" "Language: kk\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n!=1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Негізгі тақырыптама дұрыс емес. Тіркелгі деректері берілмеген." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Негізгі тақырыптама дұрыс емес. Тіркелгі деректері бос орындарсыз болуы керек." #: authentication.py:84 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Негізгі тақырыптама дұрыс емес. Тіркелгі деректері base64 форматында дұрыс кодталмаған." #: authentication.py:101 msgid "Invalid username/password." msgstr "Қате пайдаланушы аты немесе құпиясөз." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Пайдаланушы өшірулі немесе жойылған." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Токен тақырыптамасы дұрыс емес. Тіркелгі деректері берілмеген." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Токен тақырыптамасы дұрыс емес. Токен жолында бос орын болмауы керек." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Токен тақырыптамасы дұрыс емес. Токен құрамында жарамсыз таңбалар болмауы керек." #: authentication.py:203 msgid "Invalid token." msgstr "Жарамсыз токен." #: authtoken/admin.py:28 authtoken/serializers.py:9 msgid "Username" msgstr "Пайдаланушы аты" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Аутентификация токені" #: authtoken/models.py:13 msgid "Key" msgstr "Кілт" #: authtoken/models.py:16 msgid "User" msgstr "Пайдаланушы" #: authtoken/models.py:18 msgid "Created" msgstr "Құрылған" #: authtoken/models.py:27 authtoken/models.py:54 authtoken/serializers.py:19 msgid "Token" msgstr "Токен" #: authtoken/models.py:28 authtoken/models.py:55 msgid "Tokens" msgstr "Токендер" #: authtoken/serializers.py:13 msgid "Password" msgstr "Құпиясөз" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Берілген тіркелгі деректерімен кіру мүмкін емес." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"username\" мен \"password\" енгізілуі керек." #: exceptions.py:105 msgid "A server error occurred." msgstr "Серверде қате орын алды." #: exceptions.py:145 msgid "Invalid input." msgstr "Қате енгізу деректері." #: exceptions.py:166 msgid "Malformed request." msgstr "Сұраныс дұрыс құрылмаған." #: exceptions.py:172 msgid "Incorrect authentication credentials." msgstr "Аутентификация деректері қате." #: exceptions.py:178 msgid "Authentication credentials were not provided." msgstr "Аутентификация деректері берілмеген." #: exceptions.py:184 msgid "You do not have permission to perform this action." msgstr "Бұл әрекетті орындауға рұқсатыңыз жоқ." #: exceptions.py:190 msgid "Not found." msgstr "Табылмады." #: exceptions.py:196 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "\"{method}\" әдісіне рұқсат етілмейді." #: exceptions.py:207 msgid "Could not satisfy the request Accept header." msgstr "Сұраныстағы Accept тақырыбын қанағаттандыру мүмкін емес." #: exceptions.py:217 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Сұраныстағы \"{media_type}\" медиа түрі қолдау көрсетілмейді." #: exceptions.py:228 msgid "Request was throttled." msgstr "Сұраныс жиілігі шектелді." #: exceptions.py:229 #, python-brace-format msgid "Expected available in {wait} second." msgstr "{wait} секундтан кейін қайта қолжетімді болады." #: exceptions.py:230 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "{wait} секундтан кейін қайта қолжетімді болады." #: fields.py:292 relations.py:240 relations.py:276 validators.py:112 #: validators.py:238 msgid "This field is required." msgstr "Бұл мән міндетті." #: fields.py:293 msgid "This field may not be null." msgstr "Бұл мән null болмауы керек." #: fields.py:661 msgid "Must be a valid boolean." msgstr "Дұрыс логикалық мән болуы керек." #: fields.py:724 msgid "Not a valid string." msgstr "Мәтін дұрыс емес." #: fields.py:725 msgid "This field may not be blank." msgstr "Бұл мән бос болмауы керек." #: fields.py:726 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Бұл мән ең көбі {max_length} таңбадан аспауы керек." #: fields.py:727 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Бұл мән кемінде {min_length} таңба болуы керек." #: fields.py:774 msgid "Enter a valid email address." msgstr "Дұрыс электрондық пошта енгізіңіз." #: fields.py:785 msgid "This value does not match the required pattern." msgstr "Бұл мән қажетті үлгіге сәйкес келмейді." #: fields.py:796 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Әріптерден, сандардан, астын сызу және сызықшалардан тұратын дұрыс \"slug\" енгізіңіз." #: fields.py:797 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "Юникод әріптері, сандар, астын сызу және сызықшалардан тұратын дұрыс \"slug\" енгізіңіз." #: fields.py:812 msgid "Enter a valid URL." msgstr "Дұрыс URL енгізіңіз." #: fields.py:825 msgid "Must be a valid UUID." msgstr "Дұрыс UUID болуы керек." #: fields.py:861 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Дұрыс IPv4 немесе IPv6 адрес енгізіңіз." #: fields.py:889 msgid "A valid integer is required." msgstr "Дұрыс бүтін сан енгізілуі қажет." #: 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} немесе одан аз болуы керек." #: 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} болуы керек." #: fields.py:892 fields.py:929 fields.py:971 msgid "String value too large." msgstr "Жолдың мәні тым үлкен." #: fields.py:926 fields.py:965 msgid "A valid number is required." msgstr "Дұрыс сан енгізілуі керек." #: fields.py:930 msgid "Integer value too large to convert to float" msgstr "Бүтін сан тым үлкен - қалқымалы санға айналдыру мүмкін емес." #: fields.py:968 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Барлығы {max_digits} саннан аспауы керек." #: fields.py:969 #, python-brace-format msgid "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Ондық бөлшектер саны ең көбі {max_decimal_places} болуы керек." #: fields.py:970 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Ондық нүктеге дейінгі сандар саны ең көбі {max_whole_digits} болуы керек." #: fields.py:1129 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime пішімі дұрыс емес. Осы пішімдердің бірін пайдаланыңыз: {format}." #: fields.py:1130 msgid "Expected a datetime but got a date." msgstr "Күтілгені - datetime, берілгені - date." #: fields.py:1131 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "\"{timezone}\" уақыт белдеуі үшін күн мен уақыт дұрыс емес." #: fields.py:1132 msgid "Datetime value out of range." msgstr "Datetime мәні рұқсат етілген ауқымнан тыс." #: fields.py:1219 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Date пішімі дұрыс емес. Осы пішімдердің бірін пайдаланыңыз: {format}." #: fields.py:1220 msgid "Expected a date but got a datetime." msgstr "Күтілгені - date, берілгені - datetime." #: fields.py:1286 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Уақыт пішімі дұрыс емес. Осы пішімдердің бірін пайдаланыңыз: {format}." #: fields.py:1348 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Ұзақтық пішімі дұрыс емес. Осы пішімдердің бірін пайдаланыңыз: {format}." #: 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}\" - дұрыс таңдау емес." #: fields.py:1389 #, python-brace-format msgid "More than {count} items..." msgstr "{count} элементтен артық..." #: fields.py:1447 fields.py:1596 relations.py:486 serializers.py:595 #, python-brace-format msgid "Expected a list of items but got type \"{input_type}\"." msgstr "Элементтер тізімі күтілді, бірақ \"{input_type}\" түрі берілген." #: fields.py:1448 msgid "This selection may not be empty." msgstr "Бұл таңдау бос болмауы керек." #: fields.py:1487 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" - дұрыс жол таңдауы емес." #: fields.py:1507 msgid "No file was submitted." msgstr "Файл жіберілмеді." #: fields.py:1508 msgid "The submitted data was not a file. Check the encoding type on the form." msgstr "Жіберілген деректер файл емес. Формадағы кодтау түрін тексеріңіз." #: fields.py:1509 msgid "No filename could be determined." msgstr "Файл атауы анықталмады." #: fields.py:1510 msgid "The submitted file is empty." msgstr "Жіберілген файл бос." #: fields.py:1511 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Файл атауы {max_length} таңбадан аспауы керек (қазір - {length})." #: fields.py:1559 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Дұрыс кескін жүктеңіз. Жүктелген файл кескін емес немесе бүлінген." #: fields.py:1597 relations.py:487 serializers.py:596 msgid "This list may not be empty." msgstr "Бұл тізім бос болмауы керек." #: fields.py:1598 serializers.py:598 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "Бұл мәнде кемінде {min_length} элемент болуы керек." #: fields.py:1599 serializers.py:597 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "Бұл мәнде {max_length} элементтен көп болмауы керек." #: fields.py:1677 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Элементтер жиыны ретінде сөздік күтілді, бірақ \"{input_type}\" түрі берілген." #: fields.py:1678 msgid "This dictionary may not be empty." msgstr "Бұл сөздік бос болмауы керек." #: fields.py:1750 msgid "Value must be valid JSON." msgstr "Мән дұрыс JSON пішімінде болуы керек." #: filters.py:72 templates/rest_framework/filters/search.html:2 #: templates/rest_framework/filters/search.html:8 msgid "Search" msgstr "Іздеу" #: filters.py:73 msgid "A search term." msgstr "Іздеу сөзі." #: filters.py:224 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Реттеу" #: filters.py:225 msgid "Which field to use when ordering the results." msgstr "Нәтижелерді реттеу үшін қай мән пайдалану керектігін көрсетеді." #: filters.py:341 msgid "ascending" msgstr "өсу ретімен" #: filters.py:342 msgid "descending" msgstr "кему ретімен" #: pagination.py:180 msgid "A page number within the paginated result set." msgstr "Беттелген нәтиже жиынындағы бет нөмірі." #: pagination.py:185 pagination.py:382 pagination.py:599 msgid "Number of results to return per page." msgstr "Әр бетте қайтарылатын нәтиже саны." #: pagination.py:195 msgid "Invalid page." msgstr "Қате бет нөмірі." #: pagination.py:384 msgid "The initial index from which to return the results." msgstr "Нәтижелер қайтарылатын бастапқы индекс." #: pagination.py:590 msgid "The pagination cursor value." msgstr "Нәтижелерді беттеуге арналған курсор мәні." #: pagination.py:592 msgid "Invalid cursor" msgstr "Қате курсор" #: relations.py:241 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Қате pk \"{pk_value}\" - нысан табылмады." #: relations.py:242 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Дерек түрі дұрыс емес. Күтілгені - pk мәні, берілгені - {data_type}." #: relations.py:277 msgid "Invalid hyperlink - No URL match." msgstr "Қате гиперсілтеме - URL сәйкестігі жоқ." #: relations.py:278 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Қате гиперсілтеме - URL сәйкестігі дұрыс емес." #: relations.py:279 msgid "Invalid hyperlink - Object does not exist." msgstr "Қате гиперсілтеме - нысан табылмады." #: relations.py:280 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Дерек түрі дұрыс емес. Күтілгені - URL жолы, берілгені - {data_type}" #: relations.py:445 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} параметрі бар нысан табылмады." #: relations.py:446 msgid "Invalid value." msgstr "Қате мән." #: schemas/utils.py:32 msgid "unique integer value" msgstr "бірегей бүтін сан мәні" #: schemas/utils.py:34 msgid "UUID string" msgstr "UUID жолы" #: schemas/utils.py:36 msgid "unique value" msgstr "бірегей мән" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "{name} нысанын анықтайтын {value_type}." #: serializers.py:342 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Деректер қате. Күтілгені - сөздік түрі, берілгені - {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "Қосымша әрекеттер" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Сүзгілер" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "навигация панелі" #: templates/rest_framework/base.html:75 msgid "content" msgstr "мазмұн" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "сұрау формасы" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "негізгі бөлім" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "сұрау ақпараты" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ешқайсысы" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Таңдайтын элементтер жоқ." #: validators.py:52 msgid "This field must be unique." msgstr "Бұл енгізу жолы бірегей болуы керек." #: validators.py:111 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "{field_names} енгізу жолдары бірегей жинақ құрауы тиіс." #: validators.py:219 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "Суррогат таңбалар рұқсат етілмейді: U+{code_point:X}." #: validators.py:309 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "\"{date_field}\" күніне бұл енгізу жолы бірегей болуы керек." #: validators.py:324 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "\"{date_field}\" айына бұл енгізу жолы бірегей болуы керек." #: validators.py:337 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "\"{date_field}\" жылына бұл енгізу жолы бірегей болуы керек." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Accept\" тақырыбында нұсқа дұрыс көрсетілмеген." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URL жолында нұсқа қате көрсетілген." #: versioning.py:118 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "URL жолында нұсқа дұрыс көрсетілмеген. Ешбір нұсқа кеңістігімен сәйкес келмейді." #: versioning.py:150 msgid "Invalid version in hostname." msgstr "Хост атауында нұсқа қате көрсетілген." #: versioning.py:172 msgid "Invalid version in query parameter." msgstr "Сұраныс параметрінде нұсқа қате көрсетілген." ================================================ FILE: rest_framework/locale/ko_KR/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # 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: 2024-10-22 16:13+0900\n" "PO-Revision-Date: 2020-10-13 19:45+0000\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" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "기본 헤더가 유효하지 않습니다. 인증 데이터가 제공되지 않았습니다." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "기본 헤더가 유효하지 않습니다. 인증 데이터 문자열은 공백을 포함하지 않아야 합니다." #: authentication.py:84 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "기본 헤더가 유효하지 않습니다. 인증 데이터가 올바르게 base64 인코딩되지 않았습니다." #: authentication.py:101 msgid "Invalid username/password." msgstr "아이디/비밀번호가 유효하지 않습니다." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "계정이 중지되었거나 삭제되었습니다." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "토큰 헤더가 유효하지 않습니다. 인증 데이터가 제공되지 않았습니다." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "토큰 헤더가 유효하지 않습니다. 토큰 문자열은 공백을 포함하지 않아야 합니다." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "토큰 헤더가 유효하지 않습니다. 토큰 문자열은 유효하지 않은 문자를 포함하지 않아야 합니다." #: authentication.py:203 msgid "Invalid token." msgstr "토큰이 유효하지 않습니다." #: authtoken/admin.py:28 authtoken/serializers.py:9 msgid "Username" msgstr "사용자 이름" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "인증 토큰" #: authtoken/models.py:13 msgid "Key" msgstr "키" #: authtoken/models.py:16 msgid "User" msgstr "사용자" #: authtoken/models.py:18 msgid "Created" msgstr "생성일시" #: authtoken/models.py:27 authtoken/models.py:54 authtoken/serializers.py:19 msgid "Token" msgstr "토큰" #: authtoken/models.py:28 authtoken/models.py:55 msgid "Tokens" msgstr "토큰(들)" #: authtoken/serializers.py:13 msgid "Password" msgstr "비밀번호" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "제공된 인증 데이터로는 로그인할 수 없습니다." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"아이디\"와 \"비밀번호\"를 포함해야 합니다." #: exceptions.py:105 msgid "A server error occurred." msgstr "서버 장애가 발생했습니다." #: exceptions.py:145 msgid "Invalid input." msgstr "유효하지 않은 입력입니다." #: exceptions.py:166 msgid "Malformed request." msgstr "잘못된 요청입니다." #: exceptions.py:172 msgid "Incorrect authentication credentials." msgstr "자격 인증 데이터가 올바르지 않습니다." #: exceptions.py:178 msgid "Authentication credentials were not provided." msgstr "자격 인증 데이터가 제공되지 않았습니다." #: exceptions.py:184 msgid "You do not have permission to perform this action." msgstr "이 작업을 수행할 권한이 없습니다." #: exceptions.py:190 msgid "Not found." msgstr "찾을 수 없습니다." #: exceptions.py:196 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "메서드 \"{method}\"는 허용되지 않습니다." #: exceptions.py:207 msgid "Could not satisfy the request Accept header." msgstr "요청 Accept 헤더를 만족시킬 수 없습니다." #: exceptions.py:217 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "요청된 \"{media_type}\"가 지원되지 않는 미디어 형태입니다." #: exceptions.py:228 msgid "Request was throttled." msgstr "요청이 제한되었습니다." #: exceptions.py:229 #, python-brace-format msgid "Expected available in {wait} second." msgstr "{wait} 초 후에 사용 가능합니다." #: exceptions.py:230 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "{wait} 초 후에 사용 가능합니다." #: fields.py:292 relations.py:240 relations.py:276 validators.py:99 #: validators.py:219 msgid "This field is required." msgstr "이 필드는 필수 항목입니다." #: fields.py:293 msgid "This field may not be null." msgstr "이 필드는 null일 수 없습니다." #: fields.py:661 msgid "Must be a valid boolean." msgstr "유효한 불리언이어야 합니다." #: fields.py:724 msgid "Not a valid string." msgstr "유효한 문자열이 아닙니다." #: fields.py:725 msgid "This field may not be blank." msgstr "이 필드는 blank일 수 없습니다." #: fields.py:726 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "이 필드의 글자 수가 {max_length} 이하인지 확인하세요." #: fields.py:727 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "이 필드의 글자 수가 적어도 {min_length} 이상인지 확인하세요." #: fields.py:774 msgid "Enter a valid email address." msgstr "유효한 이메일 주소를 입력하세요." #: fields.py:785 msgid "This value does not match the required pattern." msgstr "이 값은 요구되는 패턴과 일치하지 않습니다." #: fields.py:796 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "문자, 숫자, 밑줄( _ ) 또는 하이픈( - )으로 이루어진 유효한 \"slug\"를 입력하세요." #: fields.py:797 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "유니코드 문자, 숫자, 밑줄( _ ) 또는 하이픈( - )으로 이루어진 유효한 \"slug\"를 입력하세요." #: fields.py:812 msgid "Enter a valid URL." msgstr "유효한 URL을 입력하세요." #: fields.py:825 msgid "Must be a valid UUID." msgstr "유효한 UUID 이어야 합니다." #: fields.py:861 msgid "Enter a valid IPv4 or IPv6 address." msgstr "유효한 IPv4 또는 IPv6 주소를 입력하세요." #: fields.py:889 msgid "A valid integer is required." msgstr "유효한 정수를 입력하세요." #: 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}보다 작거나 같은지 확인하세요." #: 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}보다 크거나 같은지 확인하세요." #: fields.py:892 fields.py:929 fields.py:971 msgid "String value too large." msgstr "문자열 값이 너무 깁니다." #: fields.py:926 fields.py:965 msgid "A valid number is required." msgstr "유효한 숫자를 입력하세요." #: fields.py:930 msgid "Integer value too large to convert to float" msgstr "정수 값이 너무 커서 부동 소수점으로 변환할 수 없습니다." #: fields.py:968 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "총 자릿수가 {max_digits}을(를) 초과하지 않는지 확인하세요." #: fields.py:969 #, python-brace-format msgid "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "소수점 이하 자릿수가 {max_decimal_places}을(를) 초과하지 않는지 확인하세요." #: fields.py:970 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "소수점 앞 자릿수가 {max_whole_digits}을(를) 초과하지 않는지 확인하세요." #: fields.py:1129 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." #: fields.py:1130 msgid "Expected a datetime but got a date." msgstr "datatime이 예상되었지만 date를 받았습니다." #: fields.py:1131 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "\"{timezone}\" 시간대에 대한 유효하지 않은 datetime 입니다." #: fields.py:1132 msgid "Datetime value out of range." msgstr "Datetime 값이 범위를 벗어났습니다." #: fields.py:1219 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Date의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." #: fields.py:1220 msgid "Expected a date but got a datetime." msgstr "예상된 date 대신 datetime을 받았습니다." #: fields.py:1286 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Time의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." #: fields.py:1348 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Duration의 포멧이 잘못되었습니다. 이 형식들 중 한가지를 사용하세요: {format}." #: 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}\"은 유효하지 않은 선택입니다." #: fields.py:1389 #, python-brace-format msgid "More than {count} items..." msgstr "{count}개 이상의 아이템이 있습니다..." #: 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:1448 msgid "This selection may not be empty." msgstr "이 선택 항목은 비워 둘 수 없습니다." #: fields.py:1487 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\"은 유효하지 않은 경로 선택입니다." #: fields.py:1507 msgid "No file was submitted." msgstr "파일이 제출되지 않았습니다." #: fields.py:1508 msgid "The submitted data was not a file. Check the encoding type on the form." msgstr "제출된 데이터는 파일이 아닙니다. 제출된 서식의 인코딩 형식을 확인하세요." #: fields.py:1509 msgid "No filename could be determined." msgstr "파일명을 알 수 없습니다." #: fields.py:1510 msgid "The submitted file is empty." msgstr "제출한 파일이 비어있습니다." #: fields.py:1511 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "이 파일명의 글자수가 최대 {max_length}자를 넘지 않는지 확인하세요. (현재 {length}자입니다)." #: fields.py:1559 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "유효한 이미지 파일을 업로드하세요. 업로드하신 파일은 이미지 파일이 아니거나 손상된 이미지 파일입니다." #: fields.py:1597 relations.py:487 serializers.py:594 msgid "This list may not be empty." msgstr "이 리스트는 비워 둘 수 없습니다." #: fields.py:1598 serializers.py:596 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "이 필드가 최소 {min_length} 개의 요소를 가지는지 확인하세요." #: fields.py:1599 serializers.py:595 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "이 필드가 최대 {max_length} 개의 요소를 가지는지 확인하세요." #: fields.py:1677 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "아이템 딕셔너리가 예상되었으나 \"{input_type}\" 타입을 받았습니다." #: fields.py:1678 msgid "This dictionary may not be empty." msgstr "이 딕셔너리는 비어있을 수 없습니다." #: fields.py:1750 msgid "Value must be valid JSON." msgstr "유효한 JSON 값이어야 합니다." #: filters.py:72 templates/rest_framework/filters/search.html:2 #: templates/rest_framework/filters/search.html:8 msgid "Search" msgstr "검색" #: filters.py:73 msgid "A search term." msgstr "검색어." #: filters.py:224 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "순서" #: filters.py:225 msgid "Which field to use when ordering the results." msgstr "결과 정렬 시 사용할 필드." #: filters.py:341 msgid "ascending" msgstr "오름차순" #: filters.py:342 msgid "descending" msgstr "내림차순" #: pagination.py:180 msgid "A page number within the paginated result set." msgstr "페이지네이션된 결과 집합 내의 페이지 번호." #: pagination.py:185 pagination.py:382 pagination.py:599 msgid "Number of results to return per page." msgstr "페이지당 반환할 결과 수." #: pagination.py:195 msgid "Invalid page." msgstr "페이지가 유효하지 않습니다." #: pagination.py:384 msgid "The initial index from which to return the results." msgstr "결과를 반환할 초기 인덱스." #: pagination.py:590 msgid "The pagination cursor value." msgstr "페이지네이션 커서 값." #: pagination.py:592 msgid "Invalid cursor" msgstr "커서가 유효하지 않습니다." #: relations.py:241 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "유효하지 않은 pk \"{pk_value}\" - 객체가 존재하지 않습니다." #: relations.py:242 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "잘못된 형식입니다. pk 값이 예상되었지만, {data_type}을(를) 받았습니다." #: relations.py:277 msgid "Invalid hyperlink - No URL match." msgstr "유효하지 않은 하이퍼링크 - 일치하는 URL이 없습니다." #: relations.py:278 msgid "Invalid hyperlink - Incorrect URL match." msgstr "유효하지 않은 하이퍼링크 - URL이 일치하지 않습니다." #: relations.py:279 msgid "Invalid hyperlink - Object does not exist." msgstr "유효하지 않은 하이퍼링크 - 객체가 존재하지 않습니다." #: relations.py:280 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "잘못된 형식입니다. URL 문자열을 예상했으나 {data_type}을 받았습니다." #: relations.py:445 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} 객체가 존재하지 않습니다." #: relations.py:446 msgid "Invalid value." msgstr "값이 유효하지 않습니다." #: schemas/utils.py:32 msgid "unique integer value" msgstr "고유한 정수 값" #: schemas/utils.py:34 msgid "UUID string" msgstr "UUID 문자열" #: schemas/utils.py:36 msgid "unique value" msgstr "고유한 값" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "{name}을 식별하는 {value_type}." #: serializers.py:340 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "유효하지 않은 데이터. 딕셔너리(dictionary)대신 {datatype}를 받았습니다." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "추가 Action들" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "필터" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "네비게이션 바" #: templates/rest_framework/base.html:75 msgid "content" msgstr "콘텐츠" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "요청 폼" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "메인 콘텐츠" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "요청 정보" #: templates/rest_framework/base.html:177 msgid "response info" 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 "없음" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "선택할 아이템이 없습니다." #: validators.py:39 msgid "This field must be unique." msgstr "이 필드는 반드시 고유해야 합니다." #: validators.py:98 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "필드 {field_names} 는 반드시 고유해야 합니다." #: validators.py:200 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "대체(surrogate) 문자는 허용되지 않습니다: U+{code_point:X}." #: validators.py:290 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "이 필드는 \"{date_field}\" 날짜에 대해 고유해야 합니다." #: validators.py:305 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "이 필드는 \"{date_field}\" 월에 대해 고유해야 합니다." #: validators.py:318 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "이 필드는 \"{date_field}\" 연도에 대해 고유해야 합니다." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Accept\" 헤더의 버전이 유효하지 않습니다." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URL 경로의 버전이 유효하지 않습니다." #: versioning.py:118 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "URL 경로에 유효하지 않은 버전이 있습니다. 버전 네임스페이스와 일치하지 않습니다." #: versioning.py:150 msgid "Invalid version in hostname." msgstr "hostname 내 버전이 유효하지 않습니다." #: versioning.py:172 msgid "Invalid version in query parameter." msgstr "쿼리 파라메터 내 버전이 유효하지 않습니다." ================================================ FILE: rest_framework/locale/lt/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # vytautas , 2019 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Lithuanian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/lt/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: lt\n" "Plural-Forms: nplurals=4; plural=(n % 10 == 1 && (n % 100 > 19 || n % 100 < 11) ? 0 : (n % 10 >= 2 && n % 10 <=9) && (n % 100 > 19 || n % 100 < 11) ? 1 : n % 1 != 0 ? 2: 3);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:101 msgid "Invalid username/password." msgstr "" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Vartotojas neaktyvus arba pašalintas." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:13 msgid "Key" msgstr "Raktas" #: authtoken/models.py:16 msgid "User" msgstr "Vartotojas" #: authtoken/models.py:18 msgid "Created" msgstr "Sukurta" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "" #: authtoken/models.py:28 msgid "Tokens" msgstr "" #: authtoken/serializers.py:9 msgid "Username" msgstr "Vartotojo vardas" #: authtoken/serializers.py:13 msgid "Password" msgstr "Slaptažodis" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:102 msgid "A server error occurred." msgstr "Įvyko serverio klaida." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Netinkamai suformuota užklausa." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Neteisingi autentifikacijos duomenys." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Autentifikacijos duomenys nesuteikti." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:185 msgid "Not found." msgstr "Nerasta." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metodas \"{method}\" yra neleidžiamas." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Nepavyko patenkinti užklausos Accept antraštės." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Nepalaikomas duomenų formatas \"{media_type}\" užklausoje." #: exceptions.py:223 msgid "Request was throttled." msgstr "Užklausa pristabdyta." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Šis laukas yra privalomas." #: fields.py:317 msgid "This field may not be null." msgstr "Šis laukas negali būti nustatytas kaip null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Šis laukas negali būti tuščias." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Patikrinkite, ar šis laukas turi ne daugiau nei {max_length} simbolių." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Patikrinkite, ar šis laukas turi ne mažiau nei {min_length} simbolių." #: fields.py:816 msgid "Enter a valid email address." msgstr "Įveskite tinkamą el. pašto adresą." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Ši vertė neatitinka nustatyto šablono." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Įveskite tinkamą \"slug\" tekstą, turintį tik raidžių, skaičių, pabraukimų arba brūkšnelių." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Įveskite tinkamą URL adresą." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Įveskite tinkamą IPv4 arba IPv6 adresą." #: fields.py:931 msgid "A valid integer is required." msgstr "Reikiama tinkama integer tipo reikšmė." #: 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 "Patikrinkite, ar ši reikšmė yra mažesnė arba lygi {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 "Patikrinkite, ar ši reikšmė yra didesnė arba lygi {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "String tipo reikšmė per ilga." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Reikiamas tinkamas skaičius." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Patikrinkite, ar nėra daugiau nei {max_digits} skaitmenų." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Patikrinkite, ar nėra daugiau nei {max_decimal_places} skaitmenų po kablelio." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Patikrinkite, ar nėra daugiau nei {max_whole_digits} skaitmenų priešais kablelį." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime tipo reikšmė yra netinkamo formato. Naudokite vieną iš šių formatų: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Tikėtasi datetime, gauta date tipo reikšmė." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Date tipo reikšmė yra netinkamo formato. Naudokite vieną iš šių formatų: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Tikėtasi date, gauta datetime tipo reikšmė." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Time tipo reikšmė yra netinkamo formato. Naudokite vieną iš šių formatų: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Duration tipo reikšmė yra netinkamo formato. Naudokite vieną iš šių formatų: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" nėra tinkamas pasirinkimas." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "" #: 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 "" #: fields.py:1458 msgid "This selection may not be empty." msgstr "Šis pasirinkimas negali būti tuščias." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1516 msgid "No filename could be determined." msgstr "" #: fields.py:1517 msgid "The submitted file is empty." msgstr "" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "" #: filters.py:288 msgid "descending" msgstr "" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Netinkamas puslapis." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:449 msgid "Invalid value." msgstr "" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "" #: validators.py:39 msgid "This field must be unique." msgstr "" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "" ================================================ FILE: rest_framework/locale/lv/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # peterisb , 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Latvian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/lv/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: lv\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n != 0 ? 1 : 2);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Nederīgs pieprasījuma sākums. Akreditācijas parametri nav nodrošināti." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Nederīgs pieprasījuma sākums. Akreditācijas parametriem jābūt bez atstarpēm." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Nederīgs pieprasījuma sākums. Akreditācijas parametri nav korekti base64 kodēti." #: authentication.py:101 msgid "Invalid username/password." msgstr "Nederīgs lietotājvārds/parole." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Lietotājs neaktīvs vai dzēsts." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Nederīgs pilnvaras sākums. Akreditācijas parametri nav nodrošināti." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Nederīgs pilnvaras sākums. Pilnvaras parametros nevar būt tukšumi." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Nederīgs pilnvaras sākums. Pilnvaras parametros nevar būt nederīgas zīmes." #: authentication.py:203 msgid "Invalid token." msgstr "Nederīga pilnavara." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Autorizācijas pilnvara" #: authtoken/models.py:13 msgid "Key" msgstr "Atslēga" #: authtoken/models.py:16 msgid "User" msgstr "Lietotājs" #: authtoken/models.py:18 msgid "Created" msgstr "Izveidots" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Pilnvara" #: authtoken/models.py:28 msgid "Tokens" msgstr "Pilnvaras" #: authtoken/serializers.py:9 msgid "Username" msgstr "Lietotājvārds" #: authtoken/serializers.py:13 msgid "Password" msgstr "Parole" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Neiespējami pieteikties sistēmā ar nodrošinātajiem akreditācijas datiem." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Jābūt iekļautam \"username\" un \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Notikusi servera kļūda." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Nenoformēts pieprasījums." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Nekorekti autentifikācijas parametri." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Netika nodrošināti autorizācijas parametri." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Tev nav tiesību veikt šo darbību." #: exceptions.py:185 msgid "Not found." msgstr "Nav atrasts." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metode \"{method}\" nav atļauta." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Nevarēja apmierināt pieprasījuma Accept header." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Pieprasījumā neatbalstīts datu tips \"{media_type}\" ." #: exceptions.py:223 msgid "Request was throttled." msgstr "Pieprasījums tika apturēts." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Šis lauks ir obligāts." #: fields.py:317 msgid "This field may not be null." msgstr "Šis lauks nevar būt null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Šis lauks nevar būt tukšs." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Pārliecinies, ka laukā nav vairāk par {max_length} zīmēm." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Pārliecinies, ka laukā ir vismaz {min_length} zīmes." #: fields.py:816 msgid "Enter a valid email address." msgstr "Ievadi derīgu e-pasta adresi." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Šī vērtība neatbilst prasītajam pierakstam." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Ievadi derīgu \"slug\" vērtību, kura sastāv no burtiem, skaitļiem, apakš-svītras vai defises." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Ievadi derīgu URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Ievadi derīgu IPv4 vai IPv6 adresi." #: fields.py:931 msgid "A valid integer is required." msgstr "Prasīta ir derīga skaitliska vērtība." #: 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 "Pārliecinies, ka šī vērtība ir mazāka vai vienāda ar {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 "Pārliecinies, ka šī vērtība ir lielāka vai vienāda ar {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Teksta vērtība pārāk liela." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Derīgs skaitlis ir prasīts." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Pārliecinies, ka nav vairāk par {max_digits} zīmēm kopā." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Pārliecinies, ka nav vairāk par {max_decimal_places} decimālajām zīmēm." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Pārliecinies, ka nav vairāk par {max_whole_digits} zīmēm pirms komata." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datuma un laika formāts ir nepareizs. Lieto vienu no norādītajiem formātiem: \"{format}.\"" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Tika gaidīts datums un laiks, saņemts datums.." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Datumam ir nepareizs formāts. Lieto vienu no norādītajiem formātiem: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Tika gaidīts datums, saņemts datums un laiks." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Laikam ir nepareizs formāts. Lieto vienu no norādītajiem formātiem: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Ilgumam ir nepreizs formāts. Lieto vienu no norādītajiem formātiem: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" ir nederīga izvēle." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Vairāk par {count} ierakstiem..." #: 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 "Tika gaidīts saraksts ar ierakstiem, bet tika saņemts \"{input_type}\" tips." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Šī daļa nevar būt tukša." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" ir nederīga ceļa izvēle." #: fields.py:1514 msgid "No file was submitted." msgstr "Neviens fails netika pievienots." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Pievienotie dati nebija fails. Pārbaudi kodējuma tipu formā." #: fields.py:1516 msgid "No filename could be determined." msgstr "Faila nosaukums nevar tikt noteikts." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Pievienotais fails ir tukšs." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Pārliecinies, ka faila nosaukumā ir vismaz {max_length} zīmes (tajā ir {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Augšupielādē derīgu attēlu. Pievienotā datne nebija attēls vai bojāts attēls." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Šis saraksts nevar būt tukšs." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Tika gaidīta vārdnīca ar ierakstiem, bet tika saņemts \"{input_type}\" tips." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Vērtībai ir jābūt derīgam JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Meklēt" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Kārtošana" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "augoši" #: filters.py:288 msgid "descending" msgstr "dilstoši" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Nederīga lapa." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Nederīgs kursors" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Nederīga pk \"{pk_value}\" - objekts neeksistē." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Nepareizs tips. Tika gaidīta pk vērtība, saņemts {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Nederīga hipersaite - Nav URL sakritība." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Nederīga hipersaite - Nederīga URL sakritība." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Nederīga hipersaite - Objekts neeksistē." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Nepareizs tips. Tika gaidīts URL teksts, saņemts {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekts ar {slug_name}={value} neeksistē." #: relations.py:449 msgid "Invalid value." msgstr "Nedrīga vērtība." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Nederīgi dati. Tika gaidīta vārdnīca, saņemts {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtri" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Nekas" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Nav ierakstu, ko izvēlēties." #: validators.py:39 msgid "This field must be unique." msgstr "Šim laukam ir jābūt unikālam." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Laukiem {field_names} jāveido unikālas kombinācijas." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Šim laukam ir jābūt unikālam priekš \"{date_field}\" datuma." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Šim laukam ir jābūt unikālam priekš \"{date_field}\" mēneša." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Šim laukam ir jābūt unikālam priekš \"{date_field}\" gada." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Nederīga versija \"Accept\" galvenē." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Nederīga versija URL ceļā." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Nederīga versija URL ceļā. Nav atbilstības esošo versiju telpā." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Nederīga versija servera nosaukumā." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Nederīga versija pieprasījuma parametros." ================================================ FILE: rest_framework/locale/mk/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Filip Dimitrovski , 2015-2016 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Macedonian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/mk/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: mk\n" "Plural-Forms: nplurals=2; plural=(n % 10 == 1 && n % 100 != 11) ? 0 : 1;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Невалиден основен header. Не се внесени податоци за автентикација." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Невалиден основен header. Автентикационата низа не треба да содржи празни места." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Невалиден основен header. Податоците за автентикација не се енкодирани со base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Невалидно корисничко име/лозинка." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Корисникот е деактивиран или избришан." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Невалиден токен header. Не се внесени податоци за најава." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Невалиден токен во header. Токенот не треба да содржи празни места." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "Невалиден токен." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Автентикациски токен" #: authtoken/models.py:13 msgid "Key" msgstr "" #: authtoken/models.py:16 msgid "User" msgstr "Корисник" #: authtoken/models.py:18 msgid "Created" msgstr "" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Токен" #: authtoken/models.py:28 msgid "Tokens" msgstr "Токени" #: authtoken/serializers.py:9 msgid "Username" msgstr "Корисничко име" #: authtoken/serializers.py:13 msgid "Password" msgstr "Лозинка" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Не може да се најавите со податоците за најава." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Мора да се внесе „username“ и „password“." #: exceptions.py:102 msgid "A server error occurred." msgstr "Настана серверска грешка." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Неправилен request." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Неточни податоци за најава." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Не се внесени податоци за најава." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Немате дозвола да го сторите ова." #: exceptions.py:185 msgid "Not found." msgstr "Не е пронајдено ништо." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Методата \"{method}\" не е дозволена." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Не може да се исполни барањето на Accept header-от." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Media типот „{media_type}“ не е поддржан." #: exceptions.py:223 msgid "Request was throttled." msgstr "Request-от е забранет заради ограничувања." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Ова поле е задолжително." #: fields.py:317 msgid "This field may not be null." msgstr "Ова поле не смее да биде недефинирано." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Ова поле не смее да биде празно." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Ова поле не смее да има повеќе од {max_length} знаци." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Ова поле мора да има барем {min_length} знаци." #: fields.py:816 msgid "Enter a valid email address." msgstr "Внесете валидна email адреса." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Ова поле не е по правилната шема/барање." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Внесете валидно име што содржи букви, бројки, долни црти или црти." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Внесете валиден URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Внеси валидна IPv4 или IPv6 адреса." #: fields.py:931 msgid "A valid integer is required." 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}." #: 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}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Вредноста е преголема." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Задолжителен е валиден број." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Не смее да има повеќе од {max_digits} цифри вкупно." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Не смее да има повеќе од {max_decimal_places} децимални места." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Не смее да има повеќе од {max_whole_digits} цифри пред децималната точка." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Датата и времето се со погрешен формат. Користете го овој формат: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Очекувано беше дата и време, а внесено беше само дата." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Датата е со погрешен формат. Користете го овој формат: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Очекувана беше дата, а внесени беа и дата и време." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Времето е со погрешен формат. Користете го овој формат: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "„{input}“ не е валиден избор." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Повеќе од {count} ставки..." #: 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 "Очекувана беше листа од ставки, а внесено беше „{input_type}“." #: fields.py:1458 msgid "This selection may not be empty." msgstr "" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "Ниеден фајл не е качен (upload-иран)." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Испратените податоци не се фајл. Проверете го encoding-от на формата." #: fields.py:1516 msgid "No filename could be determined." msgstr "Не може да се открие име на фајлот." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Качениот (upload-иран) фајл е празен." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "Качете (upload-ирајте) валидна слика. Фајлот што го качивте не е валидна слика или е расипан." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Оваа листа не смее да биде празна." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Очекуван беше dictionary од ставки, a внесен беше тип \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Вредноста мора да биде валиден JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Пребарај" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Подредување" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "растечки" #: filters.py:288 msgid "descending" msgstr "опаѓачки" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Невалидна вредност за страна." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Невалиден покажувач (cursor)" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Невалиден pk „{pk_value}“ - објектот не постои." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Неточен тип. Очекувано беше pk, а внесено {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Невалиден хиперлинк - не е внесен URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Невалиден хиперлинк - внесен е неправилен URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Невалиден хиперлинк - Објектот не постои." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Неточен тип. Очекувано беше URL, a внесено {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Објектот со {slug_name}={value} не постои." #: relations.py:449 msgid "Invalid value." msgstr "Невалидна вредност." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Невалидни податоци. Очекуван беше dictionary, а внесен {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Филтри" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ништо" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Нема ставки за избирање." #: validators.py:39 msgid "This field must be unique." msgstr "Ова поле мора да биде уникатно." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Полињата {field_names} заедно мора да формираат уникатен збир." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Ова поле мора да биде уникатно за „{date_field}“ датата." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Ова поле мора да биде уникатно за „{date_field}“ месецот." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Ова поле мора да биде уникатно за „{date_field}“ годината." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Невалидна верзија во „Accept“ header-от." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Невалидна верзија во URL патеката." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Верзијата во URL патеката не е валидна. Не се согласува со ниеден version namespace (именски простор за верзии)." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Невалидна верзија во hostname-от." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Невалидна верзија во query параметарот." ================================================ FILE: rest_framework/locale/nb/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Håken Lid , 2017 # Petter Kjelkenes , 2015 # Thomas Bruun , 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Norwegian Bokmål (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/nb/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: nb\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Ugyldig basic header. Ingen legitimasjon gitt." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Ugyldig basic header. Legitimasjonsstreng bør ikke inneholde mellomrom." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Ugyldig basic header. Legitimasjonen ikke riktig Base64 kodet." #: authentication.py:101 msgid "Invalid username/password." msgstr "Ugyldig brukernavn eller passord." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Bruker inaktiv eller slettet." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Ugyldig token header. Ingen legitimasjon gitt." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Ugyldig token header. Token streng skal ikke inneholde mellomrom." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Ugyldig token header. Tokenstrengen skal ikke inneholde ugyldige tegn." #: authentication.py:203 msgid "Invalid token." msgstr "Ugyldig token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Auth Token" #: authtoken/models.py:13 msgid "Key" msgstr "Nøkkel" #: authtoken/models.py:16 msgid "User" msgstr "Bruker" #: authtoken/models.py:18 msgid "Created" msgstr "Opprettet" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokener" #: authtoken/serializers.py:9 msgid "Username" msgstr "Brukernavn" #: authtoken/serializers.py:13 msgid "Password" msgstr "Passord" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Kan ikke logge inn med gitt legitimasjon." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Må inneholde \"username\" og \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "En serverfeil skjedde." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Misformet forespørsel." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Ugyldig autentiseringsinformasjon." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Manglende autentiseringsinformasjon." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Du har ikke tilgang til å utføre denne handlingen." #: exceptions.py:185 msgid "Not found." msgstr "Ikke funnet." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metoden \"{method}\" ikke gyldig." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Kunne ikke tilfredsstille request Accept header." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Ugyldig media type \"{media_type}\" i request." #: exceptions.py:223 msgid "Request was throttled." msgstr "Forespørselen ble strupet." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Dette feltet er påkrevd." #: fields.py:317 msgid "This field may not be null." msgstr "Dette feltet må ikke være tomt." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Dette feltet må ikke være blankt." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Forsikre deg om at dette feltet ikke har mer enn {max_length} tegn." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Forsikre deg at dette feltet har minst {min_length} tegn." #: fields.py:816 msgid "Enter a valid email address." msgstr "Oppgi en gyldig epost-adresse." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Denne verdien samsvarer ikke med de påkrevde mønsteret." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Skriv inn en gyldig \"slug\" som består av bokstaver, tall, understrek eller bindestrek." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Skriv inn en gyldig URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Skriv inn en gyldig IPv4 eller IPv6-adresse." #: fields.py:931 msgid "A valid integer is required." msgstr "En gyldig heltall er nødvendig." #: 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 "Sikre denne verdien er mindre enn eller lik {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 "Sikre denne verdien er større enn eller lik {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Strengverdien for stor." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Et gyldig nummer er nødvendig." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Pass på at det ikke er flere enn {max_digits} siffer totalt." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Pass på at det ikke er flere enn {max_decimal_places} desimaler." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Pass på at det ikke er flere enn {max_whole_digits} siffer før komma." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime har feil format. Bruk et av disse formatene i stedet: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Forventet en datetime, men fikk en date." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Dato har feil format. Bruk et av disse formatene i stedet: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Forventet en date, men fikk en datetime." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Tid har feil format. Bruk et av disse formatene i stedet: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Varighet har feil format. Bruk et av disse formatene i stedet: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" er ikke et gyldig valg." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Mer enn {count} elementer ..." #: 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 "Forventet en liste over elementer, men fikk type \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Dette valget kan ikke være tomt." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" er ikke en gyldig bane valg." #: fields.py:1514 msgid "No file was submitted." msgstr "Ingen fil ble sendt." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "De innsendte data var ikke en fil. Kontroller kodingstypen på skjemaet." #: fields.py:1516 msgid "No filename could be determined." msgstr "Kunne ikke finne filnavn." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Den innsendte filen er tom." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Sikre dette filnavnet har på det meste {max_length} tegn (det har {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Last opp et gyldig bilde. Filen du lastet opp var enten ikke et bilde eller en ødelagt bilde." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Denne listen kan ikke være tom." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Forventet en dictionary av flere ting, men fikk typen \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Verdien må være gyldig JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Søk" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sortering" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "stigende" #: filters.py:288 msgid "descending" msgstr "synkende" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Ugyldig side" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Ugyldig markør" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Ugyldig pk \"{pk_value}\" - objektet eksisterer ikke." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Feil type. Forventet pk verdi, fikk {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Ugyldig hyperkobling - No URL match." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Ugyldig hyperkobling - Incorrect URL match." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Ugyldig hyperkobling - Objektet eksisterer ikke." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Feil type. Forventet URL streng, fikk {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekt med {slug_name}={value} finnes ikke." #: relations.py:449 msgid "Invalid value." msgstr "Ugyldig verdi." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Ugyldige data. Forventet en dictionary, men fikk {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtre" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ingen" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Ingenting å velge." #: validators.py:39 msgid "This field must be unique." msgstr "Dette feltet må være unikt." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Feltene {field_names} må gjøre et unikt sett." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Dette feltet må være unikt for \"{date_field}\" dato." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Dette feltet må være unikt for \"{date_field}\" måned." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Dette feltet må være unikt for \"{date_field}\" år." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Ugyldig versjon på \"Accept\" header." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Ugyldig versjon i URL-banen." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Ugyldig versjon i URL. Passer ikke med noen eksisterende versjon." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Ugyldig versjon i vertsnavn." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Ugyldig versjon i søkeparameter." ================================================ FILE: rest_framework/locale/ne_NP/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Shrawan Poudel , 2018 # Xavier Ordoquy , 2020 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:59+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Nepali (Nepal) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ne_NP/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ne_NP\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "अमान्य हेडरहरू, क्रेडेन्सियलहरू प्रदान गरिएको छैन |" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "अमान्य हेडरहरू, क्रेडेन्सियलहरूमा स्पेस हुनु हुँदैन |" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "अमान्य हेडरहरू, क्रेडेन्सियलहरूमा सही तरिकाले base64 एन्कोड गरिएको छैन |" #: authentication.py:101 msgid "Invalid username/password." msgstr "अमान्य प्रयोगकर्तानाम/पासवर्ड |" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "प्रयोगकर्ता निष्क्रिय वा मेटायिएको छ |" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "अमान्य टोकन हेडर । कुनै क्रेडेन्सियल प्रदान गरिएको छैन ।" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "अमान्य टोकन हेडर | टोकनमा स्पेस हुनु हुँदैन |" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "अमान्य टोकन हेडर | टोकनमा अवैध अक्षरहरू हुनु हुँदैन |" #: authentication.py:203 msgid "Invalid token." msgstr "अमान्य टोकन |" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "प्रयोगकर्ता प्रमाणिकरण टोकन " #: authtoken/models.py:13 msgid "Key" msgstr "मूल" #: authtoken/models.py:16 msgid "User" msgstr "प्रयोगकर्ता" #: authtoken/models.py:18 msgid "Created" msgstr "सिर्जना गरियो" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "टोकन" #: authtoken/models.py:28 msgid "Tokens" msgstr "टोकेनहरु" #: authtoken/serializers.py:9 msgid "Username" msgstr "प्रयोगकर्ताको नाम" #: authtoken/serializers.py:13 msgid "Password" msgstr "पासवर्ड" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "प्रदान गरिएको क्रेडेन्सियलसँग लग इन गर्न सकिएन |" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"प्रयोगकर्ताको नाम\" र \"पासवर्ड\" सामेल हुनु पर्छ |" #: exceptions.py:102 msgid "A server error occurred." msgstr "सर्भर त्रुटि देखापर्यो |" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "विकृत अनुरोध |" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "गलत प्रमाणीकरण क्रेडेन्सियलहरू |" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "प्रमाणीकरण क्रेडेन्सियलहरू पयिएन | " #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "तपाइँसँग यो कार्य गर्न अनुमति छैन |" #: exceptions.py:185 msgid "Not found." msgstr "फेला परेन |" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "\"{method}\" गर्ने अनुमती छैन |" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Accept Header अनुरोधलाई सन्तुष्ट गर्ने सकिएन |" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "असमर्थित मिडिया टाईप \"{media_type}\" अनुरोधको | " #: exceptions.py:223 msgid "Request was throttled." msgstr "अनुरोध प्रतिबन्दित गरियो |" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "यो फिल्ड आवश्यक छ |" #: fields.py:317 msgid "This field may not be null." msgstr "यो फिल्ड खाली हुनु हुँदैन |" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "यो फिल्ड खाली हुन सक्दैन |" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "यो फिल्डसँग {max_length} अक्षरहरू भन्दा बढी छ छैन सुनिश्चित गर्नुहोस् |" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "यो फिल्डमा कम से कम {min_length} अक्षरहरू छ छैन सुनिश्चित गर्नुहोस् |" #: fields.py:816 msgid "Enter a valid email address." msgstr "मान्य इमेल ठेगाना प्रविष्ट गर्नुहोस् |" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "यो परिमाण आवश्यक ढाँचा मेल खाँदैन ।" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "अक्षरहरू, अङ्कहरू, अन्डरसेर्सहरू वा हाइफनहरू समावेश भएका एक मान्य \"slug\" प्रविष्टि गर्नुहोस् ।" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "मान्य यूआरएल प्रविष्ट गर्नुहोस् ।" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "मान्य IPv4 वा IPv6 ठेगाना प्रविष्टि गर्नुहोस् ।" #: fields.py:931 msgid "A valid integer is required." 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} को भन्दा कम वा बराबर छ सुनिश्चित गर्नुहोस् ।" #: 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} भन्दा बढी वा बराबर छ सुनिश्चित गर्नुहोस् ।" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "स्ट्रिङ परिमाण धेरै ठूलो छ ।" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "एउटा मान्य अङ्कहरू आवश्यक छ ।" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "सुनिश्चित गर्नुहोस् कि {max_digits} अङ्कहरू भन्दा अधिक नहोस् ।" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "सुनिश्चित गर्नुहोस् कि {max_decimal_places} दशमलव स्थानहरू भन्दा अधिक नहोस् ।" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "सुनिश्चित गर्नुहोस् कि दशमलव बिन्दुभन्दा पहिले {max_whole_digits} अङ्कहरू भन्दा अधिक नहोस् ।" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "डेटटाइममा गलत ढाँचा छ । यसको सट्टामा यी मध्ये एक ढाँचा प्रयोग गर्नुहोस्: {format} ।" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "डेटटाइम अपेक्षित भए तर मिति प्राप्त भयो ।" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "डेटमा गलत ढाँचा छ । यसको सट्टामा यी मध्ये एक ढाँचा प्रयोग गर्नुहोस्: {format} ।" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "डेट अपेक्षित भए तर डेटाटाइम प्राप्त भयो ।" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "समयमा गलत ढाँचा छ । यसको सट्टामा यी मध्ये एक ढाँचा प्रयोग गर्नुहोस्: {format} ।" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "अवधिमा गलत ढाँचा छ । यसको सट्टामा यी मध्ये एक ढाँचा प्रयोग गर्नुहोस्: {format} ।" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" मान्य छनौट छैन ।" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "{count} वस्तुहरू भन्दा बढी ..." #: 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 "वस्तुहरूको सूची अपेक्षित तर \"{input_type}\" टाइप प्राप्त भयो ।" #: fields.py:1458 msgid "This selection may not be empty." msgstr "यो चयन रिक्त हुन सक्दैन ।" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" मान्य मार्गको विकल्प होइन ।" #: fields.py:1514 msgid "No file was submitted." msgstr "कुनै फाइल पेश गरिएको छैन ।" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "पेश गरिएको डेटा फाईल थिएन । एन्कोडिङ प्रकार फारममा जाँच्नुहोस् ।" #: fields.py:1516 msgid "No filename could be determined." msgstr "कुनै फाइल नाम निर्धारण गर्न सकिएन ।" #: fields.py:1517 msgid "The submitted file is empty." msgstr "पेश गरिएको फाइल खाली छ ।" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "मान्य चित्र अपलोड गर्नुहोस् । तपाईंले अपलोड गर्नुभएको फाइल होइन वा चित्र वा भ्रष्ट चित्र हो ।" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "यो सूची खाली हुन सक्दैन ।" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "वस्तुहरूको शब्दकोशको अपेक्षित तर \"{input_type}\" टाइप प्राप्त भयो ।" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "परिमाण मान्य JSON हुनु पर्छ ।" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "खोजी गर्नुहोस्" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "क्रम" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "आरोहण" #: filters.py:288 msgid "descending" msgstr "अवरोहण" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "अमान्य पृष्ठ ।" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "अमान्य कर्सर" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "अमान्य pk \"{pk_value}\" - वस्तुको अस्तित्व छैन ।" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "गलत प्रकार। अपेक्षित pk परिमाण, {data_type} प्राप्त भयो ।" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "अमान्य हाइपरलिंक - कुनै यूआरएलको मेल छैन ।" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "अमान्य हाइपरलिंक - गलत यूआरएलको मेल छ ।" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "अमान्य हाइपरलिंक - वस्तुको अस्तित्व छैन ।" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "गलत प्रकार। अपेक्षित यूआरएल स्ट्रिङ, {data_type} प्राप्त भयो ।" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "वस्तु {slug_name} = {value} सँग अस्तित्व छैन ।" #: relations.py:449 msgid "Invalid value." msgstr "अमान्य परिमाण ।" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "अमान्य डेटा । एक शब्दकोश अपेक्षित, तर {datatype} प्राप्त भयो ।" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "फिल्टरहरू" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "कुनै पनि होइन" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "चयन गर्न वस्तुहरू छैनन् ।" #: validators.py:39 msgid "This field must be unique." msgstr "यो फिल्ड अद्वितीय हुनुपर्छ ।" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "फिल्ड {field_names} ले एक अद्वितीय सेट गर्नु पर्छ ।" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "यो फिल्ड \"{date_field}\" मितिको लागि अद्वितीय हुनुपर्छ ।" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "यो फिल्ड \"{date_field}\" महिनाको लागि अद्वितीय हुनुपर्छ ।" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "यो फिल्ड \"{date_field}\" वर्षको लागि अद्वितीय हुनुपर्छ ।" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Accept\" हेडरमा अमान्य संस्करण ।" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "यूआरएल मार्गमा अमान्य संस्करण ।" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "यूआरएल मार्गमा अमान्य संस्करण । कुनै पनि संस्करणको नामसँग मेल खाँदैन ।" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "होस्ट नाममा अमान्य संस्करण ।" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr " क्वेरी परिमितिमा अमान्य संस्करण ।" ================================================ FILE: rest_framework/locale/nl/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Hans van Luttikhuizen , 2016 # Mike Dingjan , 2015 # Mike Dingjan , 2017 # Mike Dingjan , 2015 # Hans van Luttikhuizen , 2016 # Tom Hendrikx , 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Dutch (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/nl/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: nl\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Ongeldige basic header. Geen logingegevens opgegeven." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Ongeldige basic header. logingegevens kunnen geen spaties bevatten." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Ongeldige basic header. logingegevens zijn niet correct base64-versleuteld." #: authentication.py:101 msgid "Invalid username/password." msgstr "Ongeldige gebruikersnaam/wachtwoord." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Gebruiker inactief of verwijderd." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Ongeldige token header. Geen logingegevens opgegeven" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Ongeldige token header. Token kan geen spaties bevatten." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Ongeldige token header. Token kan geen ongeldige karakters bevatten." #: authentication.py:203 msgid "Invalid token." msgstr "Ongeldige token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Autorisatietoken" #: authtoken/models.py:13 msgid "Key" msgstr "Key" #: authtoken/models.py:16 msgid "User" msgstr "Gebruiker" #: authtoken/models.py:18 msgid "Created" msgstr "Aangemaakt" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Gebruikersnaam" #: authtoken/serializers.py:13 msgid "Password" msgstr "Wachtwoord" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Kan niet inloggen met opgegeven gegevens." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Moet \"username\" en \"password\" bevatten." #: exceptions.py:102 msgid "A server error occurred." msgstr "Er is een serverfout opgetreden." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Ongeldig samengestelde request." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Ongeldige authenticatiegegevens." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Authenticatiegegevens zijn niet opgegeven." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Je hebt geen toestemming om deze actie uit te voeren." #: exceptions.py:185 msgid "Not found." msgstr "Niet gevonden." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Methode \"{method}\" niet toegestaan." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Kan niet voldoen aan de opgegeven Accept header." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Ongeldige media type \"{media_type}\" in aanvraag." #: exceptions.py:223 msgid "Request was throttled." msgstr "Aanvraag was verstikt." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Dit veld is vereist." #: fields.py:317 msgid "This field may not be null." msgstr "Dit veld mag niet leeg zijn." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Dit veld mag niet leeg zijn." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Zorg ervoor dat dit veld niet meer dan {max_length} karakters bevat." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Zorg ervoor dat dit veld minimaal {min_length} karakters bevat." #: fields.py:816 msgid "Enter a valid email address." msgstr "Voer een geldig e-mailadres in." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Deze waarde voldoet niet aan het vereiste formaat." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Voer een geldige \"slug\" in, bestaande uit letters, cijfers, lage streepjes of streepjes." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Voer een geldige URL in." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Voer een geldig IPv4- of IPv6-adres in." #: fields.py:931 msgid "A valid integer is required." msgstr "Een geldig getal is vereist." #: 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 "Zorg ervoor dat deze waarde kleiner is dan of gelijk is aan {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 "Zorg ervoor dat deze waarde groter is dan of gelijk is aan {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Tekstwaarde is te lang." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Een geldig nummer is vereist." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Zorg ervoor dat er in totaal niet meer dan {max_digits} cijfers zijn." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Zorg ervoor dat er niet meer dan {max_decimal_places} cijfers achter de komma zijn." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Zorg ervoor dat er niet meer dan {max_whole_digits} cijfers voor de komma zijn." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime heeft een ongeldig formaat, gebruik 1 van de volgende formaten: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Verwachtte een datetime, maar kreeg een date." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Date heeft het verkeerde formaat, gebruik 1 van deze formaten: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Verwachtte een date, maar kreeg een datetime." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Time heeft het verkeerde formaat, gebruik 1 van onderstaande formaten: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Tijdsduur heeft een verkeerd formaat, gebruik 1 van onderstaande formaten: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" is een ongeldige keuze." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Meer dan {count} items..." #: 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 "Verwachtte een lijst met items, maar kreeg type \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Deze selectie mag niet leeg zijn." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" is niet een geldig pad." #: fields.py:1514 msgid "No file was submitted." msgstr "Er is geen bestand opgestuurd." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "De verstuurde data was geen bestand. Controleer de encoding type op het formulier." #: fields.py:1516 msgid "No filename could be determined." msgstr "Bestandsnaam kon niet vastgesteld worden." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Het verstuurde bestand is leeg." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Zorg ervoor dat deze bestandsnaam hoogstens {max_length} karakters heeft (het heeft er {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Upload een geldige afbeelding, de geüploade afbeelding is geen afbeelding of is beschadigd geraakt," #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Deze lijst mag niet leeg zijn." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Verwachtte een dictionary van items, maar kreeg type \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Waarde moet valide JSON zijn." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Zoek" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sorteer op" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "oplopend" #: filters.py:288 msgid "descending" msgstr "aflopend" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Ongeldige pagina." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Ongeldige cursor." #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Ongeldige pk \"{pk_value}\" - object bestaat niet." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Ongeldig type. Verwacht een pk-waarde, ontving {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Ongeldige hyperlink - Geen overeenkomende URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Ongeldige hyperlink - Ongeldige URL" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Ongeldige hyperlink - Object bestaat niet." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Ongeldig type. Verwacht een URL, ontving {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Object met {slug_name}={value} bestaat niet." #: relations.py:449 msgid "Invalid value." msgstr "Ongeldige waarde." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Ongeldige data. Verwacht een dictionary, kreeg een {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filters" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Geen" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Geen items geselecteerd." #: validators.py:39 msgid "This field must be unique." msgstr "Dit veld moet uniek zijn." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "De velden {field_names} moeten een unieke set zijn." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Dit veld moet uniek zijn voor de \"{date_field}\" datum." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Dit veld moet uniek zijn voor de \"{date_field}\" maand." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Dit veld moet uniek zijn voor de \"{date_field}\" year." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Ongeldige versie in \"Accept\" header." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Ongeldige versie in URL-pad." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Ongeldige versie in het URL pad, komt niet overeen met een geldige versie namespace" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Ongeldige versie in hostnaam." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Ongeldige versie in query parameter." ================================================ FILE: rest_framework/locale/nn/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Norwegian Nynorsk (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/nn/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: nn\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/no/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Norwegian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/no/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: no\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/pl/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Janusz Harkot , 2015 # Piotr Jakimiak , 2015 # m_aciek , 2016 # m_aciek , 2015-2016 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Polish (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/pl/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: pl\n" "Plural-Forms: nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && (n%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && n%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Niepoprawny podstawowy nagłówek. Brak danych uwierzytelniających." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Niepoprawny podstawowy nagłówek. Ciąg znaków danych uwierzytelniających nie powinien zawierać spacji." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Niepoprawny podstawowy nagłówek. Niewłaściwe kodowanie base64 danych uwierzytelniających." #: authentication.py:101 msgid "Invalid username/password." msgstr "Niepoprawna nazwa użytkownika lub hasło." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Użytkownik nieaktywny lub usunięty." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Niepoprawny nagłówek tokena. Brak danych uwierzytelniających." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Niepoprawny nagłówek tokena. Token nie może zawierać odstępów." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Błędny nagłówek z tokenem. Token nie może zawierać błędnych znaków." #: authentication.py:203 msgid "Invalid token." msgstr "Niepoprawny token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Token uwierzytelniający" #: authtoken/models.py:13 msgid "Key" msgstr "Klucz" #: authtoken/models.py:16 msgid "User" msgstr "Użytkownik" #: authtoken/models.py:18 msgid "Created" msgstr "Stworzono" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokeny" #: authtoken/serializers.py:9 msgid "Username" msgstr "Nazwa użytkownika" #: authtoken/serializers.py:13 msgid "Password" msgstr "Hasło" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Podane dane uwierzytelniające nie pozwalają na zalogowanie." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Musi zawierać \"username\" i \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Wystąpił błąd serwera." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Zniekształcone żądanie." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Błędne dane uwierzytelniające." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Nie podano danych uwierzytelniających." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Nie masz uprawnień, by wykonać tę czynność." #: exceptions.py:185 msgid "Not found." msgstr "Nie znaleziono." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Niedozwolona metoda \"{method}\"." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Nie można zaspokoić nagłówka Accept żądania." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Brak wsparcia dla żądanego typu danych \"{media_type}\"." #: exceptions.py:223 msgid "Request was throttled." msgstr "Żądanie zostało zdławione." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "To pole jest wymagane." #: fields.py:317 msgid "This field may not be null." msgstr "Pole nie może mieć wartości null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "To pole nie może być puste." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Upewnij się, że to pole ma nie więcej niż {max_length} znaków." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Upewnij się, że pole ma co najmniej {min_length} znaków." #: fields.py:816 msgid "Enter a valid email address." msgstr "Podaj poprawny adres e-mail." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Ta wartość nie pasuje do wymaganego wzorca." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Wprowadź poprawną wartość pola typu \"slug\", składającą się ze znaków łacińskich, cyfr, podkreślenia lub myślnika." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Wprowadź poprawny adres URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Wprowadź poprawny adres IPv4 lub IPv6." #: fields.py:931 msgid "A valid integer is required." msgstr "Wymagana poprawna liczba całkowita." #: 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 "Upewnij się, że ta wartość jest mniejsza lub równa {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 "Upewnij się, że ta wartość jest większa lub równa {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Za długi ciąg znaków." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Wymagana poprawna liczba." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Upewnij się, że liczba ma nie więcej niż {max_digits} cyfr." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Upewnij się, że liczba ma nie więcej niż {max_decimal_places} cyfr dziesiętnych." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Upewnij się, że liczba ma nie więcej niż {max_whole_digits} cyfr całkowitych." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Wartość daty z czasem ma zły format. Użyj jednego z dostępnych formatów: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Oczekiwano datę z czasem, otrzymano tylko datę." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Data ma zły format. Użyj jednego z tych formatów: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Oczekiwano daty a otrzymano datę z czasem." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Błędny format czasu. Użyj jednego z dostępnych formatów: {format}" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Czas trwania ma zły format. Użyj w zamian jednego z tych formatów: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" nie jest poprawnym wyborem." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Więcej niż {count} elementów..." #: 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 "Oczekiwano listy elementów, a otrzymano dane typu \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Zaznaczenie nie może być puste." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" nie jest poprawną ścieżką." #: fields.py:1514 msgid "No file was submitted." msgstr "Nie przesłano pliku." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Przesłane dane nie były plikiem. Sprawdź typ kodowania formatki." #: fields.py:1516 msgid "No filename could be determined." msgstr "Nie można określić nazwy pliku." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Przesłany plik jest pusty." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Upewnij się, że nazwa pliku ma długość co najwyżej {max_length} znaków (aktualnie ma {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Prześlij poprawny plik graficzny. Przesłany plik albo nie jest grafiką lub jest uszkodzony." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Lista nie może być pusta." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Oczekiwano słownika, ale otrzymano \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Wartość musi być poprawnym ciągiem znaków JSON" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Szukaj" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Kolejność" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "rosnąco" #: filters.py:288 msgid "descending" msgstr "malejąco" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Niepoprawna strona." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Niepoprawny wskaźnik" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Błędny klucz główny \"{pk_value}\" - obiekt nie istnieje." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Błędny typ danych. Oczekiwano wartość klucza głównego, otrzymano {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Błędny hyperlink - nie znaleziono pasującego adresu URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Błędny hyperlink - błędne dopasowanie adresu URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Błędny hyperlink - obiekt nie istnieje." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Błędny typ danych. Oczekiwano adresu URL, otrzymano {data_type}" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Obiekt z polem {slug_name}={value} nie istnieje" #: relations.py:449 msgid "Invalid value." msgstr "Niepoprawna wartość." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Niepoprawne dane. Oczekiwano słownika, otrzymano {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtry" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "None" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Nie wybrano wartości." #: validators.py:39 msgid "This field must be unique." msgstr "Wartość dla tego pola musi być unikalna." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Pola {field_names} muszą tworzyć unikalny zestaw." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "To pole musi mieć unikalną wartość dla jednej daty z pola \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "To pole musi mieć unikalną wartość dla konkretnego miesiąca z pola \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "To pole musi mieć unikalną wartość dla konkretnego roku z pola \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Błędna wersja w nagłówku \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Błędna wersja w ścieżce URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Niepoprawna wersja w ścieżce URL. Nie pasuje do przestrzeni nazw żadnej wersji." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Błędna wersja w nazwie hosta." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Błędna wersja w parametrach zapytania." ================================================ FILE: rest_framework/locale/pt/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Craig Blaszczyk , 2015 # Ederson Mota Pereira , 2015 # Filipe Rinaldi , 2015 # Hugo Leonardo Chalhoub Mendonça , 2015 # Jonatas Baldin , 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Portuguese (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/pt/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: pt\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Cabeçalho básico inválido. Credenciais não fornecidas." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Cabeçalho básico inválido. String de credenciais não deve incluir espaços." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Cabeçalho básico inválido. Credenciais codificadas em base64 incorretamente." #: authentication.py:101 msgid "Invalid username/password." msgstr "Usuário ou senha inválido." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Usuário inativo ou removido." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Cabeçalho de token inválido. Credenciais não fornecidas." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Cabeçalho de token inválido. String de token não deve incluir espaços." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Cabeçalho de token inválido. String de token não deve possuir caracteres inválidos." #: authentication.py:203 msgid "Invalid token." msgstr "Token inválido." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Token de autenticação" #: authtoken/models.py:13 msgid "Key" msgstr "Chave" #: authtoken/models.py:16 msgid "User" msgstr "Usuário" #: authtoken/models.py:18 msgid "Created" msgstr "Criado" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Nome do usuário" #: authtoken/serializers.py:13 msgid "Password" msgstr "Senha" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Impossível fazer login com as credenciais fornecidas." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Obrigatório incluir \"usuário\" e \"senha\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Ocorreu um erro de servidor." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Pedido malformado." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Credenciais de autenticação incorretas." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "As credenciais de autenticação não foram fornecidas." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Você não tem permissão para executar essa ação." #: exceptions.py:185 msgid "Not found." msgstr "Não encontrado." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Método \"{method}\" não é permitido." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." 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." #: exceptions.py:223 msgid "Request was throttled." msgstr "Pedido foi limitado." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Este campo é obrigatório." #: fields.py:317 msgid "This field may not be null." msgstr "Este campo não pode ser nulo." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Este campo não pode ser em branco." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Certifique-se de que este campo não tenha mais de {max_length} caracteres." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Certifique-se de que este campo tenha mais de {min_length} caracteres." #: fields.py:816 msgid "Enter a valid email address." msgstr "Insira um endereço de email válido." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Este valor não corresponde ao padrão exigido." #: fields.py:838 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." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Entrar um URL válido." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Informe um endereço IPv4 ou IPv6 válido." #: fields.py:931 msgid "A valid integer is required." msgstr "Um número inteiro válido é exigido." #: 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 "Certifique-se de que este valor seja inferior ou igual a {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 "Certifque-se de que este valor seja maior ou igual a {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Valor da string é muito grande." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Um número válido é necessário." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Certifique-se de que não haja mais de {max_digits} dígitos no total." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Certifique-se de que não haja mais de {max_decimal_places} casas decimais." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Certifique-se de que não haja mais de {max_whole_digits} dígitos antes do ponto decimal." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Formato inválido para data e hora. Use um dos formatos a seguir: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." 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 "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Formato inválido para data. Use um dos formatos a seguir: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." 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}." #: 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}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" não é um escolha válido." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." 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}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Esta seleção não pode estar vazia." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" não é uma escolha válida para um caminho." #: fields.py:1514 msgid "No file was submitted." msgstr "Nenhum arquivo foi submetido." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "O dado submetido não é um arquivo. Certifique-se do tipo de codificação no formulário." #: fields.py:1516 msgid "No filename could be determined." msgstr "Nome do arquivo não pode ser determinado." #: fields.py:1517 msgid "The submitted file is empty." msgstr "O arquivo submetido está vázio." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Certifique-se de que o nome do arquivo tem menos de {max_length} caracteres (tem {length})." #: fields.py:1566 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." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." 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 "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: 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}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Valor devo ser JSON válido." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Buscar" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordenando" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "ascendente" #: filters.py:288 msgid "descending" msgstr "descendente" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Página inválida." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Cursor inválido" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." 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}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Hyperlink inválido - Sem combinação para a URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Hyperlink inválido - Combinação URL incorreta." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Hyperlink inválido - Objeto não existe." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Tipo incorreto. Necessário string URL, recebeu {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objeto com {slug_name}={value} não existe." #: relations.py:449 msgid "Invalid value." msgstr "Valor inválido." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." 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 "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtra" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Nenhum(a/as)" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Nenhum item para escholher." #: validators.py:39 msgid "This field must be unique." msgstr "Esse campo deve ser único." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." 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 "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "O campo \"{date_field}\" deve ser único para a data." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "O campo \"{date_field}\" deve ser único para o mês." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "O campo \"{date_field}\" deve ser único para o ano." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Versão inválida no cabeçalho \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Versão inválida no caminho de URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Versão inválida no caminho da URL. Não corresponde a nenhuma versão do namespace." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Versão inválida no hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Versão inválida no parâmetro de query." ================================================ FILE: rest_framework/locale/pt_BR/LC_MESSAGES/django.po ================================================ # 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 # Ederson Mota Pereira , 2015 # Filipe Rinaldi , 2015 # Hugo Leonardo Chalhoub Mendonça , 2015 # Jonatas Baldin , 2017 # Gabriel Mitelman Tkacz , 2024 # Matheus Oliveira , 2025 # João Victor Pinheiro Reis , 2025 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2025-11-18 17:00+0300\n" "PO-Revision-Date: 2025-11-18 14:00+0000\n" "Last-Translator: João Victor Pinheiro Reis \n" "Language-Team: Portuguese (Brazil) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/pt_BR/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: pt_BR\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Cabeçalho básico inválido. Credenciais não fornecidas." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Cabeçalho básico inválido. String de credenciais não deve incluir espaços." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Cabeçalho básico inválido. Credenciais não foram corretamente codificadas em base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Usuário ou senha inválidos." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Usuário inativo ou removido." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Cabeçalho de token inválido. Credenciais não fornecidas." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Cabeçalho de token inválido. String de token não deve incluir espaços." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Cabeçalho de token inválido. String de token não deveria possuir caracteres inválidos." #: authentication.py:203 msgid "Invalid token." msgstr "Token inválido." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Token de autenticação" #: authtoken/models.py:13 msgid "Key" msgstr "Chave" #: authtoken/models.py:16 msgid "User" msgstr "Usuário" #: authtoken/models.py:18 msgid "Created" msgstr "Criado" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Nome de usuário" #: authtoken/serializers.py:13 msgid "Password" msgstr "Senha" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Impossível fazer login com as credenciais fornecidas." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Deve incluir \"username\" e \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Um erro de servidor ocorreu." #: exceptions.py:142 msgid "Invalid input." msgstr "Entrada inválida" #: exceptions.py:161 msgid "Malformed request." msgstr "Requisição malformada." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Credenciais de autenticação incorretas." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "As credenciais de autenticação não foram fornecidas." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Você não tem permissão para executar essa ação." #: exceptions.py:185 msgid "Not found." msgstr "Não encontrado." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Método \"{method}\" não é permitido." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." 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}\" não é suportado." #: exceptions.py:223 msgid "Request was throttled." msgstr "Pedido foi suprimido." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "Espera-se que esteja diponível em {wait} segundo." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "Espera-se que esteja diponível em {wait} segundos." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Este campo é obrigatório." #: fields.py:317 msgid "This field may not be null." msgstr "Este campo pode não ser nulo." #: fields.py:701 msgid "Must be a valid boolean." msgstr "Deve ser um valor booleano válido." #: fields.py:766 msgid "Not a valid string." msgstr "Não é uma string válida." #: fields.py:767 msgid "This field may not be blank." msgstr "Este campo pode não estar em branco." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Certifique-se de que este campo não tenha mais de {max_length} caracteres." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Certifique-se de que este campo tenha mais de {min_length} caracteres." #: fields.py:816 msgid "Enter a valid email address." msgstr "Insira um endereço de email válido." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Este valor não corresponde ao padrão exigido." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Insira um \"slug\" válido que consista em letras, números, sublinhados ou hífens." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "Insira um \"slug\" válido que consista em letras, números, sublinhados ou hífens Unicode." #: fields.py:854 msgid "Enter a valid URL." msgstr "Insira um URL válido." #: fields.py:867 msgid "Must be a valid UUID." msgstr "Deve ser um UUID válido." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Informe um endereço IPv4 ou IPv6 válido." #: fields.py:931 msgid "A valid integer is required." msgstr "Um número inteiro válido é exigido." #: 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 "Certifique-se de que este valor seja inferior ou igual a {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 "Certifque-se de que este valor seja maior ou igual a {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Valor da string é muito grande." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Um número válido é necessário." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Certifique-se de que não haja mais de {max_digits} dígitos no total." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Certifique-se de que não haja mais de {max_decimal_places} casas decimais." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Certifique-se de que não haja mais de {max_whole_digits} dígitos antes do ponto decimal." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Formato inválido para data e hora. Use um dos formatos a seguir: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Esperava data e hora, mas recebeu data." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "Data e hora inválidas para o fuso horário \"{timezone}\"." #: fields.py:1151 msgid "Datetime value out of range." msgstr "Valor de data e hora fora do intervalo." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Formato de data inválido. Use um dos formatos a seguir: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Esperava data, mas recebeu 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}." #: 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}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" não é uma escolha válida." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." 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 "Esperava uma lista de itens, mas recebeu tipo \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Esta seleção pode não estar vazia." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" não é uma escolha válida de caminho." #: fields.py:1514 msgid "No file was submitted." msgstr "Nenhum arquivo foi submetido." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "O dado submetido não era um arquivo. Cheque o tipo de codificação no formulário." #: fields.py:1516 msgid "No filename could be determined." msgstr "Nome do arquivo não pode ser determinado." #: fields.py:1517 msgid "The submitted file is empty." msgstr "O arquivo submetido está vázio." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Certifique-se de que o nome do arquivo tenho no máximo {max_length} caracteres (tem {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." 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." msgstr "Esta lista pode não estar vazia." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." 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 "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 "Esperava um dicionário de itens, mas recebeu tipo \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "Este dicionário pode não estar vazio." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Valor deve ser JSON válido." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Buscar" #: filters.py:50 msgid "A search term." msgstr "Um termo de busca." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordenando" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "Qual campo usar ao ordenar os resultados." #: filters.py:287 msgid "ascending" msgstr "crescente" #: filters.py:288 msgid "descending" msgstr "decrescente" #: pagination.py:174 msgid "A page number within the paginated result set." 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 "Número de resultados a serem retornados por página." #: pagination.py:189 msgid "Invalid page." msgstr "Página inválida." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "O índice inicial a partir do qual retornar os resultados." #: pagination.py:581 msgid "The pagination cursor value." msgstr "O valor do cursor de paginação." #: pagination.py:583 msgid "Invalid cursor" msgstr "Cursor inválido" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." 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. Esperava valor pk, recebeu {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Hyperlink inválido - Sem combinação para a URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Hyperlink inválido - Combinação URL incorreta." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Hyperlink inválido - Objeto não existe." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Tipo incorreto. Esperava string URL, recebeu {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objeto com {slug_name}={value} não existe." #: relations.py:449 msgid "Invalid value." msgstr "Valor inválido." #: schemas/utils.py:32 msgid "unique integer value" msgstr "valor inteiro único" #: schemas/utils.py:34 msgid "UUID string" msgstr "string UUID" #: schemas/utils.py:36 msgid "unique value" msgstr "valor único" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "Um {value_type} que identifica este {name}." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Dado inválido. Esperava um dicionário, mas recebeu {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "Ações Extras" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtros" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "conteúdo" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "formulário de requisição" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "conteúdo principal" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "informações da requisição" #: templates/rest_framework/base.html:177 msgid "response info" msgstr "informações da resposta" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 #: templates/rest_framework/vertical/radio.html:3 msgid "None" msgstr "Nenhum(a/as)" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Nenhum item para selecionar." #: validators.py:39 msgid "This field must be unique." msgstr "Este campo deve ser único." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." 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 "Caracteres substitutos não são permitidos: U+{code_point:X}." #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Este campo deve ser único para a data de \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Este campo deve ser único para o mês de \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Este campo deve ser único para o ano de \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Versão inválida no cabeçalho \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Versão inválida no caminho de URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Versão inválida no caminho da URL. Não corresponde a nenhuma versão do namespace." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Versão inválida no hostname." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Versão inválida no parâmetro de consulta." ================================================ FILE: rest_framework/locale/pt_PT/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Portuguese (Portugal) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/pt_PT/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: pt_PT\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/locale/ro/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Bogdan Mateescu, 2019 # Elena-Adela Neacsu , 2016 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Romanian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ro/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ro\n" "Plural-Forms: nplurals=3; plural=(n==1?0:(((n%100>19)||((n%100==0)&&(n!=0)))?2:1));\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Antet de bază invalid. Datele de autentificare nu au fost furnizate." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Antet de bază invalid. Şirul de caractere cu datele de autentificare nu trebuie să conțină spații." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Antet de bază invalid. Datele de autentificare nu au fost corect codificate în base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Nume utilizator / Parolă invalid(ă)." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Utilizator inactiv sau șters." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Antet token invalid. Datele de autentificare nu au fost furnizate." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Antet token invalid. Şirul de caractere pentru token nu trebuie să conțină spații." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Antet token invalid. Şirul de caractere pentru token nu trebuie să conțină caractere nevalide." #: authentication.py:203 msgid "Invalid token." msgstr "Token nevalid." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Token de autentificare" #: authtoken/models.py:13 msgid "Key" msgstr "Cheie" #: authtoken/models.py:16 msgid "User" msgstr "Utilizator" #: authtoken/models.py:18 msgid "Created" msgstr "Creat" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokenuri" #: authtoken/serializers.py:9 msgid "Username" msgstr "Nume de utilizator" #: authtoken/serializers.py:13 msgid "Password" msgstr "Parola" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Nu se poate conecta cu datele de conectare furnizate." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Trebuie să includă \"numele de utilizator\" și \"parola\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "A apărut o eroare pe server." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Cerere incorectă." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Date de autentificare incorecte." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Datele de autentificare nu au fost furnizate." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Nu aveți permisiunea de a efectua această acțiune." #: exceptions.py:185 msgid "Not found." msgstr "Nu a fost găsit(ă)." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metoda \"{method}\" nu este permisa." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Antetul Accept al cererii nu a putut fi îndeplinit." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Cererea conține tipul media neacceptat \"{media_type}\"" #: exceptions.py:223 msgid "Request was throttled." msgstr "Cererea a fost gâtuită." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Acest câmp este obligatoriu." #: fields.py:317 msgid "This field may not be null." msgstr "Acest câmp nu poate fi nul." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Acest câmp nu poate fi gol." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Asigurați-vă că acest câmp nu are mai mult de {max_length} caractere." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Asigurați-vă că acest câmp are cel puțin{min_length} caractere." #: fields.py:816 msgid "Enter a valid email address." msgstr "Introduceți o adresă de email validă." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Această valoare nu se potrivește cu şablonul cerut." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Introduceți un \"slug\" valid format din litere, numere, caractere de subliniere sau cratime." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Introduceți un URL valid." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Introduceți o adresă IPv4 sau IPv6 validă." #: fields.py:931 msgid "A valid integer is required." msgstr "Este necesar un întreg valid." #: 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 "Asigurați-vă că această valoare este mai mică sau egală cu {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 "Asigurați-vă că această valoare este mai mare sau egală cu {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Valoare șir de caractere prea mare." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Este necesar un număr valid." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Asigurați-vă că nu există mai mult de {max_digits} cifre în total." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Asigurați-vă că nu există mai mult de {max_decimal_places} zecimale." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Asigurați-vă că nu există mai mult de {max_whole_digits} cifre înainte de punctul zecimal." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Câmpul datetime are format greșit. Utilizați unul dintre aceste formate în loc: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Se aștepta un câmp datetime, dar s-a primit o dată." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Data are formatul greșit. Utilizați unul dintre aceste formate în loc: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Se aștepta o dată, dar s-a primit un câmp datetime." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Timpul are formatul greșit. Utilizați unul dintre aceste formate în loc: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Durata are formatul greșit. Utilizați unul dintre aceste formate în loc: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" nu este o opțiune validă." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Mai mult de {count} articole ..." #: 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 "Se aștepta o listă de elemente, dar s-a primit tip \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Această selecție nu poate fi goală." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" nu este o cale validă." #: fields.py:1514 msgid "No file was submitted." msgstr "Nu a fost trimis nici un fișier." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Datele prezentate nu sunt un fișier. Verificați tipul de codificare de pe formular." #: fields.py:1516 msgid "No filename could be determined." msgstr "Numele fișierului nu a putut fi determinat." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Fișierul trimis este gol." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Asigurați-vă că acest nume de fișier are cel mult {max_length} caractere (momentan are {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Încărcați o imagine validă. Fișierul încărcat a fost fie nu o imagine sau o imagine coruptă." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Această listă nu poate fi goală." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Se aștepta un dicționar de obiecte, dar s-a primit tipul \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Valoarea trebuie să fie JSON valid." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Căutare" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordonare" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "ascendent" #: filters.py:288 msgid "descending" msgstr "descendent" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Pagină nevalidă." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Cursor nevalid" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Pk \"{pk_value}\" nevalid - obiectul nu există." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Tip incorect. Se aștepta un pk, dar s-a primit \"{data_type}\"." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Hyperlink nevalid - Nici un URL nu se potrivește." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Hyperlink nevalid - Potrivire URL incorectă." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Hyperlink nevalid - Obiectul nu există." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Tip incorect. Se aștepta un URL, dar s-a primit \"{data_type}\"." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Obiectul cu {slug_name}={value} nu există." #: relations.py:449 msgid "Invalid value." msgstr "Valoare nevalidă." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Date nevalide. Se aștepta un dicționar de obiecte, dar s-a primit \"{datatype}\"." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtre" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Nici unul/una" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Nu există elemente pentru a fi selectate." #: validators.py:39 msgid "This field must be unique." msgstr "Acest câmp trebuie să fie unic." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Câmpurile {field_names} trebuie să formeze un set unic." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Acest câmp trebuie să fie unic pentru data \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Acest câmp trebuie să fie unic pentru luna \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Acest câmp trebuie să fie unic pentru anul \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Versiune nevalidă în antetul \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Versiune nevalidă în calea URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Versiune nevalidă în calea URL. Nu se potrivește cu niciun spațiu de nume al versiunii." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Versiune nevalidă în numele de gazdă." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Versiune nevalidă în parametrul de interogare." ================================================ FILE: rest_framework/locale/ru/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Anton Bazhanov , 2018 # Grigory Mishchenko , 2017 # Kirill Tarasenko, 2015 # koodjo , 2015 # Mike TUMS , 2015 # Sergei Sinitsyn , 2016 # Val Grom , 2020 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Russian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ru/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ru\n" "Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Недопустимый заголовок. Не предоставлены учетные данные." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Недопустимый заголовок. Учетные данные не должны содержать пробелов." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Недопустимый заголовок. Учетные данные некорректно закодированны в base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Недопустимые имя пользователя или пароль." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Пользователь неактивен или удален." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Недопустимый заголовок токена. Не предоставлены учетные данные." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Недопустимый заголовок токена. Токен не должен содержать пробелов." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Недопустимый заголовок токена. Токен не должен содержать недопустимые символы." #: authentication.py:203 msgid "Invalid token." msgstr "Недопустимый токен." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Токен аутентификации" #: authtoken/models.py:13 msgid "Key" msgstr "Ключ" #: authtoken/models.py:16 msgid "User" msgstr "Пользователь" #: authtoken/models.py:18 msgid "Created" msgstr "Создан" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Токен" #: authtoken/models.py:28 msgid "Tokens" msgstr "Токены" #: authtoken/serializers.py:9 msgid "Username" msgstr "Имя пользователя" #: authtoken/serializers.py:13 msgid "Password" msgstr "Пароль" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Невозможно войти с предоставленными учетными данными." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Должен включать \"username\" и \"password\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Произошла ошибка сервера." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Искаженный запрос." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Некорректные учетные данные." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Учетные данные не были предоставлены." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "У вас нет прав для выполнения этой операции." #: exceptions.py:185 msgid "Not found." msgstr "Не найдено." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Метод \"{method}\" не разрешен." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Невозможно удовлетворить \"Accept\" заголовок запроса." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Неподдерживаемый тип данных \"{media_type}\" в запросе." #: exceptions.py:223 msgid "Request was throttled." msgstr "Запрос был проигнорирован." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Это поле обязательно." #: fields.py:317 msgid "This field may not be null." msgstr "Это поле не может быть null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Это поле не может быть пустым." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Убедитесь, что в этом поле не больше {max_length} символов." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Убедитесь, что в этом поле как минимум {min_length} символов." #: fields.py:816 msgid "Enter a valid email address." msgstr "Введите корректный адрес электронной почты." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Значение не соответствует требуемому паттерну." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Введите корректный \"slug\", состоящий из букв, цифр, знаков подчеркивания или дефисов." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Введите корректный URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Введите действительный адрес IPv4 или IPv6." #: fields.py:931 msgid "A valid integer is required." 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}." #: 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}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Слишком длинное значение." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Требуется численное значение." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Убедитесь, что в числе не больше {max_digits} знаков." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Убедитесь, что в числе не больше {max_decimal_places} знаков в дробной части." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Убедитесь, что в числе не больше {max_whole_digits} знаков в целой части." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Неправильный формат datetime. Используйте один из этих форматов: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Ожидался datetime, но был получен date." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Неправильный формат date. Используйте один из этих форматов: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Ожидался date, но был получен datetime." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Неправильный формат времени. Используйте один из этих форматов: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Неправильный формат. Используйте один из этих форматов: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" не является корректным значением." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Элементов больше чем {count}" #: 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 "Ожидался list со значениями, но был получен \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Выбор не может быть пустым." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" не является корректным путем до файла" #: fields.py:1514 msgid "No file was submitted." msgstr "Не был загружен файл." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Загруженный файл не является корректным файлом." #: fields.py:1516 msgid "No filename could be determined." msgstr "Невозможно определить имя файла." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Загруженный файл пуст." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "Загрузите корректное изображение. Загруженный файл не является изображением, либо является испорченным." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Этот список не может быть пустым." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Ожидался словарь со значениями, но был получен \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Значение должно быть правильным JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Поиск" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Порядок сортировки" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "по возрастанию" #: filters.py:288 msgid "descending" msgstr "по убыванию" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Неправильная страница" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Не корректный курсор" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Недопустимый первичный ключ \"{pk_value}\" - объект не существует." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Некорректный тип. Ожидалось значение первичного ключа, получен {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Недопустимая ссылка - нет совпадения по URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Недопустимая ссылка - некорректное совпадение по URL," #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Недопустимая ссылка - объект не существует." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Некорректный тип. Ожидался URL, получен {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Объект с {slug_name}={value} не существует." #: relations.py:449 msgid "Invalid value." msgstr "Недопустимое значение." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Недопустимые данные. Ожидался dictionary, но был получен {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Фильтры" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Ничего" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Нет элементов для выбора" #: validators.py:39 msgid "This field must be unique." msgstr "Это поле должно быть уникально." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Поля {field_names} должны производить массив с уникальными значениями." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Это поле должно быть уникально для даты \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Это поле должно быть уникально для месяца \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Это поле должно быть уникально для года \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Недопустимая версия в заголовке \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Недопустимая версия в пути URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Недопустимая версия в пути URL. Не соответствует ни одному version namespace." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Недопустимая версия в имени хоста." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Недопустимая версия в параметре запроса." ================================================ FILE: rest_framework/locale/ru_RU/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Anton Bazhanov , 2018-2019 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Russian (Russia) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/ru_RU/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ru_RU\n" "Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:101 msgid "Invalid username/password." msgstr "Пожалуйста, введите корректные имя пользователя и пароль учётной записи. Оба поля могут быть чувствительны к регистру." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Пользователь неактивен или удален." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "Недействительный токен." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:13 msgid "Key" msgstr "Ключ" #: authtoken/models.py:16 msgid "User" msgstr "Пользователь" #: authtoken/models.py:18 msgid "Created" msgstr "" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "" #: authtoken/models.py:28 msgid "Tokens" msgstr "" #: authtoken/serializers.py:9 msgid "Username" msgstr "Имя пользователя" #: authtoken/serializers.py:13 msgid "Password" msgstr "Пароль" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:102 msgid "A server error occurred." msgstr "Ошибка сервера." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "У вас недостаточно прав для выполнения данного действия." #: exceptions.py:185 msgid "Not found." msgstr "Страница не найдена." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:223 msgid "Request was throttled." msgstr "" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Обязательное поле." #: fields.py:317 msgid "This field may not be null." msgstr "Это поле не может быть пустым." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Это поле не может быть пустым." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Убедитесь, что это значение содержит не более {max_length} символов." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Убедитесь, что это значение содержит не менее {min_length} символов." #: fields.py:816 msgid "Enter a valid email address." msgstr "Введите правильный адрес электронной почты." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Значение должно состоять только из букв, цифр, символов подчёркивания или дефисов, входящих в стандарт Юникод." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Введите правильный URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Введите действительный IPv4 или IPv6 адрес." #: fields.py:931 msgid "A valid integer is required." 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}." #: 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}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Убедитесь, что вы ввели не более {max_digits} цифры." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Убедитесь, что вы ввели не более {max_decimal_places} цифры после запятой." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Убедитесь, что вы ввели не более {max_whole_digits} цифры перед запятой." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "Значения {input} нет среди допустимых вариантов." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "" #: 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 "" #: fields.py:1458 msgid "This selection may not be empty." msgstr "" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "Ни одного файла не было отправлено." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1516 msgid "No filename could be determined." msgstr "" #: fields.py:1517 msgid "The submitted file is empty." msgstr "Отправленный файл пуст." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "Загрузите правильное изображение. Файл, который вы загрузили, поврежден или не является изображением." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Сортировка" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "по возрастанию" #: filters.py:288 msgid "descending" msgstr "по убыванию" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:449 msgid "Invalid value." msgstr "Введите правильное значение." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Фильтры" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "" #: validators.py:39 msgid "This field must be unique." msgstr "Значения поля должны быть уникальны." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "" ================================================ FILE: rest_framework/locale/sk/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Stanislav Komanec , 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" "PO-Revision-Date: 2020-10-13 19:45+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Slovak (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/sk/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: sk\n" "Plural-Forms: nplurals=4; plural=(n % 1 == 0 && n == 1 ? 0 : n % 1 == 0 && n >= 2 && n <= 4 ? 1 : n % 1 != 0 ? 2: 3);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Nesprávna hlavička. Neboli poskytnuté prihlasovacie údaje." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Nesprávna hlavička. Prihlasovacie údaje nesmú obsahovať medzery." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Nesprávna hlavička. Prihlasovacie údaje nie sú správne zakódované pomocou metódy base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Nesprávne prihlasovacie údaje." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Daný používateľ je neaktívny, alebo zmazaný." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Nesprávna token hlavička. Neboli poskytnuté prihlasovacie údaje." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Nesprávna token hlavička. Token hlavička nesmie obsahovať medzery." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "Nesprávny token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:13 msgid "Key" msgstr "" #: authtoken/models.py:16 msgid "User" msgstr "" #: authtoken/models.py:18 msgid "Created" msgstr "" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "" #: authtoken/models.py:28 msgid "Tokens" msgstr "" #: authtoken/serializers.py:9 msgid "Username" msgstr "" #: authtoken/serializers.py:13 msgid "Password" msgstr "" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "S danými prihlasovacími údajmi nebolo možné sa prihlásiť." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Musí obsahovať parametre \"používateľské meno\" a \"heslo\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Vyskytla sa chyba na strane servera." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Požiadavok má nesprávny formát, alebo je poškodený." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Nesprávne prihlasovacie údaje." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Prihlasovacie údaje neboli zadané." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "K danej akcii nemáte oprávnenie." #: exceptions.py:185 msgid "Not found." msgstr "Nebolo nájdené." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metóda \"{method}\" nie je povolená." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Nie je možné vyhovieť požiadavku v hlavičke \"Accept\"." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Požiadavok obsahuje nepodporovaný media type: \"{media_type}\"." #: exceptions.py:223 msgid "Request was throttled." msgstr "Požiadavok bol obmedzený, z dôvodu prekročenia limitu." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Toto pole je povinné." #: fields.py:317 msgid "This field may not be null." msgstr "Toto pole nemôže byť nulové." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Toto pole nemože byť prázdne." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Uistite sa, že toto pole nemá viac ako {max_length} znakov." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Uistite sa, že toto pole má viac ako {min_length} znakov." #: fields.py:816 msgid "Enter a valid email address." msgstr "Vložte správnu emailovú adresu." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Toto pole nezodpovedá požadovanému formátu." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Zadajte platný \"slug\", ktorý obsahuje len malé písmená, čísla, spojovník alebopodtržítko." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Zadajte platnú URL adresu." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:931 msgid "A valid integer is required." msgstr "Je vyžadované celé číslo." #: 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 "Uistite sa, že hodnota je menšia alebo rovná {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 "Uistite sa, že hodnota je väčšia alebo rovná {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Zadaný textový reťazec je príliš dlhý." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Je vyžadované číslo." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Uistite sa, že hodnota neobsahuje viac ako {max_digits} cifier." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Uistite sa, že hodnota neobsahuje viac ako {max_decimal_places} desatinných miest." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Uistite sa, že hodnota neobsahuje viac ako {max_whole_digits} cifier pred desatinnou čiarkou." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Nesprávny formát dátumu a času. Prosím použite jeden z nasledujúcich formátov: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Vložený len dátum - date namiesto dátumu a času - datetime." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Nesprávny formát dátumu. Prosím použite jeden z nasledujúcich formátov: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Vložený dátum a čas - datetime namiesto jednoduchého dátumu - date." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Nesprávny formát času. Prosím použite jeden z nasledujúcich formátov: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" je nesprávny výber z daných možností." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "" #: 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 "Bol očakávaný zoznam položiek, no namiesto toho bol nájdený \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "Nebol odoslaný žiadny súbor." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Odoslané dáta neobsahujú súbor. Prosím skontrolujte kódovanie - encoding type daného formuláru." #: fields.py:1516 msgid "No filename could be determined." msgstr "Nebolo možné určiť meno súboru." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Odoslaný súbor je prázdny." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Uistite sa, že meno súboru neobsahuje viac ako {max_length} znakov. (V skutočnosti ich má {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Uploadujte prosím obrázok. Súbor, ktorý ste uploadovali buď nie je obrázok, alebo daný obrázok je poškodený." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Bol očakávaný slovník položiek, no namiesto toho bol nájdený \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "" #: filters.py:288 msgid "descending" msgstr "" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Nesprávny kurzor." #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Nesprávny primárny kľúč \"{pk_value}\" - objekt s daným primárnym kľúčom neexistuje." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Nesprávny typ. Bol prijatý {data_type} namiesto primárneho kľúča." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Nesprávny hypertextový odkaz - žiadna zhoda." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Nesprávny hypertextový odkaz - chybná URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Nesprávny hypertextový odkaz - požadovný objekt neexistuje." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Nesprávny typ {data_type}. Požadovaný typ: hypertextový odkaz." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekt, ktorého atribút \"{slug_name}\" je \"{value}\" neexistuje." #: relations.py:449 msgid "Invalid value." msgstr "Nesprávna hodnota." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Bol očakávaný slovník položiek, no namiesto toho bol nájdený \"{datatype}\"." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "" #: validators.py:39 msgid "This field must be unique." msgstr "Táto položka musí byť unikátna." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Dané položky: {field_names} musia tvoriť musia spolu tvoriť unikátnu množinu." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Položka musí byť pre špecifický deň \"{date_field}\" unikátna." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Položka musí byť pre mesiac \"{date_field}\" unikátna." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Položka musí byť pre rok \"{date_field}\" unikátna." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Nesprávna verzia v \"Accept\" hlavičke." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Nesprávna verzia v URL adrese." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Nesprávna verzia v \"hostname\"." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Nesprávna verzia v parametri požiadavku." ================================================ FILE: rest_framework/locale/sl/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Gregor Cimerman, 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Slovenian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/sl/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: sl\n" "Plural-Forms: nplurals=4; plural=(n%100==1 ? 0 : n%100==2 ? 1 : n%100==3 || n%100==4 ? 2 : 3);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Napačno enostavno zagalvje. Ni podanih poverilnic." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Napačno enostavno zaglavje. Poverilniški niz ne sme vsebovati presledkov." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Napačno enostavno zaglavje. Poverilnice niso pravilno base64 kodirane." #: authentication.py:101 msgid "Invalid username/password." msgstr "Napačno uporabniško ime ali geslo." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Uporabnik neaktiven ali izbrisan." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Neveljaven žeton v zaglavju. Ni vsebovanih poverilnic." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Neveljaven žeton v zaglavju. Žeton ne sme vsebovati presledkov." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Neveljaven žeton v zaglavju. Žeton ne sme vsebovati napačnih znakov." #: authentication.py:203 msgid "Invalid token." msgstr "Neveljaven žeton." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Prijavni žeton" #: authtoken/models.py:13 msgid "Key" msgstr "Ključ" #: authtoken/models.py:16 msgid "User" msgstr "Uporabnik" #: authtoken/models.py:18 msgid "Created" msgstr "Ustvarjen" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Žeton" #: authtoken/models.py:28 msgid "Tokens" msgstr "Žetoni" #: authtoken/serializers.py:9 msgid "Username" msgstr "Uporabniško ime" #: authtoken/serializers.py:13 msgid "Password" msgstr "Geslo" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Neuspešna prijava s podanimi poverilnicami." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Mora vsebovati \"uporabniško ime\" in \"geslo\"." #: exceptions.py:102 msgid "A server error occurred." msgstr "Napaka na strežniku." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Okvarjen zahtevek." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Napačni avtentikacijski podatki." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Avtentikacijski podatki niso bili podani." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Nimate dovoljenj za izvedbo te akcije." #: exceptions.py:185 msgid "Not found." msgstr "Ni najdeno" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metoda \"{method}\" ni dovoljena" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Ni bilo mogoče zagotoviti zaglavja Accept zahtevka." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Nepodprt medijski tip \"{media_type}\" v zahtevku." #: exceptions.py:223 msgid "Request was throttled." msgstr "Zahtevek je bil pridržan." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "To polje je obvezno." #: fields.py:317 msgid "This field may not be null." msgstr "To polje ne sme biti null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "To polje ne sme biti prazno." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "To polje ne sme biti daljše od {max_length} znakov." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "To polje mora vsebovati vsaj {min_length} znakov." #: fields.py:816 msgid "Enter a valid email address." msgstr "Vnesite veljaven elektronski naslov." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Ta vrednost ne ustreza zahtevanemu vzorcu." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Vnesite veljaven \"slug\", ki vsebuje črke, številke, podčrtaje ali vezaje." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Vnesite veljaven URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Vnesite veljaven IPv4 ali IPv6 naslov." #: fields.py:931 msgid "A valid integer is required." msgstr "Zahtevano je veljavno celo število." #: 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 "Vrednost mora biti manjša ali enaka {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 "Vrednost mora biti večija ali enaka {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Niz je prevelik." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Zahtevano je veljavno število." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Vnesete lahko največ {max_digits} števk." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Vnesete lahko največ {max_decimal_places} decimalnih mest." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Vnesete lahko največ {max_whole_digits} števk pred decimalno piko." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datim in čas v napačnem formatu. Uporabite eno izmed naslednjih formatov: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Pričakovan datum in čas, prejet le datum." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Datum je v napačnem formatu. Uporabnite enega izmed naslednjih: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Pričakovan datum vendar prejet datum in čas." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Čas je v napačnem formatu. Uporabite enega izmed naslednjih: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Trajanje je v napačnem formatu. Uporabite enega izmed naslednjih: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" ni veljavna izbira." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Več kot {count} elementov..." #: 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 "Pričakovan seznam elementov vendar prejet tip \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Ta izbria ne sme ostati prazna." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" ni veljavna izbira poti." #: fields.py:1514 msgid "No file was submitted." msgstr "Datoteka ni bila oddana." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Oddani podatki niso datoteka. Preverite vrsto kodiranja na formi." #: fields.py:1516 msgid "No filename could be determined." msgstr "Imena datoteke ni bilo mogoče določiti." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Oddana datoteka je prazna." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Ime datoteke lahko vsebuje največ {max_length} znakov (ta jih ima {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Naložite veljavno sliko. Naložena datoteka ni bila slika ali pa je okvarjena." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Seznam ne sme biti prazen." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Pričakovan je slovar elementov, prejet element je tipa \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Vrednost mora biti veljaven JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Iskanje" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Razvrščanje" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "naraščujoče" #: filters.py:288 msgid "descending" msgstr "padajoče" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Neveljavna stran." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Neveljaven kazalec" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Neveljaven pk \"{pk_value}\" - objekt ne obstaja." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Neveljaven tip. Pričakovana vrednost pk, prejet {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Neveljavna povezava - Ni URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Ni veljavna povezava - Napačen URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Ni veljavna povezava - Objekt ne obstaja." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Napačen tip. Pričakovan URL niz, prejet {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekt z {slug_name}={value} ne obstaja." #: relations.py:449 msgid "Invalid value." msgstr "Neveljavna vrednost." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Napačni podatki. Pričakovan slovar, prejet {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtri" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "None" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Ni elementov za izbiro." #: validators.py:39 msgid "This field must be unique." msgstr "To polje mora biti unikatno." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Polja {field_names} morajo skupaj sestavljati unikaten niz." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Polje mora biti unikatno za \"{date_field}\" dan." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Polje mora biti unikatno za \"{date_field} mesec.\"" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Polje mora biti unikatno za \"{date_field}\" leto." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Neveljavna verzija v \"Accept\" zaglavju." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Neveljavna različca v poti URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Neveljavna različica v poti URL. Se ne ujema z nobeno različico imenskega prostora." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Neveljavna različica v imenu gostitelja." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Neveljavna verzija v poizvedbenem parametru." ================================================ FILE: rest_framework/locale/sv/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Frank Wickström , 2015 # Joakim Soderlund, 2015-2016 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Swedish (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/sv/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: sv\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Ogiltig \"basic\"-header. Inga användaruppgifter tillhandahölls." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Ogiltig \"basic\"-header. Strängen för användaruppgifterna ska inte innehålla mellanslag." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Ogiltig \"basic\"-header. Användaruppgifterna är inte korrekt base64-kodade." #: authentication.py:101 msgid "Invalid username/password." msgstr "Ogiltigt användarnamn/lösenord." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Användaren borttagen eller inaktiv." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Ogiltig \"token\"-header. Inga användaruppgifter tillhandahölls." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Ogiltig \"token\"-header. Strängen ska inte innehålla mellanslag." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Ogiltig \"token\"-header. Strängen ska inte innehålla ogiltiga tecken." #: authentication.py:203 msgid "Invalid token." msgstr "Ogiltig \"token\"." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Autentiseringstoken" #: authtoken/models.py:13 msgid "Key" msgstr "Nyckel" #: authtoken/models.py:16 msgid "User" msgstr "Användare" #: authtoken/models.py:18 msgid "Created" msgstr "Skapad" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "Användarnamn" #: authtoken/serializers.py:13 msgid "Password" msgstr "Lösenord" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Kunde inte logga in med de angivna inloggningsuppgifterna." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Användarnamn och lösenord måste anges." #: exceptions.py:102 msgid "A server error occurred." msgstr "Ett serverfel inträffade." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Ogiltig förfrågan." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Ogiltiga inloggningsuppgifter. " #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Autentiseringsuppgifter ej tillhandahållna." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Du har inte tillåtelse att utföra denna förfrågan." #: exceptions.py:185 msgid "Not found." msgstr "Hittades inte." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Metoden \"{method}\" tillåts inte." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Kunde inte tillfredsställa förfrågans \"Accept\"-header." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Medietypen \"{media_type}\" stöds inte." #: exceptions.py:223 msgid "Request was throttled." msgstr "Förfrågan stoppades eftersom du har skickat för många." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Det här fältet är obligatoriskt." #: fields.py:317 msgid "This field may not be null." msgstr "Det här fältet får inte vara null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Det här fältet får inte vara blankt." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Se till att detta fält inte har fler än {max_length} tecken." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Se till att detta fält har minst {min_length} tecken." #: fields.py:816 msgid "Enter a valid email address." msgstr "Ange en giltig mejladress." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Det här värdet matchar inte mallen." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Ange en giltig \"slug\" bestående av bokstäver, nummer, understreck eller bindestreck." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Ange en giltig URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Ange en giltig IPv4- eller IPv6-adress." #: fields.py:931 msgid "A valid integer is required." msgstr "Ett giltigt heltal krävs." #: 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 "Se till att detta värde är mindre än eller lika med {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 "Se till att detta värde är större än eller lika med {min_value}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Textvärdet är för långt." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Ett giltigt nummer krävs." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Se till att det inte finns fler än totalt {max_digits} siffror." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Se till att det inte finns fler än {max_decimal_places} decimaler." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Se till att det inte finns fler än {max_whole_digits} siffror före decimalpunkten." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datumtiden har fel format. Använd ett av dessa format istället: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Förväntade en datumtid men fick ett datum." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Datumet har fel format. Använde ett av dessa format istället: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Förväntade ett datum men fick en datumtid." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Tiden har fel format. Använd ett av dessa format istället: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Perioden har fel format. Använd ett av dessa format istället: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" är inte ett giltigt val." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Fler än {count} objekt..." #: 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 "Förväntade en lista med element men fick typen \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Det här valet får inte vara tomt." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" är inte ett giltigt val för en sökväg." #: fields.py:1514 msgid "No file was submitted." msgstr "Ingen fil skickades." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Den skickade informationen var inte en fil. Kontrollera formulärets kodningstyp." #: fields.py:1516 msgid "No filename could be determined." msgstr "Inget filnamn kunde bestämmas." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Den skickade filen var tom." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Se till att det här filnamnet har högst {max_length} tecken (det har {length})." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Ladda upp en giltig bild. Filen du laddade upp var antingen inte en bild eller en skadad bild." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Den här listan får inte vara tom." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Förväntade en \"dictionary\" med element men fick typen \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Värdet måste vara giltig JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Sök" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Ordning" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "stigande" #: filters.py:288 msgid "descending" msgstr "fallande" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Ogiltig sida." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Ogiltig cursor." #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Ogiltigt pk \"{pk_value}\" - Objektet finns inte." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Felaktig typ. Förväntade pk-värde, fick {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Ogiltig hyperlänk - Ingen URL matchade." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Ogiltig hyperlänk - Felaktig URL-matching." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Ogiltig hyperlänk - Objektet finns inte." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Felaktig typ. Förväntade URL-sträng, fick {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Objekt med {slug_name}={value} finns inte." #: relations.py:449 msgid "Invalid value." msgstr "Ogiltigt värde." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Ogiltig data. Förväntade en dictionary, men fick {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filter" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Inget" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Inga valbara objekt." #: validators.py:39 msgid "This field must be unique." msgstr "Det här fältet måste vara unikt." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Fälten {field_names} måste skapa ett unikt set." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Det här fältet måste vara unikt för datumet \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Det här fältet måste vara unikt för månaden \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Det här fältet måste vara unikt för året \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Ogiltig version i \"Accept\"-headern." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Ogiltig version i URL-resursen." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Ogiltig version i URL-resursen. Matchar inget versions-namespace." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Ogiltig version i värdnamnet." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Ogiltig version i förfrågningsparametern." ================================================ FILE: rest_framework/locale/th/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Preeti Yuankrathok , 2018 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Thai (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/th/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: th\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:101 msgid "Invalid username/password." msgstr "ชื่อผู้ใช้งานหรือรหัสผ่านไม่ถูกต้อง" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "ผู้ใช้ไม่ได้เปิดใช้งานหรือถูกลบ" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "Token ไม่ถูกต้อง" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Auth Token" #: authtoken/models.py:13 msgid "Key" msgstr "คีย์" #: authtoken/models.py:16 msgid "User" msgstr "ผู้ใช้" #: authtoken/models.py:18 msgid "Created" msgstr "" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Token" #: authtoken/serializers.py:9 msgid "Username" msgstr "ชื่อผู้ใช้งาน" #: authtoken/serializers.py:13 msgid "Password" msgstr "รหัสผ่าน" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "ไม่สามารถเข้าสู่ระบบได้" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "จำเป็นต้องใส่ชื่อผู้ใช้งานและรหัสผ่าน" #: exceptions.py:102 msgid "A server error occurred." msgstr "เซิร์ฟเวอร์เกิดข้อผิดพลาด" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "ข้อมูลการเข้าสู่ระบบไม่ถูกต้อง" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "ไม่พบข้อมูลการเข้าสู่ระบบ" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "คุณไม่มีสิทธิ์ที่จะดำเนินการ" #: exceptions.py:185 msgid "Not found." msgstr "ไม่พบ" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "ไม่ใช่อนุญาติให้ใช้ Method \"{method}\"" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "ไม่รองรับมีเดียประเภท \"{media_type}\" ใน Request" #: exceptions.py:223 msgid "Request was throttled." msgstr "" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "ฟิลด์นี้จำเป็น" #: fields.py:317 msgid "This field may not be null." msgstr "ฟิลด์นี้จำเป็นต้องมีค่า" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "ฟิลด์นี้ไม่สามารถเว้นว่างได้" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "ตรวจสอบฟิลด์ว่ามีความยาวไม่เกิน {max_length} ตัวอักษร" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "ตรวตสอบฟิลด์ว่ามีความยาวอย่างน้อย {min_length} ตัวอักษร" #: fields.py:816 msgid "Enter a valid email address." msgstr "กรอกอีเมลให้ถูกต้อง" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "ค่านี้ไม่ตรงกับรูปแบบที่ต้องการ" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "กรอกข้อมูลที่ประกอบด้วยตัวอักษร ตัวเลข สัญประกาศ และยัติภังค์เท่านั้น" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "กรอก URL ให้ถูกต้อง" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "กรอก IPv4 หรือ IPv6 ให้ถูกต้อง" #: fields.py:931 msgid "A valid integer is required." 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}" #: 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}" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "ข้อความยาวเกินไป" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "ต้องการตัวเลขที่ถูกต้อง" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "ตรวจสอบตัวเลขว่ามีไม่เกิน {max_digits} ตัว" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "ตรวจสอบทศนิยมว่ามีไม่เกิน {max_decimal_places} หลัก" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "ตรวจสอบตัวเลขและทศนิยมรวมกันว่ามีไม่เกิน {max_whole_digits} ตัว" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "รูปแบบวันที่และเวลาไม่ถูกต้อง โปรดใช้รูปแบบใดรูปแบบหนึ่งจาก: {format}" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "ต้องการวันที่และเวลา แต่ได้รับเพียงวันที่" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "รูปแบบวันที่ไม่ถูกต้อง โปรดใช้รูปแบบใดรูปแบบหนึ่งจาก: {format}" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "ต้องการวันที่ แต่ได้รับวันที่และเวลา" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "รูปแบบเวลาไม่ถูกต้อง โปรดใช้รูปแบบใดรูปแบบหนึ่งจาก: {format}" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "รูปแบบระยะเวลาไม่ถูกต้อง โปรดใช้รูปแบบใดรูปแบบหนึ่งจาก: {format}" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" ไม่ใช่ตัวเลือกที่ถูกต้อง" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "มีมากกว่า {count} ไอเทม..." #: 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 "ต้องการ List ของข้อมูล แต่ได้รับ \"{input_type}\"" #: fields.py:1458 msgid "This selection may not be empty." msgstr "" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "ไม่พบไฟล์" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "ข้อมูลที่ส่งไม่ใช่ไฟล์ โปรดตรวจสอบการเข้ารหัสของฟอร์ม" #: fields.py:1516 msgid "No filename could be determined." msgstr "ไม่สามารถระบุชื่อไฟล์ได้" #: fields.py:1517 msgid "The submitted file is empty." msgstr "ไฟล์ที่ส่งว่างเปล่า" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "List นี้ไม่สามารถว่างได้" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "ต้องการ Dictionary แต่ได้รับ \"{input_type}\"" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "ค่าจะต้องเป็น JSON ที่ถูกต้อง" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "ค้นหา" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "การเรียงลำดับ" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "น้อยไปมาก" #: filters.py:288 msgid "descending" msgstr "มากไปน้อย" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "หน้าไม่ถูกต้อง" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "เคอร์เซอร์ไม่ถูกต้อง" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:449 msgid "Invalid value." msgstr "ค่าไม่ถูกต้อง" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "ข้อมูลไม่ถูกต้อง ต้องการ Dictionary แต่ได้รับ {datatype}" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "การกรองข้อมูล" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "ไม่มี" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "" #: validators.py:39 msgid "This field must be unique." msgstr "" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "" ================================================ FILE: rest_framework/locale/tr/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Dogukan Tufekci , 2015 # Emrah BİLBAY , 2015 # Ertaç Paprat , 2015 # José Luis , 2016 # Mesut Can Gürle , 2015 # Murat Çorlu , 2015 # Recep KIRMIZI , 2015 # Ülgen Sarıkavak , 2015 # Sezer BOZKIR , 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Turkish (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/tr/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: tr\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Geçersiz yetkilendirme başlığı. Gerekli uygunluk kriterleri sağlanmamış." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Geçersiz yetkilendirme başlığı. Uygunluk kriterine ait veri boşluk karakteri içermemeli." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Geçersiz yetkilendirme başlığı. Uygunluk kriterleri base64 formatına uygun olarak kodlanmamış." #: authentication.py:101 msgid "Invalid username/password." msgstr "Geçersiz kullanıcı adı/parola" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Kullanıcı aktif değil ya da silinmiş." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Geçersiz token başlığı. Kimlik bilgileri eksik." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Geçersiz token başlığı. Token'da boşluk olmamalı." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Geçersiz token başlığı. Token geçersiz karakter içermemeli." #: authentication.py:203 msgid "Invalid token." msgstr "Geçersiz token." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Kimlik doğrulama belirteci" #: authtoken/models.py:13 msgid "Key" msgstr "Anahtar" #: authtoken/models.py:16 msgid "User" msgstr "Kullanan" #: authtoken/models.py:18 msgid "Created" msgstr "Oluşturulan" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "İşaret" #: authtoken/models.py:28 msgid "Tokens" msgstr "İşaretler" #: authtoken/serializers.py:9 msgid "Username" msgstr "Kullanıcı adı" #: authtoken/serializers.py:13 msgid "Password" msgstr "Şifre" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Verilen bilgiler ile giriş sağlanamadı." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"Kullanıcı Adı\" ve \"Parola\" eklenmeli." #: exceptions.py:102 msgid "A server error occurred." msgstr "Sunucu hatası oluştu." #: exceptions.py:142 msgid "Invalid input." msgstr "Geçersiz girdi." #: exceptions.py:161 msgid "Malformed request." msgstr "Bozuk istek." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Giriş bilgileri hatalı." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Giriş bilgileri verilmedi." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Bu işlemi yapmak için izniniz bulunmuyor." #: exceptions.py:185 msgid "Not found." msgstr "Bulunamadı." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "\"{method}\" metoduna izin verilmiyor." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "İsteğe ait Accept başlık bilgisi yanıt verilecek başlık bilgileri arasında değil." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "İstekte desteklenmeyen medya tipi: \"{media_type}\"." #: exceptions.py:223 msgid "Request was throttled." msgstr "Üst üste çok fazla istek yapıldı." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "{wait} saniye içinde erişilebilir olması bekleniyor." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "{wait} saniye içinde erişilebilir olması bekleniyor." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Bu alan zorunlu." #: fields.py:317 msgid "This field may not be null." msgstr "Bu alan boş bırakılmamalı." #: fields.py:701 msgid "Must be a valid boolean." msgstr "Geçerli bir boolean olmalı." #: fields.py:766 msgid "Not a valid string." msgstr "Geçerli bir string değil." #: fields.py:767 msgid "This field may not be blank." msgstr "Bu alan boş bırakılmamalı." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Bu alanın {max_length} karakterden fazla karakter barındırmadığından emin olun." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Bu alanın en az {min_length} karakter barındırdığından emin olun." #: fields.py:816 msgid "Enter a valid email address." msgstr "Geçerli bir e-posta adresi girin." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Bu değer gereken düzenli ifade deseni ile uyuşmuyor." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Harf, rakam, altçizgi veya tireden oluşan geçerli bir \"slug\" giriniz." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Geçerli bir URL girin." #: fields.py:867 msgid "Must be a valid UUID." msgstr "Geçerli bir UUID olmalı." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Geçerli bir IPv4 ya da IPv6 adresi girin." #: fields.py:931 msgid "A valid integer is required." msgstr "Geçerli bir tam sayı girin." #: 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 "Değerin {max_value} değerinden küçük ya da eşit olduğundan emin olun." #: 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 "Değerin {min_value} değerinden büyük ya da eşit olduğundan emin olun." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "String değeri çok uzun." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Geçerli bir numara gerekiyor." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Toplamda {max_digits} haneden fazla hane olmadığından emin olun." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Ondalık basamak değerinin {max_decimal_places} haneden fazla olmadığından emin olun." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Ondalık ayracından önce {max_whole_digits} basamaktan fazla olmadığından emin olun." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime alanı yanlış biçimde. {format} biçimlerinden birini kullanın." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Datetime değeri bekleniyor, ama date değeri geldi." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "\"{timezone}\" zaman dilimi için geçersiz datetime." #: fields.py:1151 msgid "Datetime value out of range." msgstr "Datetime değeri aralığın dışında." #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Tarih biçimi yanlış. {format} biçimlerinden birini kullanın." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Date tipi beklenmekteydi, fakat datetime tipi geldi." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Time biçimi yanlış. {format} biçimlerinden birini kullanın." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Duration biçimi yanlış. {format} biçimlerinden birini kullanın." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" geçerli bir seçim değil." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "{count} elemandan daha fazla..." #: 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 "Elemanların listesi beklenirken \"{input_type}\" alındı." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Bu seçim boş bırakılmamalı." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" geçerli bir yol seçimi değil." #: fields.py:1514 msgid "No file was submitted." msgstr "Hiçbir dosya verilmedi." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Gönderilen veri dosya değil. Formdaki kodlama tipini kontrol edin." #: fields.py:1516 msgid "No filename could be determined." msgstr "Hiçbir dosya adı belirlenemedi." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Gönderilen dosya boş." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Bu dosya adının en fazla {max_length} karakter uzunluğunda olduğundan emin olun. (şu anda {length} karakter)." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Geçerli bir resim yükleyin. Yüklediğiniz dosya resim değil ya da bozuk." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Bu liste boş olmamalı." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "Bu alanın en az {min_length} eleman içerdiğinden emin olun." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "Bu alanın en fazla {max_length} eleman içerdiğinden emin olun." #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Sözlük tipi bir değişken beklenirken \"{input_type}\" tipi bir değişken alındı." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "Bu sözlük boş olmamalı." #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Değer geçerli bir JSON olmalı." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Arama" #: filters.py:50 msgid "A search term." msgstr "Bir arama terimi." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sıralama" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "Sonuçların sıralanmasında kullanılacak alan." #: filters.py:287 msgid "ascending" msgstr "artan" #: filters.py:288 msgid "descending" msgstr "azalan" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "Sayfalanmış sonuç kümesinde bir sayfa numarası." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "Her sayfada döndürülecek sonuç sayısı." #: pagination.py:189 msgid "Invalid page." msgstr "Geçersiz sayfa." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "Döndürülecek sonuçların başlangıç indeksi." #: pagination.py:581 msgid "The pagination cursor value." msgstr "Sayfalandırma imleci değeri." #: pagination.py:583 msgid "Invalid cursor" msgstr "Sayfalandırma imleci geçersiz" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Geçersiz pk \"{pk_value}\" - obje bulunamadı." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Hatalı tip. Pk değeri beklenirken, alınan {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Geçersiz bağlantı - Hiçbir URL eşleşmedi." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Geçersiz bağlantı - Yanlış URL eşleşmesi." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Geçersiz bağlantı - Obje bulunamadı." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Hatalı tip. URL metni bekleniyor, {data_type} alındı." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} değerini taşıyan obje bulunamadı." #: relations.py:449 msgid "Invalid value." msgstr "Geçersiz değer." #: schemas/utils.py:32 msgid "unique integer value" msgstr "benzersiz tamsayı değeri" #: schemas/utils.py:34 msgid "UUID string" msgstr "UUID metni" #: schemas/utils.py:36 msgid "unique value" msgstr "benzersiz değer" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "Bir {name} öğesini tanımlayan {value_type}." #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Geçersiz veri. Sözlük bekleniyordu fakat {datatype} geldi. " #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "Ekstra Eylemler" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtreler" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "navigasyon çubuğu" #: templates/rest_framework/base.html:75 msgid "content" msgstr "içerik" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "istek formu" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "ana içerik" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "istek bilgisi" #: templates/rest_framework/base.html:177 msgid "response info" msgstr "cevap bilgisi" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 #: templates/rest_framework/vertical/radio.html:3 msgid "None" msgstr "Hiçbiri" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Seçenek yok." #: validators.py:39 msgid "This field must be unique." msgstr "Bu alan eşsiz olmalı." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "{field_names} hep birlikte eşsiz bir küme oluşturmalılar." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "Yerine konulmuş karakterlere izin verilmiyor: U+{code_point:X}." #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Bu alan \"{date_field}\" tarihine göre eşsiz olmalı." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Bu alan \"{date_field}\" ayına göre eşsiz olmalı." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Bu alan \"{date_field}\" yılına göre eşsiz olmalı." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Accept\" başlığındaki sürüm geçersiz." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URL dizininde geçersiz versiyon." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Geçersiz versiyon URL dizininde. Hiçbir versiyon ad alanı ile eşleşmiyor." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Host adında geçersiz versiyon." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Sorgu parametresinde geçersiz versiyon." ================================================ FILE: rest_framework/locale/tr_TR/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Deniz , 2019 # José Luis , 2015-2016 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Turkish (Turkey) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/tr_TR/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: tr_TR\n" "Plural-Forms: nplurals=2; plural=(n > 1);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Geçersiz yetkilendirme başlığı. Gerekli uygunluk kriterleri sağlanmamış." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Geçersiz yetkilendirme başlığı. Uygunluk kriterine ait veri boşluk karakteri içermemeli." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Geçersiz yetkilendirme başlığı. Uygunluk kriterleri base64 formatına uygun olarak kodlanmamış." #: authentication.py:101 msgid "Invalid username/password." msgstr "Geçersiz kullanıcı adı / şifre." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Kullanıcı aktif değil ya da silinmiş" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Geçersiz token başlığı. Kimlik bilgileri eksik." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Geçersiz token başlığı. Token'da boşluk olmamalı." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Geçersiz token başlığı. Token geçersiz karakter içermemeli." #: authentication.py:203 msgid "Invalid token." msgstr "Geçersiz simge." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Kimlik doğrulama belirteci" #: authtoken/models.py:13 msgid "Key" msgstr "Anahtar" #: authtoken/models.py:16 msgid "User" msgstr "Kullanan" #: authtoken/models.py:18 msgid "Created" msgstr "Oluşturulan" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "İşaret" #: authtoken/models.py:28 msgid "Tokens" msgstr "İşaretler" #: authtoken/serializers.py:9 msgid "Username" msgstr "Kullanıcı adı" #: authtoken/serializers.py:13 msgid "Password" msgstr "Şifre" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Verilen bilgiler ile giriş sağlanamadı." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "\"Kullanıcı Adı\" ve \"Parola\" eklenmeli." #: exceptions.py:102 msgid "A server error occurred." msgstr "Sunucu hatası oluştu." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Bozuk istek." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Giriş bilgileri hatalı." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Giriş bilgileri verilmedi." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Bu işlemi yapmak için izniniz bulunmuyor." #: exceptions.py:185 msgid "Not found." msgstr "Bulunamadı." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "\"{method}\" metoduna izin verilmiyor." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "İsteğe ait Accept başlık bilgisi yanıt verilecek başlık bilgileri arasında değil." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "İstekte desteklenmeyen medya tipi: \"{media_type}\"." #: exceptions.py:223 msgid "Request was throttled." msgstr "Üst üste çok fazla istek yapıldı." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Bu alan zorunlu." #: fields.py:317 msgid "This field may not be null." msgstr "Bu alan boş bırakılmamalı." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Bu alan boş bırakılmamalı." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Bu alanın {max_length} karakterden fazla karakter barındırmadığından emin olun." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Bu alanın en az {min_length} karakter barındırdığından emin olun." #: fields.py:816 msgid "Enter a valid email address." msgstr "Geçerli bir e-posta adresi girin." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Bu değer gereken düzenli ifade deseni ile uyuşmuyor." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Harf, rakam, altçizgi veya tireden oluşan geçerli bir \"slug\" giriniz." #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Geçerli bir URL girin." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Geçerli bir IPv4 ya da IPv6 adresi girin." #: fields.py:931 msgid "A valid integer is required." msgstr "Geçerli bir tam sayı girin." #: 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 "Değerin {max_value} değerinden küçük ya da eşit olduğundan emin olun." #: 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 "Değerin {min_value} değerinden büyük ya da eşit olduğundan emin olun." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "String değeri çok uzun." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Geçerli bir numara gerekiyor." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Toplamda {max_digits} haneden fazla hane olmadığından emin olun." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Ondalık basamak değerinin {max_decimal_places} haneden fazla olmadığından emin olun." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Ondalık ayracından önce {max_whole_digits} basamaktan fazla olmadığından emin olun." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Datetime alanı yanlış biçimde. {format} biçimlerinden birini kullanın." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Datetime değeri bekleniyor, ama date değeri geldi." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Tarih biçimi yanlış. {format} biçimlerinden birini kullanın." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Date tipi beklenmekteydi, fakat datetime tipi geldi." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Time biçimi yanlış. {format} biçimlerinden birini kullanın." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Duration biçimi yanlış. {format} biçimlerinden birini kullanın." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" geçerli bir seçim değil." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "{count} elemandan daha fazla..." #: 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 "Elemanların listesi beklenirken \"{input_type}\" alındı." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Bu seçim boş bırakılmamalı." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" geçerli bir yol seçimi değil." #: fields.py:1514 msgid "No file was submitted." msgstr "Hiçbir dosya verilmedi." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Gönderilen veri dosya değil. Formdaki kodlama tipini kontrol edin." #: fields.py:1516 msgid "No filename could be determined." msgstr "Hiçbir dosya adı belirlenemedi." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Gönderilen dosya boş." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "Bu dosya adının en fazla {max_length} karakter uzunluğunda olduğundan emin olun. (şu anda {length} karakter)." #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "Geçerli bir resim yükleyin. Yüklediğiniz dosya resim değil ya da bozuk." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Bu liste boş olmamalı." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Sözlük tipi bir değişken beklenirken \"{input_type}\" tipi bir değişken alındı." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Değer geçerli bir JSON olmalı." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Arama" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sıralama" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "artan" #: filters.py:288 msgid "descending" msgstr "azalan" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Geçersiz sayfa." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Geçersiz imleç." #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Geçersiz pk \"{pk_value}\" - obje bulunamadı." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Hatalı tip. Pk değeri beklenirken, alınan {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Geçersiz hyper link - URL maçı yok." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Geçersiz hyper link - Yanlış URL maçı." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Geçersiz hyper link - Nesne yok.." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Hatalı tip. URL metni bekleniyor, {data_type} alındı." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "{slug_name}={value} değerini taşıyan obje bulunamadı." #: relations.py:449 msgid "Invalid value." msgstr "Geçersiz değer." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Geçersiz veri. Bir sözlük bekleniyor, ama var {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Filtreler" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Hiç kimse" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Seçenek yok." #: validators.py:39 msgid "This field must be unique." msgstr "Bu alan benzersiz olmalıdır." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "{field_names} alanları benzersiz bir set yapmak gerekir." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Bu alan \"{date_field}\" tarihine göre eşsiz olmalı." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Bu alan \"{date_field}\" ayına göre eşsiz olmalı." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Bu alan \"{date_field}\" yılına göre eşsiz olmalı." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "\"Kabul et\" başlığında geçersiz sürümü." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URL yolunda geçersiz sürüm." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "URL yolunda geçersiz sürüm. Sürüm adlarında eşleşen bulunamadı." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Hostname geçersiz sürümü." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Sorgu parametresi geçersiz sürümü." ================================================ FILE: rest_framework/locale/uk/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Denis Podlesniy , 2016 # Illarion , 2016 # Kirill Tarasenko, 2016,2018 # Victor Mireyev , 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Ukrainian (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/uk/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: uk\n" "Plural-Forms: nplurals=4; plural=(n % 1 == 0 && n % 10 == 1 && n % 100 != 11 ? 0 : n % 1 == 0 && n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 12 || n % 100 > 14) ? 1 : n % 1 == 0 && (n % 10 ==0 || (n % 10 >=5 && n % 10 <=9) || (n % 100 >=11 && n % 100 <=14 )) ? 2: 3);\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "Недійсний основний заголовок. Облікові дані відсутні." #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "Недійсний основний заголовок. Строка з обліковими даними має бути без пробілів." #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "Недійсний основний заголовок. Облікові дані невірно закодовані у base64." #: authentication.py:101 msgid "Invalid username/password." msgstr "Недійсне iм'я користувача/пароль." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Користувач неактивний або видалений." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "Недійсний токен. Облікові дані відсутні." #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "Недійсний токен. Значення токена не повинне містити пробіли." #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "Недійсний токен. Значення токена не повинне містити некоректні символи." #: authentication.py:203 msgid "Invalid token." msgstr "Недійсний токен." #: authtoken/apps.py:7 msgid "Auth Token" msgstr "Авторизаційний токен" #: authtoken/models.py:13 msgid "Key" msgstr "Ключ" #: authtoken/models.py:16 msgid "User" msgstr "Користувач" #: authtoken/models.py:18 msgid "Created" msgstr "Створено" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Токен" #: authtoken/models.py:28 msgid "Tokens" msgstr "Токени" #: authtoken/serializers.py:9 msgid "Username" msgstr "Ім'я користувача" #: authtoken/serializers.py:13 msgid "Password" msgstr "Пароль" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Неможливо зайти з введеними даними." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Має включати iм'я користувача та пароль" #: exceptions.py:102 msgid "A server error occurred." msgstr "Помилка сервера." #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "Некоректний запит." #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "Некоректні реквізити перевірки достовірності." #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "Реквізити перевірки достовірності не надані." #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "У вас нема дозволу робити цю дію." #: exceptions.py:185 msgid "Not found." msgstr "Не знайдено." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Метод \"{method}\" не дозволений." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "Неможливо виконати запит заголовку Accept." #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "Непідтримуваний тип даних \"{media_type}\" в запиті." #: exceptions.py:223 msgid "Request was throttled." msgstr "Запит було проігноровано." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "Це поле обов'язкове." #: fields.py:317 msgid "This field may not be null." msgstr "Це поле не може бути null." #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Це поле не може бути порожнім." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "Переконайтесь, що кількість символів в цьому полі не перевищує {max_length}." #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "Переконайтесь, що в цьому полі мінімум {min_length} символів." #: fields.py:816 msgid "Enter a valid email address." msgstr "Введіть коректну адресу електронної пошти." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "Значення не відповідає необхідному патерну." #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "Введіть коректний \"slug\", що складається із букв, цифр, нижніх підкреслень або дефісів. " #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "Введіть коректний URL." #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "Введіть коректну IPv4 або IPv6 адресу." #: fields.py:931 msgid "A valid integer is required." 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}." #: 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}." #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "Строкове значення занадто велике." #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "Необхідне чисельне значення." #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "Переконайтесь, що в числі не більше {max_digits} знаків." #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "Переконайтесь, що в числі не більше {max_decimal_places} знаків у дробовій частині." #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "Переконайтесь, що в числі не більше {max_whole_digits} знаків у цілій частині." #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "Невірний формат дата з часом. Використайте один з цих форматів: {format}." #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "Очікувалась дата з часом, але було отримано дату." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Невірний формат дати. Використайте один з цих форматів: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "Очікувалась дата, але було отримано дату з часом." #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "Неправильний формат часу. Використайте один з цих форматів: {format}." #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "Невірний формат тривалості. Використайте один з цих форматів: {format}." #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" не є коректним вибором." #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "Елементів більше, ніж {count}..." #: 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 "Очікувався список елементів, але було отримано \"{input_type}\"." #: fields.py:1458 msgid "This selection may not be empty." msgstr "Вибір не може бути порожнім." #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\" вибраний шлях не є коректним." #: fields.py:1514 msgid "No file was submitted." msgstr "Файл не було відправленно." #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "Відправленні дані не є файл. Перевірте тип кодування у формі." #: fields.py:1516 msgid "No filename could be determined." msgstr "Неможливо визначити ім'я файлу." #: fields.py:1517 msgid "The submitted file is empty." msgstr "Відправленний файл порожній." #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "Завантажте коректне зображення. Завантажений файл або не є зображенням, або пошкоджений." #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "Цей список не може бути порожнім." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "Очікувався словник зі елементами, але було отримано \"{input_type}\"." #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Значення повинно бути коректним JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Пошук" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Впорядкування" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "у порядку зростання" #: filters.py:288 msgid "descending" msgstr "у порядку зменшення" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "Недійсна сторінка." #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "Недійсний курсор." #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "Недопустимий первинний ключ \"{pk_value}\" - об'єкт не існує." #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "Некоректний тип. Очікувалось значення первинного ключа, отримано {data_type}." #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "Недійсне посилання - немає збігу за URL." #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "Недійсне посилання - некоректний збіг за URL." #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "Недійсне посилання - об'єкт не існує." #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "Некоректний тип. Очікувався URL, отримано {data_type}." #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "Об'єкт із {slug_name}={value} не існує." #: relations.py:449 msgid "Invalid value." msgstr "Недійсне значення." #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "Недопустимі дані. Очікувався словник, але було отримано {datatype}." #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "Фільтри" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "Нічого" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Немає елементів для вибору." #: validators.py:39 msgid "This field must be unique." msgstr "Це поле повинне бути унікальним." #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "Поля {field_names} повинні створювати унікальний масив значень." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "Це поле повинне бути унікальним для дати \"{date_field}\"." #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "Це поле повинне бути унікальним для місяця \"{date_field}\"." #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "Це поле повинне бути унікальним для року \"{date_field}\"." #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "Недопустима версія в загаловку \"Accept\"." #: versioning.py:71 msgid "Invalid version in URL path." msgstr "Недопустима версія в шляху URL." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "Недопустима версія в шляху URL. Не співпадає з будь-яким простором версій." #: versioning.py:148 msgid "Invalid version in hostname." msgstr "Недопустима версія в імені хоста." #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "Недопустима версія в параметрі запиту." ================================================ FILE: rest_framework/locale/vi/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Nguyen Tuan Anh , 2019 # Xavier Ordoquy , 2020 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 20:02+0000\n" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Vietnamese (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/vi/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: vi\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:101 msgid "Invalid username/password." msgstr "Sai tên đăng nhập hoặc mật khẩu." #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "Người dùng không còn hoạt động, hoặc đã bị xoá." #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:13 msgid "Key" msgstr "Khoá" #: authtoken/models.py:16 msgid "User" msgstr "Người dùng" #: authtoken/models.py:18 msgid "Created" msgstr "Đã tạo" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "" #: authtoken/models.py:28 msgid "Tokens" msgstr "" #: authtoken/serializers.py:9 msgid "Username" msgstr "Tên người dùng" #: authtoken/serializers.py:13 msgid "Password" msgstr "Mật khẩu" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "Không thể đăng nhập với thông tin đã nhập." #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "Bắt buộc phải có “tên người dùng” và “mật khẩu”." #: exceptions.py:102 msgid "A server error occurred." msgstr "" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "Bạn không được cấp quyền để thực hiện hành động này." #: exceptions.py:185 msgid "Not found." msgstr "Không tìm thấy." #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "Phương thức “{method}” không được chấp nhận." #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:223 msgid "Request was throttled." msgstr "" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "" #: fields.py:317 msgid "This field may not be null." msgstr "" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "Trường này không được bỏ trống." #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:816 msgid "Enter a valid email address." msgstr "Nhập một địa chỉ email hợp lệ." #: fields.py:827 msgid "This value does not match the required pattern." msgstr "" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:931 msgid "A valid integer is required." 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 "" #: 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 "" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "Ngày sai định dạng. Dùng một trong những định dạng sau để thay thế: {format}." #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "" #: 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 "" #: fields.py:1458 msgid "This selection may not be empty." msgstr "" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1516 msgid "No filename could be determined." msgstr "" #: fields.py:1517 msgid "The submitted file is empty." msgstr "" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr " Danh sách này không thể để trống." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "Giá trị bắt buộc phải là định dạng JSON." #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "Tìm kiếm" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "Sắp xếp" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "" #: filters.py:288 msgid "descending" msgstr "" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:449 msgid "Invalid value." msgstr "" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "Không có gì để chọn." #: validators.py:39 msgid "This field must be unique." msgstr "" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "" ================================================ FILE: rest_framework/locale/zh_CN/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # hunter007 , 2015 # Lele Long , 2015,2017 # Ming Chen , 2015-2016 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Chinese (China) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "无效的Basic认证头,没有提供认证信息。" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "认证字符串不应该包含空格(基本认证HTTP头无效)。" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "认证字符串base64编码错误(基本认证HTTP头无效)。" #: authentication.py:101 msgid "Invalid username/password." msgstr "用户名或者密码错误。" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "用户未激活或者已删除。" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "没有提供认证信息(认证令牌HTTP头无效)。" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "认证令牌字符串不应该包含空格(无效的认证令牌HTTP头)。" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "无效的Token。Token字符串不能包含非法的字符。" #: authentication.py:203 msgid "Invalid token." msgstr "认证令牌无效。" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "认证令牌" #: authtoken/models.py:13 msgid "Key" msgstr "键" #: authtoken/models.py:16 msgid "User" msgstr "用户" #: authtoken/models.py:18 msgid "Created" msgstr "已创建" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "令牌" #: authtoken/models.py:28 msgid "Tokens" msgstr "令牌" #: authtoken/serializers.py:9 msgid "Username" msgstr "用户名" #: authtoken/serializers.py:13 msgid "Password" msgstr "密码" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "无法使用提供的认证信息登录。" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "必须包含 “用户名” 和 “密码”。" #: exceptions.py:102 msgid "A server error occurred." msgstr "服务器出现了错误。" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "错误的请求。" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "不正确的身份认证信息。" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "身份认证信息未提供。" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "您没有执行该操作的权限。" #: exceptions.py:185 msgid "Not found." msgstr "未找到。" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "方法 “{method}” 不被允许。" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "无法满足Accept HTTP头的请求。" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "不支持请求中的媒体类型 “{media_type}”。" #: exceptions.py:223 msgid "Request was throttled." msgstr "请求超过了限速。" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "该字段是必填项。" #: fields.py:317 msgid "This field may not be null." msgstr "该字段不能为 null。" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "该字段不能为空。" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "请确保这个字段不能超过 {max_length} 个字符。" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "请确保这个字段至少包含 {min_length} 个字符。" #: fields.py:816 msgid "Enter a valid email address." msgstr "请输入合法的邮件地址。" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "输入值不匹配要求的模式。" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "请输入合法的“短语“,只能包含字母,数字,下划线或者中划线。" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "请输入合法的URL。" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "请输入一个有效的IPv4或IPv6地址。" #: fields.py:931 msgid "A valid integer is required." 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}。" #: 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}。" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "字符串值太长。" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "请填写合法的数字。" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "请确保总计不超过 {max_digits} 个数字。" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "请确保总计不超过 {max_decimal_places} 个小数位。" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "请确保小数点前不超过 {max_whole_digits} 个数字。" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "日期时间格式错误。请从这些格式中选择:{format}。" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "期望为日期时间,得到的是日期。" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "日期格式错误。请从这些格式中选择:{format}。" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "期望为日期,得到的是日期时间。" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "时间格式错误。请从这些格式中选择:{format}。" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "持续时间的格式错误。使用这些格式中的一个:{format}。" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "“{input}” 不是合法选项。" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "多于{count}条记录。" #: 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 "期望为一个包含物件的列表,得到的类型是“{input_type}”。" #: fields.py:1458 msgid "This selection may not be empty." msgstr "这项选择不能为空。" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "“{input}” 不是有效路径选项。" #: fields.py:1514 msgid "No file was submitted." msgstr "没有提交任何文件。" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "提交的数据不是一个文件。请检查表单的编码类型。" #: fields.py:1516 msgid "No filename could be determined." msgstr "无法检测到文件名。" #: fields.py:1517 msgid "The submitted file is empty." msgstr "提交的是空文件。" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "请上传有效图片。您上传的该文件不是图片或者图片已经损坏。" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "列表字段不能为空值。" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "请确保这个字段至少包含 {min_length} 个元素。" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "请确保这个字段不能超过 {max_length} 个元素。" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "期望是包含类目的字典,得到类型为 “{input_type}”。" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "这个字典可能不是空的。" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "值必须是有效的 JSON 数据。" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "查找" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "排序" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "升序" #: filters.py:288 msgid "descending" msgstr "降序" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "无效页。" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "无效游标" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "无效主键 “{pk_value}” - 对象不存在。" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "类型错误。期望为主键,得到的类型为 {data_type}。" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "无效超链接 -没有匹配的URL。" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "无效超链接 -错误的URL匹配。" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "无效超链接 -对象不存在。" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "类型错误。期望为URL字符串,实际的类型是 {data_type}。" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "属性 {slug_name} 为 {value} 的对象不存在。" #: relations.py:449 msgid "Invalid value." msgstr "无效值。" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "无效数据。期待为字典类型,得到的是 {datatype} 。" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "过滤器" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "无" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "没有可选项。" #: validators.py:39 msgid "This field must be unique." msgstr "该字段必须唯一。" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "字段 {field_names} 必须能构成唯一集合。" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "该字段必须在日期 “{date_field}” 唯一。" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "该字段必须在月份 “{date_field}” 唯一。" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "该字段必须在年 “{date_field}” 唯一。" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "“Accept” HTTP头包含无效版本。" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URL路径包含无效版本。" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "URL路径中存在无效版本。版本空间中无法匹配上。" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "主机名包含无效版本。" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "请求参数里包含无效版本。" ================================================ FILE: rest_framework/locale/zh_Hans/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # cokky , 2015 # hunter007 , 2015 # 3eb8e7e672c2428f1223e00920bfd2b3, 2015 # ppppfly , 2017 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Chinese Simplified (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/zh-Hans/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh-Hans\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "无效的Basic认证头,没有提供认证信息。" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "认证字符串不应该包含空格(基本认证HTTP头无效)。" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "认证字符串base64编码错误(基本认证HTTP头无效)。" #: authentication.py:101 msgid "Invalid username/password." msgstr "用户名或者密码错误。" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "用户未激活或者已删除。" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "没有提供认证信息(认证令牌HTTP头无效)。" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "认证令牌字符串不应该包含空格(无效的认证令牌HTTP头)。" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "无效的Token。Token字符串不能包含非法的字符。" #: authentication.py:203 msgid "Invalid token." msgstr "认证令牌无效。" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "认证令牌" #: authtoken/models.py:13 msgid "Key" msgstr "键" #: authtoken/models.py:16 msgid "User" msgstr "用户" #: authtoken/models.py:18 msgid "Created" msgstr "已创建" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "令牌" #: authtoken/models.py:28 msgid "Tokens" msgstr "令牌" #: authtoken/serializers.py:9 msgid "Username" msgstr "用户名" #: authtoken/serializers.py:13 msgid "Password" msgstr "密码" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "无法使用提供的认证信息登录。" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "必须包含 “用户名” 和 “密码”。" #: exceptions.py:102 msgid "A server error occurred." msgstr "服务器出现了错误。" #: exceptions.py:142 msgid "Invalid input." msgstr "无效的输入。" #: exceptions.py:161 msgid "Malformed request." msgstr "错误的请求。" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "不正确的身份认证信息。" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "身份认证信息未提供。" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "您没有执行该操作的权限。" #: exceptions.py:185 msgid "Not found." msgstr "未找到。" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "方法 “{method}” 不被允许。" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "无法满足Accept HTTP头的请求。" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "不支持请求中的媒体类型 “{media_type}”。" #: exceptions.py:223 msgid "Request was throttled." msgstr "请求已被限流。" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "预计 {wait} 秒后可用。" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "预计 {wait} 秒后可用。" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "该字段是必填项。" #: fields.py:317 msgid "This field may not be null." msgstr "该字段不能为 null。" #: fields.py:701 msgid "Must be a valid boolean." msgstr "必须是有效的布尔值。" #: fields.py:766 msgid "Not a valid string." msgstr "不是有效的字符串。" #: fields.py:767 msgid "This field may not be blank." msgstr "该字段不能为空。" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "请确保这个字段不能超过 {max_length} 个字符。" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "请确保这个字段至少包含 {min_length} 个字符。" #: fields.py:816 msgid "Enter a valid email address." msgstr "请输入合法的邮件地址。" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "输入值不匹配要求的模式。" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "请输入合法的“短语“,只能包含字母,数字,下划线或者中划线。" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "请输入有效的“slug”,由 Unicode 字母、数字、下划线或连字符组成。" #: fields.py:854 msgid "Enter a valid URL." msgstr "请输入合法的URL。" #: fields.py:867 msgid "Must be a valid UUID." msgstr "必须是有效的 UUID。" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "请输入一个有效的IPv4或IPv6地址。" #: fields.py:931 msgid "A valid integer is required." 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}。" #: 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}。" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "字符串值太长。" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "请填写合法的数字。" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "请确保总计不超过 {max_digits} 个数字。" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "请确保总计不超过 {max_decimal_places} 个小数位。" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "请确保小数点前不超过 {max_whole_digits} 个数字。" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "日期时间格式错误。请从这些格式中选择:{format}。" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "期望为日期时间,获得的是日期。" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "时区“{timezone}”的时间格式无效。" #: fields.py:1151 msgid "Datetime value out of range." msgstr "时间数值超出有效范围。" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "日期格式错误。请从这些格式中选择:{format}。" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "期望为日期,获得的是日期时间。" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "时间格式错误。请从这些格式中选择:{format}。" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "持续时间的格式错误。使用这些格式中的一个:{format}。" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "“{input}” 不是合法选项。" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "多于{count}条记录。" #: 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 "期望为一个包含物件的列表,得到的类型是“{input_type}”。" #: fields.py:1458 msgid "This selection may not be empty." msgstr "这项选择不能为空。" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "\"{input}\"不是一个有效路径选项。" #: fields.py:1514 msgid "No file was submitted." msgstr "没有提交任何文件。" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "提交的数据不是一个文件。请检查表单的编码类型。" #: fields.py:1516 msgid "No filename could be determined." msgstr "无法检测到文件名。" #: fields.py:1517 msgid "The submitted file is empty." msgstr "提交的是空文件。" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {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 "请上传有效图片。您上传的该文件不是图片或者图片已经损坏。" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "列表不能为空。" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "该字段必须包含至少 {min_length} 个元素。" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "该字段不能超过 {max_length} 个元素。" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "期望是包含类目的字典,得到类型为 “{input_type}”。" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "该字典不能为空。" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "值必须是有效的 JSON 数据。" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr " 搜索" #: filters.py:50 msgid "A search term." msgstr "搜索关键词。" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "排序" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "用于排序结果的字段。" #: filters.py:287 msgid "ascending" msgstr "正排序" #: filters.py:288 msgid "descending" msgstr "倒排序" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "分页结果集中的页码。" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "每页返回的结果数量。" #: pagination.py:189 msgid "Invalid page." msgstr "无效页面。" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "返回结果的起始索引位置。" #: pagination.py:581 msgid "The pagination cursor value." msgstr "分页游标值" #: pagination.py:583 msgid "Invalid cursor" msgstr "无效游标" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "无效主键 “{pk_value}” - 对象不存在。" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "类型错误。期望为主键,获得的类型为 {data_type}。" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "无效超链接 -没有匹配的URL。" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "无效超链接 -错误的URL匹配。" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "无效超链接 -对象不存在。" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "类型错误。期望为URL字符串,实际的类型是 {data_type}。" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "属性 {slug_name} 为 {value} 的对象不存在。" #: relations.py:449 msgid "Invalid value." msgstr "无效值。" #: schemas/utils.py:32 msgid "unique integer value" msgstr "唯一整数值" #: schemas/utils.py:34 msgid "UUID string" msgstr "UUID 字符串" #: schemas/utils.py:36 msgid "unique value" msgstr "唯一值" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "标识此 {name} 的 {value_type}。" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "无效数据。期待为字典类型,得到的是 {datatype} 。" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "扩展操作" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "过滤器" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "导航栏" #: templates/rest_framework/base.html:75 msgid "content" msgstr "内容主体" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "请求表单" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "主要内容区" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "请求信息" #: templates/rest_framework/base.html:177 msgid "response info" 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 "无" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "没有可选项。" #: validators.py:39 msgid "This field must be unique." msgstr "该字段必须唯一。" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "字段 {field_names} 必须能构成唯一集合。" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "不允许使用代理字符: U+{code_point:X}。" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "该字段必须在日期 “{date_field}” 唯一。" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "该字段必须在月份 “{date_field}” 唯一。" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "该字段必须在年 “{date_field}” 唯一。" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "“Accept” HTTP头包含无效版本。" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "URL路径包含无效版本。" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "在URL路径中发现无效的版本。无法匹配任何的版本命名空间。" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "主机名包含无效版本。" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "请求参数里包含无效版本。" ================================================ FILE: rest_framework/locale/zh_Hant/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: # Matsui Lin , 2019 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" "Last-Translator: Xavier Ordoquy \n" "Language-Team: Chinese Traditional (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/zh-Hant/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh-Hant\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:70 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:73 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:83 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:101 msgid "Invalid username/password." msgstr "無效的使用者名稱及密碼。" #: authentication.py:104 authentication.py:206 msgid "User inactive or deleted." msgstr "帳號未啟用或已被刪除。" #: authentication.py:184 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:187 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:193 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:203 msgid "Invalid token." msgstr "無效的token。" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "驗證 Token" #: authtoken/models.py:13 msgid "Key" msgstr "金鑰" #: authtoken/models.py:16 msgid "User" msgstr "使用者" #: authtoken/models.py:18 msgid "Created" msgstr "建立者" #: authtoken/models.py:27 authtoken/serializers.py:19 msgid "Token" msgstr "Token" #: authtoken/models.py:28 msgid "Tokens" msgstr "Tokens" #: authtoken/serializers.py:9 msgid "Username" msgstr "使用者名稱" #: authtoken/serializers.py:13 msgid "Password" msgstr "密碼" #: authtoken/serializers.py:35 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:38 msgid "Must include \"username\" and \"password\"." msgstr "必須包含使用者名稱及密碼。" #: exceptions.py:102 msgid "A server error occurred." msgstr "" #: exceptions.py:142 msgid "Invalid input." msgstr "" #: exceptions.py:161 msgid "Malformed request." msgstr "" #: exceptions.py:167 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:173 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:179 msgid "You do not have permission to perform this action." msgstr "你沒有執行此操作的權限。" #: exceptions.py:185 msgid "Not found." msgstr "找不到資源。" #: exceptions.py:191 #, python-brace-format msgid "Method \"{method}\" not allowed." msgstr "不被允許的方法 \"{method}\"。" #: exceptions.py:202 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:212 #, python-brace-format msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:223 msgid "Request was throttled." msgstr "" #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." msgstr "" #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." msgstr "" #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 msgid "This field is required." msgstr "此為必需欄位。" #: fields.py:317 msgid "This field may not be null." msgstr "此欄位不可為null。" #: fields.py:701 msgid "Must be a valid boolean." msgstr "" #: fields.py:766 msgid "Not a valid string." msgstr "" #: fields.py:767 msgid "This field may not be blank." msgstr "此欄位不可為空白。" #: fields.py:768 fields.py:1881 #, python-brace-format msgid "Ensure this field has no more than {max_length} characters." msgstr "請確認此欄位字元長度不超過 {max_length}。" #: fields.py:769 #, python-brace-format msgid "Ensure this field has at least {min_length} characters." msgstr "請確認此欄位字元長度最少超過 {min_length}。" #: fields.py:816 msgid "Enter a valid email address." msgstr "請輸入有效的電子郵件地址。" #: fields.py:827 msgid "This value does not match the required pattern." msgstr "" #: fields.py:838 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:839 msgid "" "Enter a valid \"slug\" consisting of Unicode letters, numbers, underscores, " "or hyphens." msgstr "" #: fields.py:854 msgid "Enter a valid URL." msgstr "請輸入有效的URL。" #: fields.py:867 msgid "Must be a valid UUID." msgstr "" #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." msgstr "請輸入有效的 IPv4 或 IPv6 地址。" #: fields.py:931 msgid "A valid integer is required." 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}。" #: 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}。" #: fields.py:934 fields.py:971 fields.py:1010 msgid "String value too large." msgstr "字串長度太長。" #: fields.py:968 fields.py:1004 msgid "A valid number is required." msgstr "請輸入有效的數字。" #: fields.py:1007 #, python-brace-format msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:1008 #, python-brace-format msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:1009 #, python-brace-format msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1148 #, python-brace-format msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1149 msgid "Expected a datetime but got a date." msgstr "應該為日期時間格式,並非日期格式。" #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." msgstr "" #: fields.py:1151 msgid "Datetime value out of range." msgstr "" #: fields.py:1236 #, python-brace-format msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1237 msgid "Expected a date but got a datetime." msgstr "應該為日期格式,並非日期時間格式。" #: fields.py:1303 #, python-brace-format msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "時間格式錯誤,請在下列格式中擇一取代:{format}。" #: fields.py:1365 #, python-brace-format msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1399 fields.py:1456 #, python-brace-format msgid "\"{input}\" is not a valid choice." msgstr "\"{input}\" 不是有效的選擇。" #: fields.py:1402 #, python-brace-format msgid "More than {count} items..." msgstr "超過 {count} 個項目..." #: 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 "應該為項目組成的列表,並非 \"{input_type}\" 類型。" #: fields.py:1458 msgid "This selection may not be empty." msgstr "此選項不可為空。" #: fields.py:1495 #, python-brace-format msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1514 msgid "No file was submitted." msgstr "沒有任何檔案被提交。" #: fields.py:1515 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "提交的資料並不是檔案格式,請確認表單的編碼類型。" #: fields.py:1516 msgid "No filename could be determined." msgstr "" #: fields.py:1517 msgid "The submitted file is empty." msgstr "沒有任何檔案被提交。" #: fields.py:1518 #, python-brace-format msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1566 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1604 relations.py:486 serializers.py:571 msgid "This list may not be empty." msgstr "此列表不可為空。" #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." msgstr "" #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." msgstr "" #: fields.py:1682 #, python-brace-format msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1683 msgid "This dictionary may not be empty." msgstr "" #: fields.py:1755 msgid "Value must be valid JSON." msgstr "輸入值必須為有效的JSON。" #: filters.py:49 templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "搜尋" #: filters.py:50 msgid "A search term." msgstr "" #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "排序" #: filters.py:181 msgid "Which field to use when ordering the results." msgstr "" #: filters.py:287 msgid "ascending" msgstr "升序排列" #: filters.py:288 msgid "descending" msgstr "降序排列" #: pagination.py:174 msgid "A page number within the paginated result set." msgstr "" #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." msgstr "" #: pagination.py:189 msgid "Invalid page." msgstr "無效的頁面。" #: pagination.py:374 msgid "The initial index from which to return the results." msgstr "" #: pagination.py:581 msgid "The pagination cursor value." msgstr "" #: pagination.py:583 msgid "Invalid cursor" msgstr "" #: relations.py:246 #, python-brace-format msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "無效的主鍵 \"{pk_value}\" - 物件不存在。" #: relations.py:247 #, python-brace-format msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:280 msgid "Invalid hyperlink - No URL match." msgstr "無效的超連結 - 沒有匹配的URL。" #: relations.py:281 msgid "Invalid hyperlink - Incorrect URL match." msgstr "無效的超連結 - 匹配的URL不正確。" #: relations.py:282 msgid "Invalid hyperlink - Object does not exist." msgstr "無效的超連結 - 物件不存在。" #: relations.py:283 #, python-brace-format msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:448 #, python-brace-format msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:449 msgid "Invalid value." msgstr "無效值。" #: schemas/utils.py:32 msgid "unique integer value" msgstr "" #: schemas/utils.py:34 msgid "UUID string" msgstr "" #: schemas/utils.py:36 msgid "unique value" msgstr "" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." msgstr "" #: serializers.py:337 #, python-brace-format msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "無效的資料,應該為字典類型,並非 {datatype}。" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" msgstr "" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 msgid "Filters" msgstr "篩選" #: templates/rest_framework/base.html:37 msgid "navbar" msgstr "" #: templates/rest_framework/base.html:75 msgid "content" msgstr "" #: templates/rest_framework/base.html:78 msgid "request form" msgstr "" #: templates/rest_framework/base.html:157 msgid "main content" msgstr "" #: templates/rest_framework/base.html:173 msgid "request info" msgstr "" #: templates/rest_framework/base.html:177 msgid "response info" 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 "無" #: templates/rest_framework/horizontal/select_multiple.html:4 #: templates/rest_framework/inline/select_multiple.html:3 #: templates/rest_framework/vertical/select_multiple.html:3 msgid "No items to select." msgstr "" #: validators.py:39 msgid "This field must be unique." msgstr "此欄位必須唯一。" #: validators.py:89 #, python-brace-format msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." msgstr "" #: validators.py:243 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:258 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:271 #, python-brace-format msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:40 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:71 msgid "Invalid version in URL path." msgstr "" #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:148 msgid "Invalid version in hostname." msgstr "" #: versioning.py:170 msgid "Invalid version in query parameter." msgstr "" ================================================ FILE: rest_framework/locale/zh_TW/LC_MESSAGES/django.po ================================================ # SOME DESCRIPTIVE TITLE. # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER # This file is distributed under the same license as the PACKAGE package. # # Translators: msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2016-07-12 16:13+0100\n" "PO-Revision-Date: 2016-07-12 15:14+0000\n" "Last-Translator: Thomas Christie \n" "Language-Team: Chinese (Taiwan) (http://www.transifex.com/django-rest-framework-1/django-rest-framework/language/zh_TW/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: zh_TW\n" "Plural-Forms: nplurals=1; plural=0;\n" #: authentication.py:73 msgid "Invalid basic header. No credentials provided." msgstr "" #: authentication.py:76 msgid "Invalid basic header. Credentials string should not contain spaces." msgstr "" #: authentication.py:82 msgid "Invalid basic header. Credentials not correctly base64 encoded." msgstr "" #: authentication.py:99 msgid "Invalid username/password." msgstr "" #: authentication.py:102 authentication.py:198 msgid "User inactive or deleted." msgstr "" #: authentication.py:176 msgid "Invalid token header. No credentials provided." msgstr "" #: authentication.py:179 msgid "Invalid token header. Token string should not contain spaces." msgstr "" #: authentication.py:185 msgid "" "Invalid token header. Token string should not contain invalid characters." msgstr "" #: authentication.py:195 msgid "Invalid token." msgstr "" #: authtoken/apps.py:7 msgid "Auth Token" msgstr "" #: authtoken/models.py:15 msgid "Key" msgstr "" #: authtoken/models.py:18 msgid "User" msgstr "" #: authtoken/models.py:20 msgid "Created" msgstr "" #: authtoken/models.py:29 msgid "Token" msgstr "" #: authtoken/models.py:30 msgid "Tokens" msgstr "" #: authtoken/serializers.py:8 msgid "Username" msgstr "" #: authtoken/serializers.py:9 msgid "Password" msgstr "" #: authtoken/serializers.py:20 msgid "User account is disabled." msgstr "" #: authtoken/serializers.py:23 msgid "Unable to log in with provided credentials." msgstr "" #: authtoken/serializers.py:26 msgid "Must include \"username\" and \"password\"." msgstr "" #: exceptions.py:49 msgid "A server error occurred." msgstr "" #: exceptions.py:84 msgid "Malformed request." msgstr "" #: exceptions.py:89 msgid "Incorrect authentication credentials." msgstr "" #: exceptions.py:94 msgid "Authentication credentials were not provided." msgstr "" #: exceptions.py:99 msgid "You do not have permission to perform this action." msgstr "" #: exceptions.py:104 views.py:81 msgid "Not found." msgstr "" #: exceptions.py:109 msgid "Method \"{method}\" not allowed." msgstr "" #: exceptions.py:120 msgid "Could not satisfy the request Accept header." msgstr "" #: exceptions.py:132 msgid "Unsupported media type \"{media_type}\" in request." msgstr "" #: exceptions.py:145 msgid "Request was throttled." msgstr "" #: fields.py:269 relations.py:206 relations.py:239 validators.py:98 #: validators.py:181 msgid "This field is required." msgstr "" #: fields.py:270 msgid "This field may not be null." msgstr "" #: fields.py:608 fields.py:639 msgid "\"{input}\" is not a valid boolean." msgstr "" #: fields.py:674 msgid "This field may not be blank." msgstr "" #: fields.py:675 fields.py:1675 msgid "Ensure this field has no more than {max_length} characters." msgstr "" #: fields.py:676 msgid "Ensure this field has at least {min_length} characters." msgstr "" #: fields.py:713 msgid "Enter a valid email address." msgstr "" #: fields.py:724 msgid "This value does not match the required pattern." msgstr "" #: fields.py:735 msgid "" "Enter a valid \"slug\" consisting of letters, numbers, underscores or " "hyphens." msgstr "" #: fields.py:747 msgid "Enter a valid URL." msgstr "" #: fields.py:760 msgid "\"{value}\" is not a valid UUID." msgstr "" #: fields.py:796 msgid "Enter a valid IPv4 or IPv6 address." msgstr "" #: fields.py:821 msgid "A valid integer is required." msgstr "" #: fields.py:822 fields.py:857 fields.py:891 msgid "Ensure this value is less than or equal to {max_value}." msgstr "" #: fields.py:823 fields.py:858 fields.py:892 msgid "Ensure this value is greater than or equal to {min_value}." msgstr "" #: fields.py:824 fields.py:859 fields.py:896 msgid "String value too large." msgstr "" #: fields.py:856 fields.py:890 msgid "A valid number is required." msgstr "" #: fields.py:893 msgid "Ensure that there are no more than {max_digits} digits in total." msgstr "" #: fields.py:894 msgid "" "Ensure that there are no more than {max_decimal_places} decimal places." msgstr "" #: fields.py:895 msgid "" "Ensure that there are no more than {max_whole_digits} digits before the " "decimal point." msgstr "" #: fields.py:1025 msgid "Datetime has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1026 msgid "Expected a datetime but got a date." msgstr "" #: fields.py:1103 msgid "Date has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1104 msgid "Expected a date but got a datetime." msgstr "" #: fields.py:1170 msgid "Time has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1232 msgid "Duration has wrong format. Use one of these formats instead: {format}." msgstr "" #: fields.py:1251 fields.py:1300 msgid "\"{input}\" is not a valid choice." msgstr "" #: fields.py:1254 relations.py:71 relations.py:441 msgid "More than {count} items..." msgstr "" #: fields.py:1301 fields.py:1448 relations.py:437 serializers.py:524 msgid "Expected a list of items but got type \"{input_type}\"." msgstr "" #: fields.py:1302 msgid "This selection may not be empty." msgstr "" #: fields.py:1339 msgid "\"{input}\" is not a valid path choice." msgstr "" #: fields.py:1358 msgid "No file was submitted." msgstr "" #: fields.py:1359 msgid "" "The submitted data was not a file. Check the encoding type on the form." msgstr "" #: fields.py:1360 msgid "No filename could be determined." msgstr "" #: fields.py:1361 msgid "The submitted file is empty." msgstr "" #: fields.py:1362 msgid "" "Ensure this filename has at most {max_length} characters (it has {length})." msgstr "" #: fields.py:1410 msgid "" "Upload a valid image. The file you uploaded was either not an image or a " "corrupted image." msgstr "" #: fields.py:1449 relations.py:438 serializers.py:525 msgid "This list may not be empty." msgstr "" #: fields.py:1502 msgid "Expected a dictionary of items but got type \"{input_type}\"." msgstr "" #: fields.py:1549 msgid "Value must be valid JSON." msgstr "" #: filters.py:36 templates/rest_framework/filters/django_filter.html:5 msgid "Submit" msgstr "" #: filters.py:336 msgid "ascending" msgstr "" #: filters.py:337 msgid "descending" msgstr "" #: pagination.py:193 msgid "Invalid page." msgstr "" #: pagination.py:427 msgid "Invalid cursor" msgstr "" #: relations.py:207 msgid "Invalid pk \"{pk_value}\" - object does not exist." msgstr "" #: relations.py:208 msgid "Incorrect type. Expected pk value, received {data_type}." msgstr "" #: relations.py:240 msgid "Invalid hyperlink - No URL match." msgstr "" #: relations.py:241 msgid "Invalid hyperlink - Incorrect URL match." msgstr "" #: relations.py:242 msgid "Invalid hyperlink - Object does not exist." msgstr "" #: relations.py:243 msgid "Incorrect type. Expected URL string, received {data_type}." msgstr "" #: relations.py:401 msgid "Object with {slug_name}={value} does not exist." msgstr "" #: relations.py:402 msgid "Invalid value." msgstr "" #: serializers.py:326 msgid "Invalid data. Expected a dictionary, but got {datatype}." msgstr "" #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:128 msgid "Filters" msgstr "" #: templates/rest_framework/filters/django_filter.html:2 #: templates/rest_framework/filters/django_filter_crispyforms.html:4 msgid "Field filters" msgstr "" #: templates/rest_framework/filters/ordering.html:3 msgid "Ordering" msgstr "" #: templates/rest_framework/filters/search.html:2 msgid "Search" msgstr "" #: templates/rest_framework/horizontal/radio.html:2 #: templates/rest_framework/inline/radio.html:2 #: templates/rest_framework/vertical/radio.html:2 msgid "None" msgstr "" #: templates/rest_framework/horizontal/select_multiple.html:2 #: templates/rest_framework/inline/select_multiple.html:2 #: templates/rest_framework/vertical/select_multiple.html:2 msgid "No items to select." msgstr "" #: validators.py:43 msgid "This field must be unique." msgstr "" #: validators.py:97 msgid "The fields {field_names} must make a unique set." msgstr "" #: validators.py:245 msgid "This field must be unique for the \"{date_field}\" date." msgstr "" #: validators.py:260 msgid "This field must be unique for the \"{date_field}\" month." msgstr "" #: validators.py:273 msgid "This field must be unique for the \"{date_field}\" year." msgstr "" #: versioning.py:42 msgid "Invalid version in \"Accept\" header." msgstr "" #: versioning.py:73 msgid "Invalid version in URL path." msgstr "" #: versioning.py:115 msgid "Invalid version in URL path. Does not match any version namespace." msgstr "" #: versioning.py:147 msgid "Invalid version in hostname." msgstr "" #: versioning.py:169 msgid "Invalid version in query parameter." msgstr "" #: views.py:88 msgid "Permission denied." msgstr "" ================================================ FILE: rest_framework/management/__init__.py ================================================ ================================================ FILE: rest_framework/management/commands/__init__.py ================================================ ================================================ FILE: rest_framework/management/commands/generateschema.py ================================================ from django.core.management.base import BaseCommand from django.utils.module_loading import import_string from rest_framework import renderers from rest_framework.schemas.openapi import SchemaGenerator class Command(BaseCommand): help = "Generates configured API schema for project." def add_arguments(self, parser): parser.add_argument('--title', dest="title", default='', type=str) parser.add_argument('--url', dest="url", default=None, type=str) parser.add_argument('--description', dest="description", default=None, type=str) parser.add_argument('--format', dest="format", choices=['openapi', 'openapi-json'], default='openapi', type=str) parser.add_argument('--urlconf', dest="urlconf", default=None, type=str) parser.add_argument('--generator_class', dest="generator_class", default=None, type=str) parser.add_argument('--file', dest="file", default=None, type=str) parser.add_argument('--api_version', dest="api_version", default='', type=str) def handle(self, *args, **options): if options['generator_class']: generator_class = import_string(options['generator_class']) else: generator_class = SchemaGenerator generator = generator_class( url=options['url'], title=options['title'], description=options['description'], urlconf=options['urlconf'], version=options['api_version'], ) schema = generator.get_schema(request=None, public=True) renderer = self.get_renderer(options['format']) output = renderer.render(schema, renderer_context={}) if options['file']: with open(options['file'], 'wb') as f: f.write(output) else: self.stdout.write(output.decode()) def get_renderer(self, format): renderer_cls = { 'openapi': renderers.OpenAPIRenderer, 'openapi-json': renderers.JSONOpenAPIRenderer, }[format] return renderer_cls() ================================================ FILE: rest_framework/metadata.py ================================================ """ The metadata API is used to allow customization of how `OPTIONS` requests are handled. We currently provide a single default implementation that returns some fairly ad-hoc information about the view. Future implementations might use JSON schema or other definitions in order to return this information in a more standardized way. """ from django.core.exceptions import PermissionDenied from django.http import Http404 from django.utils.encoding import force_str from rest_framework import exceptions, serializers from rest_framework.request import clone_request from rest_framework.utils.field_mapping import ClassLookupDict class BaseMetadata: def determine_metadata(self, request, view): """ Return a dictionary of metadata about the view. Used to return responses for OPTIONS requests. """ raise NotImplementedError(".determine_metadata() must be overridden.") class SimpleMetadata(BaseMetadata): """ This is the default metadata implementation. It returns an ad-hoc set of information about the view. There are not any formalized standards for `OPTIONS` responses for us to base this on. """ label_lookup = ClassLookupDict({ serializers.Field: 'field', serializers.BooleanField: 'boolean', serializers.CharField: 'string', serializers.UUIDField: 'string', serializers.URLField: 'url', serializers.EmailField: 'email', serializers.RegexField: 'regex', serializers.SlugField: 'slug', serializers.IntegerField: 'integer', serializers.FloatField: 'float', serializers.DecimalField: 'decimal', serializers.DateField: 'date', serializers.DateTimeField: 'datetime', serializers.TimeField: 'time', serializers.DurationField: 'duration', serializers.ChoiceField: 'choice', serializers.MultipleChoiceField: 'multiple choice', serializers.FileField: 'file upload', serializers.ImageField: 'image upload', serializers.ListField: 'list', serializers.DictField: 'nested object', serializers.Serializer: 'nested object', }) def determine_metadata(self, request, view): 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: metadata['actions'] = actions return metadata def determine_actions(self, request, view): """ For generic class based views we return information about the fields that are accepted for 'PUT' and 'POST' methods. """ actions = {} for method in {'PUT', 'POST'} & set(view.allowed_methods): view.request = clone_request(request, method) try: # Test global permissions if hasattr(view, 'check_permissions'): view.check_permissions(view.request) # Test object permissions if method == 'PUT' and hasattr(view, 'get_object'): view.get_object() except (exceptions.APIException, PermissionDenied, Http404): pass else: # If user has appropriate permissions for the view, include # appropriate metadata about the fields that should be supplied. serializer = view.get_serializer() actions[method] = self.get_serializer_info(serializer) finally: view.request = request return actions def get_serializer_info(self, serializer): """ Given an instance of a serializer, return a dictionary of metadata about its fields. """ if hasattr(serializer, 'child'): # If this is a `ListSerializer` then we want to examine the # underlying child serializer instance instead. serializer = serializer.child return { 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 = { "type": self.label_lookup[field], "required": getattr(field, "required", False), } attrs = [ 'read_only', 'label', 'help_text', 'min_length', 'max_length', 'min_value', 'max_value', 'max_digits', 'decimal_places' ] for attr in attrs: value = getattr(field, attr, None) if value is not None and value != '': field_info[attr] = force_str(value, strings_only=True) if getattr(field, 'child', None): field_info['child'] = self.get_field_info(field.child) elif getattr(field, 'fields', None): field_info['children'] = self.get_serializer_info(field) if (not field_info.get('read_only') and not isinstance(field, (serializers.RelatedField, serializers.ManyRelatedField)) and hasattr(field, 'choices')): field_info['choices'] = [ { 'value': choice_value, 'display_name': force_str(choice_name, strings_only=True) } for choice_value, choice_name in field.choices.items() ] return field_info ================================================ FILE: rest_framework/mixins.py ================================================ """ Basic building blocks for generic class based views. We don't bind behavior to http method handlers yet, which allows mixin classes to be composed in interesting ways. """ from rest_framework import status from rest_framework.response import Response from rest_framework.settings import api_settings class CreateModelMixin: """ Create a model instance. """ def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) def perform_create(self, serializer): serializer.save() def get_success_headers(self, data): try: return {'Location': str(data[api_settings.URL_FIELD_NAME])} except (TypeError, KeyError): return {} class ListModelMixin: """ List a queryset. """ def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) class RetrieveModelMixin: """ Retrieve a model instance. """ def retrieve(self, request, *args, **kwargs): instance = self.get_object() serializer = self.get_serializer(instance) return Response(serializer.data) class UpdateModelMixin: """ Update a model instance. """ def update(self, request, *args, **kwargs): partial = kwargs.pop('partial', False) instance = self.get_object() serializer = self.get_serializer(instance, data=request.data, partial=partial) serializer.is_valid(raise_exception=True) self.perform_update(serializer) if getattr(instance, '_prefetched_objects_cache', None): # If 'prefetch_related' has been applied to a queryset, we need to # forcibly invalidate the prefetch cache on the instance. instance._prefetched_objects_cache = {} return Response(serializer.data) def perform_update(self, serializer): serializer.save() def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) class DestroyModelMixin: """ Destroy a model instance. """ def destroy(self, request, *args, **kwargs): instance = self.get_object() self.perform_destroy(instance) return Response(status=status.HTTP_204_NO_CONTENT) def perform_destroy(self, instance): instance.delete() ================================================ FILE: rest_framework/negotiation.py ================================================ """ Content negotiation deals with selecting an appropriate renderer given the incoming request. Typically this will be based on the request's Accept header. """ from django.http import Http404 from rest_framework import exceptions from rest_framework.settings import api_settings from rest_framework.utils.mediatypes import ( _MediaType, media_type_matches, order_by_precedence ) class BaseContentNegotiation: def select_parser(self, request, parsers): raise NotImplementedError('.select_parser() must be implemented') def select_renderer(self, request, renderers, format_suffix=None): raise NotImplementedError('.select_renderer() must be implemented') class DefaultContentNegotiation(BaseContentNegotiation): settings = api_settings def select_parser(self, request, parsers): """ Given a list of parsers and a media type, return the appropriate parser to handle the incoming request. """ for parser in parsers: if media_type_matches(parser.media_type, request.content_type): return parser return None def select_renderer(self, request, renderers, format_suffix=None): """ Given a request and a list of renderers, return a two-tuple of: (renderer, media type). """ # Allow URL style format override. eg. "?format=json format_query_param = self.settings.URL_FORMAT_OVERRIDE format = format_suffix or request.query_params.get(format_query_param) if format: renderers = self.filter_renderers(renderers, format) accepts = self.get_accept_list(request) # Check the acceptable media types against each renderer, # attempting more specific media types first # NB. The inner loop here isn't as bad as it first looks :) # Worst case is we're looping over len(accept_list) * len(self.renderers) for media_type_set in order_by_precedence(accepts): for renderer in renderers: for media_type in media_type_set: if media_type_matches(renderer.media_type, media_type): # Return the most specific media type as accepted. media_type_wrapper = _MediaType(media_type) if ( _MediaType(renderer.media_type).precedence > media_type_wrapper.precedence ): # Eg client requests '*/*' # Accepted media type is 'application/json' full_media_type = ';'.join( (renderer.media_type,) + tuple( f'{key}={value}' for key, value in media_type_wrapper.params.items() ) ) return renderer, full_media_type else: # Eg client requests 'application/json; indent=8' # Accepted media type is 'application/json; indent=8' return renderer, media_type raise exceptions.NotAcceptable(available_renderers=renderers) def filter_renderers(self, renderers, format): """ If there is a '.json' style format suffix, filter the renderers so that we only negotiation against those that accept that format. """ renderers = [renderer for renderer in renderers if renderer.format == format] if not renderers: raise Http404 return renderers def get_accept_list(self, request): """ Given the incoming request, return a tokenized list of media type strings. """ header = request.META.get('HTTP_ACCEPT', '*/*') return [token.strip() for token in header.split(',')] ================================================ FILE: rest_framework/pagination.py ================================================ """ Pagination serializers determine the structure of the output that should be used for paginated responses. """ import contextlib from base64 import b64decode, b64encode from collections import namedtuple from urllib import parse from django.core.paginator import InvalidPage from django.core.paginator import Paginator as DjangoPaginator from django.template import loader from django.utils.encoding import force_str from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import NotFound from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.utils.urls import remove_query_param, replace_query_param def _positive_int(integer_string, strict=False, cutoff=None): """ Cast a string to a strictly positive integer. """ ret = int(integer_string) if ret < 0 or (ret == 0 and strict): raise ValueError() if cutoff: return min(ret, cutoff) return ret def _divide_with_ceil(a, b): """ Returns 'a' divided by 'b', with any remainder rounded up. """ if a % b: return (a // b) + 1 return a // b def _get_displayed_page_numbers(current, final): """ This utility function determines a list of page numbers to display. This gives us a nice contextually relevant set of page numbers. For example: current=14, final=16 -> [1, None, 13, 14, 15, 16] This implementation gives one page to each side of the cursor, or two pages to the side when the cursor is at the edge, then ensures that any breaks between non-continuous page numbers never remove only a single page. For an alternative implementation which gives two pages to each side of the cursor, eg. as in GitHub issue list pagination, see: https://gist.github.com/tomchristie/321140cebb1c4a558b15 """ assert current >= 1 assert final >= current if final <= 5: return list(range(1, final + 1)) # We always include the first two pages, last two pages, and # two pages either side of the current page. included = {1, current - 1, current, current + 1, final} # If the break would only exclude a single page number then we # may as well include the page number instead of the break. if current <= 4: included.add(2) included.add(3) if current >= final - 3: included.add(final - 1) included.add(final - 2) # Now sort the page numbers and drop anything outside the limits. included = [ idx for idx in sorted(included) if 0 < idx <= final ] # Finally insert any `...` breaks if current > 4: included.insert(1, None) if current < final - 3: included.insert(len(included) - 1, None) return included def _get_page_links(page_numbers, current, url_func): """ Given a list of page numbers and `None` page breaks, return a list of `PageLink` objects. """ page_links = [] for page_number in page_numbers: if page_number is None: page_link = PAGE_BREAK else: page_link = PageLink( url=url_func(page_number), number=page_number, is_active=(page_number == current), is_break=False ) page_links.append(page_link) return page_links def _reverse_ordering(ordering_tuple): """ Given an order_by tuple such as `('-created', 'uuid')` reverse the ordering and return a new tuple, eg. `('created', '-uuid')`. """ def invert(x): return x[1:] if x.startswith('-') else '-' + x return tuple([invert(item) for item in ordering_tuple]) Cursor = namedtuple('Cursor', ['offset', 'reverse', 'position']) PageLink = namedtuple('PageLink', ['url', 'number', 'is_active', 'is_break']) PAGE_BREAK = PageLink(url=None, number=None, is_active=False, is_break=True) class BasePagination: display_page_controls = False def paginate_queryset(self, queryset, request, view=None): # pragma: no cover raise NotImplementedError('paginate_queryset() must be implemented.') def get_paginated_response(self, data): # pragma: no cover raise NotImplementedError('get_paginated_response() must be implemented.') def get_paginated_response_schema(self, schema): return schema def to_html(self): # pragma: no cover raise NotImplementedError('to_html() must be implemented to display page controls.') def get_results(self, data): return data['results'] def get_schema_operation_parameters(self, view): return [] class PageNumberPagination(BasePagination): """ A simple page number based style that supports page numbers as query parameters. For example: http://api.example.org/accounts/?page=4 http://api.example.org/accounts/?page=4&page_size=100 """ # The default page size. # Defaults to `None`, meaning pagination is disabled. page_size = api_settings.PAGE_SIZE django_paginator_class = DjangoPaginator # Client can control the page using this query parameter. page_query_param = 'page' page_query_description = _('A page number within the paginated result set.') # Client can control the page size using this query parameter. # Default is 'None'. Set to eg 'page_size' to enable usage. page_size_query_param = None page_size_query_description = _('Number of results to return per page.') # Set to an integer to limit the maximum page size the client may request. # Only relevant if 'page_size_query_param' has also been set. max_page_size = None last_page_strings = ('last',) template = 'rest_framework/pagination/numbers.html' invalid_page_message = _('Invalid page.') 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 paginator = self.django_paginator_class(queryset, page_size) page_number = self.get_page_number(request, paginator) try: self.page = paginator.page(page_number) except InvalidPage as exc: msg = self.invalid_page_message.format( page_number=page_number, message=str(exc) ) raise NotFound(msg) if paginator.num_pages > 1 and self.template is not None: # The browsable API should display pagination controls. self.display_page_controls = True return list(self.page) def get_page_number(self, request, paginator): 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({ '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', 'example': 123, }, 'next': { 'type': 'string', 'nullable': True, 'format': 'uri', 'example': 'http://api.example.org/accounts/?{page_query_param}=4'.format( page_query_param=self.page_query_param) }, 'previous': { 'type': 'string', 'nullable': True, 'format': 'uri', 'example': 'http://api.example.org/accounts/?{page_query_param}=2'.format( page_query_param=self.page_query_param) }, 'results': schema, }, } def get_page_size(self, request): if self.page_size_query_param: with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) return self.page_size def get_next_link(self): if not self.page.has_next(): return None url = self.request.build_absolute_uri() page_number = self.page.next_page_number() return replace_query_param(url, self.page_query_param, page_number) def get_previous_link(self): if not self.page.has_previous(): return None url = self.request.build_absolute_uri() page_number = self.page.previous_page_number() if page_number == 1: return remove_query_param(url, self.page_query_param) return replace_query_param(url, self.page_query_param, page_number) def get_html_context(self): base_url = self.request.build_absolute_uri() def page_number_to_url(page_number): if page_number == 1: return remove_query_param(base_url, self.page_query_param) else: return replace_query_param(base_url, self.page_query_param, page_number) current = self.page.number final = self.page.paginator.num_pages page_numbers = _get_displayed_page_numbers(current, final) page_links = _get_page_links(page_numbers, current, page_number_to_url) return { 'previous_url': self.get_previous_link(), 'next_url': self.get_next_link(), 'page_links': page_links } def to_html(self): template = loader.get_template(self.template) context = self.get_html_context() return template.render(context) def get_schema_operation_parameters(self, view): parameters = [ { 'name': self.page_query_param, 'required': False, 'in': 'query', 'description': force_str(self.page_query_description), 'schema': { 'type': 'integer', }, }, ] if self.page_size_query_param is not None: parameters.append( { 'name': self.page_size_query_param, 'required': False, 'in': 'query', 'description': force_str(self.page_size_query_description), 'schema': { 'type': 'integer', }, }, ) return parameters class LimitOffsetPagination(BasePagination): """ A limit/offset based style. For example: http://api.example.org/accounts/?limit=100 http://api.example.org/accounts/?offset=400&limit=100 """ default_limit = api_settings.PAGE_SIZE limit_query_param = 'limit' limit_query_description = _('Number of results to return per page.') offset_query_param = 'offset' offset_query_description = _('The initial index from which to return the results.') max_limit = None 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) if self.count > self.limit and self.template is not None: self.display_page_controls = True if self.count == 0 or self.offset > self.count: return [] return list(queryset[self.offset:self.offset + self.limit]) def get_paginated_response(self, 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', 'example': 123, }, 'next': { 'type': 'string', 'nullable': True, 'format': 'uri', 'example': 'http://api.example.org/accounts/?{offset_param}=400&{limit_param}=100'.format( offset_param=self.offset_query_param, limit_param=self.limit_query_param), }, 'previous': { 'type': 'string', 'nullable': True, 'format': 'uri', 'example': 'http://api.example.org/accounts/?{offset_param}=200&{limit_param}=100'.format( offset_param=self.offset_query_param, limit_param=self.limit_query_param), }, 'results': schema, }, } def get_limit(self, request): if self.limit_query_param: with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.limit_query_param], strict=True, cutoff=self.max_limit ) return self.default_limit def get_offset(self, request): try: return _positive_int( request.query_params[self.offset_query_param], ) except (KeyError, ValueError): return 0 def get_next_link(self): if self.offset + self.limit >= self.count: return None url = self.request.build_absolute_uri() url = replace_query_param(url, self.limit_query_param, self.limit) offset = self.offset + self.limit return replace_query_param(url, self.offset_query_param, offset) def get_previous_link(self): if self.offset <= 0: return None url = self.request.build_absolute_uri() url = replace_query_param(url, self.limit_query_param, self.limit) if self.offset - self.limit <= 0: return remove_query_param(url, self.offset_query_param) offset = self.offset - self.limit return replace_query_param(url, self.offset_query_param, offset) def get_html_context(self): base_url = self.request.build_absolute_uri() if self.limit: current = _divide_with_ceil(self.offset, self.limit) + 1 # The number of pages is a little bit fiddly. # We need to sum both the number of pages from current offset to end # plus the number of pages up to the current offset. # When offset is not strictly divisible by the limit then we may # end up introducing an extra page as an artifact. final = ( _divide_with_ceil(self.count - self.offset, self.limit) + _divide_with_ceil(self.offset, self.limit) ) final = max(final, 1) else: current = 1 final = 1 if current > final: current = final def page_number_to_url(page_number): if page_number == 1: return remove_query_param(base_url, self.offset_query_param) else: offset = self.offset + ((page_number - current) * self.limit) return replace_query_param(base_url, self.offset_query_param, offset) page_numbers = _get_displayed_page_numbers(current, final) page_links = _get_page_links(page_numbers, current, page_number_to_url) return { 'previous_url': self.get_previous_link(), 'next_url': self.get_next_link(), 'page_links': page_links } def to_html(self): template = loader.get_template(self.template) context = self.get_html_context() return template.render(context) def get_count(self, queryset): """ Determine an object count, supporting either querysets or regular lists. """ try: return queryset.count() except (AttributeError, TypeError): return len(queryset) def get_schema_operation_parameters(self, view): parameters = [ { 'name': self.limit_query_param, 'required': False, 'in': 'query', 'description': force_str(self.limit_query_description), 'schema': { 'type': 'integer', }, }, { 'name': self.offset_query_param, 'required': False, 'in': 'query', 'description': force_str(self.offset_query_description), 'schema': { 'type': 'integer', }, }, ] return parameters class CursorPagination(BasePagination): """ The cursor pagination implementation is necessarily complex. For an overview of the position/offset style we use, see this post: https://cra.mr/2011/03/08/building-cursors-for-the-disqus-api """ cursor_query_param = 'cursor' cursor_query_description = _('The pagination cursor value.') page_size = api_settings.PAGE_SIZE invalid_cursor_message = _('Invalid cursor') ordering = '-created' template = 'rest_framework/pagination/previous_and_next.html' # Client can control the page size using this query parameter. # Default is 'None'. Set to eg 'page_size' to enable usage. page_size_query_param = None page_size_query_description = _('Number of results to return per page.') # Set to an integer to limit the maximum page size the client may request. # Only relevant if 'page_size_query_param' has also been set. max_page_size = None # The offset in the cursor is used in situations where we have a # nearly-unique index. (Eg millisecond precision creation timestamps) # We guard against malicious users attempting to cause expensive database # queries, by having a hard cap on the maximum possible size of the offset. 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 self.base_url = request.build_absolute_uri() self.ordering = self.get_ordering(request, queryset, view) self.cursor = self.decode_cursor(request) if self.cursor is None: (offset, reverse, current_position) = (0, False, None) else: (offset, reverse, current_position) = self.cursor # Cursor pagination always enforces an ordering. if reverse: queryset = queryset.order_by(*_reverse_ordering(self.ordering)) else: queryset = queryset.order_by(*self.ordering) # If we have a cursor with a fixed position then filter by that. if current_position is not None: order = self.ordering[0] is_reversed = order.startswith('-') order_attr = order.lstrip('-') # Test for: (cursor reversed) XOR (queryset reversed) if self.cursor.reverse != is_reversed: kwargs = {order_attr + '__lt': current_position} else: kwargs = {order_attr + '__gt': current_position} queryset = queryset.filter(**kwargs) # If we have an offset cursor then offset the entire page by that amount. # We also always fetch an extra item in order to determine if there is a # page following on from this one. results = list(queryset[offset:offset + self.page_size + 1]) self.page = list(results[:self.page_size]) # Determine the position of the final item following the page. if len(results) > len(self.page): has_following_position = True following_position = self._get_position_from_instance(results[-1], self.ordering) else: has_following_position = False following_position = None if reverse: # If we have a reverse queryset, then the query ordering was in reverse # so we need to reverse the items again before returning them to the user. self.page = list(reversed(self.page)) # Determine next and previous positions for reverse cursors. self.has_next = (current_position is not None) or (offset > 0) self.has_previous = has_following_position if self.has_next: self.next_position = current_position if self.has_previous: self.previous_position = following_position else: # Determine next and previous positions for forward cursors. self.has_next = has_following_position self.has_previous = (current_position is not None) or (offset > 0) if self.has_next: self.next_position = following_position if self.has_previous: self.previous_position = current_position # Display page controls in the browsable API if there is more # than one page. if (self.has_previous or self.has_next) and self.template is not None: self.display_page_controls = True return self.page def get_page_size(self, request): if self.page_size_query_param: with contextlib.suppress(KeyError, ValueError): return _positive_int( request.query_params[self.page_size_query_param], strict=True, cutoff=self.max_page_size ) return self.page_size def get_next_link(self): if not self.has_next: return None if self.page and self.cursor and self.cursor.reverse and self.cursor.offset != 0: # If we're reversing direction and we have an offset cursor # then we cannot use the first position we find as a marker. compare = self._get_position_from_instance(self.page[-1], self.ordering) else: compare = self.next_position offset = 0 has_item_with_unique_position = False for item in reversed(self.page): position = self._get_position_from_instance(item, self.ordering) if position != compare: # The item in this position and the item following it # have different positions. We can use this position as # our marker. has_item_with_unique_position = True break # The item in this position has the same position as the item # following it, we can't use it as a marker position, so increment # the offset and keep seeking to the previous item. compare = position offset += 1 if self.page and not has_item_with_unique_position: # There were no unique positions in the page. if not self.has_previous: # We are on the first page. # Our cursor will have an offset equal to the page size, # but no position to filter against yet. offset = self.page_size position = None elif self.cursor.reverse: # The change in direction will introduce a paging artifact, # where we end up skipping forward a few extra items. offset = 0 position = self.previous_position else: # Use the position from the existing cursor and increment # it's offset by the page size. offset = self.cursor.offset + self.page_size position = self.previous_position if not self.page: position = self.next_position cursor = Cursor(offset=offset, reverse=False, position=position) return self.encode_cursor(cursor) def get_previous_link(self): if not self.has_previous: return None if self.page and self.cursor and not self.cursor.reverse and self.cursor.offset != 0: # If we're reversing direction and we have an offset cursor # then we cannot use the first position we find as a marker. compare = self._get_position_from_instance(self.page[0], self.ordering) else: compare = self.previous_position offset = 0 has_item_with_unique_position = False for item in self.page: position = self._get_position_from_instance(item, self.ordering) if position != compare: # The item in this position and the item following it # have different positions. We can use this position as # our marker. has_item_with_unique_position = True break # The item in this position has the same position as the item # following it, we can't use it as a marker position, so increment # the offset and keep seeking to the previous item. compare = position offset += 1 if self.page and not has_item_with_unique_position: # There were no unique positions in the page. if not self.has_next: # We are on the final page. # Our cursor will have an offset equal to the page size, # but no position to filter against yet. offset = self.page_size position = None elif self.cursor.reverse: # Use the position from the existing cursor and increment # it's offset by the page size. offset = self.cursor.offset + self.page_size position = self.next_position else: # The change in direction will introduce a paging artifact, # where we end up skipping back a few extra items. offset = 0 position = self.next_position if not self.page: position = self.previous_position cursor = Cursor(offset=offset, reverse=True, position=position) return self.encode_cursor(cursor) 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') ] if ordering_filters: # If a filter exists on the view that implements `get_ordering` # then we defer to that filter to determine the ordering. filter_cls = ordering_filters[0] filter_instance = filter_cls() 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( type=type(ordering).__name__ ) ) if isinstance(ordering, str): return (ordering,) return tuple(ordering) def decode_cursor(self, request): """ Given a request with a cursor, return a `Cursor` instance. """ # Determine if we have a cursor, and if so then decode it. encoded = request.query_params.get(self.cursor_query_param) if encoded is None: return None try: querystring = b64decode(encoded.encode('ascii')).decode('ascii') tokens = parse.parse_qs(querystring, keep_blank_values=True) offset = tokens.get('o', ['0'])[0] offset = _positive_int(offset, cutoff=self.offset_cutoff) reverse = tokens.get('r', ['0'])[0] reverse = bool(int(reverse)) position = tokens.get('p', [None])[0] except (TypeError, ValueError): raise NotFound(self.invalid_cursor_message) return Cursor(offset=offset, reverse=reverse, position=position) def encode_cursor(self, cursor): """ Given a Cursor instance, return an url with encoded cursor. """ tokens = {} if cursor.offset != 0: tokens['o'] = str(cursor.offset) if cursor.reverse: tokens['r'] = '1' if cursor.position is not None: tokens['p'] = cursor.position querystring = parse.urlencode(tokens, doseq=True) encoded = b64encode(querystring.encode('ascii')).decode('ascii') return replace_query_param(self.base_url, self.cursor_query_param, encoded) def _get_position_from_instance(self, instance, ordering): field_name = ordering[0].lstrip('-') if isinstance(instance, dict): attr = instance[field_name] else: attr = getattr(instance, field_name) return str(attr) def get_paginated_response(self, 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, }, } def get_html_context(self): return { 'previous_url': self.get_previous_link(), 'next_url': self.get_next_link() } def to_html(self): template = loader.get_template(self.template) context = self.get_html_context() return template.render(context) def get_schema_operation_parameters(self, view): parameters = [ { 'name': self.cursor_query_param, 'required': False, 'in': 'query', 'description': force_str(self.cursor_query_description), 'schema': { 'type': 'string', }, } ] if self.page_size_query_param is not None: parameters.append( { 'name': self.page_size_query_param, 'required': False, 'in': 'query', 'description': force_str(self.page_size_query_description), 'schema': { 'type': 'integer', }, } ) return parameters ================================================ FILE: rest_framework/parsers.py ================================================ """ Parsers are used to parse the content of incoming HTTP requests. 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 from django.http import QueryDict from django.http.multipartparser import ChunkIter 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.exceptions import ParseError from rest_framework.settings import api_settings from rest_framework.utils import json class DataAndFiles: def __init__(self, data, files): self.data = data self.files = files class BaseParser: """ All parsers should extend `BaseParser`, specifying a `media_type` attribute, and overriding the `.parse()` method. """ media_type = None def parse(self, stream, media_type=None, parser_context=None): """ Given a stream to read from, return the parsed representation. Should return parsed data, or a `DataAndFiles` object consisting of the parsed data and files. """ raise NotImplementedError(".parse() must be overridden.") class JSONParser(BaseParser): """ Parses JSON-serialized data. """ media_type = 'application/json' renderer_class = renderers.JSONRenderer strict = api_settings.STRICT_JSON def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as JSON and returns the resulting data. """ parser_context = parser_context or {} encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) try: decoded_stream = codecs.getreader(encoding)(stream) parse_constant = json.strict_constant if self.strict else None return json.load(decoded_stream, parse_constant=parse_constant) except ValueError as exc: raise ParseError('JSON parse error - %s' % str(exc)) class FormParser(BaseParser): """ Parser for form data. """ media_type = 'application/x-www-form-urlencoded' def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a URL encoded form, and returns the resulting QueryDict. """ parser_context = parser_context or {} encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) return QueryDict(stream.read(), encoding=encoding) class MultiPartParser(BaseParser): """ Parser for multipart form data, which may include file data. """ media_type = 'multipart/form-data' def parse(self, stream, media_type=None, parser_context=None): """ Parses the incoming bytestream as a multipart encoded form, and returns a DataAndFiles object. `.data` will be a `QueryDict` containing all the form parameters. `.files` will be a `QueryDict` containing all the form files. """ parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META.copy() meta['CONTENT_TYPE'] = media_type upload_handlers = request.upload_handlers try: parser = DjangoMultiPartParser(meta, stream, upload_handlers, encoding) data, files = parser.parse() return DataAndFiles(data, files) except MultiPartParserError as exc: raise ParseError('Multipart form parse error - %s' % str(exc)) class FileUploadParser(BaseParser): """ Parser for file upload data. """ media_type = '*/*' errors = { 'unhandled': 'FileUpload parse error - none of upload handlers can handle the stream', 'no_filename': 'Missing filename. Request should include a Content-Disposition header with a filename parameter.', } def parse(self, stream, media_type=None, parser_context=None): """ Treats the incoming bytestream as a raw file upload and returns a `DataAndFiles` object. `.data` will be None (we expect request body to be a file content). `.files` will be a `QueryDict` containing one 'file' element. """ parser_context = parser_context or {} request = parser_context['request'] encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET) meta = request.META upload_handlers = request.upload_handlers filename = self.get_filename(stream, media_type, parser_context) if not filename: raise ParseError(self.errors['no_filename']) # Note that this code is extracted from Django's handling of # file uploads in MultiPartParser. content_type = meta.get('HTTP_CONTENT_TYPE', meta.get('CONTENT_TYPE', '')) try: content_length = int(meta.get('HTTP_CONTENT_LENGTH', meta.get('CONTENT_LENGTH', 0))) except (ValueError, TypeError): content_length = None # See if the handler will want to take care of the parsing. for handler in upload_handlers: result = handler.handle_raw_input(stream, meta, content_length, None, encoding) if result is not None: return DataAndFiles({}, {'file': result[1]}) # This is the standard case. possible_sizes = [x.chunk_size for x in upload_handlers if x.chunk_size] chunk_size = min([2 ** 31 - 4] + possible_sizes) chunks = ChunkIter(stream, chunk_size) counters = [0] * len(upload_handlers) for index, handler in enumerate(upload_handlers): try: handler.new_file(None, filename, content_type, content_length, encoding) except StopFutureHandlers: upload_handlers = upload_handlers[:index + 1] break for chunk in chunks: for index, handler in enumerate(upload_handlers): chunk_length = len(chunk) chunk = handler.receive_data_chunk(chunk, counters[index]) counters[index] += chunk_length if chunk is None: break for index, handler in enumerate(upload_handlers): file_obj = handler.file_complete(counters[index]) if file_obj is not None: return DataAndFiles({}, {'file': file_obj}) raise ParseError(self.errors['unhandled']) 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. """ with contextlib.suppress(KeyError): return parser_context['kwargs']['filename'] 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*'] return params['filename'] ================================================ FILE: rest_framework/permissions.py ================================================ """ Provides a set of pluggable permission policies. """ from django.http import Http404 from rest_framework import exceptions SAFE_METHODS = ('GET', 'HEAD', 'OPTIONS') class OperationHolderMixin: def __and__(self, other): return OperandHolder(AND, self, other) def __or__(self, other): return OperandHolder(OR, self, other) def __rand__(self, other): return OperandHolder(AND, other, self) def __ror__(self, other): return OperandHolder(OR, other, self) def __invert__(self): return SingleOperandHolder(NOT, self) class SingleOperandHolder(OperationHolderMixin): def __init__(self, operator_class, op1_class): self.operator_class = operator_class self.op1_class = op1_class def __call__(self, *args, **kwargs): op1 = self.op1_class(*args, **kwargs) return self.operator_class(op1) class OperandHolder(OperationHolderMixin): def __init__(self, operator_class, op1_class, op2_class): self.operator_class = operator_class self.op1_class = op1_class self.op2_class = op2_class def __call__(self, *args, **kwargs): op1 = self.op1_class(*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): self.op1 = op1 self.op2 = op2 def has_permission(self, request, view): return ( self.op1.has_permission(request, view) and self.op2.has_permission(request, view) ) def has_object_permission(self, request, view, obj): return ( self.op1.has_object_permission(request, view, obj) and self.op2.has_object_permission(request, view, obj) ) class OR: def __init__(self, op1, op2): self.op1 = op1 self.op2 = op2 def has_permission(self, request, view): return ( self.op1.has_permission(request, view) or self.op2.has_permission(request, view) ) def has_object_permission(self, request, view, obj): return ( self.op1.has_permission(request, view) and self.op1.has_object_permission(request, view, obj) ) or ( self.op2.has_permission(request, view) and self.op2.has_object_permission(request, view, obj) ) class NOT: def __init__(self, op1): self.op1 = op1 def has_permission(self, request, view): return not self.op1.has_permission(request, view) def has_object_permission(self, request, view, obj): return not self.op1.has_object_permission(request, view, obj) class BasePermissionMetaclass(OperationHolderMixin, type): pass class BasePermission(metaclass=BasePermissionMetaclass): """ A base class from which all permission classes should inherit. """ def has_permission(self, request, view): """ Return `True` if permission is granted, `False` otherwise. """ return True def has_object_permission(self, request, view, obj): """ Return `True` if permission is granted, `False` otherwise. """ return True class AllowAny(BasePermission): """ Allow any access. This isn't strictly required, since you could use an empty permission_classes list, but it's useful because it makes the intention more explicit. """ def has_permission(self, request, view): return True class IsAuthenticated(BasePermission): """ Allows access only to authenticated users. """ def has_permission(self, request, view): return bool(request.user and request.user.is_authenticated) class IsAdminUser(BasePermission): """ Allows access only to admin users. """ def has_permission(self, request, view): return bool(request.user and request.user.is_staff) class IsAuthenticatedOrReadOnly(BasePermission): """ The request is authenticated as a user, or is a read-only request. """ def has_permission(self, request, view): return bool( request.method in SAFE_METHODS or request.user and request.user.is_authenticated ) class DjangoModelPermissions(BasePermission): """ The request is authenticated using `django.contrib.auth` permissions. See: https://docs.djangoproject.com/en/dev/topics/auth/#permissions It ensures that the user is authenticated, and has the appropriate `add`/`change`/`delete` permissions on the model. This permission can only be applied against view classes that provide a `.queryset` attribute. """ # Map methods into required permission codes. # Override this if you need to also provide 'view' permissions, # or if you want to provide custom permission codes. perms_map = { 'GET': [], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } authenticated_users_only = True def get_required_permissions(self, method, model_cls): """ Given a model and an HTTP method, return the list of permission codes that the user is required to have. """ kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return [perm % kwargs for perm in self.perms_map[method]] def _queryset(self, view): assert hasattr(view, 'get_queryset') \ or getattr(view, 'queryset', None) is not None, ( 'Cannot apply {} on a view that does not set ' '`.queryset` or have a `.get_queryset()` method.' ).format(self.__class__.__name__) if hasattr(view, 'get_queryset'): queryset = view.get_queryset() assert queryset is not None, ( 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 queryset = self._queryset(view) perms = self.get_required_permissions(request.method, queryset.model) return request.user.has_perms(perms) class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions): """ Similar to DjangoModelPermissions, except that anonymous users are allowed read-only access. """ authenticated_users_only = False class DjangoObjectPermissions(DjangoModelPermissions): """ The request is authenticated using Django's object-level permissions. It requires an object-permissions-enabled backend, such as Django Guardian. It ensures that the user is authenticated, and has the appropriate `add`/`change`/`delete` permissions on the object using .has_perms. This permission can only be applied against view classes that provide a `.queryset` attribute. """ perms_map = { 'GET': [], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } def get_required_object_permissions(self, method, model_cls): kwargs = { 'app_label': model_cls._meta.app_label, 'model_name': model_cls._meta.model_name } if method not in self.perms_map: raise exceptions.MethodNotAllowed(method) return [perm % kwargs for perm in self.perms_map[method]] def has_object_permission(self, request, view, obj): # authentication checks have already executed via has_permission queryset = self._queryset(view) model_cls = queryset.model user = request.user perms = self.get_required_object_permissions(request.method, model_cls) if not user.has_perms(perms, obj): # If the user does not have permissions we need to determine if # they have read permissions to see 403, or not, and simply see # a 404 response. if request.method in SAFE_METHODS: # Read permissions already checked and failed, no need # to make another lookup. raise Http404 read_perms = self.get_required_object_permissions('GET', model_cls) if not user.has_perms(read_perms, obj): raise Http404 # Has read permissions. return False return True ================================================ FILE: rest_framework/relations.py ================================================ import contextlib import sys from operator import attrgetter from urllib import parse from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist from django.db.models import Manager from django.db.models.query import QuerySet from django.urls import NoReverseMatch, Resolver404, get_script_prefix, resolve from django.utils.encoding import smart_str, uri_to_iri from django.utils.translation import gettext_lazy as _ from rest_framework.fields import ( Field, SkipField, empty, get_attribute, is_simple_callable, iter_options ) from rest_framework.reverse import reverse from rest_framework.settings import api_settings from rest_framework.utils import html def method_overridden(method_name, klass, instance): """ Determine if a method has been overridden. """ method = getattr(klass, method_name) default_method = getattr(method, '__func__', method) # Python 3 compat return default_method is not getattr(instance, method_name).__func__ class ObjectValueError(ValueError): """ Raised when `queryset.get()` failed due to an underlying `ValueError`. Wrapping prevents calling code conflating this with unrelated errors. """ class ObjectTypeError(TypeError): """ Raised when `queryset.get()` failed due to an underlying `TypeError`. Wrapping prevents calling code conflating this with unrelated errors. """ class Hyperlink(str): """ A string like object that additionally has an associated name. We use this for hyperlinked URLs that may render as a named link in some contexts, or render as a plain URL in others. """ def __new__(cls, url, obj): ret = super().__new__(cls, url) ret.obj = obj return ret def __getnewargs__(self): return (str(self), self.name) @property def name(self): # This ensures that we only called `__str__` lazily, # as in some cases calling __str__ on a model instances *might* # involve a database lookup. return str(self.obj) is_hyperlink = True class PKOnlyObject: """ This is a mock object, used for when we only need the pk of the object instance, but still want to return an object with a .pk attribute, in order to keep the same interface as a regular model instance. """ def __init__(self, pk): self.pk = pk def __str__(self): return "%s" % self.pk # We assume that 'validators' are intended for the child serializer, # rather than the parent serializer. MANY_RELATION_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'allow_empty', 'html_cutoff', 'html_cutoff_text' ) class RelatedField(Field): queryset = None html_cutoff = None html_cutoff_text = None def __init__(self, **kwargs): self.queryset = kwargs.pop('queryset', self.queryset) cutoff_from_settings = api_settings.HTML_SELECT_CUTOFF if cutoff_from_settings is not None: cutoff_from_settings = int(cutoff_from_settings) self.html_cutoff = kwargs.pop('html_cutoff', cutoff_from_settings) self.html_cutoff_text = kwargs.pop( 'html_cutoff_text', self.html_cutoff_text or _(api_settings.HTML_SELECT_CUTOFF_TEXT) ) if not method_overridden('get_queryset', RelatedField, self): assert self.queryset is not None or kwargs.get('read_only'), ( 'Relational field must provide a `queryset` argument, ' 'override `get_queryset`, or set read_only=`True`.' ) assert not (self.queryset is not None and kwargs.get('read_only')), ( 'Relational fields should not provide a `queryset` argument, ' 'when setting read_only=`True`.' ) kwargs.pop('many', None) kwargs.pop('allow_empty', None) super().__init__(**kwargs) def __new__(cls, *args, **kwargs): # We override this method in order to automagically create # `ManyRelatedField` classes instead when `many=True` is set. if kwargs.pop('many', False): return cls.many_init(*args, **kwargs) return super().__new__(cls, *args, **kwargs) @classmethod def many_init(cls, *args, **kwargs): """ This method handles creating a parent `ManyRelatedField` instance when the `many=True` keyword argument is passed. Typically you won't need to override this method. Note that we're over-cautious in passing most arguments to both parent and child classes in order to try to cover the general case. If you're overriding this method you'll probably want something much simpler, eg: @classmethod def many_init(cls, *args, **kwargs): kwargs['child'] = cls() return CustomManyRelatedField(*args, **kwargs) """ list_kwargs = {'child_relation': cls(*args, **kwargs)} for key in kwargs: if key in MANY_RELATION_KWARGS: list_kwargs[key] = kwargs[key] return ManyRelatedField(**list_kwargs) def run_validation(self, data=empty): # We force empty strings to None values for relational fields. if data == '': data = None return super().run_validation(data) def get_queryset(self): queryset = self.queryset if isinstance(queryset, (QuerySet, Manager)): # Ensure queryset is re-evaluated whenever used. # Note that actually a `Manager` class may also be used as the # queryset argument. This occurs on ModelSerializer fields, # as it allows us to generate a more expressive 'repr' output # for the field. # Eg: 'MyRelationship(queryset=ExampleModel.objects.all())' queryset = queryset.all() return queryset def use_pk_only_optimization(self): return False 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. 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): # Handle edge case where the relationship `source` argument # points to a `get_relationship()` method on the model. value = value() # Handle edge case where relationship `source` argument points # to an instance instead of a pk (e.g., a `@property`). value = getattr(value, 'pk', value) return PKOnlyObject(pk=value) # Standard case, return the object instance. return super().get_attribute(instance) def get_choices(self, cutoff=None): queryset = self.get_queryset() if queryset is None: # Ensure that field.choices returns something sensible # even when accessed with a read-only field. return {} if cutoff is not None: queryset = queryset[:cutoff] return { self.to_representation(item): self.display_value(item) for item in queryset } @property def choices(self): return self.get_choices() @property def grouped_choices(self): return self.choices def iter_options(self): return iter_options( self.get_choices(cutoff=self.html_cutoff), cutoff=self.html_cutoff, cutoff_text=self.html_cutoff_text ) def display_value(self, instance): return str(instance) class StringRelatedField(RelatedField): """ A read only field that represents its targets using their plain string representation. """ def __init__(self, **kwargs): kwargs['read_only'] = True super().__init__(**kwargs) def to_representation(self, value): return str(value) class PrimaryKeyRelatedField(RelatedField): default_error_messages = { 'required': _('This field is required.'), 'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'), 'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'), } def __init__(self, **kwargs): self.pk_field = kwargs.pop('pk_field', None) super().__init__(**kwargs) def use_pk_only_optimization(self): return True def to_internal_value(self, data): if self.pk_field is not None: data = self.pk_field.to_internal_value(data) queryset = self.get_queryset() try: if isinstance(data, bool): raise TypeError return queryset.get(pk=data) except ObjectDoesNotExist: self.fail('does_not_exist', pk_value=data) except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data).__name__) def to_representation(self, value): if self.pk_field is not None: return self.pk_field.to_representation(value.pk) return value.pk class HyperlinkedRelatedField(RelatedField): lookup_field = 'pk' view_name = None default_error_messages = { 'required': _('This field is required.'), 'no_match': _('Invalid hyperlink - No URL match.'), 'incorrect_match': _('Invalid hyperlink - Incorrect URL match.'), 'does_not_exist': _('Invalid hyperlink - Object does not exist.'), 'incorrect_type': _('Incorrect type. Expected URL string, received {data_type}.'), } def __init__(self, view_name=None, **kwargs): if view_name is not None: self.view_name = view_name assert self.view_name is not None, 'The `view_name` argument is required.' self.lookup_field = kwargs.pop('lookup_field', self.lookup_field) self.lookup_url_kwarg = kwargs.pop('lookup_url_kwarg', self.lookup_field) self.format = kwargs.pop('format', None) # We include this simply for dependency injection in tests. # We can't add it as a class attributes or it would expect an # implicit `self` argument to be passed. self.reverse = reverse super().__init__(**kwargs) def use_pk_only_optimization(self): return self.lookup_field == 'pk' def get_object(self, view_name, view_args, view_kwargs): """ Return the object corresponding to a matched URL. Takes the matched URL conf arguments, and should return an object instance, or raise an `ObjectDoesNotExist` exception. """ lookup_value = view_kwargs[self.lookup_url_kwarg] lookup_kwargs = {self.lookup_field: lookup_value} queryset = self.get_queryset() try: return queryset.get(**lookup_kwargs) except ValueError: exc = ObjectValueError(str(sys.exc_info()[1])) raise exc.with_traceback(sys.exc_info()[2]) except TypeError: exc = ObjectTypeError(str(sys.exc_info()[1])) raise exc.with_traceback(sys.exc_info()[2]) def get_url(self, obj, view_name, request, format): """ Given an object, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf. """ # Unsaved objects will not yet have a valid URL. if hasattr(obj, 'pk') and obj.pk in (None, ''): return None lookup_value = getattr(obj, self.lookup_field) kwargs = {self.lookup_url_kwarg: lookup_value} return self.reverse(view_name, kwargs=kwargs, request=request, format=format) def to_internal_value(self, data): request = self.context.get('request') try: http_prefix = data.startswith(('http:', 'https:')) except AttributeError: self.fail('incorrect_type', data_type=type(data).__name__) if http_prefix: # If needed convert absolute URLs to relative path data = parse.urlparse(data).path prefix = get_script_prefix() if data.startswith(prefix): data = '/' + data[len(prefix):] data = uri_to_iri(parse.unquote(data)) try: match = resolve(data) except Resolver404: self.fail('no_match') try: expected_viewname = request.versioning_scheme.get_versioned_viewname( self.view_name, request ) except AttributeError: expected_viewname = self.view_name if match.view_name != expected_viewname: self.fail('incorrect_match') try: return self.get_object(match.view_name, match.args, match.kwargs) except (ObjectDoesNotExist, ObjectValueError, ObjectTypeError): self.fail('does_not_exist') def to_representation(self, value): assert 'request' in self.context, ( "`%s` requires the request in the serializer" " context. Add `context={'request': request}` when instantiating " "the serializer." % self.__class__.__name__ ) request = self.context['request'] format = self.context.get('format') # By default use whatever format is given for the current context # unless the target is a different type to the source. # # Eg. Consider a HyperlinkedIdentityField pointing from a json # representation to an html property of that representation... # # '/snippets/1/' should link to '/snippets/1/highlight/' # ...but... # '/snippets/1/.json' should link to '/snippets/1/highlight/.html' if format and self.format and self.format != format: format = self.format # Return the hyperlink, or error if incorrectly configured. try: url = self.get_url(value, self.view_name, request, format) except NoReverseMatch: msg = ( 'Could not resolve URL for hyperlinked relationship using ' 'view name "%s". You may have failed to include the related ' 'model in your API, or incorrectly configured the ' '`lookup_field` attribute on this field.' ) if value in ('', None): value_string = {'': 'the empty string', None: 'None'}[value] msg += ( " WARNING: The value of the field on the model instance " "was %s, which may be why it didn't match any " "entries in your URL conf." % value_string ) raise ImproperlyConfigured(msg % self.view_name) if url is None: return None return Hyperlink(url, value) class HyperlinkedIdentityField(HyperlinkedRelatedField): """ A read-only field that represents the identity URL for an object, itself. This is in contrast to `HyperlinkedRelatedField` which represents the URL of relationships to other objects. """ def __init__(self, view_name=None, **kwargs): assert view_name is not None, 'The `view_name` argument is required.' kwargs['read_only'] = True kwargs['source'] = '*' super().__init__(view_name, **kwargs) def use_pk_only_optimization(self): # We have the complete object instance already. We don't need # to run the 'only get the pk for this relationship' code. return False class SlugRelatedField(RelatedField): """ A read-write field that represents the target of the relationship by a unique 'slug' attribute. """ default_error_messages = { 'does_not_exist': _('Object with {slug_name}={value} does not exist.'), 'invalid': _('Invalid value.'), } def __init__(self, slug_field=None, **kwargs): assert slug_field is not None, 'The `slug_field` argument is required.' self.slug_field = slug_field super().__init__(**kwargs) def to_internal_value(self, data): queryset = self.get_queryset() try: return queryset.get(**{self.slug_field: data}) except ObjectDoesNotExist: self.fail('does_not_exist', slug_name=self.slug_field, value=smart_str(data)) except (TypeError, ValueError): self.fail('invalid') def to_representation(self, obj): slug = self.slug_field if "__" in slug: # handling nested relationship if defined slug = slug.replace('__', '.') return attrgetter(slug)(obj) class ManyRelatedField(Field): """ Relationships with `many=True` transparently get coerced into instead being a ManyRelatedField with a child relationship. The `ManyRelatedField` class is responsible for handling iterating through the values and passing each one to the child relationship. This class is treated as private API. You shouldn't generally need to be using this class directly yourself, and should instead simply set 'many=True' on the relationship. """ initial = [] default_empty_html = [] default_error_messages = { 'not_a_list': _('Expected a list of items but got type "{input_type}".'), 'empty': _('This list may not be empty.') } html_cutoff = None html_cutoff_text = None def __init__(self, child_relation=None, *args, **kwargs): self.child_relation = child_relation self.allow_empty = kwargs.pop('allow_empty', True) cutoff_from_settings = api_settings.HTML_SELECT_CUTOFF if cutoff_from_settings is not None: cutoff_from_settings = int(cutoff_from_settings) self.html_cutoff = kwargs.pop('html_cutoff', cutoff_from_settings) self.html_cutoff_text = kwargs.pop( 'html_cutoff_text', self.html_cutoff_text or _(api_settings.HTML_SELECT_CUTOFF_TEXT) ) assert child_relation is not None, '`child_relation` is a required argument.' super().__init__(*args, **kwargs) self.child_relation.bind(field_name='', parent=self) def get_value(self, dictionary): # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): # Don't return [] if the update is partial if self.field_name not in dictionary: if getattr(self.root, 'partial', False): return empty return dictionary.getlist(self.field_name) return dictionary.get(self.field_name, empty) def to_internal_value(self, data): if isinstance(data, str) or not hasattr(data, '__iter__'): self.fail('not_a_list', input_type=type(data).__name__) if not self.allow_empty and len(data) == 0: self.fail('empty') return [ self.child_relation.to_internal_value(item) for item in data ] def get_attribute(self, instance): # Can't have any relationships if not created if hasattr(instance, 'pk') and instance.pk is None: return [] try: relationship = get_attribute(instance, self.source_attrs) except (KeyError, AttributeError) as exc: if self.default is not empty: return self.get_default() if self.allow_null: return None if not self.required: raise SkipField() msg = ( 'Got {exc_type} when attempting to get a value for field ' '`{field}` on serializer `{serializer}`.\nThe serializer ' 'field might be named incorrectly and not match ' 'any attribute or key on the `{instance}` instance.\n' 'Original exception text was: {exc}.'.format( exc_type=type(exc).__name__, field=self.field_name, serializer=self.parent.__class__.__name__, instance=instance.__class__.__name__, exc=exc ) ) raise type(exc)(msg) return relationship.all() if hasattr(relationship, 'all') else relationship def to_representation(self, iterable): return [ self.child_relation.to_representation(value) for value in iterable ] def get_choices(self, cutoff=None): return self.child_relation.get_choices(cutoff) @property def choices(self): return self.get_choices() @property def grouped_choices(self): return self.choices def iter_options(self): return iter_options( self.get_choices(cutoff=self.html_cutoff), cutoff=self.html_cutoff, cutoff_text=self.html_cutoff_text ) ================================================ FILE: rest_framework/renderers.py ================================================ """ Renderers are used to serialize a response into specific media types. They give us a generic way of being able to handle various media types on the response, such as JSON encoded data or HTML output. REST framework also provides an HTML renderer that renders the browsable API. """ import contextlib import datetime import sys from django import forms from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.paginator import Page from django.template import engines, loader from django.urls import NoReverseMatch from django.utils.http import parse_header_parameters from django.utils.safestring import SafeString from rest_framework import ISO_8601, VERSION, exceptions, serializers, status from rest_framework.compat import ( INDENT_SEPARATORS, LONG_SEPARATORS, SHORT_SEPARATORS, pygments_css, yaml ) from rest_framework.exceptions import ParseError from rest_framework.request import is_form_media_type, override_method from rest_framework.settings import api_settings from rest_framework.utils import encoders, json from rest_framework.utils.breadcrumbs import get_breadcrumbs from rest_framework.utils.field_mapping import ClassLookupDict def zero_as_none(value): return None if value == 0 else value class BaseRenderer: """ All renderers should extend this class, setting the `media_type` and `format` attributes, and override the `.render()` method. """ media_type = None format = None charset = 'utf-8' render_style = 'text' def render(self, data, accepted_media_type=None, renderer_context=None): raise NotImplementedError('Renderer class requires .render() to be implemented') class JSONRenderer(BaseRenderer): """ Renderer which serializes to JSON. """ media_type = 'application/json' format = 'json' encoder_class = encoders.JSONEncoder ensure_ascii = not api_settings.UNICODE_JSON compact = api_settings.COMPACT_JSON strict = api_settings.STRICT_JSON # We don't set a charset because JSON is a binary encoding, # that can be encoded as utf-8, utf-16 or utf-32. # See: https://www.ietf.org/rfc/rfc4627.txt # Also: http://lucumr.pocoo.org/2013/7/19/application-mimetypes-and-encodings/ charset = None def get_indent(self, accepted_media_type, renderer_context): if accepted_media_type: # If the media type looks like 'application/json; indent=4', # then pretty print the result. # Note that we coerce `indent=0` into `indent=None`. base_media_type, params = parse_header_parameters(accepted_media_type) with contextlib.suppress(KeyError, ValueError, TypeError): return zero_as_none(max(min(int(params['indent']), 8), 0)) # 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) def render(self, data, accepted_media_type=None, renderer_context=None): """ Render `data` into JSON, returning a bytestring. """ if data is None: return b'' renderer_context = renderer_context or {} indent = self.get_indent(accepted_media_type, renderer_context) if indent is None: separators = SHORT_SEPARATORS if self.compact else LONG_SEPARATORS else: separators = INDENT_SEPARATORS ret = json.dumps( data, cls=self.encoder_class, indent=indent, ensure_ascii=self.ensure_ascii, allow_nan=not self.strict, separators=separators ) # We always fully escape \u2028 and \u2029 to ensure we output JSON # that is a strict javascript subset. # See: https://gist.github.com/damncabbage/623b879af56f850a6ddc ret = ret.replace('\u2028', '\\u2028').replace('\u2029', '\\u2029') return ret.encode() class TemplateHTMLRenderer(BaseRenderer): """ An HTML renderer for use with templates. The data supplied to the Response object should be a dictionary that will be used as context for the template. The template name is determined by (in order of preference): 1. An explicit `.template_name` attribute set on the response. 2. An explicit `.template_name` attribute set on this class. 3. The return result of calling `view.get_template_names()`. For example: data = {'users': User.objects.all()} return Response(data, template_name='users.html') For pre-rendered HTML, see StaticHTMLRenderer. """ media_type = 'text/html' format = 'html' template_name = None exception_template_names = [ '%(status_code)s.html', 'api_exception.html' ] charset = 'utf-8' def render(self, data, accepted_media_type=None, renderer_context=None): """ Renders data to HTML, using Django's standard template rendering. The template name is determined by (in order of preference): 1. An explicit .template_name set on the response. 2. An explicit .template_name set on this class. 3. The return result of calling view.get_template_names(). """ renderer_context = renderer_context or {} view = renderer_context['view'] request = renderer_context['request'] response = renderer_context['response'] if response.exception: template = self.get_exception_template(response) else: template_names = self.get_template_names(response, view) template = self.resolve_template(template_names) if hasattr(self, 'resolve_context'): # Fallback for older versions. context = self.resolve_context(data, request, response) else: context = self.get_template_context(data, renderer_context) return template.render(context, request=request) def resolve_template(self, template_names): return loader.select_template(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 def get_template_names(self, response, view): if response.template_name: return [response.template_name] elif self.template_name: return [self.template_name] elif hasattr(view, 'get_template_names'): return view.get_template_names() elif hasattr(view, 'template_name'): return [view.template_name] raise ImproperlyConfigured( 'Returned a template response with no `template_name` attribute set on either the view or response' ) def get_exception_template(self, response): template_names = [name % {'status_code': response.status_code} for name in self.exception_template_names] try: # Try to find an appropriate error template return self.resolve_template(template_names) except Exception: # Fall back to using eg '404 Not Found' body = '%d %s' % (response.status_code, response.status_text.title()) template = engines['django'].from_string(body) return template # Note, subclass TemplateHTMLRenderer simply for the exception behavior class StaticHTMLRenderer(TemplateHTMLRenderer): """ An HTML renderer class that simply returns pre-rendered HTML. The data supplied to the Response object should be a string representing the pre-rendered HTML content. For example: data = 'example' return Response(data) For template rendered HTML, see TemplateHTMLRenderer. """ media_type = 'text/html' format = 'html' charset = 'utf-8' def render(self, data, accepted_media_type=None, renderer_context=None): renderer_context = renderer_context or {} response = renderer_context.get('response') if response and response.exception: request = renderer_context['request'] template = self.get_exception_template(response) if hasattr(self, 'resolve_context'): context = self.resolve_context(data, request, response) else: context = self.get_template_context(data, renderer_context) return template.render(context, request=request) return data class HTMLFormRenderer(BaseRenderer): """ Renderers serializer data into an HTML form. If the serializer was instantiated without an object then this will return an HTML form not bound to any object, otherwise it will return an HTML form with the appropriate initial data populated from the object. Note that rendering of field and form errors is not currently supported. """ media_type = 'text/html' format = 'form' charset = 'utf-8' template_pack = 'rest_framework/vertical/' base_template = 'form.html' default_style = ClassLookupDict({ serializers.Field: { 'base_template': 'input.html', 'input_type': 'text' }, serializers.EmailField: { 'base_template': 'input.html', 'input_type': 'email' }, serializers.URLField: { 'base_template': 'input.html', 'input_type': 'url' }, serializers.IntegerField: { 'base_template': 'input.html', 'input_type': 'number' }, serializers.FloatField: { 'base_template': 'input.html', 'input_type': 'number' }, serializers.DateTimeField: { 'base_template': 'input.html', 'input_type': 'datetime-local' }, serializers.DateField: { 'base_template': 'input.html', 'input_type': 'date' }, serializers.TimeField: { 'base_template': 'input.html', 'input_type': 'time' }, serializers.FileField: { 'base_template': 'input.html', 'input_type': 'file' }, serializers.BooleanField: { 'base_template': 'checkbox.html' }, serializers.ChoiceField: { 'base_template': 'select.html', # Also valid: 'radio.html' }, serializers.MultipleChoiceField: { 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html' }, serializers.RelatedField: { 'base_template': 'select.html', # Also valid: 'radio.html' }, serializers.ManyRelatedField: { 'base_template': 'select_multiple.html', # Also valid: 'checkbox_multiple.html' }, serializers.Serializer: { 'base_template': 'fieldset.html' }, serializers.ListSerializer: { 'base_template': 'list_fieldset.html' }, serializers.ListField: { 'base_template': 'list_field.html' }, serializers.DictField: { 'base_template': 'dict_field.html' }, serializers.FilePathField: { 'base_template': 'select.html', }, serializers.JSONField: { 'base_template': 'textarea.html', }, }) def render_field(self, field, parent_style): if isinstance(field._field, serializers.HiddenField): return '' style = self.default_style[field].copy() style.update(field.style) if 'template_pack' not in style: style['template_pack'] = parent_style.get('template_pack', self.template_pack) style['renderer'] = self # Get a clone of the field with text-only value representation ('' if None or False). field = field.as_form_field() if style.get('input_type') == 'datetime-local': try: format_ = field._field.format except AttributeError: format_ = api_settings.DATETIME_FORMAT if format_ is not None: # field.value is expected to be a string # https://www.django-rest-framework.org/api-guide/fields/#datetimefield field_value = field.value if format_ == ISO_8601 and sys.version_info < (3, 11): # We can drop this branch once we drop support for Python < 3.11 # https://docs.python.org/3/whatsnew/3.11.html#datetime field_value = field_value.rstrip('Z') field.value = ( datetime.datetime.fromisoformat(field_value) if format_ == ISO_8601 else datetime.datetime.strptime(field_value, format_) ) # The format of an input type="datetime-local" is "yyyy-MM-ddThh:mm" # followed by optional ":ss" or ":ss.SSS", so keep only the first three # digits of milliseconds to avoid browser console error. field.value = field.value.replace(tzinfo=None).isoformat(timespec="milliseconds") if 'template' in style: template_name = style['template'] else: template_name = style['template_pack'].strip('/') + '/' + style['base_template'] template = loader.get_template(template_name) context = {'field': field, 'style': style} return template.render(context) def render(self, data, accepted_media_type=None, renderer_context=None): """ Render serializer data and return an HTML form, as a string. """ renderer_context = renderer_context or {} form = data.serializer style = renderer_context.get('style', {}) if 'template_pack' not in style: style['template_pack'] = self.template_pack style['renderer'] = self template_pack = style['template_pack'].strip('/') template_name = template_pack + '/' + self.base_template template = loader.get_template(template_name) context = { 'form': form, 'style': style } return template.render(context) class BrowsableAPIRenderer(BaseRenderer): """ HTML renderer used to self-document the API. """ media_type = 'text/html' format = 'api' template = 'rest_framework/api.html' filter_template = 'rest_framework/filters/base.html' code_style = 'emacs' charset = 'utf-8' form_renderer_class = HTMLFormRenderer def get_default_renderer(self, view): """ Return an instance of the first valid renderer. (Don't use another documenting renderer.) """ renderers = [renderer for renderer in view.renderer_classes if not issubclass(renderer, BrowsableAPIRenderer)] non_template_renderers = [renderer for renderer in renderers if not hasattr(renderer, 'get_template_names')] if not renderers: return None elif non_template_renderers: return non_template_renderers[0]() return renderers[0]() def get_content(self, renderer, data, accepted_media_type, renderer_context): """ Get the content as if it had been rendered by the default non-documenting renderer. """ if not renderer: return '[No renderers were found]' renderer_context['indent'] = 4 content = renderer.render(data, accepted_media_type, renderer_context) render_style = getattr(renderer, 'render_style', 'text') assert render_style in ['text', 'binary'], 'Expected .render_style ' \ '"text" or "binary", but got "%s"' % render_style if render_style == 'binary': return '[%d bytes of binary content]' % len(content) return content.decode('utf-8') if isinstance(content, bytes) else content def show_form_for_method(self, view, method, request, obj): """ Returns True if a form should be shown for this method. """ if method not in view.allowed_methods: return # Not a valid method try: view.check_permissions(request) if obj is not None: view.check_object_permissions(request, obj) except exceptions.APIException: return False # Doesn't have permissions return True def _get_serializer(self, serializer_class, view_instance, request, *args, **kwargs): kwargs['context'] = { 'request': request, 'format': self.format, 'view': view_instance } return serializer_class(*args, **kwargs) def get_rendered_html_form(self, data, view, method, request): """ Return a string representing a rendered HTML form, possibly bound to either the input or output data. In the absence of the View having an associated form then return None. """ # See issue #2089 for refactoring this. serializer = getattr(data, 'serializer', None) if serializer and not getattr(serializer, 'many', False): instance = getattr(serializer, 'instance', None) if isinstance(instance, Page): instance = None else: instance = None # If this is valid serializer data, and the form is for the same # HTTP method as was used in the request then use the existing # serializer instance, rather than dynamically creating a new one. if request.method == method and serializer is not None: try: kwargs = {'data': request.data} except ParseError: kwargs = {} existing_serializer = serializer else: kwargs = {} existing_serializer = None with override_method(view, request, method) as request: if not self.show_form_for_method(view, method, request, instance): return if method in ('DELETE', 'OPTIONS'): return True # Don't actually need to return a form has_serializer = getattr(view, 'get_serializer', None) has_serializer_class = getattr(view, 'serializer_class', None) if ( (not has_serializer and not has_serializer_class) or not any(is_form_media_type(parser.media_type) for parser in view.parser_classes) ): return if existing_serializer is not None: with contextlib.suppress(TypeError): return self.render_form_for_serializer(existing_serializer) if has_serializer: if method in ('PUT', 'PATCH'): serializer = view.get_serializer(instance=instance, **kwargs) else: serializer = view.get_serializer(**kwargs) else: # at this point we must have a serializer_class if method in ('PUT', 'PATCH'): serializer = self._get_serializer(view.serializer_class, view, request, instance=instance, **kwargs) else: serializer = self._get_serializer(view.serializer_class, view, request, **kwargs) 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() form_renderer = self.form_renderer_class() return form_renderer.render( serializer.data, self.accepted_media_type, {'style': {'template_pack': 'rest_framework/horizontal'}} ) def get_raw_data_form(self, data, view, method, request): """ Returns a form that allows for arbitrary content types to be tunneled via standard HTML forms. (Which are typically application/x-www-form-urlencoded) """ # See issue #2089 for refactoring this. serializer = getattr(data, 'serializer', None) if serializer and not getattr(serializer, 'many', False): instance = getattr(serializer, 'instance', None) if isinstance(instance, Page): instance = None else: instance = None with override_method(view, request, method) as request: # Check permissions if not self.show_form_for_method(view, method, request, instance): return # If possible, serialize the initial content for the generic form default_parser = view.parser_classes[0] renderer_class = getattr(default_parser, 'renderer_class', None) if hasattr(view, 'get_serializer') and renderer_class: # View has a serializer defined and parser class has a # corresponding renderer that can be used to render the data. if method in ('PUT', 'PATCH'): serializer = view.get_serializer(instance=instance) else: serializer = view.get_serializer() # Render the raw data content renderer = renderer_class() accepted = self.accepted_media_type context = self.renderer_context.copy() 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() else: content = None # Generate a generic form that includes a content type field, # and a content field. media_types = [parser.media_type for parser in view.parser_classes] choices = [(media_type, media_type) for media_type in media_types] initial = media_types[0] class GenericContentForm(forms.Form): _content_type = forms.ChoiceField( label='Media type', choices=choices, initial=initial, widget=forms.Select(attrs={'data-override': 'content-type'}) ) _content = forms.CharField( label='Content', widget=forms.Textarea(attrs={'data-override': 'content'}), initial=content, required=False ) return GenericContentForm() def get_name(self, view): return view.get_view_name() def get_description(self, view, status_code): if status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN): return '' return view.get_view_description(html=True) def get_breadcrumbs(self, request): return get_breadcrumbs(request.path, request) def get_extra_actions(self, view, status_code): if (status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)): return None elif not hasattr(view, 'get_extra_action_url_map'): return None return view.get_extra_action_url_map() def get_filter_form(self, data, view, request): if not hasattr(view, 'get_queryset') or not hasattr(view, 'filter_backends'): return # Infer if this is a list view or not. paginator = getattr(view, 'paginator', None) if isinstance(data, list): pass elif paginator is not None and data is not None: try: paginator.get_results(data) except (TypeError, KeyError): return elif not isinstance(data, list): return queryset = view.get_queryset() elements = [] for backend in view.filter_backends: if hasattr(backend, 'to_html'): html = backend().to_html(request, queryset, view) if html: elements.append(html) if not elements: return template = loader.get_template(self.filter_template) context = {'elements': elements} return template.render(context) def get_context(self, data, accepted_media_type, renderer_context): """ Returns the context used to render. """ view = renderer_context['view'] request = renderer_context['request'] response = renderer_context['response'] renderer = self.get_default_renderer(view) raw_data_post_form = self.get_raw_data_form(data, view, 'POST', request) raw_data_put_form = self.get_raw_data_form(data, view, 'PUT', request) raw_data_patch_form = self.get_raw_data_form(data, view, 'PATCH', request) raw_data_put_or_patch_form = raw_data_put_form or raw_data_patch_form response_headers = dict(sorted(response.items())) renderer_content_type = '' if renderer: renderer_content_type = '%s' % renderer.media_type if renderer.charset: renderer_content_type += ' ;%s' % renderer.charset response_headers['Content-Type'] = renderer_content_type if getattr(view, 'paginator', None) and view.paginator.display_page_controls: paginator = view.paginator else: paginator = None csrf_cookie_name = settings.CSRF_COOKIE_NAME csrf_header_name = settings.CSRF_HEADER_NAME if csrf_header_name.startswith('HTTP_'): csrf_header_name = csrf_header_name[5:] csrf_header_name = csrf_header_name.replace('_', '-') return { 'content': self.get_content(renderer, data, accepted_media_type, renderer_context), 'code_style': pygments_css(self.code_style), 'view': view, 'request': request, 'response': response, 'user': request.user, 'description': self.get_description(view, response.status_code), 'name': self.get_name(view), 'version': VERSION, 'paginator': paginator, 'breadcrumblist': self.get_breadcrumbs(request), 'allowed_methods': view.allowed_methods, 'available_formats': [renderer_cls.format for renderer_cls in view.renderer_classes], 'response_headers': response_headers, 'put_form': self.get_rendered_html_form(data, view, 'PUT', request), 'post_form': self.get_rendered_html_form(data, view, 'POST', request), 'delete_form': self.get_rendered_html_form(data, view, 'DELETE', request), 'options_form': self.get_rendered_html_form(data, view, 'OPTIONS', request), 'extra_actions': self.get_extra_actions(view, response.status_code), 'filter_form': self.get_filter_form(data, view, request), 'raw_data_put_form': raw_data_put_form, 'raw_data_post_form': raw_data_post_form, 'raw_data_patch_form': raw_data_patch_form, 'raw_data_put_or_patch_form': raw_data_put_or_patch_form, 'display_edit_forms': bool(response.status_code != 403), 'api_settings': api_settings, 'csrf_cookie_name': csrf_cookie_name, 'csrf_header_name': csrf_header_name } def render(self, data, accepted_media_type=None, renderer_context=None): """ Render the HTML for the browsable API representation. """ self.accepted_media_type = accepted_media_type or '' self.renderer_context = renderer_context or {} template = loader.get_template(self.template) context = self.get_context(data, accepted_media_type, renderer_context) ret = template.render(context, request=renderer_context['request']) # Munge DELETE Response code to allow us to return content # (Do this *after* we've rendered the template so that we include # the normal deletion response code in the output) response = renderer_context['response'] if response.status_code == status.HTTP_204_NO_CONTENT: response.status_code = status.HTTP_200_OK return ret class AdminRenderer(BrowsableAPIRenderer): template = 'rest_framework/admin.html' format = 'admin' def render(self, data, accepted_media_type=None, renderer_context=None): self.accepted_media_type = accepted_media_type or '' self.renderer_context = renderer_context or {} response = renderer_context['response'] request = renderer_context['request'] view = self.renderer_context['view'] if response.status_code == status.HTTP_400_BAD_REQUEST: # Errors still need to display the list or detail information. # The only way we can get at that is to simulate a GET request. self.error_form = self.get_rendered_html_form(data, view, request.method, request) self.error_title = {'POST': 'Create', 'PUT': 'Edit'}.get(request.method, 'Errors') with override_method(view, request, 'GET') as request: response = view.get(request, *view.args, **view.kwargs) data = response.data template = loader.get_template(self.template) context = self.get_context(data, accepted_media_type, renderer_context) ret = template.render(context, request=renderer_context['request']) # Creation and deletion should use redirects in the admin style. if response.status_code == status.HTTP_201_CREATED and 'Location' in response: response.status_code = status.HTTP_303_SEE_OTHER response['Location'] = request.build_absolute_uri() ret = '' if response.status_code == status.HTTP_204_NO_CONTENT: response.status_code = status.HTTP_303_SEE_OTHER try: # Attempt to get the parent breadcrumb URL. response['Location'] = self.get_breadcrumbs(request)[-2][1] except KeyError: # Otherwise reload current URL to get a 'Not Found' page. response['Location'] = request.full_path ret = '' return ret def get_context(self, data, accepted_media_type, renderer_context): """ Render the HTML for the browsable API representation. """ context = super().get_context( data, accepted_media_type, renderer_context ) paginator = getattr(context['view'], 'paginator', None) if paginator is not None and data is not None: try: results = paginator.get_results(data) except (TypeError, KeyError): results = data else: results = data if results is None: header = {} style = 'detail' elif isinstance(results, list): header = results[0] if results else {} style = 'list' else: header = results style = 'detail' columns = [key for key in header if key != 'url'] details = [key for key in header if key != 'url'] if isinstance(results, list) and 'view' in renderer_context: for result in results: url = self.get_result_url(result, context['view']) if url is not None: result.setdefault('url', url) context['style'] = style context['columns'] = columns context['details'] = details context['results'] = results context['error_form'] = getattr(self, 'error_form', None) context['error_title'] = getattr(self, 'error_title', None) return context def get_result_url(self, result, view): """ Attempt to reverse the result's detail view URL. This only works with views that are generic-like (has `.lookup_field`) and viewset-like (has `.basename` / `.reverse_action()`). """ if not hasattr(view, 'reverse_action') or \ not hasattr(view, 'lookup_field'): return lookup_field = view.lookup_field lookup_url_kwarg = getattr(view, 'lookup_url_kwarg', None) or lookup_field try: kwargs = {lookup_url_kwarg: result[lookup_field]} return view.reverse_action('detail', kwargs=kwargs) except (KeyError, NoReverseMatch): return class MultiPartRenderer(BaseRenderer): media_type = 'multipart/form-data; boundary=BoUnDaRyStRiNg' format = 'multipart' charset = 'utf-8' BOUNDARY = 'BoUnDaRyStRiNg' def render(self, data, accepted_media_type=None, renderer_context=None): from django.test.client import encode_multipart if hasattr(data, 'items'): for key, value in data.items(): assert not isinstance(value, dict), ( "Test data contained a dictionary value for key '%s', " "but multipart uploads do not support nested data. " "You may want to consider using format='json' in this " "test case." % key ) return encode_multipart(self.BOUNDARY, data) class OpenAPIRenderer(BaseRenderer): media_type = 'application/vnd.oai.openapi' charset = None format = 'openapi' def __init__(self): assert yaml, 'Using OpenAPIRenderer, but `pyyaml` is not installed.' def render(self, data, media_type=None, renderer_context=None): # disable yaml advanced feature 'alias' for clean, portable, and readable output 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') class JSONOpenAPIRenderer(BaseRenderer): media_type = 'application/vnd.oai.openapi+json' charset = None encoder_class = encoders.JSONEncoder format = 'openapi-json' ensure_ascii = not api_settings.UNICODE_JSON def render(self, data, media_type=None, renderer_context=None): return json.dumps( data, cls=self.encoder_class, indent=2, ensure_ascii=self.ensure_ascii).encode('utf-8') ================================================ FILE: rest_framework/request.py ================================================ """ The Request class is used as a wrapper around the standard request object. The wrapped request then offers a richer API, in particular : - content automatically parsed according to `Content-Type` header, and available as `request.data` - full support of PUT method, including support for file uploads - form overloading of HTTP method, content type and content """ import io import sys from contextlib import contextmanager from django.conf import settings 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.settings import api_settings def is_form_media_type(media_type): """ Return True if the media type is a valid form media type. """ base_media_type, params = parse_header_parameters(media_type) return (base_media_type == 'application/x-www-form-urlencoded' or base_media_type == 'multipart/form-data') class override_method: """ A context manager that temporarily overrides the method on a request, additionally setting the `view.request` attribute. Usage: with override_method(view, request, 'POST') as request: ... # Do stuff with `view` and `request` """ def __init__(self, view, request, method): self.view = view self.request = request self.method = method self.action = getattr(view, 'action', None) def __enter__(self): self.view.request = clone_request(self.request, self.method) # For viewsets we also set the `.action` attribute. action_map = getattr(self.view, 'action_map', {}) self.view.action = action_map.get(self.method.lower()) return self.view.request def __exit__(self, *args, **kwarg): self.view.request = self.request self.view.action = self.action class WrappedAttributeError(Exception): pass @contextmanager def wrap_attributeerrors(): """ Used to re-raise AttributeErrors caught during authentication, preventing these errors from otherwise being handled by the attribute access protocol. """ try: yield except AttributeError: info = sys.exc_info() exc = WrappedAttributeError(str(info[1])) raise exc.with_traceback(info[2]) class Empty: """ Placeholder for unset attributes. Cannot use `None`, as that may be a valid value. """ pass def _hasattr(obj, name): return not getattr(obj, name) is Empty def clone_request(request, method): """ Internal helper method to clone a request, replacing with a different HTTP method. Used for checking permissions against other methods. """ ret = Request(request=request._request, parsers=request.parsers, authenticators=request.authenticators, negotiator=request.negotiator, parser_context=request.parser_context) ret._data = request._data ret._files = request._files ret._full_data = request._full_data ret._content_type = request._content_type ret._stream = request._stream ret.method = method if hasattr(request, '_user'): ret._user = request._user if hasattr(request, '_auth'): ret._auth = request._auth if hasattr(request, '_authenticator'): ret._authenticator = request._authenticator if hasattr(request, 'accepted_renderer'): ret.accepted_renderer = request.accepted_renderer if hasattr(request, 'accepted_media_type'): ret.accepted_media_type = request.accepted_media_type if hasattr(request, 'version'): ret.version = request.version if hasattr(request, 'versioning_scheme'): ret.versioning_scheme = request.versioning_scheme return ret class ForcedAuthentication: """ This authentication class is used if the test client or request factory forcibly authenticated the request. """ def __init__(self, force_user, force_token): self.force_user = force_user self.force_token = force_token def authenticate(self, request): return (self.force_user, self.force_token) class Request: """ Wrapper allowing to enhance a standard `HttpRequest` instance. Kwargs: - request(HttpRequest). The original request instance. - parsers(list/tuple). The parsers to use for parsing the request content. - authenticators(list/tuple). The authenticators used to try authenticating the request's user. """ def __init__(self, request, parsers=None, authenticators=None, negotiator=None, parser_context=None): assert isinstance(request, HttpRequest), ( 'The `request` argument must be an instance of ' '`django.http.HttpRequest`, not `{}.{}`.' .format(request.__class__.__module__, request.__class__.__name__) ) self._request = request self.parsers = parsers or () self.authenticators = authenticators or () self.negotiator = negotiator or self._default_negotiator() self.parser_context = parser_context self._data = Empty self._files = Empty self._full_data = Empty self._content_type = Empty self._stream = Empty if self.parser_context is None: self.parser_context = {} self.parser_context['request'] = self self.parser_context['encoding'] = request.encoding or settings.DEFAULT_CHARSET force_user = getattr(request, '_force_auth_user', None) force_token = getattr(request, '_force_auth_token', None) if force_user is not None or force_token is not None: forced_auth = ForcedAuthentication(force_user, force_token) self.authenticators = (forced_auth,) def __repr__(self): return '<%s.%s: %s %r>' % ( self.__class__.__module__, self.__class__.__name__, 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() @property def content_type(self): meta = self._request.META return meta.get('CONTENT_TYPE', meta.get('HTTP_CONTENT_TYPE', '')) @property def stream(self): """ Returns an object that may be used to stream the request content. """ if not _hasattr(self, '_stream'): self._load_stream() return self._stream @property def query_params(self): """ More semantically correct name for request.GET. """ return self._request.GET @property def data(self): if not _hasattr(self, '_full_data'): with wrap_attributeerrors(): self._load_data_and_files() return self._full_data @property def user(self): """ Returns the user associated with the current request, as authenticated by the authentication classes provided to the request. """ if not hasattr(self, '_user'): with wrap_attributeerrors(): self._authenticate() return self._user @user.setter def user(self, value): """ Sets the user on the current request. This is necessary to maintain compatibility with django.contrib.auth where the user property is set in the login and logout functions. Note that we also set the user on Django's underlying `HttpRequest` instance, ensuring that it is available to any middleware in the stack. """ self._user = value self._request.user = value @property def auth(self): """ Returns any non-user authentication information associated with the request, such as an authentication token. """ if not hasattr(self, '_auth'): with wrap_attributeerrors(): self._authenticate() return self._auth @auth.setter def auth(self, value): """ Sets any non-user authentication information associated with the request, such as an authentication token. """ self._auth = value self._request.auth = value @property def successful_authenticator(self): """ Return the instance of the authentication instance class that was used to authenticate the request, or `None`. """ if not hasattr(self, '_authenticator'): with wrap_attributeerrors(): self._authenticate() return self._authenticator def _load_data_and_files(self): """ Parses the request content into `self.data`. """ if not _hasattr(self, '_data'): self._data, self._files = self._parse() if self._files: self._full_data = self._data.copy() self._full_data.update(self._files) else: self._full_data = self._data # if a form media type, copy data & files refs to the underlying # http request so that closable objects are handled appropriately. if is_form_media_type(self.content_type): self._request._post = self.POST self._request._files = self.FILES def _load_stream(self): """ Return the content body of the request, as a stream. """ meta = self._request.META try: content_length = int( meta.get('CONTENT_LENGTH', meta.get('HTTP_CONTENT_LENGTH', 0)) ) except (ValueError, TypeError): content_length = 0 if content_length == 0: self._stream = None elif not self._request._read_started: self._stream = self._request else: self._stream = io.BytesIO(self.body) def _supports_form_parsing(self): """ Return True if this requests supports parsing form data. """ form_media = ( 'application/x-www-form-urlencoded', 'multipart/form-data' ) return any(parser.media_type in form_media for parser in self.parsers) def _parse(self): """ Parse the request content, returning a two-tuple of (data, files) May raise an `UnsupportedMediaType`, or `ParseError` exception. """ media_type = self.content_type try: stream = self.stream except RawPostDataException: if not hasattr(self._request, '_post'): raise # If request.POST has been accessed in middleware, and a method='POST' # request was made with 'multipart/form-data', then the request stream # will already have been exhausted. if self._supports_form_parsing(): return (self._request.POST, self._request.FILES) stream = None if stream is None or media_type is None: if media_type and is_form_media_type(media_type): empty_data = QueryDict('', encoding=self._request._encoding) else: empty_data = {} empty_files = MultiValueDict() return (empty_data, empty_files) parser = self.negotiator.select_parser(self, self.parsers) if not parser: raise exceptions.UnsupportedMediaType(media_type) try: parsed = parser.parse(stream, media_type, self.parser_context) except Exception: # If we get an exception during parsing, fill in empty data and # re-raise. Ensures we don't simply repeat the error when # attempting to render the browsable renderer response, or when # logging the request or similar. self._data = QueryDict('', encoding=self._request._encoding) self._files = MultiValueDict() self._full_data = self._data raise # Parser classes may return the raw data, or a # DataAndFiles object. Unpack the result as required. try: return (parsed.data, parsed.files) except AttributeError: empty_files = MultiValueDict() return (parsed, empty_files) def _authenticate(self): """ Attempt to authenticate the request using each authentication instance in turn. """ for authenticator in self.authenticators: try: user_auth_tuple = authenticator.authenticate(self) except exceptions.APIException: self._not_authenticated() raise if user_auth_tuple is not None: self._authenticator = authenticator self.user, self.auth = user_auth_tuple return self._not_authenticated() def _not_authenticated(self): """ Set authenticator, user & authtoken representing an unauthenticated request. Defaults are None, AnonymousUser & None. """ self._authenticator = None if api_settings.UNAUTHENTICATED_USER: self.user = api_settings.UNAUTHENTICATED_USER() else: self.user = None if api_settings.UNAUTHENTICATED_TOKEN: self.auth = api_settings.UNAUTHENTICATED_TOKEN() else: self.auth = None def __getattr__(self, attr): """ If an attribute does not exist on this instance, then we also attempt to proxy it to the underlying HttpRequest object. """ try: _request = self.__getattribute__("_request") return getattr(_request, attr) except AttributeError: 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'): 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) @property def FILES(self): # Leave this one alone for backwards compat with Django's request.FILES # Different from the other two cases, which are not valid property # names on the WSGIRequest class. if not _hasattr(self, '_files'): with wrap_attributeerrors(): self._load_data_and_files() return self._files def force_plaintext_errors(self, value): # Hack to allow our exception handler to force choice of # plaintext or html error responses. self._request.is_ajax = lambda: value ================================================ FILE: rest_framework/response.py ================================================ """ The Response class in REST framework is similar to HTTPResponse, except that it is initialized with unrendered data, instead of a pre-rendered string. The appropriate renderer is called during Django's template response rendering. """ from http.client import responses from django.template.response import SimpleTemplateResponse from rest_framework.serializers import Serializer class Response(SimpleTemplateResponse): """ An HttpResponse that allows its data to be rendered into arbitrary media types. """ def __init__(self, data=None, status=None, template_name=None, headers=None, exception=False, content_type=None): """ Alters the init arguments slightly. For example, drop 'template_name', and instead use 'data'. Setting 'renderer' and 'media_type' will typically be deferred, For example being set automatically by the `APIView`. """ super().__init__(None, status=status) if isinstance(data, Serializer): msg = ( 'You passed a Serializer instance as data, but ' 'probably meant to pass serialized `.data` or ' '`.error`. representation.' ) raise AssertionError(msg) self.data = data self.template_name = template_name self.exception = exception self.content_type = content_type if headers: 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) accepted_media_type = getattr(self, 'accepted_media_type', None) context = getattr(self, 'renderer_context', None) assert renderer, ".accepted_renderer not set on Response" assert accepted_media_type, ".accepted_media_type not set on Response" assert context is not None, ".renderer_context not set on Response" context['response'] = self media_type = renderer.media_type charset = renderer.charset content_type = self.content_type if content_type is None and charset is not None: content_type = f"{media_type}; charset={charset}" elif content_type is None: content_type = media_type self['Content-Type'] = content_type ret = renderer.render(self.data, accepted_media_type, context) if isinstance(ret, str): assert charset, ( 'renderer returned unicode, and did not specify ' 'a charset value.' ) return ret.encode(charset) if not ret: del self['Content-Type'] return ret @property def status_text(self): """ Returns reason text corresponding to our HTTP response status code. Provided for convenience. """ return responses.get(self.status_code, '') def __getstate__(self): """ Remove attributes from the response that shouldn't be cached. """ state = super().__getstate__() for key in ( 'accepted_renderer', 'renderer_context', 'resolver_match', 'client', 'request', 'json', 'wsgi_request' ): if key in state: del state[key] state['_closable_objects'] = [] return state ================================================ FILE: rest_framework/reverse.py ================================================ """ Provide urlresolver functions that return fully qualified URLs or view names """ from django.urls import NoReverseMatch from django.urls import reverse as django_reverse from django.utils.functional import lazy from rest_framework.settings import api_settings from rest_framework.utils.urls import replace_query_param def preserve_builtin_query_params(url, request=None): """ Given an incoming request, and an outgoing URL representation, append the value of any built-in query parameters. """ if request is None: return url overrides = [ api_settings.URL_FORMAT_OVERRIDE, ] for param in overrides: if param and (param in request.GET): value = request.GET[param] url = replace_query_param(url, param, value) return url def reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ If versioning is being used then we pass any `reverse` calls through to the versioning scheme instance, so that the resulting URL can be modified if needed. """ scheme = getattr(request, 'versioning_scheme', None) if scheme is not None: try: url = scheme.reverse(viewname, args, kwargs, request, format, **extra) except NoReverseMatch: # In case the versioning scheme reversal fails, fallback to the # default implementation url = _reverse(viewname, args, kwargs, request, format, **extra) else: url = _reverse(viewname, args, kwargs, request, format, **extra) return preserve_builtin_query_params(url, request) def _reverse(viewname, args=None, kwargs=None, request=None, format=None, **extra): """ Same as `django.urls.reverse`, but optionally takes a request and returns a fully qualified URL, using the request to get the base URL. """ if format is not None: kwargs = kwargs or {} kwargs['format'] = format url = django_reverse(viewname, args=args, kwargs=kwargs, **extra) if request: return request.build_absolute_uri(url) return url reverse_lazy = lazy(reverse, str) ================================================ FILE: rest_framework/routers.py ================================================ """ Routers provide a convenient and consistent way of automatically determining the URL conf for your API. They are used by simply instantiating a Router class, and then registering all the required ViewSets with that router. For example, you might have a `urls.py` that looks something like this: router = routers.DefaultRouter() router.register('users', UserViewSet, 'user') router.register('accounts', AccountViewSet, 'account') urlpatterns = router.urls """ import itertools from collections import namedtuple from django.core.exceptions import ImproperlyConfigured from django.urls import NoReverseMatch, path, re_path from rest_framework import views from rest_framework.response import Response from rest_framework.reverse import reverse from rest_framework.schemas import SchemaGenerator from rest_framework.schemas.views import SchemaView from rest_framework.settings import api_settings from rest_framework.urlpatterns import format_suffix_patterns Route = namedtuple('Route', ['url', 'mapping', 'name', 'detail', 'initkwargs']) DynamicRoute = namedtuple('DynamicRoute', ['url', 'name', 'detail', 'initkwargs']) def escape_curly_brackets(url_path): """ Double brackets in regex of url_path for escape string formatting """ return url_path.replace('{', '{{').replace('}', '}}') def flatten(list_of_lists): """ Takes an iterable of iterables, returns a single iterable containing all items """ return itertools.chain(*list_of_lists) class BaseRouter: def __init__(self): self.registry = [] 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 it from the viewset. """ raise NotImplementedError('get_default_basename must be overridden') def get_urls(self): """ Return a list of URL patterns, given the registered viewsets. """ raise NotImplementedError('get_urls must be overridden') @property def urls(self): if not hasattr(self, '_urls'): self._urls = self.get_urls() return self._urls class SimpleRouter(BaseRouter): routes = [ # List route. Route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create' }, name='{basename}-list', detail=False, initkwargs={'suffix': 'List'} ), # Dynamically generated list routes. Generated using # @action(detail=False) decorator on methods of the viewset. DynamicRoute( url=r'^{prefix}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=False, initkwargs={} ), # Detail route. Route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy' }, name='{basename}-detail', detail=True, initkwargs={'suffix': 'Instance'} ), # Dynamically generated detail routes. Generated using # @action(detail=True) decorator on methods of the viewset. DynamicRoute( url=r'^{prefix}/{lookup}/{url_path}{trailing_slash}$', name='{basename}-{url_name}', detail=True, initkwargs={} ), ] 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): """ If `basename` is not specified, attempt to automatically determine it from the viewset. """ queryset = getattr(viewset, 'queryset', None) assert queryset is not None, '`basename` argument not specified, and could ' \ 'not automatically determine the name from the viewset, as ' \ 'it does not have a `.queryset` attribute.' return queryset.model._meta.object_name.lower() def get_routes(self, viewset): """ Augment `self.routes` with any dynamically generated routes. Returns a list of the Route namedtuple. """ # converting to list as iterables are good for one pass, known host needs to be checked again and again for # different functions. known_actions = list(flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)])) extra_actions = viewset.get_extra_actions() # checking action names against the known actions list not_allowed = [ action.__name__ for action in extra_actions if action.__name__ in known_actions ] if not_allowed: msg = ('Cannot use the @action decorator on the following ' 'methods, as they are existing routes: %s') raise ImproperlyConfigured(msg % ', '.join(not_allowed)) # partition detail and list actions detail_actions = [action for action in extra_actions if action.detail] list_actions = [action for action in extra_actions if not action.detail] routes = [] for route in self.routes: if isinstance(route, DynamicRoute) and route.detail: routes += [self._get_dynamic_route(route, action) for action in detail_actions] elif isinstance(route, DynamicRoute) and not route.detail: routes += [self._get_dynamic_route(route, action) for action in list_actions] else: routes.append(route) return routes def _get_dynamic_route(self, route, action): initkwargs = route.initkwargs.copy() initkwargs.update(action.kwargs) url_path = escape_curly_brackets(action.url_path) return Route( url=route.url.replace('{url_path}', url_path), mapping=action.mapping, name=route.name.replace('{url_name}', action.url_name), detail=route.detail, initkwargs=initkwargs, ) def get_method_map(self, viewset, method_map): """ Given a viewset, and a mapping of http methods to actions, return a new mapping which only includes any mappings that are actually implemented by the viewset. """ bound_methods = {} for method, action in method_map.items(): if hasattr(viewset, action): bound_methods[method] = action return bound_methods def get_lookup_regex(self, viewset, lookup_prefix=''): """ Given a viewset, return the portion of URL regex that is used to match against a single instance. Note that lookup_prefix is not used directly inside REST rest_framework itself, but is required in order to nicely support nested router implementations, such as drf-nested-routers. https://github.com/alanjds/drf-nested-routers """ # 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 = 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 ) def get_urls(self): """ Use the registered viewsets to generate a list of URL patterns. """ ret = [] for prefix, viewset, basename in self.registry: lookup = self.get_lookup_regex(viewset) routes = self.get_routes(viewset) for route in routes: # Only actions which actually exist on the viewset will be bound mapping = self.get_method_map(viewset, route.mapping) if not mapping: continue # Build the url pattern regex = route.url.format( prefix=prefix, lookup=lookup, trailing_slash=self.trailing_slash ) # If there is no prefix, the first part of the url is probably # 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: if self._url_conf is path: if regex[0] == '/': regex = regex[1:] elif regex[:2] == '^/': regex = '^' + regex[2:] initkwargs = route.initkwargs.copy() initkwargs.update({ 'basename': basename, 'detail': route.detail, }) view = viewset.as_view(mapping, **initkwargs) name = route.name.format(basename=basename) ret.append(self._url_conf(regex, view, name=name)) return ret class APIRootView(views.APIView): """ The default basic root view for DefaultRouter """ _ignore_model_permissions = True schema = None # exclude from schema api_root_dict = None def get(self, request, *args, **kwargs): # Return a plain {"name": "hyperlink"} response. ret = {} namespace = request.resolver_match.namespace for key, url_name in self.api_root_dict.items(): if namespace: url_name = namespace + ':' + url_name try: ret[key] = reverse( url_name, args=args, kwargs=kwargs, request=request, format=kwargs.get('format') ) except NoReverseMatch: # Don't bail out if eg. no list routes exist, only detail routes. continue return Response(ret) class DefaultRouter(SimpleRouter): """ The default router extends the SimpleRouter, but also adds in a default API root view, and adds format suffix patterns to the URLs. """ include_root_view = True include_format_suffixes = True root_view_name = 'api-root' default_schema_renderers = None APIRootView = APIRootView APISchemaView = SchemaView SchemaGenerator = SchemaGenerator def __init__(self, *args, **kwargs): if 'root_renderers' in kwargs: self.root_renderers = kwargs.pop('root_renderers') else: self.root_renderers = list(api_settings.DEFAULT_RENDERER_CLASSES) super().__init__(*args, **kwargs) def get_api_root_view(self, api_urls=None): """ Return a basic root view. """ 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) return self.APIRootView.as_view(api_root_dict=api_root_dict) def get_urls(self): """ Generate the list of URL patterns, including a default root view for the API, and appending `.json` style format suffixes. """ urls = super().get_urls() if self.include_root_view: view = self.get_api_root_view(api_urls=urls) root_url = path('', view, name=self.root_view_name) urls.append(root_url) if self.include_format_suffixes: urls = format_suffix_patterns(urls) return urls ================================================ FILE: rest_framework/schemas/__init__.py ================================================ """ rest_framework.schemas schemas: __init__.py generators.py # Top-down schema generation inspectors.py # Per-endpoint view introspection utils.py # Shared helper functions views.py # Houses `SchemaView`, `APIView` subclass. We expose a minimal "public" API directly from `schemas`. This covers the basic use-cases: from rest_framework.schemas import ( AutoSchema, get_schema_view, SchemaGenerator, ) Other access should target the submodules directly """ from rest_framework.settings import api_settings from . import openapi from .inspectors import DefaultSchema # noqa from .openapi import AutoSchema, SchemaGenerator # noqa def get_schema_view( title=None, url=None, description=None, urlconf=None, renderer_classes=None, public=False, patterns=None, generator_class=None, authentication_classes=api_settings.DEFAULT_AUTHENTICATION_CLASSES, permission_classes=api_settings.DEFAULT_PERMISSION_CLASSES, version=None): """ Return a schema view. """ if generator_class is None: generator_class = openapi.SchemaGenerator generator = generator_class( title=title, url=url, description=description, urlconf=urlconf, patterns=patterns, version=version ) # Avoid import cycle on APIView from .views import SchemaView return SchemaView.as_view( renderer_classes=renderer_classes, schema_generator=generator, public=public, authentication_classes=authentication_classes, permission_classes=permission_classes, ) ================================================ FILE: rest_framework/schemas/generators.py ================================================ """ generators.py # Top-down schema generation See schemas.__init__.py for package overview. """ import re from importlib import import_module from django.conf import settings from django.contrib.admindocs.views import simplify_regex from django.core.exceptions import PermissionDenied from django.http import Http404 from django.urls import URLPattern, URLResolver from rest_framework import exceptions from rest_framework.request import clone_request from rest_framework.settings import api_settings from rest_framework.utils.model_meta import _get_pk def get_pk_name(model): meta = model._meta.concrete_model._meta return _get_pk(meta).name def is_api_view(callback): """ Return `True` if the given view callback is a REST framework view/viewset. """ # Avoid import cycle on APIView from rest_framework.views import APIView cls = getattr(callback, 'cls', None) return (cls is not None) and issubclass(cls, APIView) def endpoint_ordering(endpoint): path, method, callback = endpoint method_priority = { 'GET': 0, 'POST': 1, 'PUT': 2, 'PATCH': 3, 'DELETE': 4 }.get(method, 5) return (method_priority,) _PATH_PARAMETER_COMPONENT_RE = re.compile( r'<(?:(?P[^>:]+):)?(?P\w+)>' ) class EndpointEnumerator: """ A class to determine the available API endpoints that a project exposes. """ def __init__(self, patterns=None, urlconf=None): if patterns is None: if urlconf is None: # Use the default Django URL conf urlconf = settings.ROOT_URLCONF # Load the given URLconf module if isinstance(urlconf, str): urls = import_module(urlconf) else: urls = urlconf patterns = urls.urlpatterns self.patterns = patterns def get_api_endpoints(self, patterns=None, prefix=''): """ Return a list of all available API endpoints by inspecting the URL conf. """ if patterns is None: patterns = self.patterns api_endpoints = [] for pattern in patterns: path_regex = prefix + str(pattern.pattern) if isinstance(pattern, URLPattern): path = self.get_path_from_regex(path_regex) callback = pattern.callback if self.should_include_endpoint(path, callback): for method in self.get_allowed_methods(callback): endpoint = (path, method, callback) api_endpoints.append(endpoint) elif isinstance(pattern, URLResolver): nested_endpoints = self.get_api_endpoints( patterns=pattern.url_patterns, prefix=path_regex ) api_endpoints.extend(nested_endpoints) return sorted(api_endpoints, key=endpoint_ordering) 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 converter, such that we # could feed that straight into the parameter schema object? path = simplify_regex(path_regex) # 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): """ Return `True` if the given endpoint should be included. """ if not is_api_view(callback): return False # Ignore anything except REST framework views. if callback.cls.schema is None: return False if 'schema' in callback.initkwargs: if callback.initkwargs['schema'] is None: return False if path.endswith('.{format}') or path.endswith('.{format}/'): return False # Ignore .json style URLs. return True def get_allowed_methods(self, callback): """ Return a list of the valid HTTP methods for this endpoint. """ if hasattr(callback, 'actions'): actions = set(callback.actions) http_method_names = set(callback.cls.http_method_names) methods = [method.upper() for method in actions & http_method_names] else: methods = callback.cls().allowed_methods return [method for method in methods if method not in ('OPTIONS', 'HEAD')] class BaseSchemaGenerator: endpoint_inspector_cls = EndpointEnumerator # 'pk' isn't great as an externally exposed name for an identifier, # so by default we prefer to use the actual model field name for schemas. # Set by 'SCHEMA_COERCE_PATH_PK'. coerce_path_pk = None def __init__(self, title=None, url=None, description=None, patterns=None, urlconf=None, version=None): if url and not url.endswith('/'): url += '/' self.coerce_path_pk = api_settings.SCHEMA_COERCE_PATH_PK self.patterns = patterns self.urlconf = urlconf self.title = title self.description = description self.version = version self.url = url self.endpoints = None def _initialise_endpoints(self): if self.endpoints is None: inspector = self.endpoint_inspector_cls(self.patterns, self.urlconf) self.endpoints = inspector.get_api_endpoints() def _get_paths_and_endpoints(self, request): """ Generate (path, method, view) given (path, method, callback) for paths. """ paths = [] view_endpoints = [] for path, method, callback in self.endpoints: view = self.create_view(callback, method, request) path = self.coerce_path(path, method, view) paths.append(path) view_endpoints.append((path, method, view)) return paths, view_endpoints def create_view(self, callback, method, request=None): """ Given a callback, return an actual view instance. """ view = callback.cls(**getattr(callback, 'initkwargs', {})) view.args = () view.kwargs = {} view.format_kwarg = None view.request = None view.action_map = getattr(callback, 'actions', None) actions = getattr(callback, 'actions', None) if actions is not None: if method == 'OPTIONS': view.action = 'metadata' else: view.action = actions.get(method.lower()) if request is not None: view.request = clone_request(request, method) return view def coerce_path(self, path, method, view): """ Coerce {pk} path arguments into the name of the model field, where possible. This is cleaner for an external representation. (Ie. "this is an identifier", not "this is a database primary key") """ if not self.coerce_path_pk or '{pk}' not in path: return path model = getattr(getattr(view, 'queryset', None), 'model', None) if model: field_name = get_pk_name(model) else: field_name = 'id' return path.replace('{pk}', '{%s}' % field_name) def get_schema(self, request=None, public=False): raise NotImplementedError(".get_schema() must be implemented in subclasses.") def has_view_permissions(self, path, method, view): """ Return `True` if the incoming request has the correct view permissions. """ if view.request is None: return True try: view.check_permissions(view.request) except (exceptions.APIException, Http404, PermissionDenied): return False return True ================================================ FILE: rest_framework/schemas/inspectors.py ================================================ """ inspectors.py # Per-endpoint view introspection See schemas.__init__.py for package overview. """ import re from weakref import WeakKeyDictionary from django.utils.encoding import smart_str from rest_framework.settings import api_settings from rest_framework.utils import formatting class ViewInspector: """ Descriptor class on APIView. Provide subclass for per-view schema generation """ # Used in _get_description_section() header_regex = re.compile('^[a-zA-Z][0-9A-Za-z_]*:') def __init__(self): self.instance_schemas = WeakKeyDictionary() def __get__(self, instance, owner): """ Enables `ViewInspector` as a Python _Descriptor_. This is how `view.schema` knows about `view`. `__get__` is called when the descriptor is accessed on the owner. (That will be when view.schema is called in our case.) `owner` is always the owner class. (An APIView, or subclass for us.) `instance` is the view instance or `None` if accessed from the class, rather than an instance. See: https://docs.python.org/3/howto/descriptor.html for info on descriptor usage. """ if instance in self.instance_schemas: return self.instance_schemas[instance] self.view = instance return self def __set__(self, instance, other): self.instance_schemas[instance] = other if other is not None: other.view = instance @property def view(self): """View property.""" assert self._view is not None, ( "Schema generation REQUIRES a view instance. (Hint: you accessed " "`schema` from the view class rather than an instance.)" ) return self._view @view.setter def view(self, value): self._view = value @view.deleter def view(self): self._view = None def get_description(self, path, method): """ Determine a path description. This will be based on the method docstring if one exists, or else the class docstring. """ view = self.view method_name = getattr(view, 'action', method.lower()) 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: return self._get_description_section(view, getattr(view, 'action', method.lower()), view.get_view_description()) def _get_description_section(self, view, header, description): lines = description.splitlines() current_section = '' sections = {'': ''} for line in lines: if self.header_regex.match(line): current_section, separator, lead = line.partition(':') sections[current_section] = lead.strip() else: sections[current_section] += '\n' + line # TODO: SCHEMA_COERCE_METHOD_NAMES appears here and in `SchemaGenerator.get_keys` coerce_method_names = api_settings.SCHEMA_COERCE_METHOD_NAMES if header in sections: return sections[header].strip() if header in coerce_method_names: if coerce_method_names[header] in sections: return sections[coerce_method_names[header]].strip() return sections[''].strip() class DefaultSchema(ViewInspector): """Allows overriding AutoSchema using DEFAULT_SCHEMA_CLASS setting""" def __get__(self, instance, owner): result = super().__get__(instance, owner) if not isinstance(result, DefaultSchema): return result inspector_class = api_settings.DEFAULT_SCHEMA_CLASS assert issubclass(inspector_class, ViewInspector), ( "DEFAULT_SCHEMA_CLASS must be set to a ViewInspector (usually an AutoSchema) subclass" ) inspector = inspector_class() inspector.view = instance return inspector ================================================ FILE: rest_framework/schemas/openapi.py ================================================ import re import warnings from decimal import Decimal from operator import attrgetter from urllib.parse import urljoin from django.core.validators import ( DecimalValidator, EmailValidator, MaxLengthValidator, MaxValueValidator, MinLengthValidator, MinValueValidator, RegexValidator, URLValidator ) from django.db import models from django.utils.encoding import force_str 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 from .generators import BaseSchemaGenerator from .inspectors import ViewInspector from .utils import get_pk_description, is_list_view class SchemaGenerator(BaseSchemaGenerator): def get_info(self): # Title and version are required by openapi specification 3.x info = { 'title': self.title or '', 'version': self.version or '' } if self.description is not None: info['description'] = self.description return info def check_duplicate_operation_id(self, paths): ids = {} for route in paths: for method in paths[route]: if 'operationId' not in paths[route][method]: continue operation_id = paths[route][method]['operationId'] if operation_id in ids: warnings.warn( 'You have a duplicated operationId in your OpenAPI schema: {operation_id}\n' '\tRoute: {route1}, Method: {method1}\n' '\tRoute: {route2}, Method: {method2}\n' '\tAn operationId has to be unique across your schema. Your schema may not work in other tools.' .format( route1=ids[operation_id]['route'], method1=ids[operation_id]['method'], route2=route, method2=method, operation_id=operation_id ) ) ids[operation_id] = { 'route': route, 'method': method } def get_schema(self, request=None, public=False): """ Generate a OpenAPI schema. """ self._initialise_endpoints() components_schemas = {} # Iterate endpoints generating per method path operations. paths = {} _, view_endpoints = self._get_paths_and_endpoints(None if public else request) for path, method, view in view_endpoints: if not self.has_view_permissions(path, method, view): continue operation = view.schema.get_operation(path, method) components = view.schema.get_components(path, method) for k in components.keys(): if k not in components_schemas: continue if components_schemas[k] == components[k]: continue warnings.warn(f'Schema component "{k}" has been overridden with a different value.') components_schemas.update(components) # Normalize path for any provided mount url. if path.startswith('/'): path = path[1:] path = urljoin(self.url or '/', path) paths.setdefault(path, {}) paths[path][method.lower()] = operation self.check_duplicate_operation_id(paths) # Compile final schema. schema = { 'openapi': '3.0.2', 'info': self.get_info(), 'paths': paths, } if len(components_schemas) > 0: schema['components'] = { 'schemas': components_schemas } return schema # View Inspectors class AutoSchema(ViewInspector): def __init__(self, tags=None, operation_id_base=None, component_name=None): """ :param operation_id_base: user-defined name in operationId. If empty, it will be deducted from the Model/Serializer/View name. :param component_name: user-defined component's name. If empty, it will be deducted from the Serializer's class name. """ if tags and not all(isinstance(tag, str) for tag in tags): raise ValueError('tags must be a list or tuple of string.') self._tags = tags self.operation_id_base = operation_id_base self.component_name = component_name super().__init__() request_media_types = [] response_media_types = [] method_mapping = { 'get': 'retrieve', 'post': 'create', 'put': 'update', 'patch': 'partialUpdate', 'delete': 'destroy', } def get_operation(self, path, method): operation = {} operation['operationId'] = self.get_operation_id(path, method) operation['description'] = self.get_description(path, method) parameters = [] parameters += self.get_path_parameters(path, method) parameters += self.get_pagination_parameters(path, method) parameters += self.get_filter_parameters(path, method) operation['parameters'] = parameters request_body = self.get_request_body(path, method) if request_body: operation['requestBody'] = request_body operation['responses'] = self.get_responses(path, method) operation['tags'] = self.get_tags(path, method) return operation def get_component_name(self, serializer): """ Compute the component's name from the serializer. Raise an exception if the serializer's class name is "Serializer" (case-insensitive). """ if self.component_name is not None: return self.component_name # use the serializer's class name as the component name. component_name = serializer.__class__.__name__ # We remove the "serializer" string from the class name. pattern = re.compile("serializer", re.IGNORECASE) component_name = pattern.sub("", component_name) if component_name == "": raise Exception( '"{}" is an invalid class name for schema generation. ' 'Serializer\'s class name should be unique and explicit. e.g. "ItemSerializer"' .format(serializer.__class__.__name__) ) return component_name def get_components(self, path, method): """ Return components with their properties from the serializer. """ if method.lower() == 'delete': return {} request_serializer = self.get_request_serializer(path, method) response_serializer = self.get_response_serializer(path, method) components = {} if isinstance(request_serializer, serializers.Serializer): component_name = self.get_component_name(request_serializer) content = self.map_serializer(request_serializer) components.setdefault(component_name, content) if isinstance(response_serializer, serializers.Serializer): component_name = self.get_component_name(response_serializer) content = self.map_serializer(response_serializer) components.setdefault(component_name, content) return components def _to_camel_case(self, snake_str): components = snake_str.split('_') # We capitalize the first letter of each component except the first one # with the 'title' method and join them together. return components[0] + ''.join(x.title() for x in components[1:]) def get_operation_id_base(self, path, method, action): """ Compute the base part for operation ID from the model, serializer or view name. """ model = getattr(getattr(self.view, 'queryset', None), 'model', None) if self.operation_id_base is not None: name = self.operation_id_base # Try to deduce the ID from the view's model elif model is not None: name = model.__name__ # Try with the serializer class name elif self.get_serializer(path, method) is not None: name = self.get_serializer(path, method).__class__.__name__ if name.endswith('Serializer'): name = name[:-10] # Fallback to the view name else: name = self.view.__class__.__name__ if name.endswith('APIView'): name = name[:-7] elif name.endswith('View'): name = name[:-4] # Due to camel-casing of classes and `action` being lowercase, apply title in order to find if action truly # comes at the end of the name if name.endswith(action.title()): # ListView, UpdateAPIView, ThingDelete ... name = name[:-len(action)] if action == 'list': assert inflection, '`inflection` must be installed for OpenAPI schema support.' name = inflection.pluralize(name) return name def get_operation_id(self, path, method): """ Compute an operation ID from the view type and get_operation_id_base method. """ method_name = getattr(self.view, 'action', method.lower()) if is_list_view(path, method, self.view): action = 'list' elif method_name not in self.method_mapping: action = self._to_camel_case(method_name) else: action = self.method_mapping[method.lower()] name = self.get_operation_id_base(path, method, action) return action + name def get_path_parameters(self, path, method): """ Return a list of parameters from templated path variables. """ assert uritemplate, '`uritemplate` must be installed for OpenAPI schema support.' model = getattr(getattr(self.view, 'queryset', None), 'model', None) parameters = [] for variable in uritemplate.variables(path): description = '' if model is not None: # TODO: test this. # Attempt to infer a field description if possible. try: model_field = model._meta.get_field(variable) except Exception: model_field = None if model_field is not None and model_field.help_text: description = force_str(model_field.help_text) elif model_field is not None and model_field.primary_key: description = get_pk_description(model, model_field) parameter = { "name": variable, "in": "path", "required": True, "description": description, 'schema': { 'type': 'string', # TODO: integer, pattern, ... }, } parameters.append(parameter) return parameters def get_filter_parameters(self, path, method): if not self.allows_filters(path, method): return [] parameters = [] for filter_backend in self.view.filter_backends: parameters += filter_backend().get_schema_operation_parameters(self.view) return parameters def allows_filters(self, path, method): """ Determine whether to include filter Fields in schema. Default implementation looks for ModelViewSet or GenericAPIView actions/methods that cause filtering on the default implementation. """ if getattr(self.view, 'filter_backends', None) is None: return False if hasattr(self.view, 'action'): return self.view.action in ["list", "retrieve", "update", "partial_update", "destroy"] return method.lower() in ["get", "put", "patch", "delete"] def get_pagination_parameters(self, path, method): view = self.view if not is_list_view(path, method, view): return [] paginator = self.get_paginator() if not paginator: return [] return paginator.get_schema_operation_parameters(view) def map_choicefield(self, field): 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): type = 'integer' elif all(isinstance(choice, (int, float, Decimal)) for choice in choices): # `number` includes `integer` # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21 type = 'number' elif all(isinstance(choice, str) for choice in choices): type = 'string' else: type = None mapping = { # The value of `enum` keyword MUST be an array and SHOULD be unique. # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.20 'enum': choices } # If We figured out `type` then and only then we should set it. It must be a string. # Ref: https://swagger.io/docs/specification/data-models/data-types/#mixed-type # It is optional but it can not be null. # Ref: https://tools.ietf.org/html/draft-wright-json-schema-validation-00#section-5.21 if type: mapping['type'] = type return mapping def map_field(self, field): # Nested Serializers, `many` or not. if isinstance(field, serializers.ListSerializer): return { 'type': 'array', 'items': self.map_serializer(field.child) } if isinstance(field, serializers.Serializer): data = self.map_serializer(field) data['type'] = 'object' return data # Related fields. if isinstance(field, serializers.ManyRelatedField): return { 'type': 'array', '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 if isinstance(model_field, models.AutoField): return {'type': 'integer'} # ChoiceFields (single and multiple). # Q: # - Is 'type' required? # - can we determine the TYPE of a choicefield? if isinstance(field, serializers.MultipleChoiceField): return { 'type': 'array', 'items': self.map_choicefield(field) } if isinstance(field, serializers.ChoiceField): return self.map_choicefield(field) # ListField. if isinstance(field, serializers.ListField): mapping = { 'type': 'array', 'items': {}, } if not isinstance(field.child, _UnvalidatedField): mapping['items'] = self.map_field(field.child) return mapping # DateField and DateTimeField type is string if isinstance(field, serializers.DateField): return { 'type': 'string', 'format': 'date', } if isinstance(field, serializers.DateTimeField): return { 'type': 'string', 'format': 'date-time', } # "Formats such as "email", "uuid", and so on, MAY be used even though undefined by this specification." # see: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#data-types # see also: https://swagger.io/docs/specification/data-models/data-types/#string if isinstance(field, serializers.EmailField): return { 'type': 'string', 'format': 'email' } if isinstance(field, serializers.URLField): return { 'type': 'string', 'format': 'uri' } if isinstance(field, serializers.UUIDField): return { 'type': 'string', 'format': 'uuid' } if isinstance(field, serializers.IPAddressField): content = { 'type': 'string', } if field.protocol != 'both': content['format'] = field.protocol return content if isinstance(field, serializers.DecimalField): if getattr(field, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING): content = { 'type': 'string', 'format': 'decimal', } else: content = { 'type': 'number' } if field.decimal_places: content['multipleOf'] = float('.' + (field.decimal_places - 1) * '0' + '1') if field.max_whole_digits: content['maximum'] = int(field.max_whole_digits * '9') + 1 content['minimum'] = -content['maximum'] self._map_min_max(field, content) return content if isinstance(field, serializers.FloatField): content = { 'type': 'number', } self._map_min_max(field, content) return content if isinstance(field, serializers.IntegerField): content = { 'type': 'integer' } self._map_min_max(field, content) # 2147483647 is max for int32_size, so we use int64 for format if int(content.get('maximum', 0)) > 2147483647 or int(content.get('minimum', 0)) > 2147483647: content['format'] = 'int64' return content if isinstance(field, serializers.FileField): return { 'type': 'string', 'format': 'binary' } # Simplest cases, default to 'string' type: FIELD_CLASS_SCHEMA_TYPE = { serializers.BooleanField: 'boolean', serializers.JSONField: 'object', serializers.DictField: 'object', serializers.HStoreField: 'object', } return {'type': FIELD_CLASS_SCHEMA_TYPE.get(field.__class__, 'string')} def _map_min_max(self, field, content): if field.max_value: content['maximum'] = field.max_value if field.min_value: content['minimum'] = field.min_value def map_serializer(self, serializer): # Assuming we have a valid serializer instance. required = [] properties = {} for field in serializer.fields.values(): if isinstance(field, serializers.HiddenField): continue if field.required and not serializer.partial: required.append(self.get_field_name(field)) schema = self.map_field(field) if field.read_only: schema['readOnly'] = True if field.write_only: schema['writeOnly'] = True if field.allow_null: schema['nullable'] = True if field.default is not None and field.default != empty and not callable(field.default): schema['default'] = field.default if field.help_text: schema['description'] = str(field.help_text) self.map_field_validators(field, schema) properties[self.get_field_name(field)] = schema result = { 'type': 'object', 'properties': properties } if required: result['required'] = required return result def map_field_validators(self, field, schema): """ map field validators """ for v in field.validators: # "Formats such as "email", "uuid", and so on, MAY be used even though undefined by this specification." # https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#data-types if isinstance(v, EmailValidator): schema['format'] = 'email' if isinstance(v, URLValidator): schema['format'] = 'uri' if isinstance(v, RegexValidator): # In Python, the token \Z does what \z does in other engines. # https://stackoverflow.com/questions/53283160 schema['pattern'] = v.regex.pattern.replace('\\Z', '\\z') elif isinstance(v, MaxLengthValidator): attr_name = 'maxLength' if isinstance(field, serializers.ListField): attr_name = 'maxItems' schema[attr_name] = v.limit_value elif isinstance(v, MinLengthValidator): attr_name = 'minLength' if isinstance(field, serializers.ListField): attr_name = 'minItems' schema[attr_name] = v.limit_value elif isinstance(v, MaxValueValidator): schema['maximum'] = v.limit_value elif isinstance(v, MinValueValidator): schema['minimum'] = v.limit_value elif isinstance(v, DecimalValidator) and \ not getattr(field, 'coerce_to_string', api_settings.COERCE_DECIMAL_TO_STRING): if v.decimal_places: schema['multipleOf'] = float('.' + (v.decimal_places - 1) * '0' + '1') if v.max_digits: digits = v.max_digits if v.decimal_places is not None and v.decimal_places > 0: digits -= v.decimal_places 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: return pagination_class() return None def map_parsers(self, path, method): return list(map(attrgetter('media_type'), self.view.parser_classes)) def map_renderers(self, path, method): media_types = [] for renderer in self.view.renderer_classes: # BrowsableAPIRenderer not relevant to OpenAPI spec if issubclass(renderer, renderers.BrowsableAPIRenderer): continue media_types.append(renderer.media_type) return media_types def get_serializer(self, path, method): view = self.view if not hasattr(view, 'get_serializer'): return None try: return view.get_serializer() except exceptions.APIException: warnings.warn('{}.get_serializer() raised an exception during ' 'schema generation. Serializer fields will not be ' 'generated for {} {}.' .format(view.__class__.__name__, method, path)) return None def get_request_serializer(self, path, method): """ Override this method if your view uses a different serializer for handling request body. """ return self.get_serializer(path, method) def get_response_serializer(self, path, method): """ Override this method if your view uses a different serializer for populating response data. """ return self.get_serializer(path, method) def get_reference(self, 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'): return {} self.request_media_types = self.map_parsers(path, method) serializer = self.get_request_serializer(path, method) if not isinstance(serializer, serializers.Serializer): item_schema = {} else: item_schema = self.get_reference(serializer) return { 'content': { ct: {'schema': item_schema} for ct in self.request_media_types } } def get_responses(self, path, method): if method == 'DELETE': return { '204': { 'description': '' } } self.response_media_types = self.map_renderers(path, method) serializer = self.get_response_serializer(path, method) if not isinstance(serializer, serializers.Serializer): item_schema = {} else: item_schema = self.get_reference(serializer) if is_list_view(path, method, self.view): response_schema = { 'type': 'array', 'items': item_schema, } paginator = self.get_paginator() if paginator: response_schema = paginator.get_paginated_response_schema(response_schema) else: response_schema = item_schema status_code = '201' if method == 'POST' else '200' return { status_code: { 'content': { ct: {'schema': response_schema} for ct in self.response_media_types }, # description is a mandatory property, # https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#responseObject # TODO: put something meaningful into it 'description': "" } } def get_tags(self, path, method): # If user have specified tags, use them. if self._tags: return self._tags # First element of a specific path could be valid tag. This is a fallback solution. # PUT, PATCH, GET(Retrieve), DELETE: /user_profile/{id}/ tags = [user-profile] # POST, GET(List): /user_profile/ tags = [user-profile] if path.startswith('/'): path = path[1:] return [path.split('/')[0].replace('_', '-')] ================================================ FILE: rest_framework/schemas/utils.py ================================================ """ utils.py # Shared helper functions See schemas.__init__.py for package overview. """ from django.db import models from django.utils.translation import gettext_lazy as _ from rest_framework.mixins import RetrieveModelMixin def is_list_view(path, method, view): """ Return True if the given path/method appears to represent a list view. """ if hasattr(view, 'action'): # Viewsets have an explicitly defined action, which we can inspect. return view.action == 'list' if method.lower() != 'get': return False if isinstance(view, RetrieveModelMixin): return False path_components = path.strip('/').split('/') if path_components and '{' in path_components[-1]: return False return True def get_pk_description(model, model_field): if isinstance(model_field, models.AutoField): value_type = _('unique integer value') elif isinstance(model_field, models.UUIDField): value_type = _('UUID string') else: value_type = _('unique value') return _('A {value_type} identifying this {name}.').format( value_type=value_type, name=model._meta.verbose_name, ) ================================================ FILE: rest_framework/schemas/views.py ================================================ """ views.py # Houses `SchemaView`, `APIView` subclass. See schemas.__init__.py for package overview. """ from rest_framework import exceptions, renderers from rest_framework.response import Response from rest_framework.settings import api_settings from rest_framework.views import APIView class SchemaView(APIView): _ignore_model_permissions = True schema = None # exclude from schema renderer_classes = None schema_generator = None public = False def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.renderer_classes is None: self.renderer_classes = [ renderers.OpenAPIRenderer, renderers.JSONOpenAPIRenderer, ] if renderers.BrowsableAPIRenderer in api_settings.DEFAULT_RENDERER_CLASSES: self.renderer_classes += [renderers.BrowsableAPIRenderer] def get(self, request, *args, **kwargs): schema = self.schema_generator.get_schema(request, self.public) if schema is None: raise exceptions.PermissionDenied() return Response(schema) def handle_exception(self, exc): # Schema renderers do not render exceptions, so re-perform content # negotiation with default renderers. self.renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES neg = self.perform_content_negotiation(self.request, force=True) self.request.accepted_renderer, self.request.accepted_media_type = neg return super().handle_exception(exc) ================================================ FILE: rest_framework/serializers.py ================================================ """ Serializers and ModelSerializers are similar to Forms and ModelForms. Unlike forms, they are not constrained to dealing with HTML output, and form encoded input. Serialization in REST framework is a two-phase process: 1. Serializers marshal between complex types like model instances, and python primitives. 2. The process of marshaling 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 defaultdict from collections.abc import Mapping from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured from django.core.exceptions import ValidationError as DjangoValidationError from django.db import models from django.db.models.fields import Field as DjangoModelField from django.utils import timezone from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ 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 from rest_framework.settings import api_settings from rest_framework.utils import html, model_meta, representation from rest_framework.utils.field_mapping import ( ClassLookupDict, get_field_kwargs, get_nested_relation_kwargs, get_relation_kwargs, get_url_kwargs ) from rest_framework.utils.serializer_helpers import ( BindingDict, BoundField, JSONBoundField, NestedBoundField, ReturnDict, ReturnList ) from rest_framework.validators import ( UniqueForDateValidator, UniqueForMonthValidator, UniqueForYearValidator, UniqueTogetherValidator ) # Note: We do the following so that users of the framework can use this style: # # example_field = serializers.CharField(...) # # This helps keep the separation between model fields, form fields, and # serializer fields more explicit. from rest_framework.fields import ( # NOQA # isort:skip BigIntegerField, BooleanField, CharField, ChoiceField, DateField, DateTimeField, DecimalField, DictField, DurationField, EmailField, Field, FileField, FilePathField, FloatField, HiddenField, HStoreField, IPAddressField, ImageField, IntegerField, JSONField, ListField, ModelField, MultipleChoiceField, ReadOnlyField, RegexField, SerializerMethodField, SlugField, TimeField, URLField, UUIDField, ) from rest_framework.relations import ( # NOQA # isort:skip HyperlinkedIdentityField, HyperlinkedRelatedField, ManyRelatedField, PrimaryKeyRelatedField, RelatedField, SlugRelatedField, StringRelatedField, ) # Non-field imports, but public API from rest_framework.fields import ( # NOQA # isort:skip CreateOnlyDefault, CurrentUserDefault, SkipField, empty ) from rest_framework.relations import Hyperlink, PKOnlyObject # NOQA # isort:skip # We assume that 'validators' are intended for the child serializer, # rather than the parent serializer. LIST_SERIALIZER_KWARGS = ( 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'allow_empty', 'instance', 'data', 'partial', 'context', 'allow_null', 'max_length', 'min_length' ) LIST_SERIALIZER_KWARGS_REMOVE = ('allow_empty', 'min_length', 'max_length') ALL_FIELDS = '__all__' # BaseSerializer # -------------- class BaseSerializer(Field): """ The BaseSerializer class provides a minimal class which may be used for writing custom serializer implementations. Note that we strongly restrict the ordering of operations/properties that may be used on the serializer in order to enforce correct usage. In particular, if a `data=` argument is passed then: .is_valid() - Available. .initial_data - Available. .validated_data - Only available after calling `is_valid()` .errors - Only available after calling `is_valid()` .data - Only available after calling `is_valid()` If a `data=` argument is not passed then: .is_valid() - Not available. .initial_data - Not available. .validated_data - Not available. .errors - Not available. .data - Available. """ def __init__(self, instance=None, data=empty, **kwargs): self.instance = instance if data is not empty: self.initial_data = data self.partial = kwargs.pop('partial', False) self._context = kwargs.pop('context', {}) kwargs.pop('many', None) super().__init__(**kwargs) def __new__(cls, *args, **kwargs): # We override this method in order to automatically create # `ListSerializer` classes instead when `many=True` is set. if kwargs.pop('many', False): return cls.many_init(*args, **kwargs) return super().__new__(cls, *args, **kwargs) # Allow type checkers to make serializers generic. def __class_getitem__(cls, *args, **kwargs): return cls @classmethod def many_init(cls, *args, **kwargs): """ This method implements the creation of a `ListSerializer` parent class when `many=True` is used. You can customize it if you need to control which keyword arguments are passed to the parent, and which are passed to the child. Note that we're over-cautious in passing most arguments to both parent and child classes in order to try to cover the general case. If you're overriding this method you'll probably want something much simpler, eg: @classmethod def many_init(cls, *args, **kwargs): kwargs['child'] = cls() return CustomListSerializer(*args, **kwargs) """ 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 }) meta = getattr(cls, 'Meta', None) list_serializer_class = getattr(meta, 'list_serializer_class', ListSerializer) return list_serializer_class(*args, **list_kwargs) def to_internal_value(self, data): raise NotImplementedError('`to_internal_value()` must be implemented.') def to_representation(self, instance): raise NotImplementedError('`to_representation()` must be implemented.') def update(self, instance, validated_data): raise NotImplementedError('`update()` must be implemented.') def create(self, validated_data): raise NotImplementedError('`create()` must be implemented.') def save(self, **kwargs): assert hasattr(self, '_errors'), ( 'You must call `.is_valid()` before calling `.save()`.' ) assert not self.errors, ( 'You cannot call `.save()` on a serializer with invalid data.' ) # Guard against incorrect use of `serializer.save(commit=False)` assert 'commit' not in kwargs, ( "'commit' is not a valid keyword argument to the 'save()' method. " "If you need to access data before committing to the database then " "inspect 'serializer.validated_data' instead. " "You can also pass additional keyword arguments to 'save()' if you " "need to set extra attributes on the saved model instance. " "For example: 'serializer.save(owner=request.user)'.'" ) assert not hasattr(self, '_data'), ( "You cannot call `.save()` after accessing `serializer.data`." "If you need to access data before committing to the database then " "inspect 'serializer.validated_data' instead. " ) validated_data = {**self.validated_data, **kwargs} if self.instance is not None: self.instance = self.update(self.instance, validated_data) assert self.instance is not None, ( '`update()` did not return an object instance.' ) else: self.instance = self.create(validated_data) assert self.instance is not None, ( '`create()` did not return an object instance.' ) return self.instance def is_valid(self, *, raise_exception=False): assert hasattr(self, 'initial_data'), ( 'Cannot call `.is_valid()` as no `data=` keyword argument was ' 'passed when instantiating the serializer instance.' ) if not hasattr(self, '_validated_data'): try: self._validated_data = self.run_validation(self.initial_data) except ValidationError as exc: self._validated_data = {} self._errors = exc.detail else: self._errors = {} if self._errors and raise_exception: raise ValidationError(self.errors) return not bool(self._errors) @property def data(self): if hasattr(self, 'initial_data') and not hasattr(self, '_validated_data'): msg = ( 'When a serializer is passed a `data` keyword argument you ' 'must call `.is_valid()` before attempting to access the ' 'serialized `.data` representation.\n' 'You should either call `.is_valid()` first, ' 'or access `.initial_data` instead.' ) raise AssertionError(msg) if not hasattr(self, '_data'): if self.instance is not None and not getattr(self, '_errors', None): self._data = self.to_representation(self.instance) elif hasattr(self, '_validated_data') and not getattr(self, '_errors', None): self._data = self.to_representation(self.validated_data) else: self._data = self.get_initial() return self._data @property def errors(self): if not hasattr(self, '_errors'): msg = 'You must call `.is_valid()` before accessing `.errors`.' raise AssertionError(msg) return self._errors @property def validated_data(self): if not hasattr(self, '_validated_data'): msg = 'You must call `.is_valid()` before accessing `.validated_data`.' raise AssertionError(msg) return self._validated_data # Serializer & ListSerializer classes # ----------------------------------- class SerializerMetaclass(type): """ This metaclass sets a dictionary named `_declared_fields` on the class. Any instances of `Field` included as attributes on either the class or on any of its superclasses will be include in the `_declared_fields` dictionary. """ @classmethod def _get_declared_fields(cls, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(attrs.items()) if isinstance(obj, Field)] fields.sort(key=lambda x: x[1]._creation_counter) # Ensures a base class field doesn't override cls attrs, and maintains # field precedence when inheriting multiple parents. e.g. if there is a # class C(A, B), and A and B both define 'field', use 'field' from A. known = set(attrs) def visit(name): known.add(name) return name base_fields = [ (visit(name), f) for base in bases if hasattr(base, '_declared_fields') for name, f in base._declared_fields.items() if name not in known ] return dict(base_fields + fields) def __new__(cls, name, bases, attrs): attrs['_declared_fields'] = cls._get_declared_fields(bases, attrs) return super().__new__(cls, name, bases, attrs) def as_serializer_error(exc): """ Coerce validation exceptions into a standardized serialized error format. This function normalizes both Django's `ValidationError` and REST framework's `ValidationError` into a dictionary structure compatible with serializer `.errors`, ensuring all values are represented as lists of error details. The returned structure conforms to the serializer error contract: - Field-specific errors are returned as '{field-name: [errors]}' - Non-field errors are returned under the 'NON_FIELD_ERRORS_KEY' """ assert isinstance(exc, (ValidationError, DjangoValidationError)) if isinstance(exc, DjangoValidationError): detail = get_error_detail(exc) else: detail = exc.detail if isinstance(detail, Mapping): # If errors may be a dict we use the standard {key: list of values}. # Here we ensure that all the values are *lists* of errors. return { key: value if isinstance(value, (list, Mapping)) else [value] for key, value in detail.items() } elif isinstance(detail, list): # Errors raised as a list are non-field errors. return { api_settings.NON_FIELD_ERRORS_KEY: detail } # Errors raised as a string are non-field errors. return { api_settings.NON_FIELD_ERRORS_KEY: [detail] } class Serializer(BaseSerializer, metaclass=SerializerMetaclass): default_error_messages = { '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): """ A dictionary of {field_name: field_instance}. """ # `fields` is evaluated lazily. We do this to ensure that we don't # have issues importing modules that use ModelSerializers as fields, # even if Django's app-loading stage has not yet run. fields = BindingDict(self) for key, value in self.get_fields().items(): fields[key] = value return fields @property def _writable_fields(self): for field in self.fields.values(): if not field.read_only: yield field @property def _readable_fields(self): for field in self.fields.values(): if not field.write_only: yield field def get_fields(self): """ Returns a dictionary of {field_name: field_instance}. """ # Every new serializer is created with a clone of the field instances. # This allows users to dynamically modify the fields on a serializer # instance without affecting every other serializer instance. return copy.deepcopy(self._declared_fields) def get_validators(self): """ Returns a list of validator callables. """ # Used by the lazily-evaluated `validators` property. meta = getattr(self, 'Meta', None) validators = getattr(meta, 'validators', None) return list(validators) if validators else [] 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 {} 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 { 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 # nested HTML forms. if html.is_html_input(dictionary): return html.parse_html_dict(dictionary, prefix=self.field_name) or empty return dictionary.get(self.field_name, empty) def run_validation(self, data=empty): """ We override the default `run_validation`, because the validation performed by validators and the `.validate()` method should be coerced into an error dictionary with a 'non_fields_error' key. """ (is_empty_value, data) = self.validate_empty_values(data) if is_empty_value: return data value = self.to_internal_value(data) try: self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' except (ValidationError, DjangoValidationError) as exc: raise ValidationError(detail=as_serializer_error(exc)) return value def _read_only_defaults(self): fields = [ field for field in self.fields.values() if (field.read_only) and (field.default != empty) and (field.source != '*') and ('.' not in field.source) ] defaults = {} for field in fields: try: default = field.get_default() except SkipField: continue defaults[field.source] = default return defaults def run_validators(self, value): """ Add read_only fields with defaults to value before running validators. """ if isinstance(value, dict): to_validate = self._read_only_defaults() to_validate.update(value) else: to_validate = value super().run_validators(to_validate) def to_internal_value(self, data): """ Dict of native values <- Dict of primitive datatypes. """ if not isinstance(data, Mapping): message = self.error_messages['invalid'].format( datatype=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='invalid') ret = {} errors = {} fields = self._writable_fields for field in fields: validate_method = getattr(self, 'validate_' + field.field_name, None) primitive_value = field.get_value(data) try: validated_value = field.run_validation(primitive_value) if validate_method is not None: validated_value = validate_method(validated_value) except ValidationError as exc: errors[field.field_name] = exc.detail except DjangoValidationError as exc: errors[field.field_name] = get_error_detail(exc) except SkipField: pass else: self.set_value(ret, field.source_attrs, validated_value) if errors: raise ValidationError(errors) return ret def to_representation(self, instance): """ Object instance -> Dict of primitive datatypes. """ ret = {} fields = self._readable_fields for field in fields: try: attribute = field.get_attribute(instance) except SkipField: continue # We skip `to_representation` for `None` values so that fields do # not have to explicitly deal with that case. # # For related fields with `use_pk_only_optimization` we need to # resolve the pk value. check_for_none = attribute.pk if isinstance(attribute, PKOnlyObject) else attribute if check_for_none is None: ret[field.field_name] = None else: ret[field.field_name] = field.to_representation(attribute) return ret def validate(self, attrs): return attrs def __repr__(self): return representation.serializer_repr(self, indent=1) # The following are used for accessing `BoundField` instances on the # serializer, for the purposes of presenting a form-like API onto the # field values and field errors. def __iter__(self): for field in self.fields.values(): yield self[field.field_name] def __getitem__(self, key): field = self.fields[key] value = self.data.get(key) error = self.errors.get(key) if hasattr(self, '_errors') else None if isinstance(field, Serializer): return NestedBoundField(field, value, error) if isinstance(field, JSONField): return JSONBoundField(field, value, error) return BoundField(field, value, error) # Include a backlink to the serializer class on return objects. # Allows renderers such as HTMLFormRenderer to get the full field info. @property def data(self): ret = super().data return ReturnDict(ret, serializer=self) @property def errors(self): ret = super().errors if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null': # Edge case. Provide a more descriptive error than # "this field may not be null", when no data is passed. detail = ErrorDetail('No data provided', code='null') ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]} return ReturnDict(ret, serializer=self) # There's some replication of `ListField` here, # but that's probably better than obfuscating the call hierarchy. class ListSerializer(BaseSerializer): child = None many = True default_error_messages = { 'not_a_list': _('Expected a list of items but got type "{input_type}".'), 'empty': _('This list may not be empty.'), 'max_length': _('Ensure this field has no more than {max_length} elements.'), 'min_length': _('Ensure this field has at least {min_length} elements.') } def __init__(self, *args, **kwargs): self.child = kwargs.pop('child', copy.deepcopy(self.child)) self.allow_empty = kwargs.pop('allow_empty', True) self.max_length = kwargs.pop('max_length', None) self.min_length = kwargs.pop('min_length', None) assert self.child is not None, '`child` is a required argument.' assert not inspect.isclass(self.child), '`child` has not been instantiated.' super().__init__(*args, **kwargs) self.child.bind(field_name='', parent=self) def get_initial(self): if hasattr(self, 'initial_data'): return self.to_representation(self.initial_data) return [] def get_value(self, dictionary): """ Given the input dictionary, return the field value. """ # We override the default field access in order to support # lists in HTML forms. if html.is_html_input(dictionary): return html.parse_html_list(dictionary, prefix=self.field_name, default=empty) return dictionary.get(self.field_name, empty) def run_validation(self, data=empty): """ We override the default `run_validation`, because the validation performed by validators and the `.validate()` method should be coerced into an error dictionary with a 'non_fields_error' key. """ (is_empty_value, data) = self.validate_empty_values(data) if is_empty_value: return data value = self.to_internal_value(data) try: self.run_validators(value) value = self.validate(value) assert value is not None, '.validate() should return the validated data' except (ValidationError, DjangoValidationError) as exc: raise ValidationError(detail=as_serializer_error(exc)) 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. """ if html.is_html_input(data): data = html.parse_html_list(data, default=[]) if not isinstance(data, list): message = self.error_messages['not_a_list'].format( input_type=type(data).__name__ ) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='not_a_list') if not self.allow_empty and len(data) == 0: message = self.error_messages['empty'] raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='empty') if self.max_length is not None and len(data) > self.max_length: message = self.error_messages['max_length'].format(max_length=self.max_length) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='max_length') if self.min_length is not None and len(data) < self.min_length: message = self.error_messages['min_length'].format(min_length=self.min_length) raise ValidationError({ api_settings.NON_FIELD_ERRORS_KEY: [message] }, code='min_length') ret = [] errors = [] for item in data: try: validated = self.run_child_validation(item) except ValidationError as exc: errors.append(exc.detail) else: ret.append(validated) errors.append({}) if any(errors): raise ValidationError(errors) return ret def to_representation(self, data): """ List of object instances -> List of dicts of primitive datatypes. """ # 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.BaseManager) else data return [ self.child.to_representation(item) for item in iterable ] def validate(self, attrs): return attrs def update(self, instance, validated_data): raise NotImplementedError( "Serializers with many=True do not support multiple update by " "default, only multiple create. For updates it is unclear how to " "deal with insertions and deletions. If you need to support " "multiple update, use a `ListSerializer` class and override " "`.update()` so you can specify the behavior exactly." ) def create(self, validated_data): return [ self.child.create(attrs) for attrs in validated_data ] def save(self, **kwargs): """ Save and return a list of object instances. """ # Guard against incorrect use of `serializer.save(commit=False)` assert 'commit' not in kwargs, ( "'commit' is not a valid keyword argument to the 'save()' method. " "If you need to access data before committing to the database then " "inspect 'serializer.validated_data' instead. " "You can also pass additional keyword arguments to 'save()' if you " "need to set extra attributes on the saved model instance. " "For example: 'serializer.save(owner=request.user)'.'" ) validated_data = [ {**attrs, **kwargs} for attrs in self.validated_data ] if self.instance is not None: self.instance = self.update(self.instance, validated_data) assert self.instance is not None, ( '`update()` did not return an object instance.' ) else: self.instance = self.create(validated_data) assert self.instance is not None, ( '`create()` did not return an object instance.' ) return self.instance def is_valid(self, *, raise_exception=False): # This implementation is the same as the default, # except that we use lists, rather than dicts, as the empty case. assert hasattr(self, 'initial_data'), ( 'Cannot call `.is_valid()` as no `data=` keyword argument was ' 'passed when instantiating the serializer instance.' ) if not hasattr(self, '_validated_data'): try: self._validated_data = self.run_validation(self.initial_data) except ValidationError as exc: self._validated_data = [] self._errors = exc.detail else: self._errors = [] if self._errors and raise_exception: raise ValidationError(self.errors) return not bool(self._errors) def __repr__(self): return representation.list_repr(self, indent=1) # Include a backlink to the serializer class on return objects. # Allows renderers such as HTMLFormRenderer to get the full field info. @property def data(self): ret = super().data return ReturnList(ret, serializer=self) @property def errors(self): ret = super().errors if isinstance(ret, list) and len(ret) == 1 and getattr(ret[0], 'code', None) == 'null': # Edge case. Provide a more descriptive error than # "this field may not be null", when no data is passed. detail = ErrorDetail('No data provided', code='null') ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]} if isinstance(ret, dict): return ReturnDict(ret, serializer=self) return ReturnList(ret, serializer=self) # ModelSerializer & HyperlinkedModelSerializer # -------------------------------------------- def raise_errors_on_nested_writes(method_name, serializer, validated_data): """ Enforce explicit handling of writable nested and dotted-source fields. This helper raises clear and actionable errors when a serializer attempts to perform writable nested updates or creates using the default `ModelSerializer` behavior. Writable nested relationships and dotted-source fields are intentionally unsupported by default due to ambiguous persistence semantics. Developers must either: - Override the `.create()` / `.update()` methods explicitly, or - Mark nested serializers as `read_only=True` This check is invoked internally by default `ModelSerializer.create()` and `ModelSerializer.update()` implementations. Eg. Suppose we have a `UserSerializer` with a nested profile. How should we handle the case of an update, where the `profile` relationship does not exist? Any of the following might be valid: * Raise an application error. * Silently ignore the nested part of the update. * Automatically create a profile instance. """ ModelClass = serializer.Meta.model model_field_info = model_meta.get_field_info(ModelClass) # Ensure we don't have a writable nested field. For example: # # class UserSerializer(ModelSerializer): # ... # profile = ProfileSerializer() assert not any( isinstance(field, BaseSerializer) and (field.source in validated_data) and (field.source in model_field_info.relations) and isinstance(validated_data[field.source], (list, dict)) for field in serializer._writable_fields ), ( 'The `.{method_name}()` method does not support writable nested ' 'fields by default.\nWrite an explicit `.{method_name}()` method for ' 'serializer `{module}.{class_name}`, or set `read_only=True` on ' 'nested serializer fields.'.format( method_name=method_name, module=serializer.__class__.__module__, class_name=serializer.__class__.__name__ ) ) # Ensure we don't have a writable dotted-source field. For example: # # class UserSerializer(ModelSerializer): # ... # address = serializer.CharField('profile.address') # # Though, non-relational fields (e.g., JSONField) are acceptable. For example: # # class NonRelationalPersonModel(models.Model): # profile = JSONField() # # class UserSerializer(ModelSerializer): # ... # address = serializer.CharField('profile.address') assert not any( len(field.source_attrs) > 1 and (field.source_attrs[0] in validated_data) and (field.source_attrs[0] in model_field_info.relations) and isinstance(validated_data[field.source_attrs[0]], (list, dict)) for field in serializer._writable_fields ), ( 'The `.{method_name}()` method does not support writable dotted-source ' 'fields by default.\nWrite an explicit `.{method_name}()` method for ' 'serializer `{module}.{class_name}`, or set `read_only=True` on ' 'dotted-source serializer fields.'.format( method_name=method_name, module=serializer.__class__.__module__, class_name=serializer.__class__.__name__ ) ) class ModelSerializer(Serializer): """ A `ModelSerializer` is just a regular `Serializer`, except that: * A set of default fields are automatically populated. * A set of default validators are automatically populated. * Default `.create()` and `.update()` implementations are provided. The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don't need to dig into the implementation. If the `ModelSerializer` class *doesn't* generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a `Serializer` class. """ serializer_field_mapping = { models.AutoField: IntegerField, models.BigAutoField: BigIntegerField, models.BigIntegerField: BigIntegerField, models.BooleanField: BooleanField, models.CharField: CharField, models.CommaSeparatedIntegerField: CharField, models.DateField: DateField, models.DateTimeField: DateTimeField, models.DecimalField: DecimalField, models.DurationField: DurationField, models.EmailField: EmailField, models.Field: ModelField, models.FileField: FileField, models.FloatField: FloatField, models.ImageField: ImageField, models.IntegerField: IntegerField, models.NullBooleanField: BooleanField, models.PositiveIntegerField: IntegerField, models.PositiveSmallIntegerField: IntegerField, models.SlugField: SlugField, models.SmallIntegerField: IntegerField, models.TextField: CharField, models.TimeField: TimeField, models.URLField: URLField, models.UUIDField: UUIDField, models.GenericIPAddressField: IPAddressField, models.FilePathField: FilePathField, } if hasattr(models, 'JSONField'): serializer_field_mapping[models.JSONField] = JSONField if postgres_fields: serializer_field_mapping[postgres_fields.HStoreField] = HStoreField serializer_field_mapping[postgres_fields.ArrayField] = ListField serializer_field_mapping[postgres_fields.JSONField] = JSONField serializer_related_field = PrimaryKeyRelatedField serializer_related_to_field = SlugRelatedField serializer_url_field = HyperlinkedIdentityField serializer_choice_field = ChoiceField # The field name for hyperlinked identity fields. Defaults to 'url'. # You can modify this using the API setting. # # Note that if you instead need modify this on a per-serializer basis, # you'll also need to ensure you update the `create` method on any generic # views, to correctly handle the 'Location' response header for # "HTTP 201 Created" responses. url_field_name = None # Default `create` and `update` behavior... def create(self, validated_data): """ We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just: return ExampleModel.objects.create(**validated_data) If there are many to many fields present on the instance then they cannot be set until the model is instantiated, in which case the implementation is like so: example_relationship = validated_data.pop('example_relationship') instance = ExampleModel.objects.create(**validated_data) instance.example_relationship = example_relationship return instance The default implementation also does not handle nested relationships. If you want to support writable nested relationships you'll need to write an explicit `.create()` method. """ raise_errors_on_nested_writes('create', self, validated_data) ModelClass = self.Meta.model # Remove many-to-many relationships from validated_data. # They are not valid arguments to the default `.create()` method, # as they require that the instance has already been saved. info = model_meta.get_field_info(ModelClass) many_to_many = {} for field_name, relation_info in info.relations.items(): if relation_info.to_many and (field_name in validated_data): many_to_many[field_name] = validated_data.pop(field_name) try: instance = ModelClass._default_manager.create(**validated_data) except TypeError: tb = traceback.format_exc() msg = ( 'Got a `TypeError` when calling `%s.%s.create()`. ' 'This may be because you have a writable field on the ' 'serializer class that is not a valid argument to ' '`%s.%s.create()`. You may need to make the field ' 'read-only, or override the %s.create() method to handle ' 'this correctly.\nOriginal exception was:\n %s' % ( ModelClass.__name__, ModelClass._default_manager.name, ModelClass.__name__, ModelClass._default_manager.name, self.__class__.__name__, tb ) ) raise TypeError(msg) # Save many-to-many relationships after the instance is created. if many_to_many: for field_name, value in many_to_many.items(): field = getattr(instance, field_name) field.set(value) return instance def update(self, instance, validated_data): raise_errors_on_nested_writes('update', self, validated_data) info = model_meta.get_field_info(instance) # Simply set each attribute on the instance, and then save it. # Note that unlike `.create()` we don't need to treat many-to-many # relationships as being a special case. During updates we already # have an instance pk for the relationships to be associated with. m2m_fields = [] for attr, value in validated_data.items(): if attr in info.relations and info.relations[attr].to_many: m2m_fields.append((attr, value)) else: setattr(instance, attr, value) instance.save() # Note that many-to-many fields are set after updating instance. # Setting m2m fields triggers signals which could potentially change # updated instance and we do not want it to collide with .update() for attr, value in m2m_fields: field = getattr(instance, attr) field.set(value) return instance # Determine the fields to apply... def get_fields(self): """ Return the dict of field names -> field instances that should be used for `self.fields` when instantiating the serializer. """ if self.url_field_name is None: self.url_field_name = api_settings.URL_FIELD_NAME assert hasattr(self, 'Meta'), ( 'Class {serializer_class} missing "Meta" attribute'.format( serializer_class=self.__class__.__name__ ) ) assert hasattr(self.Meta, 'model'), ( 'Class {serializer_class} missing "Meta.model" attribute'.format( serializer_class=self.__class__.__name__ ) ) if model_meta.is_abstract_model(self.Meta.model): raise ValueError( 'Cannot use ModelSerializer with Abstract Models.' ) declared_fields = copy.deepcopy(self._declared_fields) model = getattr(self.Meta, 'model') depth = getattr(self.Meta, 'depth', 0) if depth is not None: assert depth >= 0, "'depth' may not be negative." assert depth <= 10, "'depth' may not be greater than 10." # Retrieve metadata about fields & relationships on the model class. info = model_meta.get_field_info(model) field_names = self.get_field_names(declared_fields, info) # Determine any extra field arguments and hidden fields that # should be included extra_kwargs = self.get_extra_kwargs() extra_kwargs, hidden_fields = self.get_uniqueness_extra_kwargs( field_names, declared_fields, extra_kwargs ) # Determine the fields that should be included on the serializer. fields = {} # If it's a ManyToMany field, and the default is None, then raises an exception to prevent exceptions on .set() for field_name in declared_fields.keys(): if field_name in info.relations and info.relations[field_name].to_many and declared_fields[field_name].default is None: raise ValueError( f"The field '{field_name}' on serializer '{self.__class__.__name__}' is a ManyToMany field and cannot have a default value of None." ) for field_name in field_names: # If the field is explicitly declared on the class then use that. if field_name in declared_fields: fields[field_name] = declared_fields[field_name] continue extra_field_kwargs = extra_kwargs.get(field_name, {}) source = extra_field_kwargs.get('source', '*') if source == '*': source = field_name # Determine the serializer field class and keyword arguments. field_class, field_kwargs = self.build_field( source, info, model, depth ) # Include any kwargs defined in `Meta.extra_kwargs` field_kwargs = self.include_extra_kwargs( field_kwargs, extra_field_kwargs ) # Create the serializer field. fields[field_name] = field_class(**field_kwargs) # Add in any hidden fields. fields.update(hidden_fields) return fields # Methods for determining the set of field names to include... def get_field_names(self, declared_fields, info): """ Returns the list of all field names that should be created when instantiating this serializer class. This is based on the default set of fields, but also takes into account the `Meta.fields` or `Meta.exclude` options if they have been specified. """ fields = getattr(self.Meta, 'fields', None) exclude = getattr(self.Meta, 'exclude', None) if fields and fields != ALL_FIELDS and not isinstance(fields, (list, tuple)): raise TypeError( 'The `fields` option must be a list or tuple or "__all__". ' 'Got %s.' % type(fields).__name__ ) if exclude and not isinstance(exclude, (list, tuple)): raise TypeError( 'The `exclude` option must be a list or tuple. Got %s.' % type(exclude).__name__ ) assert not (fields and exclude), ( "Cannot set both 'fields' and 'exclude' options on " "serializer {serializer_class}.".format( serializer_class=self.__class__.__name__ ) ) assert not (fields is None and exclude is None), ( "Creating a ModelSerializer without either the 'fields' attribute " "or the 'exclude' attribute has been deprecated since 3.3.0, " "and is now disallowed. Add an explicit fields = '__all__' to the " "{serializer_class} serializer.".format( serializer_class=self.__class__.__name__ ), ) if fields == ALL_FIELDS: fields = None if fields is not None: # Ensure that all declared fields have also been included in the # `Meta.fields` option. # Do not require any fields that are declared in a parent class, # in order to allow serializer subclasses to only include # a subset of fields. required_field_names = set(declared_fields) for cls in self.__class__.__bases__: required_field_names -= set(getattr(cls, '_declared_fields', [])) for field_name in required_field_names: assert field_name in fields, ( "The field '{field_name}' was declared on serializer " "{serializer_class}, but has not been included in the " "'fields' option.".format( field_name=field_name, serializer_class=self.__class__.__name__ ) ) return fields # Use the default set of field names if `Meta.fields` is not specified. fields = self.get_default_field_names(declared_fields, info) if exclude is not None: # If `Meta.exclude` is included, then remove those fields. for field_name in exclude: assert field_name not in self._declared_fields, ( "Cannot both declare the field '{field_name}' and include " "it in the {serializer_class} 'exclude' option. Remove the " "field or, if inherited from a parent serializer, disable " "with `{field_name} = None`." .format( field_name=field_name, serializer_class=self.__class__.__name__ ) ) assert field_name in fields, ( "The field '{field_name}' was included on serializer " "{serializer_class} in the 'exclude' option, but does " "not match any model field.".format( field_name=field_name, serializer_class=self.__class__.__name__ ) ) fields.remove(field_name) return fields def get_default_field_names(self, declared_fields, model_info): """ Return the default list of field names that will be used if the `Meta.fields` option is not specified. """ return ( [model_info.pk.name] + list(declared_fields) + list(model_info.fields) + list(model_info.forward_relations) ) # Methods for constructing serializer fields... def build_field(self, field_name, info, model_class, nested_depth): """ Return a two tuple of (cls, kwargs) to build a serializer field with. """ if field_name in info.fields_and_pk: model_field = info.fields_and_pk[field_name] return self.build_standard_field(field_name, model_field) elif field_name in info.relations: relation_info = info.relations[field_name] if not nested_depth: return self.build_relational_field(field_name, relation_info) else: return self.build_nested_field(field_name, relation_info, nested_depth) elif hasattr(model_class, field_name): return self.build_property_field(field_name, model_class) elif field_name == self.url_field_name: return self.build_url_field(field_name, model_class) return self.build_unknown_field(field_name, model_class) def build_standard_field(self, field_name, model_field): """ Create regular model fields. """ field_mapping = ClassLookupDict(self.serializer_field_mapping) field_class = field_mapping[model_field] field_kwargs = get_field_kwargs(field_name, model_field) # Special case to handle when a OneToOneField is also the primary key if model_field.one_to_one and model_field.primary_key: field_class = self.serializer_related_field field_kwargs['queryset'] = model_field.related_model.objects if 'choices' in field_kwargs: # Fields with choices get coerced into `ChoiceField` # instead of using their regular typed field. field_class = self.serializer_choice_field # Some model fields may introduce kwargs that would not be valid # for the choice field. We need to strip these out. # Eg. models.DecimalField(max_digits=3, decimal_places=1, choices=DECIMAL_CHOICES) valid_kwargs = { 'read_only', 'write_only', 'required', 'default', 'initial', 'source', 'label', 'help_text', 'style', 'error_messages', 'validators', 'allow_null', 'allow_blank', 'choices' } for key in list(field_kwargs): if key not in valid_kwargs: field_kwargs.pop(key) if not issubclass(field_class, ModelField): # `model_field` is only valid for the fallback case of # `ModelField`, which is used when no other typed field # matched to the model field. field_kwargs.pop('model_field', None) if not issubclass(field_class, CharField) and not issubclass(field_class, ChoiceField): # `allow_blank` is only valid for textual fields. field_kwargs.pop('allow_blank', None) is_django_jsonfield = hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField) if (postgres_fields and isinstance(model_field, postgres_fields.JSONField)) or is_django_jsonfield: # Populate the `encoder` argument of `JSONField` instances generated # for the model `JSONField`. field_kwargs['encoder'] = getattr(model_field, 'encoder', None) if is_django_jsonfield: field_kwargs['decoder'] = getattr(model_field, 'decoder', None) if postgres_fields and isinstance(model_field, postgres_fields.ArrayField): # Populate the `child` argument on `ListField` instances generated # for the PostgreSQL specific `ArrayField`. child_model_field = model_field.base_field child_field_class, child_field_kwargs = self.build_standard_field( 'child', child_model_field ) field_kwargs['child'] = child_field_class(**child_field_kwargs) return field_class, field_kwargs def build_relational_field(self, field_name, relation_info): """ Create fields for forward and reverse relationships. """ field_class = self.serializer_related_field field_kwargs = get_relation_kwargs(field_name, relation_info) to_field = field_kwargs.pop('to_field', None) if to_field and not relation_info.reverse and not relation_info.related_model._meta.get_field(to_field).primary_key: field_kwargs['slug_field'] = to_field field_class = self.serializer_related_to_field # `view_name` is only valid for hyperlinked relationships. if not issubclass(field_class, HyperlinkedRelatedField): field_kwargs.pop('view_name', None) return field_class, field_kwargs def build_nested_field(self, field_name, relation_info, nested_depth): """ Create nested fields for forward and reverse relationships. """ class NestedSerializer(ModelSerializer): class Meta: model = relation_info.related_model depth = nested_depth - 1 fields = '__all__' field_class = NestedSerializer field_kwargs = get_nested_relation_kwargs(relation_info) return field_class, field_kwargs def build_property_field(self, field_name, model_class): """ Create a read only field for model methods and properties. """ field_class = ReadOnlyField field_kwargs = {} return field_class, field_kwargs def build_url_field(self, field_name, model_class): """ Create a field representing the object's own URL. """ field_class = self.serializer_url_field field_kwargs = get_url_kwargs(model_class) return field_class, field_kwargs 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` in `%s.%s`.' % (field_name, model_class.__name__, self.__class__.__module__, self.__class__.__name__) ) def include_extra_kwargs(self, kwargs, extra_kwargs): """ Include any 'extra_kwargs' that have been included for this field, possibly removing any incompatible existing keyword arguments. """ if extra_kwargs.get('read_only', False): for attr in [ 'required', 'default', 'allow_blank', 'min_length', 'max_length', 'min_value', 'max_value', 'validators', 'queryset' ]: kwargs.pop(attr, None) if extra_kwargs.get('default') and kwargs.get('required') is False: kwargs.pop('required') if extra_kwargs.get('read_only', kwargs.get('read_only', False)): extra_kwargs.pop('required', None) # Read only fields should always omit the 'required' argument. kwargs.update(extra_kwargs) return kwargs # Methods for determining additional keyword arguments to apply... def get_extra_kwargs(self): """ Return a dictionary mapping field names to a dictionary of additional keyword arguments. """ extra_kwargs = copy.deepcopy(getattr(self.Meta, 'extra_kwargs', {})) read_only_fields = getattr(self.Meta, 'read_only_fields', None) if read_only_fields is not None: if not isinstance(read_only_fields, (list, tuple)): raise TypeError( 'The `read_only_fields` option must be a list or tuple. ' 'Got %s.' % type(read_only_fields).__name__ ) for field_name in read_only_fields: kwargs = extra_kwargs.get(field_name, {}) kwargs['read_only'] = True extra_kwargs[field_name] = kwargs else: # Guard against the possible misspelling `readonly_fields` (used # by the Django admin and others). assert not hasattr(self.Meta, 'readonly_fields'), ( 'Serializer `%s.%s` has field `readonly_fields`; ' 'the correct spelling for the option is `read_only_fields`.' % (self.__class__.__module__, self.__class__.__name__) ) 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 result of uniqueness constraints on the model. This is returned as a two-tuple of: ('dict of updated extra kwargs', 'mapping of hidden fields') """ if getattr(self.Meta, 'validators', None) is not None: return (extra_kwargs, {}) model = getattr(self.Meta, 'model') model_fields = self._get_model_fields( field_names, declared_fields, extra_kwargs ) # Determine if we need any additional `HiddenField` or extra keyword # arguments to deal with `unique_for` dates that are required to # be in the input data in order to validate it. unique_constraint_names = set() for model_field in model_fields.values(): # Include each of the `unique_for_*` field names. unique_constraint_names |= {model_field.unique_for_date, model_field.unique_for_month, model_field.unique_for_year} unique_constraint_names -= {None} model_fields_names = set(model_fields.keys()) # Include each of the `unique_together` and `UniqueConstraint` field names, # so long as all the field names are included on the serializer. 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 model_fields_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=...' # arguments that are appropriate to these fields, or add a `HiddenField` for it. hidden_fields = {} uniqueness_extra_kwargs = {} for unique_constraint_name in unique_constraint_names: # Get the model field that is referred too. unique_constraint_field = model._meta.get_field(unique_constraint_name) if getattr(unique_constraint_field, 'auto_now_add', None): default = CreateOnlyDefault(timezone.now) elif getattr(unique_constraint_field, 'auto_now', None): default = timezone.now elif unique_constraint_field.has_default(): default = unique_constraint_field.default elif unique_constraint_field.null: default = None else: default = empty if unique_constraint_name in model_fields: # The corresponding field is present in the serializer if default is empty: uniqueness_extra_kwargs[unique_constraint_name] = {'required': True} else: uniqueness_extra_kwargs[unique_constraint_name] = {'default': default} elif default is not empty: # The corresponding field is not present in the # serializer. We have a default to use for it, so # add in a hidden field that populates it. hidden_fields[unique_constraint_name] = HiddenField(default=default) # Update `extra_kwargs` with any new options. for key, value in uniqueness_extra_kwargs.items(): if key in extra_kwargs: value.update(extra_kwargs[key]) extra_kwargs[key] = value return extra_kwargs, hidden_fields def _get_model_fields(self, field_names, declared_fields, extra_kwargs): """ Returns all the model fields that are being mapped to by fields on the serializer class. Returned as a dict of 'model field name' -> 'model field'. Used internally by `get_uniqueness_field_options`. """ model = getattr(self.Meta, 'model') model_fields = {} for field_name in field_names: if field_name in declared_fields: # If the field is declared on the serializer field = declared_fields[field_name] source = field.source or field_name else: try: source = extra_kwargs[field_name]['source'] except KeyError: source = field_name if '.' in source or source == '*': # Model fields will always have a simple source mapping, # they can't be nested attribute lookups. continue with contextlib.suppress(FieldDoesNotExist): field = model._meta.get_field(source) if isinstance(field, DjangoModelField): model_fields[source] = field return model_fields # Determine the validators to apply... def get_validators(self): """ Determine the set of validators to use when instantiating serializer. """ # If the validators have been declared explicitly then use that. validators = getattr(getattr(self, 'Meta', None), 'validators', None) if validators is not None: return list(validators) # Otherwise use the default set of validators. return ( self.get_unique_together_validators() + self.get_unique_for_date_validators() ) def _get_constraint_violation_error_message(self, constraint): """ Returns the violation error message for the UniqueConstraint, or None if the message is the default. """ violation_error_message = constraint.get_violation_error_message() default_error_message = constraint.default_violation_error_message % {"name": constraint.name} if violation_error_message == default_error_message: return None return violation_error_message def get_unique_together_validators(self): """ Determine a default set of validators for any unique_together constraints. """ # 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 = { 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({ 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 # us to check that multiple fields don't map to the same source. source_map = defaultdict(list) for name, source in field_sources.items(): source_map[source].append(name) unique_constraint_by_fields = { constraint.fields: constraint for model_cls in (*self.Meta.model._meta.parents, self.Meta.model) for constraint in model_cls._meta.constraints if isinstance(constraint, models.UniqueConstraint) } # Note that we make sure to check `unique_together` both on the # base model class, but also on any parent classes. validators = [] 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 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]), ) ) field_names = tuple(source_map[f][0] for f in unique_together) constraint = unique_constraint_by_fields.get(tuple(unique_together)) violation_error_message = self._get_constraint_violation_error_message(constraint) if constraint else None validator = UniqueTogetherValidator( queryset=queryset, fields=field_names, condition_fields=tuple(source_map[f][0] for f in condition_fields), condition=condition, message=violation_error_message, code=getattr(constraint, 'violation_error_code', None), ) validators.append(validator) return validators def get_unique_for_date_validators(self): """ Determine a default set of validators for the following constraints: * unique_for_date * unique_for_month * unique_for_year """ info = model_meta.get_field_info(self.Meta.model) default_manager = self.Meta.model._default_manager field_names = [field.source for field in self.fields.values()] validators = [] for field_name, field in info.fields_and_pk.items(): if field.unique_for_date and field_name in field_names: validator = UniqueForDateValidator( queryset=default_manager, field=field_name, date_field=field.unique_for_date ) validators.append(validator) if field.unique_for_month and field_name in field_names: validator = UniqueForMonthValidator( queryset=default_manager, field=field_name, date_field=field.unique_for_month ) validators.append(validator) if field.unique_for_year and field_name in field_names: validator = UniqueForYearValidator( queryset=default_manager, field=field_name, date_field=field.unique_for_year ) validators.append(validator) return validators class HyperlinkedModelSerializer(ModelSerializer): """ A type of `ModelSerializer` that uses hyperlinked relationships instead of primary key relationships. Specifically: * A 'url' field is included instead of the 'id' field. * Relationships to other instances are hyperlinks, instead of primary keys. """ serializer_related_field = HyperlinkedRelatedField def get_default_field_names(self, declared_fields, model_info): """ Return the default list of field names that will be used if the `Meta.fields` option is not specified. """ return ( [self.url_field_name] + list(declared_fields) + list(model_info.fields) + list(model_info.forward_relations) ) def build_nested_field(self, field_name, relation_info, nested_depth): """ Create nested fields for forward and reverse relationships. """ class NestedSerializer(HyperlinkedModelSerializer): class Meta: model = relation_info.related_model depth = nested_depth - 1 fields = '__all__' field_class = NestedSerializer field_kwargs = get_nested_relation_kwargs(relation_info) return field_class, field_kwargs ================================================ FILE: rest_framework/settings.py ================================================ """ Settings for REST framework are all namespaced in the REST_FRAMEWORK setting. For example your project's `settings.py` file might look like this: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.TemplateHTMLRenderer', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', ], } This module provides the `api_setting` object, that is used to access REST framework settings, checking for user settings first, then falling back to the defaults. """ from django.conf import settings # 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 DJANGO_DURATION_FORMAT, ISO_8601 DEFAULTS = { # Base API policies 'DEFAULT_RENDERER_CLASSES': [ 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ], 'DEFAULT_PARSER_CLASSES': [ 'rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ], 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.BasicAuthentication' ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.AllowAny', ], 'DEFAULT_THROTTLE_CLASSES': [], 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'rest_framework.negotiation.DefaultContentNegotiation', 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata', 'DEFAULT_VERSIONING_CLASS': None, # Generic view behavior 'DEFAULT_PAGINATION_CLASS': None, 'DEFAULT_FILTER_BACKENDS': [], # Schema 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.openapi.AutoSchema', # Throttling 'DEFAULT_THROTTLE_RATES': { 'user': None, 'anon': None, }, 'NUM_PROXIES': None, # Pagination 'PAGE_SIZE': None, # Filtering 'SEARCH_PARAM': 'search', 'ORDERING_PARAM': 'ordering', # Versioning 'DEFAULT_VERSION': None, 'ALLOWED_VERSIONS': None, 'VERSION_PARAM': 'version', # Authentication 'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser', 'UNAUTHENTICATED_TOKEN': None, # View configuration 'VIEW_NAME_FUNCTION': 'rest_framework.views.get_view_name', 'VIEW_DESCRIPTION_FUNCTION': 'rest_framework.views.get_view_description', # Exception handling 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler', 'NON_FIELD_ERRORS_KEY': 'non_field_errors', # Testing 'TEST_REQUEST_RENDERER_CLASSES': [ 'rest_framework.renderers.MultiPartRenderer', 'rest_framework.renderers.JSONRenderer' ], 'TEST_REQUEST_DEFAULT_FORMAT': 'multipart', # Hyperlink settings 'URL_FORMAT_OVERRIDE': 'format', 'FORMAT_SUFFIX_KWARG': 'format', 'URL_FIELD_NAME': 'url', # Input and output formats 'DATE_FORMAT': ISO_8601, 'DATE_INPUT_FORMATS': [ISO_8601], 'DATETIME_FORMAT': ISO_8601, 'DATETIME_INPUT_FORMATS': [ISO_8601], 'TIME_FORMAT': ISO_8601, 'TIME_INPUT_FORMATS': [ISO_8601], 'DURATION_FORMAT': DJANGO_DURATION_FORMAT, # Encoding 'UNICODE_JSON': True, 'COMPACT_JSON': True, 'STRICT_JSON': True, 'COERCE_DECIMAL_TO_STRING': True, 'COERCE_BIGINT_TO_STRING': False, 'UPLOADED_FILES_USE_URL': True, # Browsable API 'HTML_SELECT_CUTOFF': 1000, 'HTML_SELECT_CUTOFF_TEXT': "More than {count} items...", # Schemas 'SCHEMA_COERCE_PATH_PK': True, 'SCHEMA_COERCE_METHOD_NAMES': { 'retrieve': 'read', 'destroy': 'delete' }, } # List of settings that may be in string import notation. IMPORT_STRINGS = [ 'DEFAULT_RENDERER_CLASSES', 'DEFAULT_PARSER_CLASSES', 'DEFAULT_AUTHENTICATION_CLASSES', 'DEFAULT_PERMISSION_CLASSES', 'DEFAULT_THROTTLE_CLASSES', 'DEFAULT_CONTENT_NEGOTIATION_CLASS', 'DEFAULT_METADATA_CLASS', 'DEFAULT_VERSIONING_CLASS', 'DEFAULT_PAGINATION_CLASS', 'DEFAULT_FILTER_BACKENDS', 'DEFAULT_SCHEMA_CLASS', 'EXCEPTION_HANDLER', 'TEST_REQUEST_RENDERER_CLASSES', 'UNAUTHENTICATED_USER', 'UNAUTHENTICATED_TOKEN', 'VIEW_NAME_FUNCTION', 'VIEW_DESCRIPTION_FUNCTION' ] # List of settings that have been removed REMOVED_SETTINGS = [ 'PAGINATE_BY', 'PAGINATE_BY_PARAM', 'MAX_PAGINATE_BY', ] def perform_import(val, setting_name): """ If the given setting is a string import notation, then perform the necessary import or imports. """ if val is None: return None elif isinstance(val, str): return import_from_string(val, setting_name) elif isinstance(val, (list, tuple)): return [import_from_string(item, setting_name) for item in val] return val def import_from_string(val, setting_name): """ Attempt to import a class from a string representation. """ try: return import_string(val) except ImportError as e: msg = "Could not import '%s' for API setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e) raise ImportError(msg) class APISettings: """ A settings object that allows REST Framework settings to be accessed as properties. For example: from rest_framework.settings import api_settings print(api_settings.DEFAULT_RENDERER_CLASSES) Any setting with string import paths will be automatically resolved and return the class, rather than the string literal. Note: This is an internal class that is only compatible with settings namespaced under the REST_FRAMEWORK name. It is not intended to be used by 3rd-party apps, and test helpers like `override_settings` may not work as expected. """ def __init__(self, user_settings=None, defaults=None, import_strings=None): if user_settings: self._user_settings = self.__check_user_settings(user_settings) self.defaults = defaults or DEFAULTS self.import_strings = import_strings or IMPORT_STRINGS self._cached_attrs = set() @property def user_settings(self): if not hasattr(self, '_user_settings'): self._user_settings = getattr(settings, 'REST_FRAMEWORK', {}) return self._user_settings def __getattr__(self, attr): if attr not in self.defaults: raise AttributeError("Invalid API setting: '%s'" % attr) try: # Check if present in user settings val = self.user_settings[attr] except KeyError: # Fall back to defaults val = self.defaults[attr] # Coerce import strings into classes if attr in self.import_strings: val = perform_import(val, attr) # Cache the result self._cached_attrs.add(attr) setattr(self, attr, val) return val def __check_user_settings(self, user_settings): SETTINGS_DOC = "https://www.django-rest-framework.org/api-guide/settings/" for setting in REMOVED_SETTINGS: if setting in user_settings: raise RuntimeError("The '%s' setting has been removed. Please refer to '%s' for available settings." % (setting, SETTINGS_DOC)) return user_settings def reload(self): for attr in self._cached_attrs: delattr(self, attr) self._cached_attrs.clear() if hasattr(self, '_user_settings'): delattr(self, '_user_settings') api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS) def reload_api_settings(*args, **kwargs): setting = kwargs['setting'] if setting == 'REST_FRAMEWORK': api_settings.reload() setting_changed.connect(reload_api_settings) ================================================ FILE: rest_framework/static/rest_framework/css/bootstrap-tweaks.css ================================================ /* This CSS file contains some tweaks specific to the included Bootstrap theme. It's separate from `style.css` so that it can be easily overridden by replacing a single block in the template. */ .form-actions { background: transparent; border-top-color: transparent; padding-top: 0; text-align: right; } #generic-content-form textarea { font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace; font-size: 80%; } .navbar-inverse .brand a { color: #999999; } .navbar-inverse .brand:hover a { color: white; text-decoration: none; } /* custom navigation styles */ .navbar { width: 100%; position: fixed; left: 0; top: 0; } .navbar { background: #2C2C2C; color: white; border: none; border-top: 5px solid #A30000; border-radius: 0px; } .navbar .nav li, .navbar .nav li a, .navbar .brand:hover { color: white; } .nav-list > .active > a, .nav-list > .active > a:hover { background: #2C2C2C; } .navbar .dropdown-menu li a, .navbar .dropdown-menu li { color: #A30000; } .navbar .dropdown-menu li a:hover { background: #EEEEEE; color: #C20000; } ul.breadcrumb { margin: 70px 0 0 0; } .breadcrumb li.active a { color: #777; } .pagination>.disabled>a, .pagination>.disabled>a:hover, .pagination>.disabled>a:focus { cursor: not-allowed; pointer-events: none; } .pager>.disabled>a, .pager>.disabled>a:hover, .pager>.disabled>a:focus { pointer-events: none; } .pager .next { margin-left: 10px; } /*=== dabapps bootstrap styles ====*/ html { width:100%; background: none; } /*body, .navbar .container-fluid { max-width: 1150px; margin: 0 auto; }*/ body { background: url("../img/grid.png") repeat-x; background-attachment: fixed; } #content { margin: 0; padding-bottom: 60px; } /* sticky footer and footer */ html, body { height: 100%; } .wrapper { position: relative; top: 0; left: 0; padding-top: 60px; margin: -60px 0; min-height: 100%; } .form-switcher { margin-bottom: 0; } .well { -webkit-box-shadow: none; -moz-box-shadow: none; box-shadow: none; } .well .form-actions { padding-bottom: 0; margin-bottom: 0; } .well form { margin-bottom: 0; } .nav-tabs { border: 0; } .nav-tabs > li { float: right; } .nav-tabs li a { margin-right: 0; } .nav-tabs > .active > a { background: #F5F5F5; } .nav-tabs > .active > a:hover { background: #F5F5F5; } .tabbable.first-tab-active .tab-content { border-top-right-radius: 0; } footer { position: absolute; bottom: 0; left: 0; clear: both; z-index: 10; height: 60px; width: 95%; margin: 0 2.5%; } footer p { text-align: center; color: gray; border-top: 1px solid #DDDDDD; padding-top: 10px; } footer a { color: gray !important; font-weight: bold; } footer a:hover { color: gray; } .page-header { border-bottom: none; padding-bottom: 0px; margin: 0; } /* custom general page styles */ .hero-unit h1, .hero-unit h2 { color: #A30000; } body a { color: #A30000; } body a:hover { color: #c20000; } .request-info { clear:both; } .horizontal-checkbox label { padding-top: 0; } .horizontal-checkbox label { padding-top: 0 !important; } .horizontal-checkbox input { float: left; width: 20px; margin-top: 3px; } .modal-footer form { margin-left: 5px; margin-right: 5px; } .pagination { margin: 5px 0 10px 0; } ================================================ FILE: rest_framework/static/rest_framework/css/default.css ================================================ /* The navbar is fixed at >= 980px wide, so add padding to the body to prevent content running up underneath it. */ h1 { font-weight: 300; } h2, h3 { font-weight: 300; } .resource-description, .response-info { margin-bottom: 2em; } .version:before { content: "v"; opacity: 0.6; padding-right: 0.25em; } .version { font-size: 70%; } .format-option { font-family: Menlo, Consolas, "Andale Mono", "Lucida Console", monospace; } .button-form { float: right; margin-right: 1em; } td.nested { padding: 0 !important; } td.nested > table { margin: 0; } form select, form input:not([type=checkbox]), form textarea { width: 90%; } form select[multiple] { height: 150px; } /* To allow tooltips to work on disabled elements */ .disabled-tooltip-shield { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } .errorlist { margin-top: 0.5em; } pre { overflow: auto; word-wrap: normal; white-space: pre; font-size: 12px; } .page-header { border-bottom: none; padding-bottom: 0px; } #filtersModal form input[type=submit] { width: auto; } #filtersModal .modal-body h2 { margin-top: 0 } ================================================ FILE: rest_framework/static/rest_framework/css/font-awesome-4.0.3.css ================================================ /*! * Font Awesome 4.0.3 by @davegandy - http://fontawesome.io - @fontawesome * License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License) */ /* FONT PATH * -------------------------- */ @font-face { font-family: 'FontAwesome'; src: url('../fonts/fontawesome-webfont.eot?v=4.0.3'); src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.0.3') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.0.3') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.0.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.0.3#fontawesomeregular') format('svg'); font-weight: normal; font-style: normal; } .fa { display: inline-block; font-family: FontAwesome; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } /* makes the font 33% larger relative to the icon container */ .fa-lg { font-size: 1.3333333333333333em; line-height: 0.75em; vertical-align: -15%; } .fa-2x { font-size: 2em; } .fa-3x { font-size: 3em; } .fa-4x { font-size: 4em; } .fa-5x { font-size: 5em; } .fa-fw { width: 1.2857142857142858em; text-align: center; } .fa-ul { padding-left: 0; margin-left: 2.142857142857143em; list-style-type: none; } .fa-ul > li { position: relative; } .fa-li { position: absolute; left: -2.142857142857143em; width: 2.142857142857143em; top: 0.14285714285714285em; text-align: center; } .fa-li.fa-lg { left: -1.8571428571428572em; } .fa-border { padding: .2em .25em .15em; border: solid 0.08em #eeeeee; border-radius: .1em; } .pull-right { float: right; } .pull-left { float: left; } .fa.pull-left { margin-right: .3em; } .fa.pull-right { margin-left: .3em; } .fa-spin { -webkit-animation: spin 2s infinite linear; -moz-animation: spin 2s infinite linear; -o-animation: spin 2s infinite linear; animation: spin 2s infinite linear; } @-moz-keyframes spin { 0% { -moz-transform: rotate(0deg); } 100% { -moz-transform: rotate(359deg); } } @-webkit-keyframes spin { 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(359deg); } } @-o-keyframes spin { 0% { -o-transform: rotate(0deg); } 100% { -o-transform: rotate(359deg); } } @-ms-keyframes spin { 0% { -ms-transform: rotate(0deg); } 100% { -ms-transform: rotate(359deg); } } @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(359deg); } } .fa-rotate-90 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=1); -webkit-transform: rotate(90deg); -moz-transform: rotate(90deg); -ms-transform: rotate(90deg); -o-transform: rotate(90deg); transform: rotate(90deg); } .fa-rotate-180 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2); -webkit-transform: rotate(180deg); -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -o-transform: rotate(180deg); transform: rotate(180deg); } .fa-rotate-270 { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); -webkit-transform: rotate(270deg); -moz-transform: rotate(270deg); -ms-transform: rotate(270deg); -o-transform: rotate(270deg); transform: rotate(270deg); } .fa-flip-horizontal { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1); -webkit-transform: scale(-1, 1); -moz-transform: scale(-1, 1); -ms-transform: scale(-1, 1); -o-transform: scale(-1, 1); transform: scale(-1, 1); } .fa-flip-vertical { filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1); -webkit-transform: scale(1, -1); -moz-transform: scale(1, -1); -ms-transform: scale(1, -1); -o-transform: scale(1, -1); transform: scale(1, -1); } .fa-stack { position: relative; display: inline-block; width: 2em; height: 2em; line-height: 2em; vertical-align: middle; } .fa-stack-1x, .fa-stack-2x { position: absolute; left: 0; width: 100%; text-align: center; } .fa-stack-1x { line-height: inherit; } .fa-stack-2x { font-size: 2em; } .fa-inverse { color: #ffffff; } /* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen readers do not read off random characters that represent icons */ .fa-glass:before { content: "\f000"; } .fa-music:before { content: "\f001"; } .fa-search:before { content: "\f002"; } .fa-envelope-o:before { content: "\f003"; } .fa-heart:before { content: "\f004"; } .fa-star:before { content: "\f005"; } .fa-star-o:before { content: "\f006"; } .fa-user:before { content: "\f007"; } .fa-film:before { content: "\f008"; } .fa-th-large:before { content: "\f009"; } .fa-th:before { content: "\f00a"; } .fa-th-list:before { content: "\f00b"; } .fa-check:before { content: "\f00c"; } .fa-times:before { content: "\f00d"; } .fa-search-plus:before { content: "\f00e"; } .fa-search-minus:before { content: "\f010"; } .fa-power-off:before { content: "\f011"; } .fa-signal:before { content: "\f012"; } .fa-gear:before, .fa-cog:before { content: "\f013"; } .fa-trash-o:before { content: "\f014"; } .fa-home:before { content: "\f015"; } .fa-file-o:before { content: "\f016"; } .fa-clock-o:before { content: "\f017"; } .fa-road:before { content: "\f018"; } .fa-download:before { content: "\f019"; } .fa-arrow-circle-o-down:before { content: "\f01a"; } .fa-arrow-circle-o-up:before { content: "\f01b"; } .fa-inbox:before { content: "\f01c"; } .fa-play-circle-o:before { content: "\f01d"; } .fa-rotate-right:before, .fa-repeat:before { content: "\f01e"; } .fa-refresh:before { content: "\f021"; } .fa-list-alt:before { content: "\f022"; } .fa-lock:before { content: "\f023"; } .fa-flag:before { content: "\f024"; } .fa-headphones:before { content: "\f025"; } .fa-volume-off:before { content: "\f026"; } .fa-volume-down:before { content: "\f027"; } .fa-volume-up:before { content: "\f028"; } .fa-qrcode:before { content: "\f029"; } .fa-barcode:before { content: "\f02a"; } .fa-tag:before { content: "\f02b"; } .fa-tags:before { content: "\f02c"; } .fa-book:before { content: "\f02d"; } .fa-bookmark:before { content: "\f02e"; } .fa-print:before { content: "\f02f"; } .fa-camera:before { content: "\f030"; } .fa-font:before { content: "\f031"; } .fa-bold:before { content: "\f032"; } .fa-italic:before { content: "\f033"; } .fa-text-height:before { content: "\f034"; } .fa-text-width:before { content: "\f035"; } .fa-align-left:before { content: "\f036"; } .fa-align-center:before { content: "\f037"; } .fa-align-right:before { content: "\f038"; } .fa-align-justify:before { content: "\f039"; } .fa-list:before { content: "\f03a"; } .fa-dedent:before, .fa-outdent:before { content: "\f03b"; } .fa-indent:before { content: "\f03c"; } .fa-video-camera:before { content: "\f03d"; } .fa-picture-o:before { content: "\f03e"; } .fa-pencil:before { content: "\f040"; } .fa-map-marker:before { content: "\f041"; } .fa-adjust:before { content: "\f042"; } .fa-tint:before { content: "\f043"; } .fa-edit:before, .fa-pencil-square-o:before { content: "\f044"; } .fa-share-square-o:before { content: "\f045"; } .fa-check-square-o:before { content: "\f046"; } .fa-arrows:before { content: "\f047"; } .fa-step-backward:before { content: "\f048"; } .fa-fast-backward:before { content: "\f049"; } .fa-backward:before { content: "\f04a"; } .fa-play:before { content: "\f04b"; } .fa-pause:before { content: "\f04c"; } .fa-stop:before { content: "\f04d"; } .fa-forward:before { content: "\f04e"; } .fa-fast-forward:before { content: "\f050"; } .fa-step-forward:before { content: "\f051"; } .fa-eject:before { content: "\f052"; } .fa-chevron-left:before { content: "\f053"; } .fa-chevron-right:before { content: "\f054"; } .fa-plus-circle:before { content: "\f055"; } .fa-minus-circle:before { content: "\f056"; } .fa-times-circle:before { content: "\f057"; } .fa-check-circle:before { content: "\f058"; } .fa-question-circle:before { content: "\f059"; } .fa-info-circle:before { content: "\f05a"; } .fa-crosshairs:before { content: "\f05b"; } .fa-times-circle-o:before { content: "\f05c"; } .fa-check-circle-o:before { content: "\f05d"; } .fa-ban:before { content: "\f05e"; } .fa-arrow-left:before { content: "\f060"; } .fa-arrow-right:before { content: "\f061"; } .fa-arrow-up:before { content: "\f062"; } .fa-arrow-down:before { content: "\f063"; } .fa-mail-forward:before, .fa-share:before { content: "\f064"; } .fa-expand:before { content: "\f065"; } .fa-compress:before { content: "\f066"; } .fa-plus:before { content: "\f067"; } .fa-minus:before { content: "\f068"; } .fa-asterisk:before { content: "\f069"; } .fa-exclamation-circle:before { content: "\f06a"; } .fa-gift:before { content: "\f06b"; } .fa-leaf:before { content: "\f06c"; } .fa-fire:before { content: "\f06d"; } .fa-eye:before { content: "\f06e"; } .fa-eye-slash:before { content: "\f070"; } .fa-warning:before, .fa-exclamation-triangle:before { content: "\f071"; } .fa-plane:before { content: "\f072"; } .fa-calendar:before { content: "\f073"; } .fa-random:before { content: "\f074"; } .fa-comment:before { content: "\f075"; } .fa-magnet:before { content: "\f076"; } .fa-chevron-up:before { content: "\f077"; } .fa-chevron-down:before { content: "\f078"; } .fa-retweet:before { content: "\f079"; } .fa-shopping-cart:before { content: "\f07a"; } .fa-folder:before { content: "\f07b"; } .fa-folder-open:before { content: "\f07c"; } .fa-arrows-v:before { content: "\f07d"; } .fa-arrows-h:before { content: "\f07e"; } .fa-bar-chart-o:before { content: "\f080"; } .fa-twitter-square:before { content: "\f081"; } .fa-facebook-square:before { content: "\f082"; } .fa-camera-retro:before { content: "\f083"; } .fa-key:before { content: "\f084"; } .fa-gears:before, .fa-cogs:before { content: "\f085"; } .fa-comments:before { content: "\f086"; } .fa-thumbs-o-up:before { content: "\f087"; } .fa-thumbs-o-down:before { content: "\f088"; } .fa-star-half:before { content: "\f089"; } .fa-heart-o:before { content: "\f08a"; } .fa-sign-out:before { content: "\f08b"; } .fa-linkedin-square:before { content: "\f08c"; } .fa-thumb-tack:before { content: "\f08d"; } .fa-external-link:before { content: "\f08e"; } .fa-sign-in:before { content: "\f090"; } .fa-trophy:before { content: "\f091"; } .fa-github-square:before { content: "\f092"; } .fa-upload:before { content: "\f093"; } .fa-lemon-o:before { content: "\f094"; } .fa-phone:before { content: "\f095"; } .fa-square-o:before { content: "\f096"; } .fa-bookmark-o:before { content: "\f097"; } .fa-phone-square:before { content: "\f098"; } .fa-twitter:before { content: "\f099"; } .fa-facebook:before { content: "\f09a"; } .fa-github:before { content: "\f09b"; } .fa-unlock:before { content: "\f09c"; } .fa-credit-card:before { content: "\f09d"; } .fa-rss:before { content: "\f09e"; } .fa-hdd-o:before { content: "\f0a0"; } .fa-bullhorn:before { content: "\f0a1"; } .fa-bell:before { content: "\f0f3"; } .fa-certificate:before { content: "\f0a3"; } .fa-hand-o-right:before { content: "\f0a4"; } .fa-hand-o-left:before { content: "\f0a5"; } .fa-hand-o-up:before { content: "\f0a6"; } .fa-hand-o-down:before { content: "\f0a7"; } .fa-arrow-circle-left:before { content: "\f0a8"; } .fa-arrow-circle-right:before { content: "\f0a9"; } .fa-arrow-circle-up:before { content: "\f0aa"; } .fa-arrow-circle-down:before { content: "\f0ab"; } .fa-globe:before { content: "\f0ac"; } .fa-wrench:before { content: "\f0ad"; } .fa-tasks:before { content: "\f0ae"; } .fa-filter:before { content: "\f0b0"; } .fa-briefcase:before { content: "\f0b1"; } .fa-arrows-alt:before { content: "\f0b2"; } .fa-group:before, .fa-users:before { content: "\f0c0"; } .fa-chain:before, .fa-link:before { content: "\f0c1"; } .fa-cloud:before { content: "\f0c2"; } .fa-flask:before { content: "\f0c3"; } .fa-cut:before, .fa-scissors:before { content: "\f0c4"; } .fa-copy:before, .fa-files-o:before { content: "\f0c5"; } .fa-paperclip:before { content: "\f0c6"; } .fa-save:before, .fa-floppy-o:before { content: "\f0c7"; } .fa-square:before { content: "\f0c8"; } .fa-bars:before { content: "\f0c9"; } .fa-list-ul:before { content: "\f0ca"; } .fa-list-ol:before { content: "\f0cb"; } .fa-strikethrough:before { content: "\f0cc"; } .fa-underline:before { content: "\f0cd"; } .fa-table:before { content: "\f0ce"; } .fa-magic:before { content: "\f0d0"; } .fa-truck:before { content: "\f0d1"; } .fa-pinterest:before { content: "\f0d2"; } .fa-pinterest-square:before { content: "\f0d3"; } .fa-google-plus-square:before { content: "\f0d4"; } .fa-google-plus:before { content: "\f0d5"; } .fa-money:before { content: "\f0d6"; } .fa-caret-down:before { content: "\f0d7"; } .fa-caret-up:before { content: "\f0d8"; } .fa-caret-left:before { content: "\f0d9"; } .fa-caret-right:before { content: "\f0da"; } .fa-columns:before { content: "\f0db"; } .fa-unsorted:before, .fa-sort:before { content: "\f0dc"; } .fa-sort-down:before, .fa-sort-asc:before { content: "\f0dd"; } .fa-sort-up:before, .fa-sort-desc:before { content: "\f0de"; } .fa-envelope:before { content: "\f0e0"; } .fa-linkedin:before { content: "\f0e1"; } .fa-rotate-left:before, .fa-undo:before { content: "\f0e2"; } .fa-legal:before, .fa-gavel:before { content: "\f0e3"; } .fa-dashboard:before, .fa-tachometer:before { content: "\f0e4"; } .fa-comment-o:before { content: "\f0e5"; } .fa-comments-o:before { content: "\f0e6"; } .fa-flash:before, .fa-bolt:before { content: "\f0e7"; } .fa-sitemap:before { content: "\f0e8"; } .fa-umbrella:before { content: "\f0e9"; } .fa-paste:before, .fa-clipboard:before { content: "\f0ea"; } .fa-lightbulb-o:before { content: "\f0eb"; } .fa-exchange:before { content: "\f0ec"; } .fa-cloud-download:before { content: "\f0ed"; } .fa-cloud-upload:before { content: "\f0ee"; } .fa-user-md:before { content: "\f0f0"; } .fa-stethoscope:before { content: "\f0f1"; } .fa-suitcase:before { content: "\f0f2"; } .fa-bell-o:before { content: "\f0a2"; } .fa-coffee:before { content: "\f0f4"; } .fa-cutlery:before { content: "\f0f5"; } .fa-file-text-o:before { content: "\f0f6"; } .fa-building-o:before { content: "\f0f7"; } .fa-hospital-o:before { content: "\f0f8"; } .fa-ambulance:before { content: "\f0f9"; } .fa-medkit:before { content: "\f0fa"; } .fa-fighter-jet:before { content: "\f0fb"; } .fa-beer:before { content: "\f0fc"; } .fa-h-square:before { content: "\f0fd"; } .fa-plus-square:before { content: "\f0fe"; } .fa-angle-double-left:before { content: "\f100"; } .fa-angle-double-right:before { content: "\f101"; } .fa-angle-double-up:before { content: "\f102"; } .fa-angle-double-down:before { content: "\f103"; } .fa-angle-left:before { content: "\f104"; } .fa-angle-right:before { content: "\f105"; } .fa-angle-up:before { content: "\f106"; } .fa-angle-down:before { content: "\f107"; } .fa-desktop:before { content: "\f108"; } .fa-laptop:before { content: "\f109"; } .fa-tablet:before { content: "\f10a"; } .fa-mobile-phone:before, .fa-mobile:before { content: "\f10b"; } .fa-circle-o:before { content: "\f10c"; } .fa-quote-left:before { content: "\f10d"; } .fa-quote-right:before { content: "\f10e"; } .fa-spinner:before { content: "\f110"; } .fa-circle:before { content: "\f111"; } .fa-mail-reply:before, .fa-reply:before { content: "\f112"; } .fa-github-alt:before { content: "\f113"; } .fa-folder-o:before { content: "\f114"; } .fa-folder-open-o:before { content: "\f115"; } .fa-smile-o:before { content: "\f118"; } .fa-frown-o:before { content: "\f119"; } .fa-meh-o:before { content: "\f11a"; } .fa-gamepad:before { content: "\f11b"; } .fa-keyboard-o:before { content: "\f11c"; } .fa-flag-o:before { content: "\f11d"; } .fa-flag-checkered:before { content: "\f11e"; } .fa-terminal:before { content: "\f120"; } .fa-code:before { content: "\f121"; } .fa-reply-all:before { content: "\f122"; } .fa-mail-reply-all:before { content: "\f122"; } .fa-star-half-empty:before, .fa-star-half-full:before, .fa-star-half-o:before { content: "\f123"; } .fa-location-arrow:before { content: "\f124"; } .fa-crop:before { content: "\f125"; } .fa-code-fork:before { content: "\f126"; } .fa-unlink:before, .fa-chain-broken:before { content: "\f127"; } .fa-question:before { content: "\f128"; } .fa-info:before { content: "\f129"; } .fa-exclamation:before { content: "\f12a"; } .fa-superscript:before { content: "\f12b"; } .fa-subscript:before { content: "\f12c"; } .fa-eraser:before { content: "\f12d"; } .fa-puzzle-piece:before { content: "\f12e"; } .fa-microphone:before { content: "\f130"; } .fa-microphone-slash:before { content: "\f131"; } .fa-shield:before { content: "\f132"; } .fa-calendar-o:before { content: "\f133"; } .fa-fire-extinguisher:before { content: "\f134"; } .fa-rocket:before { content: "\f135"; } .fa-maxcdn:before { content: "\f136"; } .fa-chevron-circle-left:before { content: "\f137"; } .fa-chevron-circle-right:before { content: "\f138"; } .fa-chevron-circle-up:before { content: "\f139"; } .fa-chevron-circle-down:before { content: "\f13a"; } .fa-html5:before { content: "\f13b"; } .fa-css3:before { content: "\f13c"; } .fa-anchor:before { content: "\f13d"; } .fa-unlock-alt:before { content: "\f13e"; } .fa-bullseye:before { content: "\f140"; } .fa-ellipsis-h:before { content: "\f141"; } .fa-ellipsis-v:before { content: "\f142"; } .fa-rss-square:before { content: "\f143"; } .fa-play-circle:before { content: "\f144"; } .fa-ticket:before { content: "\f145"; } .fa-minus-square:before { content: "\f146"; } .fa-minus-square-o:before { content: "\f147"; } .fa-level-up:before { content: "\f148"; } .fa-level-down:before { content: "\f149"; } .fa-check-square:before { content: "\f14a"; } .fa-pencil-square:before { content: "\f14b"; } .fa-external-link-square:before { content: "\f14c"; } .fa-share-square:before { content: "\f14d"; } .fa-compass:before { content: "\f14e"; } .fa-toggle-down:before, .fa-caret-square-o-down:before { content: "\f150"; } .fa-toggle-up:before, .fa-caret-square-o-up:before { content: "\f151"; } .fa-toggle-right:before, .fa-caret-square-o-right:before { content: "\f152"; } .fa-euro:before, .fa-eur:before { content: "\f153"; } .fa-gbp:before { content: "\f154"; } .fa-dollar:before, .fa-usd:before { content: "\f155"; } .fa-rupee:before, .fa-inr:before { content: "\f156"; } .fa-cny:before, .fa-rmb:before, .fa-yen:before, .fa-jpy:before { content: "\f157"; } .fa-ruble:before, .fa-rouble:before, .fa-rub:before { content: "\f158"; } .fa-won:before, .fa-krw:before { content: "\f159"; } .fa-bitcoin:before, .fa-btc:before { content: "\f15a"; } .fa-file:before { content: "\f15b"; } .fa-file-text:before { content: "\f15c"; } .fa-sort-alpha-asc:before { content: "\f15d"; } .fa-sort-alpha-desc:before { content: "\f15e"; } .fa-sort-amount-asc:before { content: "\f160"; } .fa-sort-amount-desc:before { content: "\f161"; } .fa-sort-numeric-asc:before { content: "\f162"; } .fa-sort-numeric-desc:before { content: "\f163"; } .fa-thumbs-up:before { content: "\f164"; } .fa-thumbs-down:before { content: "\f165"; } .fa-youtube-square:before { content: "\f166"; } .fa-youtube:before { content: "\f167"; } .fa-xing:before { content: "\f168"; } .fa-xing-square:before { content: "\f169"; } .fa-youtube-play:before { content: "\f16a"; } .fa-dropbox:before { content: "\f16b"; } .fa-stack-overflow:before { content: "\f16c"; } .fa-instagram:before { content: "\f16d"; } .fa-flickr:before { content: "\f16e"; } .fa-adn:before { content: "\f170"; } .fa-bitbucket:before { content: "\f171"; } .fa-bitbucket-square:before { content: "\f172"; } .fa-tumblr:before { content: "\f173"; } .fa-tumblr-square:before { content: "\f174"; } .fa-long-arrow-down:before { content: "\f175"; } .fa-long-arrow-up:before { content: "\f176"; } .fa-long-arrow-left:before { content: "\f177"; } .fa-long-arrow-right:before { content: "\f178"; } .fa-apple:before { content: "\f179"; } .fa-windows:before { content: "\f17a"; } .fa-android:before { content: "\f17b"; } .fa-linux:before { content: "\f17c"; } .fa-dribbble:before { content: "\f17d"; } .fa-skype:before { content: "\f17e"; } .fa-foursquare:before { content: "\f180"; } .fa-trello:before { content: "\f181"; } .fa-female:before { content: "\f182"; } .fa-male:before { content: "\f183"; } .fa-gittip:before { content: "\f184"; } .fa-sun-o:before { content: "\f185"; } .fa-moon-o:before { content: "\f186"; } .fa-archive:before { content: "\f187"; } .fa-bug:before { content: "\f188"; } .fa-vk:before { content: "\f189"; } .fa-weibo:before { content: "\f18a"; } .fa-renren:before { content: "\f18b"; } .fa-pagelines:before { content: "\f18c"; } .fa-stack-exchange:before { content: "\f18d"; } .fa-arrow-circle-o-right:before { content: "\f18e"; } .fa-arrow-circle-o-left:before { content: "\f190"; } .fa-toggle-left:before, .fa-caret-square-o-left:before { content: "\f191"; } .fa-dot-circle-o:before { content: "\f192"; } .fa-wheelchair:before { content: "\f193"; } .fa-vimeo-square:before { content: "\f194"; } .fa-turkish-lira:before, .fa-try:before { content: "\f195"; } .fa-plus-square-o:before { content: "\f196"; } ================================================ FILE: rest_framework/static/rest_framework/css/prettify.css ================================================ .com { color: #93a1a1; } .lit { color: #195f91; } .pun, .opn, .clo { color: #93a1a1; } .fun { color: #dc322f; } .str, .atv { color: #D14; } .kwd, .prettyprint .tag { color: #1e347b; } .typ, .atn, .dec, .var { color: teal; } .pln { color: #48484c; } .prettyprint { padding: 8px; background-color: #f7f7f9; border: 1px solid #e1e1e8; } .prettyprint.linenums { -webkit-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; -moz-box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; box-shadow: inset 40px 0 0 #fbfbfc, inset 41px 0 0 #ececf0; } /* Specify class=linenums on a pre to get line numbering */ ol.linenums { margin: 0 0 0 33px; /* IE indents via margin-left */ } ol.linenums li { padding-left: 12px; color: #bebec5; line-height: 20px; text-shadow: 0 1px 0 #fff; } ================================================ FILE: rest_framework/static/rest_framework/js/ajax-form.js ================================================ function replaceDocument(docString) { var doc = document.open("text/html"); 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) { var form = $(this); var btn = $(this.clk); var method = ( btn.data('method') || form.data('method') || form.attr('method') || 'GET' ).toUpperCase(); if (method === 'GET') { // GET requests can always use standard form submits. return; } var contentType = form.find('input[data-override="content-type"]').val() || form.find('select[data-override="content-type"] option:selected').text(); if (method === 'POST' && !contentType) { // POST requests can use standard form submits, unless we have // overridden the content type. return; } // At this point we need to make an AJAX form submission. e.preventDefault(); var url = form.attr('action'); var data; if (contentType) { data = form.find('[data-override="content"]').val() || '' if (contentType === 'multipart/form-data') { // We need to add a boundary parameter to the header // We assume the first valid-looking boundary line in the body is correct // regex is from RFC 2046 appendix A var boundaryCharNoSpace = "0-9A-Z'()+_,-./:=?"; var boundaryChar = boundaryCharNoSpace + ' '; var re = new RegExp('^--([' + boundaryChar + ']{0,69}[' + boundaryCharNoSpace + '])[\\s]*?$', 'im'); var boundary = data.match(re); if (boundary !== null) { contentType += '; boundary="' + boundary[1] + '"'; } // Fix textarea.value EOL normalisation (multipart/form-data should use CR+NL, not NL) data = data.replace(/\n/g, '\r\n'); } } else { contentType = form.attr('enctype') || form.attr('encoding') if (contentType === 'multipart/form-data') { if (!window.FormData) { alert('Your browser does not support AJAX multipart form submissions'); return; } // Use the FormData API and allow the content type to be set automatically, // so it includes the boundary string. // See https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects contentType = false; data = new FormData(form[0]); } else { contentType = 'application/x-www-form-urlencoded; charset=UTF-8' data = form.serialize(); } } var ret = $.ajax({ url: url, method: method, data: data, contentType: contentType, processData: false, headers: { 'Accept': 'text/html; q=1.0, */*' }, }); ret.always(function(data, textStatus, jqXHR) { if (textStatus != 'success') { jqXHR = data; } var responseContentType = jqXHR.getResponseHeader("content-type") || ""; if (responseContentType.toLowerCase().indexOf('text/html') === 0) { replaceDocument(jqXHR.responseText); try { // Modify the location and scroll to top, as if after page load. history.replaceState({}, '', url); scroll(0, 0); } catch (err) { // History API not supported, so redirect. window.location = url; } } else { // Not HTML content. We can't open this directly, so redirect. window.location = url; } }); return ret; } function captureSubmittingElement(e) { var target = e.target; var form = this; form.clk = target; } $.fn.ajaxForm = function() { var options = {} return this .unbind('submit.form-plugin click.form-plugin') .bind('submit.form-plugin', options, doAjaxSubmit) .bind('click.form-plugin', options, captureSubmittingElement); }; ================================================ FILE: rest_framework/static/rest_framework/js/csrf.js ================================================ function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } function sameOrigin(url) { // test that a given url is a same-origin URL // url could be relative or scheme relative or absolute var host = document.location.host; // host + port var protocol = document.location.protocol; var sr_origin = '//' + host; var origin = protocol + sr_origin; // Allow absolute or scheme relative URLs to same origin return (url == origin || url.slice(0, origin.length + 1) == origin + '/') || (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') || // or any other URL that isn't scheme relative or absolute i.e relative. !(/^(\/\/|http:|https:).*/.test(url)); } window.drf = JSON.parse(document.getElementById('drf_csrf').textContent); var csrftoken = window.drf.csrfToken; $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) { // Send the token to same-origin, relative URLs only. // Send the token only if the method warrants CSRF protection // Using the CSRFToken value acquired earlier xhr.setRequestHeader(window.drf.csrfHeaderName, csrftoken); } } }); ================================================ FILE: rest_framework/static/rest_framework/js/default.js ================================================ $(document).ready(function() { // JSON highlighting. prettyPrint(); // Bootstrap tooltips. $('.js-tooltip').tooltip({ delay: 1000, container: 'body' }); // Deal with rounded tab styling after tab clicks. $('a[data-toggle="tab"]:first').on('shown', function(e) { $(e.target).parents('.tabbable').addClass('first-tab-active'); }); $('a[data-toggle="tab"]:not(:first)').on('shown', function(e) { $(e.target).parents('.tabbable').removeClass('first-tab-active'); }); $('a[data-toggle="tab"]').click(function() { document.cookie = "tabstyle=" + this.name + "; path=/"; }); // Store tab preference in cookies & display appropriate tab on load. var selectedTab = null; var selectedTabName = getCookie('tabstyle'); if (selectedTabName) { selectedTabName = selectedTabName.replace(/[^a-z-]/g, ''); } if (selectedTabName) { selectedTab = $('.form-switcher a[name=' + selectedTabName + ']'); } if (selectedTab && selectedTab.length > 0) { // Display whichever tab is selected. selectedTab.tab('show'); } else { // If no tab selected, display rightmost tab. $('.form-switcher a:first').tab('show'); } $(window).on('load', function() { $('#errorModal').modal('show'); }); }); ================================================ FILE: rest_framework/static/rest_framework/js/load-ajax-form.js ================================================ $(document).ready(function() { $('form').ajaxForm(); }); ================================================ FILE: rest_framework/static/rest_framework/js/prettify-min.js ================================================ var q=null;window.PR_SHOULD_USE_CONTINUATION=!0; (function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var b=a.charAt(1);return(f=r[b])?f:"0"<=b&&b<="7"?parseInt(a.substring(1),8):b==="u"||b==="x"?parseInt(a.substring(2),16):a.charCodeAt(1)}function e(a){if(a<32)return(a<16?"\\x0":"\\x")+a.toString(16);a=String.fromCharCode(a);if(a==="\\"||a==="-"||a==="["||a==="]")a="\\"+a;return a}function h(a){for(var f=a.substring(1,a.length-1).match(/\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\[0-3][0-7]{0,2}|\\[0-7]{1,2}|\\[\S\s]|[^\\]/g),a= [],b=[],o=f[0]==="^",c=o?1:0,i=f.length;c122||(d<65||j>90||b.push([Math.max(65,j)|32,Math.min(d,90)|32]),d<97||j>122||b.push([Math.max(97,j)&-33,Math.min(d,122)&-33]))}}b.sort(function(a,f){return a[0]-f[0]||f[1]-a[1]});f=[];j=[NaN,NaN];for(c=0;ci[0]&&(i[1]+1>i[0]&&b.push("-"),b.push(e(i[1])));b.push("]");return b.join("")}function y(a){for(var f=a.source.match(/\[(?:[^\\\]]|\\[\S\s])*]|\\u[\dA-Fa-f]{4}|\\x[\dA-Fa-f]{2}|\\\d+|\\[^\dux]|\(\?[!:=]|[()^]|[^()[\\^]+/g),b=f.length,d=[],c=0,i=0;c=2&&a==="["?f[c]=h(j):a!=="\\"&&(f[c]=j.replace(/[A-Za-z]/g,function(a){a=a.charCodeAt(0);return"["+String.fromCharCode(a&-33,a|32)+"]"}));return f.join("")}for(var t=0,s=!1,l=!1,p=0,d=a.length;p=5&&"lang-"===b.substring(0,5))&&!(o&&typeof o[1]==="string"))c=!1,b="src";c||(r[f]=b)}i=d;d+=f.length;if(c){c=o[1];var j=f.indexOf(c),k=j+c.length;o[2]&&(k=f.length-o[2].length,j=k-c.length);b=b.substring(5);B(l+i,f.substring(0,j),e,p);B(l+i+j,c,C(b,c),p);B(l+i+k,f.substring(k),e,p)}else p.push(l+i,b)}a.e=p}var h={},y;(function(){for(var e=a.concat(m), l=[],p={},d=0,g=e.length;d=0;)h[n.charAt(k)]=r;r=r[1];n=""+r;p.hasOwnProperty(n)||(l.push(r),p[n]=q)}l.push(/[\S\s]/);y=L(l)})();var t=m.length;return e}function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''(?:[^'\\]|\\[\S\s]|''?(?=[^']))*(?:'''|$)|"""(?:[^"\\]|\\[\S\s]|""?(?=[^"]))*(?:"""|$)|'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$))/,q,"'\""]):a.multiLineStrings?m.push(["str",/^(?:'(?:[^'\\]|\\[\S\s])*(?:'|$)|"(?:[^"\\]|\\[\S\s])*(?:"|$)|`(?:[^\\`]|\\[\S\s])*(?:`|$))/, q,"'\"`"]):m.push(["str",/^(?:'(?:[^\n\r'\\]|\\.)*(?:'|$)|"(?:[^\n\r"\\]|\\.)*(?:"|$))/,q,"\"'"]);a.verbatimStrings&&e.push(["str",/^@"(?:[^"]|"")*(?:"|$)/,q]);var h=a.hashComments;h&&(a.cStyleComments?(h>1?m.push(["com",/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,q,"#"]):m.push(["com",/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\n\r]*)/,q,"#"]),e.push(["str",/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,q])):m.push(["com",/^#[^\n\r]*/, q,"#"]));a.cStyleComments&&(e.push(["com",/^\/\/[^\n\r]*/,q]),e.push(["com",/^\/\*[\S\s]*?(?:\*\/|$)/,q]));a.regexLiterals&&e.push(["lang-regex",/^(?:^^\.?|[!+-]|!=|!==|#|%|%=|&|&&|&&=|&=|\(|\*|\*=|\+=|,|-=|->|\/|\/=|:|::|;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|[?@[^]|\^=|\^\^|\^\^=|{|\||\|=|\|\||\|\|=|~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\s*(\/(?=[^*/])(?:[^/[\\]|\\[\S\s]|\[(?:[^\\\]]|\\[\S\s])*(?:]|$))+\/)/]);(h=a.types)&&e.push(["typ",h]);a=(""+a.keywords).replace(/^ | $/g, "");a.length&&e.push(["kwd",RegExp("^(?:"+a.replace(/[\s,]+/g,"|")+")\\b"),q]);m.push(["pln",/^\s+/,q," \r\n\t\xa0"]);e.push(["lit",/^@[$_a-z][\w$@]*/i,q],["typ",/^(?:[@_]?[A-Z]+[a-z][\w$@]*|\w+_t\b)/,q],["pln",/^[$_a-z][\w$@]*/i,q],["lit",/^(?:0x[\da-f]+|(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d\+)(?:e[+-]?\d+)?)[a-z]*/i,q,"0123456789"],["pln",/^\\[\S\s]?/,q],["pun",/^.[^\s\w"-$'./@\\`]*/,q]);return x(m,e)}function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.className))break;if("BR"===a.nodeName)h(a), a.parentNode&&a.parentNode.removeChild(a);else for(a=a.firstChild;a;a=a.nextSibling)e(a);break;case 3:case 4:if(p){var b=a.nodeValue,d=b.match(t);if(d){var c=b.substring(0,d.index);a.nodeValue=c;(b=b.substring(d.index+d[0].length))&&a.parentNode.insertBefore(s.createTextNode(b),a.nextSibling);h(a);c||a.parentNode.removeChild(a)}}}}function h(a){function b(a,d){var e=d?a.cloneNode(!1):a,f=a.parentNode;if(f){var f=b(f,1),g=a.nextSibling;f.appendChild(e);for(var h=g;h;h=g)g=h.nextSibling,f.appendChild(h)}return e} for(;!a.nextSibling;)if(a=a.parentNode,!a)return;for(var a=b(a.nextSibling,0),e;(e=a.parentNode)&&e.nodeType===1;)a=e;d.push(a)}var k=/(?:^|\s)nocode(?:\s|$)/,t=/\r\n?|\n/,s=a.ownerDocument,l;a.currentStyle?l=a.currentStyle.whiteSpace:window.getComputedStyle&&(l=s.defaultView.getComputedStyle(a,q).getPropertyValue("white-space"));var p=l&&"pre"===l.substring(0,3);for(l=s.createElement("LI");a.firstChild;)l.appendChild(a.firstChild);for(var d=[l],g=0;g=0;){var h=m[e];A.hasOwnProperty(h)?window.console&&console.warn("cannot override language handler %s",h):A[h]=a}}function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*=o&&(h+=2);e>=c&&(a+=2)}}catch(w){"console"in window&&console.log(w&&w.stack?w.stack:w)}}var v=["break,continue,do,else,for,if,return,while"],w=[[v,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"], "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"],F=[w,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"],G=[w,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"], H=[G,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"],w=[w,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"],I=[v,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"], J=[v,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"],v=[v,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"],K=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/,N=/\S/,O=u({keywords:[F,H,w,"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"+ I,J,v],hashComments:!0,cStyleComments:!0,multiLineStrings:!0,regexLiterals:!0}),A={};k(O,["default-code"]);k(x([],[["pln",/^[^]*(?:>|$)/],["com",/^<\!--[\S\s]*?(?:--\>|$)/],["lang-",/^<\?([\S\s]+?)(?:\?>|$)/],["lang-",/^<%([\S\s]+?)(?:%>|$)/],["pun",/^(?:<[%?]|[%?]>)/],["lang-",/^]*>([\S\s]+?)<\/xmp\b[^>]*>/i],["lang-js",/^]*>([\S\s]*?)(<\/script\b[^>]*>)/i],["lang-css",/^]*>([\S\s]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]), ["default-markup","htm","html","mxml","xhtml","xml","xsl"]);k(x([["pln",/^\s+/,q," \t\r\n"],["atv",/^(?:"[^"]*"?|'[^']*'?)/,q,"\"'"]],[["tag",/^^<\/?[a-z](?:[\w-.:]*\w)?|\/?>$/i],["atn",/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^\s"'>]*(?:[^\s"'/>]|\/(?=\s)))/],["pun",/^[/<->]+/],["lang-js",/^on\w+\s*=\s*"([^"]+)"/i],["lang-js",/^on\w+\s*=\s*'([^']+)'/i],["lang-js",/^on\w+\s*=\s*([^\s"'>]+)/i],["lang-css",/^style\s*=\s*"([^"]+)"/i],["lang-css",/^style\s*=\s*'([^']+)'/i],["lang-css", /^style\s*=\s*([^\s"'>]+)/i]]),["in.tag"]);k(x([],[["atv",/^[\S\s]+/]]),["uq.val"]);k(u({keywords:F,hashComments:!0,cStyleComments:!0,types:K}),["c","cc","cpp","cxx","cyc","m"]);k(u({keywords:"null,true,false"}),["json"]);k(u({keywords:H,hashComments:!0,cStyleComments:!0,verbatimStrings:!0,types:K}),["cs"]);k(u({keywords:G,cStyleComments:!0}),["java"]);k(u({keywords:v,hashComments:!0,multiLineStrings:!0}),["bsh","csh","sh"]);k(u({keywords:I,hashComments:!0,multiLineStrings:!0,tripleQuotedStrings:!0}), ["cv","py"]);k(u({keywords:"caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END",hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["perl","pl","pm"]);k(u({keywords:J,hashComments:!0,multiLineStrings:!0,regexLiterals:!0}),["rb"]);k(u({keywords:w,cStyleComments:!0,regexLiterals:!0}),["js"]);k(u({keywords:"all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes", hashComments:3,cStyleComments:!0,multilineStrings:!0,tripleQuotedStrings:!0,regexLiterals:!0}),["coffee"]);k(x([],[["str",/^[\S\s]+/]]),["regex"]);window.prettyPrintOne=function(a,m,e){var h=document.createElement("PRE");h.innerHTML=a;e&&D(h,e);E({g:m,i:e,h:h});return h.innerHTML};window.prettyPrint=function(a){function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Infinity;p=0){var k=k.match(g),f,b;if(b= !k){b=n;for(var o=void 0,c=b.firstChild;c;c=c.nextSibling)var i=c.nodeType,o=i===1?o?b:c:i===3?N.test(c.nodeValue)?b:o:o;b=(f=o===b?void 0:o)&&"CODE"===f.tagName}b&&(k=f.className.match(g));k&&(k=k[1]);b=!1;for(o=n.parentNode;o;o=o.parentNode)if((o.tagName==="pre"||o.tagName==="code"||o.tagName==="xmp")&&o.className&&o.className.indexOf("prettyprint")>=0){b=!0;break}b||((b=(b=n.className.match(/\blinenums\b(?::(\d+))?/))?b[1]&&b[1].length?+b[1]:!0:!1)&&D(n,b),d={g:k,h:n,i:b},E(d))}}p {% for key, value in results|items %} {% if key in details %} {{ key|capfirst }}{{ value|format_value }} {% endif %} {% endfor %} ================================================ FILE: rest_framework/templates/rest_framework/admin/dict_value.html ================================================ {% load rest_framework %} {% for k, v in value|items %} {% endfor %}
{{ k|format_value }} {{ v|format_value }}
================================================ FILE: rest_framework/templates/rest_framework/admin/list.html ================================================ {% load rest_framework %} {% for column in columns%}{% endfor %} {% for row in results %} {% for key, value in row|items %} {% if key in columns %} {% endif %} {% endfor %} {% endfor %}
{{ column|capfirst }}
{{ value|format_value }} {% if row.url %} {% else %} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/admin/list_value.html ================================================ {% load rest_framework %} {% for item in value %} {% endfor %}
{{ forloop.counter0 }} {{ item|format_value }}
================================================ FILE: rest_framework/templates/rest_framework/admin/simple_list_value.html ================================================ {% load rest_framework %} {% for item in value %}{% if not forloop.first%},{% endif %} {{item|format_value}}{% endfor %} ================================================ FILE: rest_framework/templates/rest_framework/admin.html ================================================ {% load static %} {% load i18n %} {% load rest_framework %} {% block head %} {% block meta %} {% endblock %} {% block title %}Django REST framework{% endblock %} {% block style %} {% block bootstrap_theme %} {% endblock %} {% endblock %} {% endblock %} {% block body %}
{% block navbar %} {% endblock %}
{% block breadcrumbs %} {% endblock %}
{% if 'GET' in allowed_methods %}
{% endif %} {% if post_form %} {% endif %} {% if put_form %} {% endif %} {% if delete_form %}
{% endif %} {% if extra_actions %} {% endif %} {% if filter_form %} {% endif %}
{% block description %} {{ description }} {% endblock %}
{% if paginator %} {% endif %}
{% if style == 'list' %} {% include "rest_framework/admin/list.html" %} {% else %} {% include "rest_framework/admin/detail.html" %} {% endif %}
{% if paginator %} {% endif %}
{% if error_form %} {% endif %} {% if filter_form %} {{ filter_form }} {% endif %} {% block script %} {% endblock %} {% endblock %} ================================================ FILE: rest_framework/templates/rest_framework/api.html ================================================ {% extends "rest_framework/base.html" %} {# Override this template in your own templates directory to customize #} ================================================ FILE: rest_framework/templates/rest_framework/base.html ================================================ {% load static %} {% load i18n %} {% load rest_framework %} {% block head %} {% block meta %} {% endblock %} {% block title %}{% if name %}{{ name }} – {% endif %}Django REST framework{% endblock %} {% block style %} {% block bootstrap_theme %} {% endblock %} {% if code_style %}{% endif %} {% endblock %} {% endblock %} {% block body %}
{% block navbar %} {% endblock %}
{% block breadcrumbs %} {% endblock %}
{% block content %}
{% block request_forms %} {% if 'GET' in allowed_methods %}
{% if api_settings.URL_FORMAT_OVERRIDE %}
GET
{% else %} GET {% endif %}
{% endif %} {% if options_form %}
{% endif %} {% if delete_form %} {% endif %} {% if extra_actions %} {% endif %} {% if filter_form %} {% endif %} {% endblock request_forms %}
{% block description %} {{ description }} {% endblock %}
{% if paginator %} {% endif %}
{{ request.method }} {{ request.get_full_path }}
HTTP {{ response.status_code }} {{ response.status_text }}{% for key, val in response_headers|items %}
{{ key }}: {{ val|urlize }}{% endfor %}

{{ content|urlize }}
{% if display_edit_forms %} {% if post_form or raw_data_post_form %}
{% if post_form %} {% endif %}
{% if post_form %}
{% with form=post_form %}
{% csrf_token %} {{ post_form }}
{% endwith %}
{% endif %}
{% with form=raw_data_post_form %}
{% include "rest_framework/raw_data_form.html" %}
{% endwith %}
{% endif %} {% if put_form or raw_data_put_form or raw_data_patch_form %}
{% if put_form %} {% endif %}
{% if put_form %}
{{ put_form }}
{% endif %}
{% with form=raw_data_put_or_patch_form %}
{% include "rest_framework/raw_data_form.html" %}
{% if raw_data_put_form %} {% endif %} {% if raw_data_patch_form %} {% endif %}
{% endwith %}
{% endif %} {% endif %} {% endblock content %}
{% if filter_form %} {{ filter_form }} {% endif %} {% block script %} {% endblock %} {% endblock %} ================================================ FILE: rest_framework/templates/rest_framework/filters/base.html ================================================ ================================================ FILE: rest_framework/templates/rest_framework/filters/ordering.html ================================================ {% load rest_framework %} {% load i18n %}

{% trans "Ordering" %}

{% for key, label in options %} {% if key == current %} {{ label }} {% else %} {{ label }} {% endif %} {% endfor %}
================================================ FILE: rest_framework/templates/rest_framework/filters/search.html ================================================ {% load i18n %}

{% trans "Search" %}

================================================ FILE: rest_framework/templates/rest_framework/horizontal/checkbox.html ================================================
{% if field.label %} {% endif %}
{% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/horizontal/checkbox_multiple.html ================================================ {% load rest_framework %}
{% if field.label %} {% endif %}
{% if style.inline %} {% for key, text in field.choices|items %} {% endfor %} {% else %} {% for key, text in field.choices|items %}
{% endfor %} {% endif %} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/horizontal/dict_field.html ================================================
{% if field.label %} {% endif %}

Dictionaries are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/horizontal/fieldset.html ================================================ {% load rest_framework %}
{% if field.label %}
{{ field.label }}
{% endif %} {% for nested_field in field %} {% if not nested_field.read_only %} {% render_field nested_field style=style %} {% endif %} {% endfor %}
================================================ FILE: rest_framework/templates/rest_framework/horizontal/form.html ================================================ {% load rest_framework %} {% for field in form %} {% if not field.read_only %} {% render_field field style=style %} {% endif %} {% endfor %} ================================================ FILE: rest_framework/templates/rest_framework/horizontal/input.html ================================================
{% if field.label %} {% endif %}
{% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/horizontal/list_field.html ================================================
{% if field.label %} {% endif %}

Lists are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/horizontal/list_fieldset.html ================================================ {% load rest_framework %}
{% if field.label %}
{{ field.label }}
{% endif %}

Lists are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/horizontal/radio.html ================================================ {% load i18n %} {% load rest_framework %} {% trans "None" as none_choice %}
{% if field.label %} {% endif %}
{% if style.inline %} {% if field.allow_null or field.allow_blank %} {% endif %} {% for key, text in field.choices|items %} {% endfor %} {% else %} {% if field.allow_null or field.allow_blank %}
{% endif %} {% for key, text in field.choices|items %}
{% endfor %} {% endif %} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/horizontal/select.html ================================================ {% load rest_framework %}
{% if field.label %} {% endif %}
{% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/horizontal/select_multiple.html ================================================ {% load i18n %} {% load rest_framework %} {% trans "No items to select." as no_items %}
{% if field.label %} {% endif %}
{% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/horizontal/textarea.html ================================================
{% if field.label %} {% endif %}
{% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/inline/checkbox.html ================================================
================================================ FILE: rest_framework/templates/rest_framework/inline/checkbox_multiple.html ================================================ {% load rest_framework %}
{% if field.label %} {% endif %} {% for key, text in field.choices|items %}
{% endfor %}
================================================ FILE: rest_framework/templates/rest_framework/inline/dict_field.html ================================================
{% if field.label %} {% endif %}

Dictionaries are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/inline/fieldset.html ================================================ {% load rest_framework %} {% for nested_field in field %} {% if not nested_field.read_only %} {% render_field nested_field style=style %} {% endif %} {% endfor %} ================================================ FILE: rest_framework/templates/rest_framework/inline/form.html ================================================ {% load rest_framework %} {% for field in form %} {% if not field.read_only %} {% render_field field style=style %} {% endif %} {% endfor %} ================================================ FILE: rest_framework/templates/rest_framework/inline/input.html ================================================
{% if field.label %} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/inline/list_field.html ================================================
{% if field.label %} {% endif %}

Lists are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/inline/list_fieldset.html ================================================ Lists are not currently supported in HTML input. ================================================ FILE: rest_framework/templates/rest_framework/inline/radio.html ================================================ {% load i18n %} {% load rest_framework %} {% trans "None" as none_choice %}
{% if field.label %} {% endif %} {% if field.allow_null or field.allow_blank %}
{% endif %} {% for key, text in field.choices|items %}
{% endfor %}
================================================ FILE: rest_framework/templates/rest_framework/inline/select.html ================================================ {% load rest_framework %}
{% if field.label %} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/inline/select_multiple.html ================================================ {% load i18n %} {% load rest_framework %} {% trans "No items to select." as no_items %}
{% if field.label %} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/inline/textarea.html ================================================
{% if field.label %} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/login.html ================================================ {% extends "rest_framework/login_base.html" %} {# Override this template in your own templates directory to customize #} ================================================ FILE: rest_framework/templates/rest_framework/login_base.html ================================================ {% extends "rest_framework/base.html" %} {% load rest_framework %} {% block body %}
{% block branding %}

Django REST framework

{% endblock %}
{% csrf_token %}
{% if form.username.errors %}

{{ form.username.errors|striptags }}

{% endif %}
{% if form.password.errors %}

{{ form.password.errors|striptags }}

{% endif %}
{% if form.non_field_errors %} {% for error in form.non_field_errors %}
{{ error }}
{% endfor %} {% endif %}
{% endblock %} ================================================ FILE: rest_framework/templates/rest_framework/pagination/numbers.html ================================================ ================================================ FILE: rest_framework/templates/rest_framework/pagination/previous_and_next.html ================================================ ================================================ FILE: rest_framework/templates/rest_framework/raw_data_form.html ================================================ {% load rest_framework %} {{ form.non_field_errors }} {% for field in form %}
{{ field.label_tag|add_class:"col-sm-2 control-label" }}
{{ field|add_class:"form-control" }} {{ field.help_text|safe }}
{% endfor %} ================================================ FILE: rest_framework/templates/rest_framework/vertical/checkbox.html ================================================
{% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/vertical/checkbox_multiple.html ================================================ {% load rest_framework %}
{% if field.label %} {% endif %} {% if style.inline %}
{% for key, text in field.choices|items %} {% endfor %}
{% else %} {% for key, text in field.choices|items %}
{% endfor %} {% endif %} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/vertical/dict_field.html ================================================
{% if field.label %} {% endif %}

Dictionaries are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/vertical/fieldset.html ================================================ {% load rest_framework %}
{% if field.label %} {{ field.label }} {% endif %} {% for nested_field in field %} {% if not nested_field.read_only %} {% render_field nested_field style=style %} {% endif %} {% endfor %}
================================================ FILE: rest_framework/templates/rest_framework/vertical/form.html ================================================ {% load rest_framework %} {% for field in form %} {% if not field.read_only %} {% render_field field style=style %} {% endif %} {% endfor %} ================================================ FILE: rest_framework/templates/rest_framework/vertical/input.html ================================================
{% if field.label %} {% endif %} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/vertical/list_field.html ================================================
{% if field.label %} {% endif %}

Lists are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/vertical/list_fieldset.html ================================================
{% if field.label %} {{ field.label }} {% endif %}

Lists are not currently supported in HTML input.

================================================ FILE: rest_framework/templates/rest_framework/vertical/radio.html ================================================ {% load i18n %} {% load rest_framework %} {% trans "None" as none_choice %}
{% if field.label %} {% endif %} {% if style.inline %}
{% if field.allow_null or field.allow_blank %} {% endif %} {% for key, text in field.choices|items %} {% endfor %}
{% else %} {% if field.allow_null or field.allow_blank %}
{% endif %} {% for key, text in field.choices|items %}
{% endfor %} {% endif %} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/vertical/select.html ================================================ {% load rest_framework %}
{% if field.label %} {% endif %} {% if field.errors %} {% for error in field.errors %} {{ error }} {% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/vertical/select_multiple.html ================================================ {% load i18n %} {% load rest_framework %} {% trans "No items to select." as no_items %}
{% if field.label %} {% endif %} {% if field.errors %} {% for error in field.errors %}{{ error }}{% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templates/rest_framework/vertical/textarea.html ================================================
{% if field.label %} {% endif %} {% if field.errors %} {% for error in field.errors %}{{ error }}{% endfor %} {% endif %} {% if field.help_text %} {{ field.help_text|safe }} {% endif %}
================================================ FILE: rest_framework/templatetags/__init__.py ================================================ ================================================ FILE: rest_framework/templatetags/rest_framework.py ================================================ import re from django import template from django.template import loader from django.urls import NoReverseMatch, reverse from django.utils.encoding import iri_to_uri from django.utils.html import escape, format_html, smart_urlquote from django.utils.safestring import mark_safe from rest_framework.compat import apply_markdown, pygments_highlight from rest_framework.renderers import HTMLFormRenderer from rest_framework.utils.urls import replace_query_param register = template.Library() # Regex for adding classes to html snippets class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])') @register.tag(name='code') def highlight_code(parser, token): code = token.split_contents()[-1] nodelist = parser.parse(('endcode',)) parser.delete_first_token() return CodeNode(code, nodelist) class CodeNode(template.Node): style = 'emacs' def __init__(self, lang, code): self.lang = lang self.nodelist = code def render(self, context): text = self.nodelist.render(context) return pygments_highlight(text, self.lang, self.style) @register.simple_tag def render_markdown(markdown_text): if apply_markdown is None: return markdown_text return mark_safe(apply_markdown(markdown_text)) @register.simple_tag def get_pagination_html(pager): return pager.to_html() @register.simple_tag def render_form(serializer, template_pack=None): style = {'template_pack': template_pack} if template_pack else {} renderer = HTMLFormRenderer() return renderer.render(serializer.data, None, {'style': style}) @register.simple_tag def render_field(field, style): renderer = style.get('renderer', HTMLFormRenderer()) return renderer.render_field(field, style) @register.simple_tag def optional_login(request): """ Include a login snippet if REST framework's login view is in the URLconf. """ try: login_url = reverse('rest_framework:login') except NoReverseMatch: return '' snippet = "
  • Log in
  • " snippet = format_html(snippet, href=login_url, next=escape(request.path)) return mark_safe(snippet) @register.simple_tag def optional_docs_login(request): """ Include a login snippet if REST framework's login view is in the URLconf. """ try: login_url = reverse('rest_framework:login') except NoReverseMatch: return 'log in' snippet = "log in" snippet = format_html(snippet, href=login_url, next=escape(request.path)) return mark_safe(snippet) @register.simple_tag def optional_logout(request, user, csrf_token): """ Include a logout snippet if REST framework's logout view is in the URLconf. """ try: logout_url = reverse('rest_framework:logout') except NoReverseMatch: snippet = format_html('', user=escape(user)) return mark_safe(snippet) snippet = """""" snippet = format_html(snippet, user=escape(user), href=logout_url, next=escape(request.path), csrf_token=csrf_token) return mark_safe(snippet) @register.simple_tag def add_query_param(request, key, val): """ Add a query parameter to the current request url, and return the new url. """ iri = request.get_full_path() uri = iri_to_uri(iri) return escape(replace_query_param(uri, key, val)) @register.filter def as_string(value): if value is None: return '' return '%s' % value @register.filter def as_list_of_strings(value): return [ '' if (item is None) else ('%s' % item) for item in value ] @register.filter def add_class(value, css_class): """ https://stackoverflow.com/questions/4124220/django-adding-css-classes-when-rendering-form-fields-in-a-template Inserts classes into template variables that contain HTML tags, useful for modifying forms without needing to change the Form objects. Usage: {{ field.label_tag|add_class:"control-label" }} In the case of REST Framework, the filter is used to add Bootstrap-specific classes to the forms. """ html = str(value) match = class_re.search(html) if match: m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class, css_class, css_class), match.group(1)) if not m: return mark_safe(class_re.sub(match.group(1) + " " + css_class, html)) else: return mark_safe(html.replace('>', ' class="%s">' % css_class, 1)) return value @register.filter def format_value(value): if getattr(value, 'is_hyperlink', False): name = str(value.obj) return mark_safe('%s' % (value, escape(name))) if value is None or isinstance(value, bool): return mark_safe('%s' % {True: 'true', False: 'false', None: 'null'}[value]) elif isinstance(value, list): if any(isinstance(item, (list, dict)) for item in value): template = loader.get_template('rest_framework/admin/list_value.html') else: template = loader.get_template('rest_framework/admin/simple_list_value.html') context = {'value': value} return template.render(context) elif isinstance(value, dict): template = loader.get_template('rest_framework/admin/dict_value.html') context = {'value': value} return template.render(context) elif isinstance(value, str): if ( (value.startswith('http:') or value.startswith('https:') or value.startswith('/')) and not re.search(r'\s', value) ): return mark_safe('{value}'.format(value=escape(value))) elif '@' in value and not re.search(r'\s', value): return mark_safe('{value}'.format(value=escape(value))) elif '\n' in value: return mark_safe('
    %s
    ' % escape(value)) return str(value) @register.filter def items(value): """ Simple filter to return the items of the dict. Useful when the dict may have a key 'items' which is resolved first in Django template dot-notation lookup. See issue #4931 Also see: https://stackoverflow.com/questions/15416662/django-template-loop-over-dictionary-items-with-items-as-key """ if value is None: # `{% for k, v in value.items %}` doesn't raise when value is None or # not in the context, so neither should `{% for k, v in value|items %}` return [] return value.items() @register.filter def add_nested_class(value): if isinstance(value, dict): return 'class=nested' if isinstance(value, list) and any(isinstance(item, (list, dict)) for item in value): return 'class=nested' return '' # Bunch of stuff cloned from urlize TRAILING_PUNCTUATION = ['.', ',', ':', ';', '.)', '"', "']", "'}", "'"] WRAPPING_PUNCTUATION = [('(', ')'), ('<', '>'), ('[', ']'), ('<', '>'), ('"', '"'), ("'", "'")] word_split_re = re.compile(r'(\s+)') simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile(r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)$', re.IGNORECASE) simple_email_re = re.compile(r'^\S+@\S+\.\S+$') def smart_urlquote_wrapper(matched_url): """ Simple wrapper for smart_urlquote. ValueError("Invalid IPv6 URL") can be raised here, see issue #1386 """ try: return smart_urlquote(matched_url) except ValueError: return None ================================================ FILE: rest_framework/test.py ================================================ # Note that we import as `DjangoRequestFactory` and `DjangoClient` in order # to make it harder for the user to import the wrong thing without realizing. import io from importlib import import_module from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.handlers.wsgi import WSGIHandler from django.test import override_settings, testcases from django.test.client import Client as DjangoClient from django.test.client import ClientHandler from django.test.client import RequestFactory as DjangoRequestFactory from django.utils.encoding import force_bytes from django.utils.http import urlencode from rest_framework.compat import requests from rest_framework.settings import api_settings def force_authenticate(request, user=None, token=None): request._force_auth_user = user request._force_auth_token = token if requests is not None: class HeaderDict(requests.packages.urllib3._collections.HTTPHeaderDict): def get_all(self, key, default): return self.getheaders(key) class MockOriginalResponse: def __init__(self, headers): self.msg = HeaderDict(headers) self.closed = False def isclosed(self): return self.closed def close(self): self.closed = True class DjangoTestAdapter(requests.adapters.HTTPAdapter): """ A transport adapter for `requests`, that makes requests via the Django WSGI app, rather than making actual HTTP requests over the network. """ def __init__(self): self.app = WSGIHandler() self.factory = DjangoRequestFactory() def get_environ(self, request): """ Given a `requests.PreparedRequest` instance, return a WSGI environ dict. """ method = request.method url = request.url kwargs = {} # Set request content, if any exists. if request.body is not None: if hasattr(request.body, 'read'): kwargs['data'] = request.body.read() else: kwargs['data'] = request.body if 'content-type' in request.headers: kwargs['content_type'] = request.headers['content-type'] # Set request headers. for key, value in request.headers.items(): key = key.upper() if key in ('CONNECTION', 'CONTENT-LENGTH', 'CONTENT-TYPE'): continue kwargs['HTTP_%s' % key.replace('-', '_')] = value return self.factory.generic(method, url, **kwargs).environ def send(self, request, *args, **kwargs): """ Make an outgoing request to the Django WSGI application. """ raw_kwargs = {} def start_response(wsgi_status, wsgi_headers, exc_info=None): status, _, reason = wsgi_status.partition(' ') raw_kwargs['status'] = int(status) raw_kwargs['reason'] = reason raw_kwargs['headers'] = wsgi_headers raw_kwargs['version'] = 11 raw_kwargs['preload_content'] = False raw_kwargs['original_response'] = MockOriginalResponse(wsgi_headers) # Make the outgoing request via WSGI. environ = self.get_environ(request) wsgi_response = self.app(environ, start_response) # Build the underlying urllib3.HTTPResponse raw_kwargs['body'] = io.BytesIO(b''.join(wsgi_response)) raw = requests.packages.urllib3.HTTPResponse(**raw_kwargs) # Build the requests.Response return self.build_response(request, raw) def close(self): pass class RequestsClient(requests.Session): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) adapter = DjangoTestAdapter() self.mount('http://', adapter) self.mount('https://', adapter) def request(self, method, url, *args, **kwargs): if not url.startswith('http'): raise ValueError('Missing "http:" or "https:". Use a fully qualified URL, eg "http://testserver%s"' % url) return super().request(method, url, *args, **kwargs) else: def RequestsClient(*args, **kwargs): raise ImproperlyConfigured('requests must be installed in order to use RequestsClient.') class APIRequestFactory(DjangoRequestFactory): renderer_classes_list = api_settings.TEST_REQUEST_RENDERER_CLASSES default_format = api_settings.TEST_REQUEST_DEFAULT_FORMAT def __init__(self, enforce_csrf_checks=False, **defaults): self.enforce_csrf_checks = enforce_csrf_checks self.renderer_classes = {} for cls in self.renderer_classes_list: self.renderer_classes[cls.format] = cls super().__init__(**defaults) def _encode_data(self, data, format=None, content_type=None): """ Encode the data returning a two tuple of (bytes, content_type) """ if data is None: return (b'', content_type) assert format is None or content_type is None, ( 'You may not set both `format` and `content_type`.' ) if content_type: try: data = self._encode_json(data, content_type) except AttributeError: pass # Content type specified explicitly, treat data as a raw bytestring ret = force_bytes(data, settings.DEFAULT_CHARSET) else: format = format or self.default_format assert format in self.renderer_classes, ( "Invalid format '{}'. Available formats are {}. " "Set TEST_REQUEST_RENDERER_CLASSES to enable " "extra request formats.".format( format, ', '.join(["'" + fmt + "'" for fmt in self.renderer_classes]) ) ) # Use format and render the data into a bytestring renderer = self.renderer_classes[format]() ret = renderer.render(data) # Determine the content-type header from the renderer content_type = renderer.media_type if renderer.charset: content_type = "{}; charset={}".format( content_type, renderer.charset ) # Coerce text to bytes if required. if isinstance(ret, str): ret = ret.encode(renderer.charset) return ret, content_type def get(self, path, data=None, **extra): r = { 'QUERY_STRING': urlencode(data or {}, doseq=True), } if not data and '?' in path: # Fix to support old behavior where you have the arguments in the # url. See #1461. query_string = force_bytes(path.split('?')[1]) query_string = query_string.decode('iso-8859-1') r['QUERY_STRING'] = query_string r.update(extra) return self.generic('GET', path, **r) def post(self, path, data=None, format=None, content_type=None, **extra): data, content_type = self._encode_data(data, format, content_type) return self.generic('POST', path, data, content_type, **extra) def put(self, path, data=None, format=None, content_type=None, **extra): data, content_type = self._encode_data(data, format, content_type) return self.generic('PUT', path, data, content_type, **extra) def patch(self, path, data=None, format=None, content_type=None, **extra): data, content_type = self._encode_data(data, format, content_type) return self.generic('PATCH', path, data, content_type, **extra) def delete(self, path, data=None, format=None, content_type=None, **extra): data, content_type = self._encode_data(data, format, content_type) return self.generic('DELETE', path, data, content_type, **extra) def options(self, path, data=None, format=None, content_type=None, **extra): data, content_type = self._encode_data(data, format, content_type) return self.generic('OPTIONS', path, data, content_type, **extra) def generic(self, method, path, data='', content_type='application/octet-stream', secure=False, **extra): # Include the CONTENT_TYPE, regardless of whether or not data is empty. if content_type is not None: extra['CONTENT_TYPE'] = str(content_type) return super().generic( method, path, data, content_type, secure, **extra) def request(self, **kwargs): request = super().request(**kwargs) request._dont_enforce_csrf_checks = not self.enforce_csrf_checks return request class ForceAuthClientHandler(ClientHandler): """ A patched version of ClientHandler that can enforce authentication on the outgoing requests. """ def __init__(self, *args, **kwargs): self._force_user = None self._force_token = None super().__init__(*args, **kwargs) def get_response(self, request): # This is the simplest place we can hook into to patch the # request object. force_authenticate(request, self._force_user, self._force_token) return super().get_response(request) class APIClient(APIRequestFactory, DjangoClient): def __init__(self, enforce_csrf_checks=False, **defaults): super().__init__(**defaults) self.handler = ForceAuthClientHandler(enforce_csrf_checks) self._credentials = {} def credentials(self, **kwargs): """ Sets headers that will be used on every outgoing request. """ self._credentials = kwargs def force_authenticate(self, user=None, token=None): """ Forcibly authenticates outgoing requests with the given user and/or token. """ self.handler._force_user = user self.handler._force_token = token if user is None and token is None: self.logout() # Also clear any possible session info if required def request(self, **kwargs): # Ensure that any credentials set get added to every request. kwargs.update(self._credentials) return super().request(**kwargs) def get(self, path, data=None, follow=False, **extra): response = super().get(path, data=data, **extra) if follow: response = self._handle_redirects(response, data=data, **extra) return response def post(self, path, data=None, format=None, content_type=None, follow=False, **extra): response = super().post( path, data=data, format=format, content_type=content_type, **extra) if follow: response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra) return response def put(self, path, data=None, format=None, content_type=None, follow=False, **extra): response = super().put( path, data=data, format=format, content_type=content_type, **extra) if follow: response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra) return response def patch(self, path, data=None, format=None, content_type=None, follow=False, **extra): response = super().patch( path, data=data, format=format, content_type=content_type, **extra) if follow: response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra) return response def delete(self, path, data=None, format=None, content_type=None, follow=False, **extra): response = super().delete( path, data=data, format=format, content_type=content_type, **extra) if follow: response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra) return response def options(self, path, data=None, format=None, content_type=None, follow=False, **extra): response = super().options( path, data=data, format=format, content_type=content_type, **extra) if follow: response = self._handle_redirects(response, data=data, format=format, content_type=content_type, **extra) return response def logout(self): self._credentials = {} # Also clear any `force_authenticate` self.handler._force_user = None self.handler._force_token = None if self.session: super().logout() class APITransactionTestCase(testcases.TransactionTestCase): client_class = APIClient class APITestCase(testcases.TestCase): client_class = APIClient class APISimpleTestCase(testcases.SimpleTestCase): client_class = APIClient class APILiveServerTestCase(testcases.LiveServerTestCase): client_class = APIClient def cleanup_url_patterns(cls): if hasattr(cls, '_module_urlpatterns'): cls._module.urlpatterns = cls._module_urlpatterns else: del cls._module.urlpatterns class URLPatternsTestCase(testcases.SimpleTestCase): """ Isolate URL patterns on a per-TestCase basis. For example, class ATestCase(URLPatternsTestCase): urlpatterns = [...] def test_something(self): ... class AnotherTestCase(URLPatternsTestCase): urlpatterns = [...] def test_something_else(self): ... """ @classmethod def setUpClass(cls): # Get the module of the TestCase subclass cls._module = import_module(cls.__module__) cls._override = override_settings(ROOT_URLCONF=cls.__module__) if hasattr(cls._module, 'urlpatterns'): cls._module_urlpatterns = cls._module.urlpatterns cls._module.urlpatterns = cls.urlpatterns cls._override.enable() cls.addClassCleanup(cls._override.disable) cls.addClassCleanup(cleanup_url_patterns, cls) super().setUpClass() ================================================ FILE: rest_framework/throttling.py ================================================ """ Provides various throttling policies. """ import time from django.core.cache import cache as default_cache from django.core.exceptions import ImproperlyConfigured from rest_framework.settings import api_settings class BaseThrottle: """ Rate throttling of requests. """ def allow_request(self, request, view): """ Return `True` if the request should be allowed, `False` otherwise. """ raise NotImplementedError('.allow_request() must be overridden') def get_ident(self, request): """ Identify the machine making the request by parsing HTTP_X_FORWARDED_FOR if present and number of proxies is > 0. If not use all of HTTP_X_FORWARDED_FOR if it is available, if not use REMOTE_ADDR. """ xff = request.META.get('HTTP_X_FORWARDED_FOR') remote_addr = request.META.get('REMOTE_ADDR') num_proxies = api_settings.NUM_PROXIES if num_proxies is not None: if num_proxies == 0 or xff is None: return remote_addr addrs = xff.split(',') client_addr = addrs[-min(num_proxies, len(addrs))] return client_addr.strip() return ''.join(xff.split()) if xff else remote_addr def wait(self): """ Optionally, return a recommended number of seconds to wait before the next request. """ return None class SimpleRateThrottle(BaseThrottle): """ A simple cache implementation, that only requires `.get_cache_key()` to be overridden. The rate (requests / seconds) is set by a `rate` attribute on the Throttle class. The attribute is a string of the form 'number_of_requests/period'. Period should be one of: ('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day') Previous request information used for throttling is stored in the cache. """ cache = default_cache timer = time.time cache_format = 'throttle_%(scope)s_%(ident)s' scope = None THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES def __init__(self): if not getattr(self, 'rate', None): self.rate = self.get_rate() self.num_requests, self.duration = self.parse_rate(self.rate) def get_cache_key(self, request, view): """ Should return a unique cache-key which can be used for throttling. Must be overridden. May return `None` if the request should not be throttled. """ raise NotImplementedError('.get_cache_key() must be overridden') def get_rate(self): """ Determine the string representation of the allowed request rate. """ if not getattr(self, 'scope', None): msg = ("You must set either `.scope` or `.rate` for '%s' throttle" % self.__class__.__name__) raise ImproperlyConfigured(msg) try: return self.THROTTLE_RATES[self.scope] except KeyError: msg = "No default throttle rate set for '%s' scope" % self.scope raise ImproperlyConfigured(msg) def parse_rate(self, rate): """ Given the request rate string, return a two tuple of: , """ if rate is None: return (None, None) num, period = rate.split('/') num_requests = int(num) duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[0]] return (num_requests, duration) def allow_request(self, request, view): """ Implement the check to see if the request should be throttled. On success calls `throttle_success`. On failure calls `throttle_failure`. """ if self.rate is None: return True self.key = self.get_cache_key(request, view) if self.key is None: return True self.history = self.cache.get(self.key, []) self.now = self.timer() # Drop any requests from the history which have now passed the # throttle duration while self.history and self.history[-1] <= self.now - self.duration: self.history.pop() if len(self.history) >= self.num_requests: return self.throttle_failure() return self.throttle_success() def throttle_success(self): """ Inserts the current request's timestamp along with the key into the cache. """ self.history.insert(0, self.now) self.cache.set(self.key, self.history, self.duration) return True def throttle_failure(self): """ Called when a request to the API has failed due to throttling. """ return False def wait(self): """ Returns the recommended next request time in seconds. """ if self.history: remaining_duration = self.duration - (self.now - self.history[-1]) else: remaining_duration = self.duration available_requests = self.num_requests - len(self.history) + 1 if available_requests <= 0: return None return remaining_duration / float(available_requests) class AnonRateThrottle(SimpleRateThrottle): """ Limits the rate of API calls that may be made by a anonymous users. The IP address of the request will be used as the unique cache key. """ scope = 'anon' def get_cache_key(self, request, view): if request.user and request.user.is_authenticated: return None # Only throttle unauthenticated requests. return self.cache_format % { 'scope': self.scope, 'ident': self.get_ident(request) } class UserRateThrottle(SimpleRateThrottle): """ Limits the rate of API calls that may be made by a given user. The user id will be used as a unique cache key if the user is authenticated. For anonymous requests, the IP address of the request will be used. """ scope = 'user' def get_cache_key(self, request, view): if request.user and request.user.is_authenticated: ident = request.user.pk else: ident = self.get_ident(request) return self.cache_format % { 'scope': self.scope, 'ident': ident } class ScopedRateThrottle(SimpleRateThrottle): """ Limits the rate of API calls by different amounts for various parts of the API. Any view that has the `throttle_scope` property set will be throttled. The unique cache key will be generated by concatenating the user id of the request, and the scope of the view being accessed. """ scope_attr = 'throttle_scope' def __init__(self): # Override the usual SimpleRateThrottle, because we can't determine # the rate until called by the view. pass def allow_request(self, request, view): # We can only determine the scope once we're called by the view. self.scope = getattr(view, self.scope_attr, None) # If a view does not have a `throttle_scope` always allow the request if not self.scope: return True # Determine the allowed request rate as we normally would during # the `__init__` call. self.rate = self.get_rate() self.num_requests, self.duration = self.parse_rate(self.rate) # We can now proceed as normal. return super().allow_request(request, view) def get_cache_key(self, request, view): """ If `view.throttle_scope` is not set, don't apply this throttle. Otherwise generate the unique cache key by concatenating the user id with the `.throttle_scope` property of the view. """ if request.user and request.user.is_authenticated: ident = request.user.pk else: ident = self.get_ident(request) return self.cache_format % { 'scope': self.scope, 'ident': ident } ================================================ FILE: rest_framework/urlpatterns.py ================================================ from django.urls import URLResolver, include, path, re_path, register_converter from django.urls.converters import get_converters from django.urls.resolvers import RoutePattern from rest_framework.settings import api_settings def _get_format_path_converter(allowed): if allowed: if len(allowed) == 1: allowed_pattern = allowed[0] else: allowed_pattern = '(?:%s)' % '|'.join(allowed) suffix_pattern = r"\.%s/?" % allowed_pattern else: suffix_pattern = r"\.[a-z0-9]+/?" class FormatSuffixConverter: regex = suffix_pattern def to_python(self, value): return value.strip('./') def to_url(self, value): return '.' + value + '/' return FormatSuffixConverter def _generate_converter_name(allowed): converter_name = 'drf_format_suffix' if allowed: converter_name += '_' + '_'.join(allowed) return converter_name def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route=None): ret = [] for urlpattern in urlpatterns: if isinstance(urlpattern, URLResolver): # Set of included URL patterns regex = urlpattern.pattern.regex.pattern namespace = urlpattern.namespace app_name = urlpattern.app_name kwargs = urlpattern.default_kwargs # Add in the included patterns, after applying the suffixes patterns = apply_suffix_patterns(urlpattern.url_patterns, suffix_pattern, suffix_required, suffix_route) # if the original pattern was a RoutePattern we need to preserve it if isinstance(urlpattern.pattern, RoutePattern): assert path is not None route = str(urlpattern.pattern) new_pattern = path(route, include((patterns, app_name), namespace), kwargs) else: new_pattern = re_path(regex, include((patterns, app_name), namespace), kwargs) ret.append(new_pattern) else: # Regular URL pattern regex = urlpattern.pattern.regex.pattern.rstrip('$').rstrip('/') + suffix_pattern view = urlpattern.callback kwargs = urlpattern.default_args name = urlpattern.name # Add in both the existing and the new urlpattern if not suffix_required: ret.append(urlpattern) # if the original pattern was a RoutePattern we need to preserve it if isinstance(urlpattern.pattern, RoutePattern): assert path is not None assert suffix_route is not None route = str(urlpattern.pattern).rstrip('$').rstrip('/') + suffix_route new_pattern = path(route, view, kwargs, name) else: new_pattern = re_path(regex, view, kwargs, name) ret.append(new_pattern) return ret def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None): """ Supplement existing urlpatterns with corresponding patterns that also include a '.format' suffix. Retains urlpattern ordering. urlpatterns: A list of URL patterns. suffix_required: If `True`, only suffixed URLs will be generated, and non-suffixed URLs will not be used. Defaults to `False`. allowed: An optional tuple/list of allowed suffixes. eg ['json', 'api'] Defaults to `None`, which allows any suffix. """ suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG if allowed: if len(allowed) == 1: allowed_pattern = allowed[0] else: allowed_pattern = '(%s)' % '|'.join(allowed) suffix_pattern = r'\.(?P<%s>%s)/?$' % (suffix_kwarg, allowed_pattern) else: suffix_pattern = r'\.(?P<%s>[a-z0-9]+)/?$' % suffix_kwarg converter_name = _generate_converter_name(allowed) if converter_name not in get_converters(): suffix_converter = _get_format_path_converter(allowed) register_converter(suffix_converter, converter_name) suffix_route = '<%s:%s>' % (converter_name, suffix_kwarg) return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, suffix_route) ================================================ FILE: rest_framework/urls.py ================================================ """ Login and logout views for the browsable API. Add these to your root URLconf if you're using the browsable API and your API requires authentication: urlpatterns = [ ... path('auth/', include('rest_framework.urls')) ] You should make sure your authentication settings include `SessionAuthentication`. """ from django.contrib.auth import views from django.urls import path app_name = 'rest_framework' urlpatterns = [ path('login/', views.LoginView.as_view(template_name='rest_framework/login.html'), name='login'), path('logout/', views.LogoutView.as_view(), name='logout'), ] ================================================ FILE: rest_framework/utils/__init__.py ================================================ ================================================ FILE: rest_framework/utils/breadcrumbs.py ================================================ from django.urls import get_script_prefix, resolve def get_breadcrumbs(url, request=None): """ Given a url returns a list of breadcrumbs, which are each a tuple of (name, url). """ from rest_framework.reverse import preserve_builtin_query_params from rest_framework.views import APIView def breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen): """ Add tuples of (name, url) to the breadcrumbs list, progressively chomping off parts of the url. """ try: (view, unused_args, unused_kwargs) = resolve(url) except Exception: pass else: # Check if this is a REST framework view, # and if so add it to the breadcrumbs cls = getattr(view, 'cls', None) initkwargs = getattr(view, 'initkwargs', {}) if cls is not None and issubclass(cls, APIView): # Don't list the same view twice in a row. # Probably an optional trailing slash. if not seen or seen[-1] != view: c = cls(**initkwargs) name = c.get_view_name() insert_url = preserve_builtin_query_params(prefix + url, request) breadcrumbs_list.insert(0, (name, insert_url)) seen.append(view) if url == '': # All done return breadcrumbs_list elif url.endswith('/'): # Drop trailing slash off the end and continue to try to # resolve more breadcrumbs url = url.rstrip('/') return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen) # Drop trailing non-slash off the end and continue to try to # resolve more breadcrumbs url = url[:url.rfind('/') + 1] return breadcrumbs_recursive(url, breadcrumbs_list, prefix, seen) prefix = get_script_prefix().rstrip('/') url = url[len(prefix):] return breadcrumbs_recursive(url, [], prefix, []) ================================================ FILE: rest_framework/utils/encoders.py ================================================ """ Helper classes for parsers. """ import contextlib import datetime import decimal import ipaddress import json # noqa import uuid from django.db.models.query import QuerySet from django.utils import timezone from django.utils.encoding import force_str from django.utils.functional import Promise class JSONEncoder(json.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time/timedelta, decimal types, generators and other basic python objects. """ def default(self, obj): # For Date Time string spec, see ECMA 262 # https://ecma-international.org/ecma-262/5.1/#sec-15.9.1.15 if isinstance(obj, Promise): return force_str(obj) elif isinstance(obj, datetime.datetime): representation = obj.isoformat() if representation.endswith('+00:00'): representation = representation[:-6] + 'Z' return representation elif isinstance(obj, datetime.date): return obj.isoformat() elif isinstance(obj, datetime.time): if timezone and timezone.is_aware(obj): raise ValueError("JSON can't represent timezone-aware times.") representation = obj.isoformat() return representation elif isinstance(obj, datetime.timedelta): return str(obj.total_seconds()) elif isinstance(obj, decimal.Decimal): # Serializers will coerce decimals to strings by default. return float(obj) elif isinstance(obj, uuid.UUID): return str(obj) elif isinstance(obj, ( ipaddress.IPv4Address, ipaddress.IPv6Address, ipaddress.IPv4Network, ipaddress.IPv6Network, ipaddress.IPv4Interface, ipaddress.IPv6Interface) ): return str(obj) elif isinstance(obj, QuerySet): return tuple(obj) elif isinstance(obj, bytes): # Best-effort for binary blobs. See #4187. return obj.decode() elif hasattr(obj, 'tolist'): # Numpy arrays and array scalars. return obj.tolist() elif hasattr(obj, '__getitem__'): cls = (list if isinstance(obj, (list, tuple)) else dict) with contextlib.suppress(Exception): return cls(obj) elif hasattr(obj, '__iter__'): return tuple(item for item in obj) return super().default(obj) class CustomScalar: """ CustomScalar that knows how to encode timedelta that renderer can understand. """ @classmethod def represent_timedelta(cls, dumper, data): value = str(data.total_seconds()) return dumper.represent_scalar('tag:yaml.org,2002:str', value) ================================================ FILE: rest_framework/utils/field_mapping.py ================================================ """ Helper functions for mapping model fields to a dictionary of default keyword arguments that should be used for their equivalent serializer fields. """ import inspect from django.core import validators from django.db import models from django.utils.text import capfirst from rest_framework.compat import postgres_fields from rest_framework.validators import UniqueValidator NUMERIC_FIELD_TYPES = ( models.IntegerField, models.FloatField, models.DecimalField, models.DurationField, ) class ClassLookupDict: """ Takes a dictionary with classes as keys. Lookups against this object will traverses the object's inheritance hierarchy in method resolution order, and returns the first matching value from the dictionary or raises a KeyError if nothing matches. """ def __init__(self, mapping): self.mapping = mapping def __getitem__(self, key): if hasattr(key, '_proxy_class'): # Deal with proxy classes. Ie. BoundField behaves as if it # is a Field instance when using ClassLookupDict. base_class = key._proxy_class else: base_class = key.__class__ for cls in inspect.getmro(base_class): if cls in self.mapping: return self.mapping[cls] raise KeyError('Class %s not found in lookup.' % base_class.__name__) def __setitem__(self, key, value): self.mapping[key] = value def needs_label(model_field, field_name): """ Returns `True` if the label based on the model's verbose name is not equal to the default label it would have based on it's field name. """ default_label = field_name.replace('_', ' ').capitalize() return capfirst(model_field.verbose_name) != default_label def get_detail_view_name(model): """ Given a model class, return the view name to use for URL relationships that refer to instances of the model. """ return '%(model_name)s-detail' % { 'model_name': model._meta.object_name.lower() } def get_unique_validators(field_name, model_field): """ Returns a list of UniqueValidators that should be applied to the field. """ field_set = {field_name} conditions = { c.condition for c in model_field.model._meta.constraints if isinstance(c, models.UniqueConstraint) and set(c.fields) == field_set } if getattr(model_field, 'unique', False): conditions.add(None) if not conditions: return unique_error_message = get_unique_error_message(model_field) queryset = model_field.model._default_manager for condition in conditions: yield UniqueValidator( queryset=queryset if condition is None else queryset.filter(condition), message=unique_error_message ) def get_field_kwargs(field_name, model_field): """ Creates a default instance of a basic non-relational field. """ kwargs = {} validator_kwarg = list(model_field.validators) # The following will only be used by ModelField classes. # Gets removed for everything else. kwargs['model_field'] = model_field if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) if model_field.help_text: kwargs['help_text'] = model_field.help_text max_digits = getattr(model_field, 'max_digits', None) if max_digits is not None: kwargs['max_digits'] = max_digits decimal_places = getattr(model_field, 'decimal_places', None) if decimal_places is not None: kwargs['decimal_places'] = decimal_places if isinstance(model_field, models.SlugField): kwargs['allow_unicode'] = model_field.allow_unicode if isinstance(model_field, models.TextField) and not model_field.choices or \ (postgres_fields and isinstance(model_field, postgres_fields.JSONField)) or \ (hasattr(models, 'JSONField') and isinstance(model_field, models.JSONField)): kwargs['style'] = {'base_template': 'textarea.html'} if model_field.null: kwargs['allow_null'] = True if isinstance(model_field, models.AutoField) or not model_field.editable: # If this field is read-only, then return early. # Further keyword arguments are not valid. kwargs['read_only'] = True return kwargs if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.blank and (isinstance(model_field, (models.CharField, models.TextField))): kwargs['allow_blank'] = True if not model_field.blank and (postgres_fields and isinstance(model_field, postgres_fields.ArrayField)): kwargs['allow_empty'] = False if isinstance(model_field, models.FilePathField): kwargs['path'] = model_field.path if model_field.match is not None: kwargs['match'] = model_field.match if model_field.recursive is not False: kwargs['recursive'] = model_field.recursive if model_field.allow_files is not True: kwargs['allow_files'] = model_field.allow_files if model_field.allow_folders is not False: kwargs['allow_folders'] = model_field.allow_folders if model_field.choices: kwargs['choices'] = model_field.choices else: # Ensure that max_value is passed explicitly as a keyword arg, # rather than as a validator. max_value = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MaxValueValidator) ), None) if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): kwargs['max_value'] = max_value validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MaxValueValidator) ] # Ensure that min_value is passed explicitly as a keyword arg, # rather than as a validator. min_value = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MinValueValidator) ), None) if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES): kwargs['min_value'] = min_value validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MinValueValidator) ] # URLField does not need to include the URLValidator argument, # as it is explicitly added in. if isinstance(model_field, models.URLField): validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.URLValidator) ] # EmailField does not need to include the validate_email argument, # as it is explicitly added in. if isinstance(model_field, models.EmailField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_email ] # SlugField do not need to include the 'validate_slug' argument, if isinstance(model_field, models.SlugField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_slug ] # IPAddressField do not need to include the 'validate_ipv46_address' argument, if isinstance(model_field, models.GenericIPAddressField): validator_kwarg = [ validator for validator in validator_kwarg if validator is not validators.validate_ipv46_address ] # Our decimal validation is handled in the field code, not validator code. if isinstance(model_field, models.DecimalField): validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.DecimalValidator) ] # Ensure that max_length is passed explicitly as a keyword arg, # rather than as a validator. max_length = getattr(model_field, 'max_length', None) if max_length is not None and (isinstance(model_field, (models.CharField, models.TextField, models.FileField))): kwargs['max_length'] = max_length validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MaxLengthValidator) ] # Ensure that min_length is passed explicitly as a keyword arg, # rather than as a validator. min_length = next(( validator.limit_value for validator in validator_kwarg if isinstance(validator, validators.MinLengthValidator) ), None) if min_length is not None and isinstance(model_field, models.CharField): kwargs['min_length'] = min_length validator_kwarg = [ validator for validator in validator_kwarg if not isinstance(validator, validators.MinLengthValidator) ] validator_kwarg += get_unique_validators(field_name, model_field) if validator_kwarg: kwargs['validators'] = validator_kwarg return kwargs def get_relation_kwargs(field_name, relation_info): """ Creates a default instance of a flat relational field. """ model_field, related_model, to_many, to_field, has_through_model, reverse = relation_info kwargs = { 'queryset': related_model._default_manager, 'view_name': get_detail_view_name(related_model) } if to_many: kwargs['many'] = True if to_field: kwargs['to_field'] = to_field limit_choices_to = model_field and model_field.get_limit_choices_to() if limit_choices_to: if not isinstance(limit_choices_to, models.Q): limit_choices_to = models.Q(**limit_choices_to) kwargs['queryset'] = kwargs['queryset'].filter(limit_choices_to) if has_through_model: kwargs['read_only'] = True kwargs.pop('queryset', None) if model_field: if model_field.verbose_name and needs_label(model_field, field_name): kwargs['label'] = capfirst(model_field.verbose_name) help_text = model_field.help_text if help_text: kwargs['help_text'] = help_text if not model_field.editable: kwargs['read_only'] = True kwargs.pop('queryset', None) if model_field.null: kwargs['allow_null'] = True if kwargs.get('read_only', False): # If this field is read-only, then return early. # No further keyword arguments are valid. return kwargs if model_field.has_default() or model_field.blank or model_field.null: kwargs['required'] = False if model_field.validators: kwargs['validators'] = model_field.validators if getattr(model_field, 'unique', False): validator = UniqueValidator( queryset=model_field.model._default_manager, message=get_unique_error_message(model_field)) kwargs['validators'] = kwargs.get('validators', []) + [validator] if to_many and not model_field.blank: kwargs['allow_empty'] = False return kwargs def get_nested_relation_kwargs(relation_info): kwargs = {'read_only': True} if relation_info.to_many: kwargs['many'] = True return kwargs def get_url_kwargs(model_field): return { 'view_name': get_detail_view_name(model_field) } def get_unique_error_message(model_field): unique_error_message = model_field.error_messages.get('unique', None) if unique_error_message: unique_error_message = unique_error_message % { 'model_name': model_field.model._meta.verbose_name, 'field_label': model_field.verbose_name } return unique_error_message ================================================ FILE: rest_framework/utils/formatting.py ================================================ """ Utility functions to return a formatted name and description for a given view. """ import re from django.utils.encoding import force_str from django.utils.html import escape from django.utils.safestring import mark_safe from rest_framework.compat import apply_markdown def remove_trailing_string(content, trailing): """ Strip trailing component `trailing` from `content` if it exists. Used when generating names from view classes. """ if content.endswith(trailing) and content != trailing: return content[:-len(trailing)] return content def dedent(content): """ Remove leading indent from a block of text. Used when generating descriptions from docstrings. Note that python's `textwrap.dedent` doesn't quite cut it, as it fails to dedent multiline docstrings that include unindented text on the initial line. """ content = force_str(content) lines = [line for line in content.splitlines()[1:] if line.lstrip()] # unindent the content if needed if lines: whitespace_counts = min([len(line) - len(line.lstrip(' ')) for line in lines]) tab_counts = min([len(line) - len(line.lstrip('\t')) for line in lines]) if whitespace_counts: whitespace_pattern = '^' + (' ' * whitespace_counts) content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content) elif tab_counts: whitespace_pattern = '^' + ('\t' * tab_counts) content = re.sub(re.compile(whitespace_pattern, re.MULTILINE), '', content) return content.strip() def camelcase_to_spaces(content): """ Translate 'CamelCaseNames' to 'Camel Case Names'. Used when generating names from view classes. """ camelcase_boundary = '(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))' content = re.sub(camelcase_boundary, ' \\1', content).strip() return ' '.join(content.split('_')).title() def markup_description(description): """ Apply HTML markup to the given description. """ if apply_markdown: description = apply_markdown(description) else: description = escape(description).replace('\n', '
    ') description = '

    ' + description + '

    ' return mark_safe(description) class lazy_format: """ Delay formatting until it's actually needed. Useful when the format string or one of the arguments is lazy. Not using Django's lazy because it is too slow. """ __slots__ = ('format_string', 'args', 'kwargs', 'result') def __init__(self, format_string, *args, **kwargs): self.result = None self.format_string = format_string self.args = args self.kwargs = kwargs def __str__(self): if self.result is None: self.result = self.format_string.format(*self.args, **self.kwargs) self.format_string, self.args, self.kwargs = None, None, None return self.result def __mod__(self, value): return str(self) % value ================================================ FILE: rest_framework/utils/html.py ================================================ """ Helpers for dealing with HTML input. """ import re from django.utils.datastructures import MultiValueDict def is_html_input(dictionary): # MultiDict type datastructures are used to represent HTML form input, # which may have more than one value for each key. return hasattr(dictionary, 'getlist') def parse_html_list(dictionary, prefix='', default=None): """ Used to support list values in HTML forms. Supports lists of primitives and/or dictionaries. * List of primitives. { '[0]': 'abc', '[1]': 'def', '[2]': 'hij' } --> [ 'abc', 'def', 'hij' ] * List of dictionaries. { '[0]foo': 'abc', '[0]bar': 'def', '[1]foo': 'hij', '[1]bar': 'klm', } --> [ {'foo': 'abc', 'bar': 'def'}, {'foo': 'hij', 'bar': 'klm'} ] :returns a list of objects, or the value specified in ``default`` if the list is empty """ ret = {} regex = re.compile(r'^%s\[([0-9]+)\](.*)$' % re.escape(prefix)) for field, value in dictionary.items(): match = regex.match(field) if not match: continue index, key = match.groups() index = int(index) if not key: ret[index] = value elif isinstance(ret.get(index), dict): ret[index][key] = value else: ret[index] = MultiValueDict({key: [value]}) # return the items of the ``ret`` dict, sorted by key, or ``default`` if the dict is empty return [ret[item] for item in sorted(ret)] if ret else default def parse_html_dict(dictionary, prefix=''): """ Used to support dictionary values in HTML forms. { 'profile.username': 'example', 'profile.email': 'example@example.com', } --> { 'profile': { 'username': 'example', 'email': 'example@example.com' } } """ ret = MultiValueDict() regex = re.compile(r'^%s\.(.+)$' % re.escape(prefix)) for field in dictionary: match = regex.match(field) if not match: continue key = match.groups()[0] value = dictionary.getlist(field) ret.setlist(key, value) return ret ================================================ FILE: rest_framework/utils/humanize_datetime.py ================================================ """ Helper functions that convert strftime formats into more readable representations. """ from rest_framework import ISO_8601 def datetime_formats(formats): format = ', '.join(formats).replace( ISO_8601, 'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]' ) return humanize_strptime(format) def date_formats(formats): format = ', '.join(formats).replace(ISO_8601, 'YYYY-MM-DD') return humanize_strptime(format) def time_formats(formats): format = ', '.join(formats).replace(ISO_8601, 'hh:mm[:ss[.uuuuuu]]') return humanize_strptime(format) def humanize_strptime(format_string): # Note that we're missing some of the locale specific mappings that # don't really make sense. mapping = { "%Y": "YYYY", "%y": "YY", "%m": "MM", "%b": "[Jan-Dec]", "%B": "[January-December]", "%d": "DD", "%H": "hh", "%I": "hh", # Requires '%p' to differentiate from '%H'. "%M": "mm", "%S": "ss", "%f": "uuuuuu", "%a": "[Mon-Sun]", "%A": "[Monday-Sunday]", "%p": "[AM|PM]", "%z": "[+HHMM|-HHMM]" } for key, val in mapping.items(): format_string = format_string.replace(key, val) return format_string ================================================ FILE: rest_framework/utils/json.py ================================================ """ Wrapper for the builtin json module that ensures compliance with the JSON spec. REST framework should always import this wrapper module in order to maintain spec-compliant encoding/decoding. Support for non-standard features should be handled by users at the renderer and parser layer. """ import functools import json # noqa def strict_constant(o): raise ValueError('Out of range float values are not JSON compliant: ' + repr(o)) @functools.wraps(json.dump) def dump(*args, **kwargs): kwargs.setdefault('allow_nan', False) return json.dump(*args, **kwargs) @functools.wraps(json.dumps) def dumps(*args, **kwargs): kwargs.setdefault('allow_nan', False) return json.dumps(*args, **kwargs) @functools.wraps(json.load) def load(*args, **kwargs): kwargs.setdefault('parse_constant', strict_constant) return json.load(*args, **kwargs) @functools.wraps(json.loads) def loads(*args, **kwargs): kwargs.setdefault('parse_constant', strict_constant) return json.loads(*args, **kwargs) ================================================ FILE: rest_framework/utils/mediatypes.py ================================================ """ Handling of media types, as found in HTTP Content-Type and Accept headers. See https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7 """ from django.utils.http import parse_header_parameters def media_type_matches(lhs, rhs): """ Returns ``True`` if the media type in the first argument <= the media type in the second argument. The media types are strings as described by the HTTP spec. Valid media type strings include: 'application/json; indent=4' 'application/json' 'text/*' '*/*' """ lhs = _MediaType(lhs) rhs = _MediaType(rhs) return lhs.match(rhs) def order_by_precedence(media_type_lst): """ Returns a list of sets of media type strings, ordered by precedence. Precedence is determined by how specific a media type is: 3. 'type/subtype; param=val' 2. 'type/subtype' 1. 'type/*' 0. '*/*' """ ret = [set(), set(), set(), set()] for media_type in media_type_lst: precedence = _MediaType(media_type).precedence ret[3 - precedence].add(media_type) return [media_types for media_types in ret if media_types] class _MediaType: def __init__(self, media_type_str): self.orig = '' if (media_type_str is None) else media_type_str self.full_type, self.params = parse_header_parameters(self.orig) self.main_type, sep, self.sub_type = self.full_type.partition('/') def match(self, other): """Return true if this MediaType satisfies the given MediaType.""" for key in self.params: if key != 'q' and other.params.get(key, None) != self.params.get(key, None): return False if self.sub_type != '*' and other.sub_type != '*' and other.sub_type != self.sub_type: return False if self.main_type != '*' and other.main_type != '*' and other.main_type != self.main_type: return False return True @property def precedence(self): """ Return a precedence level from 0-3 for the media type given how specific it is. """ if self.main_type == '*': return 0 elif self.sub_type == '*': return 1 elif not self.params or list(self.params) == ['q']: return 2 return 3 def __str__(self): ret = "%s/%s" % (self.main_type, self.sub_type) for key, val in self.params.items(): ret += "; %s=%s" % (key, val) return ret ================================================ FILE: rest_framework/utils/model_meta.py ================================================ """ Helper function for returning the field information that is associated with a model class. This includes returning all the forward and reverse relationships and their associated metadata. Usage: `get_field_info(model)` returns a `FieldInfo` instance. """ from collections import namedtuple FieldInfo = namedtuple('FieldInfo', [ 'pk', # Model field instance 'fields', # Dict of field name -> model field instance 'forward_relations', # Dict of field name -> RelationInfo 'reverse_relations', # Dict of field name -> RelationInfo 'fields_and_pk', # Shortcut for 'pk' + 'fields' 'relations' # Shortcut for 'forward_relations' + 'reverse_relations' ]) RelationInfo = namedtuple('RelationInfo', [ 'model_field', 'related_model', 'to_many', 'to_field', 'has_through_model', 'reverse' ]) def get_field_info(model): """ Given a model class, returns a `FieldInfo` instance, which is a `namedtuple`, containing metadata about the various field types on the model including information about their relationships. """ opts = model._meta.concrete_model._meta pk = _get_pk(opts) fields = _get_fields(opts) forward_relations = _get_forward_relationships(opts) reverse_relations = _get_reverse_relationships(opts) fields_and_pk = _merge_fields_and_pk(pk, fields) relationships = _merge_relationships(forward_relations, reverse_relations) return FieldInfo(pk, fields, forward_relations, reverse_relations, fields_and_pk, relationships) def _get_pk(opts): pk = opts.pk rel = pk.remote_field while rel and rel.parent_link: # If model is a child via multi-table inheritance, use parent's pk. pk = pk.remote_field.model._meta.pk rel = pk.remote_field return pk def _get_fields(opts): fields = {} for field in [field for field in opts.fields if field.serialize and not field.remote_field]: fields[field.name] = field return fields def _get_to_field(field): return getattr(field, 'to_fields', None) and field.to_fields[0] def _get_forward_relationships(opts): """ Returns a dict of field names to `RelationInfo`. """ forward_relations = {} for field in [field for field in opts.fields if field.serialize and field.remote_field]: forward_relations[field.name] = RelationInfo( model_field=field, related_model=field.remote_field.model, to_many=False, to_field=_get_to_field(field), has_through_model=False, reverse=False ) # Deal with forward many-to-many relationships. for field in [field for field in opts.many_to_many if field.serialize]: forward_relations[field.name] = RelationInfo( model_field=field, related_model=field.remote_field.model, to_many=True, # manytomany do not have to_fields to_field=None, has_through_model=( not field.remote_field.through._meta.auto_created ), reverse=False ) return forward_relations def _get_reverse_relationships(opts): """ Returns a dict of field names to `RelationInfo`. """ reverse_relations = {} all_related_objects = [r for r in opts.related_objects if not r.field.many_to_many] for relation in all_related_objects: accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( model_field=None, related_model=relation.related_model, to_many=relation.field.remote_field.multiple, to_field=_get_to_field(relation.field), has_through_model=False, reverse=True ) # Deal with reverse many-to-many relationships. all_related_many_to_many_objects = [r for r in opts.related_objects if r.field.many_to_many] for relation in all_related_many_to_many_objects: accessor_name = relation.get_accessor_name() reverse_relations[accessor_name] = RelationInfo( model_field=None, related_model=relation.related_model, to_many=True, # manytomany do not have to_fields to_field=None, has_through_model=( (getattr(relation.field.remote_field, 'through', None) is not None) and not relation.field.remote_field.through._meta.auto_created ), reverse=True ) return reverse_relations def _merge_fields_and_pk(pk, fields): fields_and_pk = {'pk': pk, pk.name: pk} fields_and_pk.update(fields) return fields_and_pk def _merge_relationships(forward_relations, reverse_relations): return {**forward_relations, **reverse_relations} def is_abstract_model(model): """ Given a model class, returns a boolean True if it is abstract and False if it is not. """ return hasattr(model, '_meta') and hasattr(model._meta, 'abstract') and model._meta.abstract ================================================ FILE: rest_framework/utils/representation.py ================================================ """ Helper functions for creating user-friendly representations of serializer classes and serializer fields. """ import re from django.db import models from django.utils.encoding import force_str from django.utils.functional import Promise def manager_repr(value): model = value.model opts = model._meta names_and_managers = [ (manager.name, manager) for manager in opts.managers ] for manager_name, manager_instance in names_and_managers: if manager_instance == value: return '%s.%s.all()' % (model._meta.object_name, manager_name) return repr(value) def smart_repr(value): if isinstance(value, models.Manager): return manager_repr(value) if isinstance(value, Promise): value = force_str(value, strings_only=True) value = repr(value) # Representations like u'help text' # should simply be presented as 'help text' if value.startswith("u'") and value.endswith("'"): return value[1:] # Representations like # # Should be presented as # return re.sub(' at 0x[0-9A-Fa-f]{4,32}>', '>', value) def field_repr(field, force_many=False): kwargs = field._kwargs if force_many: kwargs = kwargs.copy() kwargs['many'] = True kwargs.pop('child', None) arg_string = ', '.join([smart_repr(val) for val in field._args]) kwarg_string = ', '.join([ '%s=%s' % (key, smart_repr(val)) for key, val in sorted(kwargs.items()) ]) if arg_string and kwarg_string: arg_string += ', ' if force_many: class_name = force_many.__class__.__name__ else: class_name = field.__class__.__name__ return "%s(%s%s)" % (class_name, arg_string, kwarg_string) def serializer_repr(serializer, indent, force_many=None): ret = field_repr(serializer, force_many) + ':' indent_str = ' ' * indent if force_many: fields = force_many.fields else: fields = serializer.fields for field_name, field in fields.items(): ret += '\n' + indent_str + field_name + ' = ' if hasattr(field, 'fields'): ret += serializer_repr(field, indent + 1) elif hasattr(field, 'child'): ret += list_repr(field, indent + 1) elif hasattr(field, 'child_relation'): ret += field_repr(field.child_relation, force_many=field.child_relation) else: ret += field_repr(field) if serializer.validators: ret += '\n' + indent_str + 'class Meta:' ret += '\n' + indent_str + ' validators = ' + smart_repr(serializer.validators) return ret def list_repr(serializer, indent): child = serializer.child if hasattr(child, 'fields'): return serializer_repr(serializer, indent, force_many=child) return field_repr(serializer) ================================================ FILE: rest_framework/utils/serializer_helpers.py ================================================ import contextlib from collections.abc import Mapping, MutableMapping from django.utils.encoding import force_str from rest_framework.utils import json class ReturnDict(dict): """ Return object from `serializer.data` for the `Serializer` class. Includes a backlink to the serializer instance for renderers to use if they need richer field information. """ def __init__(self, *args, **kwargs): self.serializer = kwargs.pop('serializer') super().__init__(*args, **kwargs) def copy(self): return ReturnDict(self, serializer=self.serializer) def __repr__(self): return dict.__repr__(self) def __reduce__(self): # Pickling these objects will drop the .serializer backlink, # but preserve the raw data. return (dict, (dict(self),)) # These are basically copied from OrderedDict, with `serializer` added. def __or__(self, other): if not isinstance(other, dict): return NotImplemented new = self.__class__(self, serializer=self.serializer) new.update(other) return new def __ror__(self, other): if not isinstance(other, dict): return NotImplemented new = self.__class__(other, serializer=self.serializer) new.update(self) return new class ReturnList(list): """ Return object from `serializer.data` for the `SerializerList` class. Includes a backlink to the serializer instance for renderers to use if they need richer field information. """ def __init__(self, *args, **kwargs): self.serializer = kwargs.pop('serializer') super().__init__(*args, **kwargs) def __repr__(self): return list.__repr__(self) def __reduce__(self): # Pickling these objects will drop the .serializer backlink, # but preserve the raw data. return (list, (list(self),)) class BoundField: """ A field object that also includes `.value` and `.error` properties. Returned when iterating over a serializer instance, providing an API similar to Django forms and form fields. """ def __init__(self, field, value, errors, prefix=''): self._field = field self._prefix = prefix self.value = value self.errors = errors self.name = prefix + self.field_name def __getattr__(self, attr_name): return getattr(self._field, attr_name) @property def _proxy_class(self): return self._field.__class__ def __repr__(self): return '<%s value=%s errors=%s>' % ( self.__class__.__name__, self.value, self.errors ) def as_form_field(self): value = '' if (self.value is None or self.value is False) else self.value return self.__class__(self._field, value, self.errors, self._prefix) class JSONBoundField(BoundField): def as_form_field(self): value = self.value # When HTML form input is used and the input is not valid # value will be a JSONString, rather than a JSON primitive. if not getattr(value, 'is_json_string', False): with contextlib.suppress(TypeError, ValueError): value = json.dumps( self.value, sort_keys=True, indent=4, separators=(',', ': '), ) return self.__class__(self._field, value, self.errors, self._prefix) class NestedBoundField(BoundField): """ This `BoundField` additionally implements __iter__ and __getitem__ in order to support nested bound fields. This class is the type of `BoundField` that is used for serializer fields. """ def __init__(self, field, value, errors, prefix=''): if value is None or value == '' or not isinstance(value, Mapping): value = {} super().__init__(field, value, errors, prefix) def __iter__(self): for field in self.fields.values(): yield self[field.field_name] def __getitem__(self, key): field = self.fields[key] value = self.value.get(key) if self.value else None error = self.errors.get(key) if isinstance(self.errors, dict) else None if hasattr(field, 'fields'): return NestedBoundField(field, value, error, prefix=self.name + '.') elif getattr(field, '_is_jsonfield', False): return JSONBoundField(field, value, error, prefix=self.name + '.') return BoundField(field, value, error, prefix=self.name + '.') def as_form_field(self): values = {} for key, value in self.value.items(): if isinstance(value, (list, dict)): values[key] = value else: values[key] = '' if (value is None or value is False) else force_str(value) return self.__class__(self._field, values, self.errors, self._prefix) class BindingDict(MutableMapping): """ This dict-like object is used to store fields on a serializer. This ensures that whenever fields are added to the serializer we call `field.bind()` so that the `field_name` and `parent` attributes can be set correctly. """ def __init__(self, serializer): self.serializer = serializer self.fields = {} def __setitem__(self, key, field): self.fields[key] = field field.bind(field_name=key, parent=self.serializer) def __getitem__(self, key): return self.fields[key] def __delitem__(self, key): del self.fields[key] def __iter__(self): return iter(self.fields) def __len__(self): return len(self.fields) def __repr__(self): return dict.__repr__(self.fields) ================================================ FILE: rest_framework/utils/timezone.py ================================================ from datetime import datetime, timezone, tzinfo def datetime_exists(dt): """Check if a datetime exists. Taken from: https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html""" # There are no non-existent times in UTC, and comparisons between # aware time zones always compare absolute times; if a datetime is # not equal to the same datetime represented in UTC, it is imaginary. return dt.astimezone(timezone.utc) == dt def datetime_ambiguous(dt: datetime): """Check whether a datetime is ambiguous. Taken from: https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html""" # If a datetime exists and its UTC offset changes in response to # changing `fold`, it is ambiguous in the zone specified. return datetime_exists(dt) and ( dt.replace(fold=not dt.fold).utcoffset() != dt.utcoffset() ) def valid_datetime(dt): """Returns True if the datetime is not ambiguous or imaginary, False otherwise.""" if isinstance(dt.tzinfo, tzinfo) and not datetime_ambiguous(dt): return True return False ================================================ FILE: rest_framework/utils/urls.py ================================================ from urllib import parse from django.utils.encoding import force_str def replace_query_param(url, key, val): """ Given a URL and a key/val pair, set or replace an item in the query parameters of the URL, and return the new URL. """ (scheme, netloc, path, query, fragment) = parse.urlsplit(force_str(url)) query_dict = parse.parse_qs(query, keep_blank_values=True) query_dict[force_str(key)] = [force_str(val)] query = parse.urlencode(sorted(query_dict.items()), doseq=True) return parse.urlunsplit((scheme, netloc, path, query, fragment)) def remove_query_param(url, key): """ Given a URL and a key/val pair, remove an item in the query parameters of the URL, and return the new URL. """ (scheme, netloc, path, query, fragment) = parse.urlsplit(force_str(url)) query_dict = parse.parse_qs(query, keep_blank_values=True) query_dict.pop(key, None) query = parse.urlencode(sorted(query_dict.items()), doseq=True) return parse.urlunsplit((scheme, netloc, path, query, fragment)) ================================================ FILE: rest_framework/validators.py ================================================ """ We perform uniqueness checks explicitly on the serializer class, rather the using Django's `.full_clean()`. This gives us better separation of concerns, allows us to use single-step object creation, and makes it possible to switch between using the implicit `ModelSerializer` class and an equivalent explicit `Serializer` class. """ from django.core.exceptions import FieldError from django.db import DataError from django.db.models import Exists from django.utils.translation import gettext_lazy as _ from rest_framework.exceptions import ValidationError from rest_framework.utils.representation import smart_repr # Robust filter and exist implementations. Ensures that queryset.exists() for # an invalid value returns `False`, rather than raising an error. # Refs https://github.com/encode/django-rest-framework/issues/3381 def qs_exists(queryset): try: return queryset.exists() except (TypeError, ValueError, DataError): return False def qs_exists_with_condition(queryset, condition, against): if condition is None: return qs_exists(queryset) try: # use the same query as UniqueConstraint.validate # https://github.com/django/django/blob/7ba2a0db20c37a5b1500434ca4ed48022311c171/django/db/models/constraints.py#L672 return (condition & Exists(queryset.filter(condition))).check(against) except (TypeError, ValueError, DataError, FieldError): return False def qs_filter(queryset, **kwargs): try: return queryset.filter(**kwargs) except (TypeError, ValueError, DataError): return queryset.none() class UniqueValidator: """ Validator that corresponds to `unique=True` on a model field. Should be applied to an individual field on the serializer. """ message = _('This field must be unique.') requires_context = True def __init__(self, queryset, message=None, lookup='exact'): self.queryset = queryset self.message = message or self.message self.lookup = lookup def filter_queryset(self, value, queryset, field_name): """ Filter the queryset to all instances matching the given attribute. """ filter_kwargs = {'%s__%s' % (field_name, self.lookup): value} return qs_filter(queryset, **filter_kwargs) def exclude_current_instance(self, queryset, instance): """ If an instance is being updated, then do not include that instance itself as a uniqueness conflict. """ if instance is not None: return queryset.exclude(pk=instance.pk) return queryset def __call__(self, value, serializer_field): # Determine the underlying model field name. This may not be the # same as the serializer field name if `source=<>` is set. field_name = serializer_field.source_attrs[-1] # Determine the existing instance, if this is an update operation. instance = getattr(serializer_field.parent, 'instance', None) queryset = self.queryset queryset = self.filter_queryset(value, queryset, field_name) queryset = self.exclude_current_instance(queryset, instance) if qs_exists(queryset): raise ValidationError(self.message, code='unique') def __repr__(self): return '<%s(queryset=%s)>' % ( self.__class__.__name__, smart_repr(self.queryset) ) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return (self.message == other.message and self.requires_context == other.requires_context and self.queryset == other.queryset and self.lookup == other.lookup ) class UniqueTogetherValidator: """ Validator that corresponds to `unique_together = (...)` on a model class. Should be applied to the serializer class, not to an individual field. """ message = _('The fields {field_names} must make a unique set.') missing_message = _('This field is required.') requires_context = True code = 'unique' def __init__(self, queryset, fields, message=None, condition_fields=None, condition=None, code=None): self.queryset = queryset self.fields = fields self.message = message or self.message self.condition_fields = [] if condition_fields is None else condition_fields self.condition = condition self.code = code or self.code def enforce_required_fields(self, attrs, serializer): """ The `UniqueTogetherValidator` always forces an implied 'required' state on the fields it applies to. """ if serializer.instance is not None: return missing_items = { field_name: self.missing_message for field_name in (*self.fields, *self.condition_fields) if serializer.fields[field_name].source not in attrs } if missing_items: raise ValidationError(missing_items, code='required') def filter_queryset(self, attrs, queryset, serializer): """ Filter the queryset to all instances matching the given attributes. """ # field names => field sources sources = [ serializer.fields[field_name].source for field_name in self.fields ] # If this is an update, then any unprovided field should # have it's value set based on the existing instance attribute. if serializer.instance is not None: for source in sources: if source not in attrs: attrs[source] = getattr(serializer.instance, source) # Determine the filter keyword arguments and filter the queryset. filter_kwargs = { source: attrs[source] for source in sources } return qs_filter(queryset, **filter_kwargs) def exclude_current_instance(self, attrs, queryset, instance): """ If an instance is being updated, then do not include that instance itself as a uniqueness conflict. """ if instance is not None: return queryset.exclude(pk=instance.pk) return queryset def __call__(self, attrs, serializer): self.enforce_required_fields(attrs, serializer) queryset = self.queryset queryset = self.filter_queryset(attrs, queryset, serializer) queryset = self.exclude_current_instance(attrs, queryset, serializer.instance) checked_names = [ serializer.fields[field_name].source for field_name in self.fields ] # Ignore validation if any field is None if serializer.instance is None: checked_values = [attrs[field_name] for field_name in checked_names] else: # Ignore validation if all field values are unchanged checked_values = [ attrs[field_name] for field_name in checked_names if attrs[field_name] != getattr(serializer.instance, field_name) ] condition_sources = (serializer.fields[field_name].source for field_name in self.condition_fields) condition_kwargs = { source: attrs[source] if source in attrs else getattr(serializer.instance, source) for source in condition_sources } if checked_values and None not in checked_values and qs_exists_with_condition(queryset, self.condition, condition_kwargs): field_names = ', '.join(self.fields) message = self.message.format(field_names=field_names) raise ValidationError(message, code=self.code) def __repr__(self): return '<{}({})>'.format( self.__class__.__name__, ', '.join( f'{attr}={smart_repr(getattr(self, attr))}' for attr in ('queryset', 'fields', 'condition') if getattr(self, attr) is not None) ) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return (self.message == other.message and self.requires_context == other.requires_context and self.missing_message == other.missing_message and self.queryset == other.queryset and self.fields == other.fields and self.code == other.code ) class ProhibitSurrogateCharactersValidator: message = _('Surrogate characters are not allowed: U+{code_point:X}.') code = 'surrogate_characters_not_allowed' def __call__(self, value): for surrogate_character in (ch for ch in str(value) if 0xD800 <= ord(ch) <= 0xDFFF): message = self.message.format(code_point=ord(surrogate_character)) raise ValidationError(message, code=self.code) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return (self.message == other.message and self.code == other.code ) class BaseUniqueForValidator: message = None missing_message = _('This field is required.') requires_context = True def __init__(self, queryset, field, date_field, message=None): self.queryset = queryset self.field = field self.date_field = date_field self.message = message or self.message def enforce_required_fields(self, attrs): """ The `UniqueForValidator` classes always force an implied 'required' state on the fields they are applied to. """ missing_items = { field_name: self.missing_message for field_name in [self.field, self.date_field] if field_name not in attrs } if missing_items: raise ValidationError(missing_items, code='required') def filter_queryset(self, attrs, queryset, field_name, date_field_name): raise NotImplementedError('`filter_queryset` must be implemented.') def exclude_current_instance(self, attrs, queryset, instance): """ If an instance is being updated, then do not include that instance itself as a uniqueness conflict. """ if instance is not None: return queryset.exclude(pk=instance.pk) return queryset def __call__(self, attrs, serializer): # Determine the underlying model field names. These may not be the # same as the serializer field names if `source=<>` is set. field_name = serializer.fields[self.field].source_attrs[-1] date_field_name = serializer.fields[self.date_field].source_attrs[-1] self.enforce_required_fields(attrs) queryset = self.queryset queryset = self.filter_queryset(attrs, queryset, field_name, date_field_name) queryset = self.exclude_current_instance(attrs, queryset, serializer.instance) if qs_exists(queryset): message = self.message.format(date_field=self.date_field) raise ValidationError({ self.field: message }, code='unique') def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return (self.message == other.message and self.missing_message == other.missing_message and self.requires_context == other.requires_context and self.queryset == other.queryset and self.field == other.field and self.date_field == other.date_field ) def __repr__(self): return '<%s(queryset=%s, field=%s, date_field=%s)>' % ( self.__class__.__name__, smart_repr(self.queryset), smart_repr(self.field), smart_repr(self.date_field) ) class UniqueForDateValidator(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" date.') def filter_queryset(self, attrs, queryset, field_name, date_field_name): value = attrs[self.field] date = attrs[self.date_field] filter_kwargs = {} filter_kwargs[field_name] = value filter_kwargs['%s__day' % date_field_name] = date.day filter_kwargs['%s__month' % date_field_name] = date.month filter_kwargs['%s__year' % date_field_name] = date.year return qs_filter(queryset, **filter_kwargs) class UniqueForMonthValidator(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" month.') def filter_queryset(self, attrs, queryset, field_name, date_field_name): value = attrs[self.field] date = attrs[self.date_field] filter_kwargs = {} filter_kwargs[field_name] = value filter_kwargs['%s__month' % date_field_name] = date.month return qs_filter(queryset, **filter_kwargs) class UniqueForYearValidator(BaseUniqueForValidator): message = _('This field must be unique for the "{date_field}" year.') def filter_queryset(self, attrs, queryset, field_name, date_field_name): value = attrs[self.field] date = attrs[self.date_field] filter_kwargs = {} filter_kwargs[field_name] = value filter_kwargs['%s__year' % date_field_name] = date.year return qs_filter(queryset, **filter_kwargs) ================================================ FILE: rest_framework/versioning.py ================================================ import re from django.utils.translation import gettext_lazy as _ from rest_framework import exceptions from rest_framework.compat import unicode_http_header from rest_framework.reverse import _reverse from rest_framework.settings import api_settings from rest_framework.templatetags.rest_framework import replace_query_param from rest_framework.utils.mediatypes import _MediaType class BaseVersioning: default_version = api_settings.DEFAULT_VERSION allowed_versions = api_settings.ALLOWED_VERSIONS version_param = api_settings.VERSION_PARAM def determine_version(self, request, *args, **kwargs): msg = '{cls}.determine_version() must be implemented.' raise NotImplementedError(msg.format( cls=self.__class__.__name__ )) def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): return _reverse(viewname, args, kwargs, request, format, **extra) def is_allowed_version(self, version): if not self.allowed_versions: return True return ((version is not None and version == self.default_version) or (version in self.allowed_versions)) class AcceptHeaderVersioning(BaseVersioning): """ GET /something/ HTTP/1.1 Host: example.com Accept: application/json; version=1.0 """ invalid_version_message = _('Invalid version in "Accept" header.') def determine_version(self, request, *args, **kwargs): media_type = _MediaType(request.accepted_media_type) version = media_type.params.get(self.version_param, self.default_version) version = unicode_http_header(version) if not self.is_allowed_version(version): raise exceptions.NotAcceptable(self.invalid_version_message) return version # We don't need to implement `reverse`, as the versioning is based # on the `Accept` header, not on the request URL. class URLPathVersioning(BaseVersioning): """ To the client this is the same style as `NamespaceVersioning`. The difference is in the backend - this implementation uses Django's URL keyword arguments to determine the version. An example URL conf for two views that accept two different versions. urlpatterns = [ re_path(r'^(?P[v1|v2]+)/users/$', users_list, name='users-list'), re_path(r'^(?P[v1|v2]+)/users/(?P[0-9]+)/$', users_detail, name='users-detail') ] GET /1.0/something/ HTTP/1.1 Host: example.com Accept: application/json """ invalid_version_message = _('Invalid version in URL path.') def determine_version(self, request, *args, **kwargs): version = kwargs.get(self.version_param, self.default_version) if version is None: version = self.default_version if not self.is_allowed_version(version): raise exceptions.NotFound(self.invalid_version_message) return version def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): if request.version is not None: kwargs = { self.version_param: request.version, **(kwargs or {}) } return super().reverse( viewname, args, kwargs, request, format, **extra ) class NamespaceVersioning(BaseVersioning): """ To the client this is the same style as `URLPathVersioning`. The difference is in the backend - this implementation uses Django's URL namespaces to determine the version. An example URL conf that is namespaced into two separate versions # users/urls.py urlpatterns = [ path('/users/', users_list, name='users-list'), path('/users//', users_detail, name='users-detail') ] # urls.py urlpatterns = [ path('v1/', include('users.urls', namespace='v1')), path('v2/', include('users.urls', namespace='v2')) ] GET /1.0/something/ HTTP/1.1 Host: example.com Accept: application/json """ invalid_version_message = _('Invalid version in URL path. Does not match any version namespace.') def determine_version(self, request, *args, **kwargs): resolver_match = getattr(request, 'resolver_match', None) if resolver_match is None or not resolver_match.namespace: return self.default_version # Allow for possibly nested namespaces. possible_versions = resolver_match.namespace.split(':') for version in possible_versions: if self.is_allowed_version(version): return version raise exceptions.NotFound(self.invalid_version_message) def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): if request.version is not None: viewname = self.get_versioned_viewname(viewname, request) return super().reverse( viewname, args, kwargs, request, format, **extra ) def get_versioned_viewname(self, viewname, request): return request.version + ':' + viewname class HostNameVersioning(BaseVersioning): """ GET /something/ HTTP/1.1 Host: v1.example.com Accept: application/json """ hostname_regex = re.compile(r'^([a-zA-Z0-9]+)\.[a-zA-Z0-9]+\.[a-zA-Z0-9]+$') invalid_version_message = _('Invalid version in hostname.') def determine_version(self, request, *args, **kwargs): hostname, separator, port = request.get_host().partition(':') match = self.hostname_regex.match(hostname) if not match: return self.default_version version = match.group(1) if not self.is_allowed_version(version): raise exceptions.NotFound(self.invalid_version_message) return version # We don't need to implement `reverse`, as the hostname will already be # preserved as part of the REST framework `reverse` implementation. class QueryParameterVersioning(BaseVersioning): """ GET /something/?version=0.1 HTTP/1.1 Host: example.com Accept: application/json """ invalid_version_message = _('Invalid version in query parameter.') def determine_version(self, request, *args, **kwargs): version = request.query_params.get(self.version_param, self.default_version) if not self.is_allowed_version(version): raise exceptions.NotFound(self.invalid_version_message) return version def reverse(self, viewname, args=None, kwargs=None, request=None, format=None, **extra): url = super().reverse( viewname, args, kwargs, request, format, **extra ) if request.version is not None: return replace_query_param(url, self.version_param, request.version) return url ================================================ FILE: rest_framework/views.py ================================================ """ Provides an APIView class that is the base of all views in REST framework. """ from django import VERSION as DJANGO_VERSION from django.conf import settings from django.core.exceptions import PermissionDenied from django.db import connections, models from django.http import Http404 from django.http.response import HttpResponseBase from django.utils.cache import cc_delim_re, patch_vary_headers from django.utils.encoding import smart_str from django.views.decorators.csrf import csrf_exempt from django.views.generic import View from rest_framework import exceptions, status from rest_framework.request import Request from rest_framework.response import Response from rest_framework.schemas import DefaultSchema from rest_framework.settings import api_settings from rest_framework.utils import formatting def get_view_name(view): """ Given a view instance, return a textual name to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_NAME_FUNCTION` setting. """ # Name may be set by some Views, such as a ViewSet. name = getattr(view, 'name', None) if name is not None: return name name = view.__class__.__name__ name = formatting.remove_trailing_string(name, 'View') name = formatting.remove_trailing_string(name, 'ViewSet') name = formatting.camelcase_to_spaces(name) # Suffix may be set by some Views, such as a ViewSet. suffix = getattr(view, 'suffix', None) if suffix: name += ' ' + suffix return name def get_view_description(view, html=False): """ Given a view instance, return a textual description to represent the view. This name is used in the browsable API, and in OPTIONS responses. This function is the default for the `VIEW_DESCRIPTION_FUNCTION` setting. """ # Description may be set by some Views, such as a ViewSet. description = getattr(view, 'description', None) if description is None: description = view.__class__.__doc__ or '' description = formatting.dedent(smart_str(description)) if html: return formatting.markup_description(description) return description def set_rollback(): for db in connections.all(): if db.settings_dict['ATOMIC_REQUESTS'] and db.in_atomic_block: db.set_rollback(True) def exception_handler(exc, context): """ Returns the response that should be used for any given exception. By default we handle the REST framework `APIException`, and also Django's built-in `Http404` and `PermissionDenied` exceptions. Any unhandled exceptions may return `None`, which will cause a 500 error to be raised. """ if isinstance(exc, Http404): exc = exceptions.NotFound(*(exc.args)) elif isinstance(exc, PermissionDenied): exc = exceptions.PermissionDenied(*(exc.args)) if isinstance(exc, exceptions.APIException): headers = {} if getattr(exc, 'auth_header', None): headers['WWW-Authenticate'] = exc.auth_header if getattr(exc, 'wait', None): headers['Retry-After'] = '%d' % exc.wait if isinstance(exc.detail, (list, dict)): data = exc.detail else: data = {'detail': exc.detail} set_rollback() return Response(data, status=exc.status_code, headers=headers) return None class APIView(View): # The following policies may be set at either globally, or per-view. renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES parser_classes = api_settings.DEFAULT_PARSER_CLASSES authentication_classes = api_settings.DEFAULT_AUTHENTICATION_CLASSES throttle_classes = api_settings.DEFAULT_THROTTLE_CLASSES permission_classes = api_settings.DEFAULT_PERMISSION_CLASSES content_negotiation_class = api_settings.DEFAULT_CONTENT_NEGOTIATION_CLASS metadata_class = api_settings.DEFAULT_METADATA_CLASS versioning_class = api_settings.DEFAULT_VERSIONING_CLASS # Allow dependency injection of other settings to make testing easier. settings = api_settings schema = DefaultSchema() @classmethod def as_view(cls, **initkwargs): """ Store the original class on the view function. This allows us to discover information about the view when we do URL reverse lookups. Used for breadcrumb generation. """ if isinstance(getattr(cls, 'queryset', None), models.query.QuerySet): def force_evaluation(): raise RuntimeError( 'Do not evaluate the `.queryset` attribute directly, ' 'as the result will be cached and reused between requests. ' 'Use `.all()` or call `.get_queryset()` instead.' ) cls.queryset._fetch_all = force_evaluation view = super().as_view(**initkwargs) view.cls = cls view.initkwargs = initkwargs # Exempt all DRF views from Django's LoginRequiredMiddleware. Users should set # DEFAULT_PERMISSION_CLASSES to 'rest_framework.permissions.IsAuthenticated' instead if DJANGO_VERSION >= (5, 1): view.login_required = False # Note: session based authentication is explicitly CSRF validated, # all other authentication is CSRF exempt. return csrf_exempt(view) @property def allowed_methods(self): """ Wrap Django's private `_allowed_methods` interface in a public property. """ return self._allowed_methods() @property def default_response_headers(self): headers = { 'Allow': ', '.join(self.allowed_methods), } if len(self.renderer_classes) > 1: headers['Vary'] = 'Accept' return headers def http_method_not_allowed(self, request, *args, **kwargs): """ If `request.method` does not correspond to a handler method, determine what kind of exception to raise. """ raise exceptions.MethodNotAllowed(request.method) def permission_denied(self, request, message=None, code=None): """ If request is not permitted, determine what kind of exception to raise. """ if request.authenticators and not request.successful_authenticator: raise exceptions.NotAuthenticated() raise exceptions.PermissionDenied(detail=message, code=code) def throttled(self, request, wait): """ If request is throttled, determine what kind of exception to raise. """ raise exceptions.Throttled(wait) def get_authenticate_header(self, request): """ If a request is unauthenticated, determine the WWW-Authenticate header to use for 401 responses, if any. """ authenticators = self.get_authenticators() if authenticators: return authenticators[0].authenticate_header(request) def get_parser_context(self, http_request): """ Returns a dict that is passed through to Parser.parse(), as the `parser_context` keyword argument. """ # Note: Additionally `request` and `encoding` will also be added # to the context by the Request object. return { 'view': self, 'args': getattr(self, 'args', ()), 'kwargs': getattr(self, 'kwargs', {}) } def get_renderer_context(self): """ Returns a dict that is passed through to Renderer.render(), as the `renderer_context` keyword argument. """ # Note: Additionally 'response' will also be added to the context, # by the Response object. return { 'view': self, 'args': getattr(self, 'args', ()), 'kwargs': getattr(self, 'kwargs', {}), 'request': getattr(self, 'request', None) } def get_exception_handler_context(self): """ Returns a dict that is passed through to EXCEPTION_HANDLER, as the `context` argument. """ return { 'view': self, 'args': getattr(self, 'args', ()), 'kwargs': getattr(self, 'kwargs', {}), 'request': getattr(self, 'request', None) } def get_view_name(self): """ Return the view name, as used in OPTIONS responses and in the browsable API. """ func = self.settings.VIEW_NAME_FUNCTION return func(self) def get_view_description(self, html=False): """ Return some descriptive text for the view, as used in OPTIONS responses and in the browsable API. """ func = self.settings.VIEW_DESCRIPTION_FUNCTION return func(self, html) # API policy instantiation methods def get_format_suffix(self, **kwargs): """ Determine if the request includes a '.json' style format suffix """ if self.settings.FORMAT_SUFFIX_KWARG: return kwargs.get(self.settings.FORMAT_SUFFIX_KWARG) def get_renderers(self): """ Instantiates and returns the list of renderers that this view can use. """ return [renderer() for renderer in self.renderer_classes] def get_parsers(self): """ Instantiates and returns the list of parsers that this view can use. """ return [parser() for parser in self.parser_classes] def get_authenticators(self): """ Instantiates and returns the list of authenticators that this view can use. """ return [auth() for auth in self.authentication_classes] def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ return [permission() for permission in self.permission_classes] def get_throttles(self): """ Instantiates and returns the list of throttles that this view uses. """ return [throttle() for throttle in self.throttle_classes] def get_content_negotiator(self): """ Instantiate and return the content negotiation class to use. """ if not getattr(self, '_negotiator', None): self._negotiator = self.content_negotiation_class() return self._negotiator def get_exception_handler(self): """ Returns the exception handler that this view uses. """ return self.settings.EXCEPTION_HANDLER # API policy implementation methods def perform_content_negotiation(self, request, force=False): """ Determine which renderer and media type to use render the response. """ renderers = self.get_renderers() conneg = self.get_content_negotiator() try: return conneg.select_renderer(request, renderers, self.format_kwarg) except Exception: if force: return (renderers[0], renderers[0].media_type) raise def perform_authentication(self, request): """ Perform authentication on the incoming request. Note that if you override this and simply 'pass', then authentication will instead be performed lazily, the first time either `request.user` or `request.auth` is accessed. """ request.user def check_permissions(self, request): """ Check if the request should be permitted. Raises an appropriate exception if the request is not permitted. """ for permission in self.get_permissions(): if not permission.has_permission(request, self): self.permission_denied( request, message=getattr(permission, 'message', None), code=getattr(permission, 'code', None) ) def check_object_permissions(self, request, obj): """ Check if the request should be permitted for a given object. Raises an appropriate exception if the request is not permitted. """ for permission in self.get_permissions(): if not permission.has_object_permission(request, self, obj): self.permission_denied( request, message=getattr(permission, 'message', None), code=getattr(permission, 'code', None) ) def check_throttles(self, request): """ Check if request should be throttled. Raises an appropriate exception if the request is throttled. """ throttle_durations = [] for throttle in self.get_throttles(): if not throttle.allow_request(request, self): throttle_durations.append(throttle.wait()) if throttle_durations: # Filter out `None` values which may happen in case of config / rate # changes, see #1438 durations = [ duration for duration in throttle_durations if duration is not None ] duration = max(durations, default=None) self.throttled(request, duration) def determine_version(self, request, *args, **kwargs): """ If versioning is being used, then determine any API version for the incoming request. Returns a two-tuple of (version, versioning_scheme) """ if self.versioning_class is None: return (None, None) scheme = self.versioning_class() return (scheme.determine_version(request, *args, **kwargs), scheme) # Dispatch methods def initialize_request(self, request, *args, **kwargs): """ Returns the initial request object. """ parser_context = self.get_parser_context(request) return Request( request, parsers=self.get_parsers(), authenticators=self.get_authenticators(), negotiator=self.get_content_negotiator(), parser_context=parser_context ) def initial(self, request, *args, **kwargs): """ Runs anything that needs to occur prior to calling the method handler. """ self.format_kwarg = self.get_format_suffix(**kwargs) # Perform content negotiation and store the accepted info on the request neg = self.perform_content_negotiation(request) request.accepted_renderer, request.accepted_media_type = neg # Determine the API version, if versioning is in use. version, scheme = self.determine_version(request, *args, **kwargs) request.version, request.versioning_scheme = version, scheme # Ensure that the incoming request is permitted self.perform_authentication(request) self.check_permissions(request) self.check_throttles(request) def finalize_response(self, request, response, *args, **kwargs): """ Returns the final response object. """ # Make the error obvious if a proper response is not returned assert isinstance(response, HttpResponseBase), ( 'Expected a `Response`, `HttpResponse` or `StreamingHttpResponse` ' 'to be returned from the view, but received a `%s`' % type(response) ) if isinstance(response, Response): if not getattr(request, 'accepted_renderer', None): neg = self.perform_content_negotiation(request, force=True) request.accepted_renderer, request.accepted_media_type = neg response.accepted_renderer = request.accepted_renderer response.accepted_media_type = request.accepted_media_type response.renderer_context = self.get_renderer_context() # Add new vary headers to the response instead of overwriting. vary_headers = self.headers.pop('Vary', None) if vary_headers is not None: patch_vary_headers(response, cc_delim_re.split(vary_headers)) for key, value in self.headers.items(): response[key] = value return response def handle_exception(self, exc): """ Handle any exception that occurs, by returning an appropriate response, or re-raising the error. """ if isinstance(exc, (exceptions.NotAuthenticated, exceptions.AuthenticationFailed)): # WWW-Authenticate header for 401 responses, else coerce to 403 auth_header = self.get_authenticate_header(self.request) if auth_header: exc.auth_header = auth_header else: exc.status_code = status.HTTP_403_FORBIDDEN exception_handler = self.get_exception_handler() context = self.get_exception_handler_context() response = exception_handler(exc, context) if response is None: self.raise_uncaught_exception(exc) response.exception = True return response def raise_uncaught_exception(self, exc): if settings.DEBUG: request = self.request renderer_format = getattr(request.accepted_renderer, 'format') use_plaintext_traceback = renderer_format not in ('html', 'api', 'admin') request.force_plaintext_errors(use_plaintext_traceback) raise exc # Note: Views are made CSRF exempt from within `as_view` as to prevent # accidental removal of this exemption in cases where `dispatch` needs to # be overridden. def dispatch(self, request, *args, **kwargs): """ `.dispatch()` is pretty much the same as Django's regular dispatch, but with extra hooks for startup, finalize, and exception handling. """ self.args = args self.kwargs = kwargs request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response def options(self, request, *args, **kwargs): """ Handler method for HTTP 'OPTIONS' request. """ if self.metadata_class is None: return self.http_method_not_allowed(request, *args, **kwargs) data = self.metadata_class().determine_metadata(request, self) return Response(data, status=status.HTTP_200_OK) ================================================ FILE: rest_framework/viewsets.py ================================================ """ ViewSets are essentially just a type of class based view, that doesn't provide any method handlers, such as `get()`, `post()`, etc... but instead has actions, such as `list()`, `retrieve()`, `create()`, etc... Actions are only bound to methods at the point of instantiating the views. user_list = UserViewSet.as_view({'get': 'list'}) user_detail = UserViewSet.as_view({'get': 'retrieve'}) Typically, rather than instantiate views from viewsets directly, you'll register the viewset with a router and let the URL conf be determined automatically. router = DefaultRouter() router.register(r'users', UserViewSet, 'user') urlpatterns = router.urls """ from functools import update_wrapper from inspect import getmembers from django import VERSION as DJANGO_VERSION from django.urls import NoReverseMatch from django.utils.decorators import classonlymethod from django.views.decorators.csrf import csrf_exempt from rest_framework import generics, mixins, views from rest_framework.decorators import MethodMapper from rest_framework.reverse import reverse def _is_extra_action(attr): return hasattr(attr, 'mapping') and isinstance(attr.mapping, MethodMapper) def _check_attr_name(func, name): assert func.__name__ == name, ( 'Expected function (`{func.__name__}`) to match its attribute name ' '(`{name}`). If using a decorator, ensure the inner function is ' 'decorated with `functools.wraps`, or that `{func.__name__}.__name__` ' 'is otherwise set to `{name}`.').format(func=func, name=name) return func class ViewSetMixin: """ This is the magic. Overrides `.as_view()` so that it takes an `actions` keyword that performs the binding of HTTP methods to actions on the Resource. For example, to create a concrete view binding the 'GET' and 'POST' methods to the 'list' and 'create' actions... view = MyViewSet.as_view({'get': 'list', 'post': 'create'}) """ @classonlymethod def as_view(cls, actions=None, **initkwargs): """ Because of the way class based views create a closure around the instantiated view, we need to totally reimplement `.as_view`, and slightly modify the view function that is created and returned. """ # The name and description initkwargs may be explicitly overridden for # certain route configurations. eg, names of extra actions. cls.name = None cls.description = None # The suffix initkwarg is reserved for displaying the viewset type. # This initkwarg should have no effect if the name is provided. # eg. 'List' or 'Instance'. cls.suffix = None # The detail initkwarg is reserved for introspecting the viewset type. cls.detail = None # Setting a basename allows a view to reverse its action urls. This # value is provided by the router through the initkwargs. cls.basename = None # actions must not be empty if not actions: raise TypeError("The `actions` argument must be provided when " "calling `.as_view()` on a ViewSet. For example " "`.as_view({'get': 'list'})`") # sanitize keyword arguments for key in initkwargs: if key in cls.http_method_names: raise TypeError("You tried to pass in the %s method name as a " "keyword argument to %s(). Don't do that." % (key, cls.__name__)) if not hasattr(cls, key): raise TypeError("%s() received an invalid keyword %r" % ( cls.__name__, key)) # name and suffix are mutually exclusive if 'name' in initkwargs and 'suffix' in initkwargs: raise TypeError("%s() received both `name` and `suffix`, which are " "mutually exclusive arguments." % (cls.__name__)) def view(request, *args, **kwargs): self = cls(**initkwargs) if 'get' in actions and 'head' not in actions: actions['head'] = actions['get'] # We also store the mapping of request methods to actions, # so that we can later set the action attribute. # eg. `self.action = 'list'` on an incoming GET request. self.action_map = actions # Bind methods to actions # This is the bit that's different to a standard view for method, action in actions.items(): handler = getattr(self, action) setattr(self, method, handler) self.request = request self.args = args self.kwargs = kwargs # And continue as usual return self.dispatch(request, *args, **kwargs) # take name and docstring from class update_wrapper(view, cls, updated=()) # and possible attributes set by decorators # like csrf_exempt from dispatch update_wrapper(view, cls.dispatch, assigned=()) # We need to set these on the view function, so that breadcrumb # generation can pick out these bits of information from a # resolved URL. view.cls = cls view.initkwargs = initkwargs view.actions = actions # Exempt from Django's LoginRequiredMiddleware. Users should set # DEFAULT_PERMISSION_CLASSES to 'rest_framework.permissions.IsAuthenticated' instead if DJANGO_VERSION >= (5, 1): view.login_required = False return csrf_exempt(view) def initialize_request(self, request, *args, **kwargs): """ Set the `.action` attribute on the view, depending on the request method. """ request = super().initialize_request(request, *args, **kwargs) method = request.method.lower() if method == 'options': # This is a special case as we always provide handling for the # options method in the base `View` class. # Unlike the other explicitly defined actions, 'metadata' is implicit. self.action = 'metadata' else: self.action = self.action_map.get(method) return request def reverse_action(self, url_name, *args, **kwargs): """ Reverse the action for the given `url_name`. """ url_name = '%s-%s' % (self.basename, url_name) namespace = None if self.request and self.request.resolver_match: namespace = self.request.resolver_match.namespace if namespace: url_name = namespace + ':' + url_name kwargs.setdefault('request', self.request) return reverse(url_name, *args, **kwargs) @classmethod def get_extra_actions(cls): """ Get the methods that are marked as an extra ViewSet `@action`. """ return [_check_attr_name(method, name) for name, method in getmembers(cls, _is_extra_action)] def get_extra_action_url_map(self): """ Build a map of {names: urls} for the extra actions. This method will noop if `detail` was not provided as a view initkwarg. """ action_urls = {} # exit early if `detail` has not been provided if self.detail is None: return action_urls # filter for the relevant extra actions actions = [ action for action in self.get_extra_actions() if action.detail == self.detail ] for action in actions: try: url_name = '%s-%s' % (self.basename, action.url_name) namespace = self.request.resolver_match.namespace if namespace: url_name = '%s:%s' % (namespace, url_name) url = reverse(url_name, self.args, self.kwargs, request=self.request) view = self.__class__(**action.kwargs) action_urls[view.get_view_name()] = url except NoReverseMatch: pass # URL requires additional arguments, ignore return action_urls class ViewSet(ViewSetMixin, views.APIView): """ The base ViewSet class does not provide any actions by default. """ pass class GenericViewSet(ViewSetMixin, generics.GenericAPIView): """ The GenericViewSet class does not provide any actions by default, but does include the base set of generic view behavior, such as the `get_object` and `get_queryset` methods. """ pass class ReadOnlyModelViewSet(mixins.RetrieveModelMixin, mixins.ListModelMixin, GenericViewSet): """ A viewset that provides default `list()` and `retrieve()` actions. """ pass class ModelViewSet(mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, mixins.ListModelMixin, GenericViewSet): """ A viewset that provides default `create()`, `retrieve()`, `update()`, `partial_update()`, `destroy()` and `list()` actions. """ pass ================================================ FILE: runtests.py ================================================ #! /usr/bin/env python3 import os import sys import pytest def split_class_and_function(string): class_string, function_string = string.split('.', 1) return "%s and %s" % (class_string, function_string) def is_function(string): # `True` if it looks like a test function is included in the string. return string.startswith('test_') or '.test_' in string def is_class(string): # `True` if first character is uppercase - assume it's a class name. return string[0] == string[0].upper() if __name__ == "__main__": if len(sys.argv) > 1: pytest_args = sys.argv[1:] first_arg = pytest_args[0] try: pytest_args.remove('--coverage') except ValueError: pass else: pytest_args = [ '--cov', '.', '--cov-report', 'xml', ] + pytest_args try: pytest_args.remove('--no-pkgroot') except ValueError: pass else: sys.path.pop(0) # import rest_framework before pytest re-adds the package root directory. import rest_framework package_dir = os.path.join(os.getcwd(), 'rest_framework') assert not rest_framework.__file__.startswith(package_dir) if first_arg.startswith('-'): # `runtests.py [flags]` pytest_args = ['tests'] + pytest_args elif is_class(first_arg) and is_function(first_arg): # `runtests.py TestCase.test_function [flags]` expression = split_class_and_function(first_arg) pytest_args = ['tests', '-k', expression] + pytest_args[1:] elif is_class(first_arg) or is_function(first_arg): # `runtests.py TestCase [flags]` # `runtests.py test_function [flags]` pytest_args = ['tests', '-k', pytest_args[0]] + pytest_args[1:] else: pytest_args = [] sys.exit(pytest.main(pytest_args)) ================================================ FILE: setup.cfg ================================================ [flake8] extend-ignore = E501,W503,W504,B extend-select = B006 banned-modules = json = use from rest_framework.utils import json! ================================================ FILE: tests/__init__.py ================================================ ================================================ FILE: tests/authentication/__init__.py ================================================ ================================================ FILE: tests/authentication/migrations/0001_initial.py ================================================ from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='CustomToken', fields=[ ('key', models.CharField(max_length=40, primary_key=True, serialize=False)), ('user', models.OneToOneField(on_delete=models.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] ================================================ FILE: tests/authentication/migrations/__init__.py ================================================ ================================================ FILE: tests/authentication/models.py ================================================ from django.conf import settings from django.db import models class CustomToken(models.Model): key = models.CharField(max_length=40, primary_key=True) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ================================================ FILE: tests/authentication/test_authentication.py ================================================ import base64 import pytest from django.conf import settings from django.contrib.auth.models import User from django.http import HttpResponse from django.test import TestCase, override_settings from django.urls import include, path from rest_framework import ( HTTP_HEADER_ENCODING, exceptions, permissions, renderers, status ) from rest_framework.authentication import ( BaseAuthentication, BasicAuthentication, RemoteUserAuthentication, SessionAuthentication, TokenAuthentication ) from rest_framework.authtoken.models import Token from rest_framework.authtoken.views import obtain_auth_token from rest_framework.response import Response from rest_framework.test import APIClient, APIRequestFactory from rest_framework.views import APIView from .models import CustomToken factory = APIRequestFactory() class CustomTokenAuthentication(TokenAuthentication): model = CustomToken class CustomKeywordTokenAuthentication(TokenAuthentication): keyword = 'Bearer' class MockView(APIView): permission_classes = (permissions.IsAuthenticated,) def get(self, request): return HttpResponse({'a': 1, 'b': 2, 'c': 3}) def post(self, request): return HttpResponse({'a': 1, 'b': 2, 'c': 3}) def put(self, request): return HttpResponse({'a': 1, 'b': 2, 'c': 3}) urlpatterns = [ path( 'session/', MockView.as_view(authentication_classes=[SessionAuthentication]) ), path( 'basic/', MockView.as_view(authentication_classes=[BasicAuthentication]) ), path( 'remote-user/', MockView.as_view(authentication_classes=[RemoteUserAuthentication]) ), path( 'token/', MockView.as_view(authentication_classes=[TokenAuthentication]) ), path( 'customtoken/', MockView.as_view(authentication_classes=[CustomTokenAuthentication]) ), path( 'customkeywordtoken/', MockView.as_view( authentication_classes=[CustomKeywordTokenAuthentication] ) ), path('auth-token/', obtain_auth_token), path('auth/', include('rest_framework.urls', namespace='rest_framework')), ] @override_settings(ROOT_URLCONF=__name__) class BasicAuthTests(TestCase): """Basic authentication""" def setUp(self): self.csrf_client = APIClient(enforce_csrf_checks=True) self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user = User.objects.create_user( self.username, self.email, self.password ) def test_post_form_passing_basic_auth(self): """Ensure POSTing json over basic auth with correct credentials passes and does not require CSRF""" credentials = ('%s:%s' % (self.username, self.password)) base64_credentials = base64.b64encode( credentials.encode(HTTP_HEADER_ENCODING) ).decode(HTTP_HEADER_ENCODING) auth = 'Basic %s' % base64_credentials response = self.csrf_client.post( '/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_200_OK def test_post_json_passing_basic_auth(self): """Ensure POSTing form over basic auth with correct credentials passes and does not require CSRF""" credentials = ('%s:%s' % (self.username, self.password)) base64_credentials = base64.b64encode( credentials.encode(HTTP_HEADER_ENCODING) ).decode(HTTP_HEADER_ENCODING) auth = 'Basic %s' % base64_credentials response = self.csrf_client.post( '/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_200_OK def test_post_json_without_password_failing_basic_auth(self): """Ensure POSTing json without password (even if password is empty string) returns 401""" self.user.set_password("") credentials = ('%s' % (self.username)) base64_credentials = base64.b64encode( credentials.encode(HTTP_HEADER_ENCODING) ).decode(HTTP_HEADER_ENCODING) auth = 'Basic %s' % base64_credentials response = self.csrf_client.post( '/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_regression_handle_bad_base64_basic_auth_header(self): """Ensure POSTing JSON over basic auth with incorrectly padded Base64 string is handled correctly""" # regression test for issue in 'rest_framework.authentication.BasicAuthentication.authenticate' # https://github.com/encode/django-rest-framework/issues/4089 auth = 'Basic =a=' response = self.csrf_client.post( '/basic/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_post_form_failing_basic_auth(self): """Ensure POSTing form over basic auth without correct credentials fails""" response = self.csrf_client.post('/basic/', {'example': 'example'}) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_post_json_failing_basic_auth(self): """Ensure POSTing json over basic auth without correct credentials fails""" response = self.csrf_client.post( '/basic/', {'example': 'example'}, format='json' ) assert response.status_code == status.HTTP_401_UNAUTHORIZED assert response['WWW-Authenticate'] == 'Basic realm="api"' def test_fail_post_if_credentials_are_missing(self): response = self.csrf_client.post( '/basic/', {'example': 'example'}, HTTP_AUTHORIZATION='Basic ') assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_fail_post_if_credentials_contain_spaces(self): response = self.csrf_client.post( '/basic/', {'example': 'example'}, HTTP_AUTHORIZATION='Basic foo bar' ) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_decoding_of_utf8_credentials(self): username = 'walterwhité' email = 'walterwhite@example.com' password = 'pässwörd' User.objects.create_user( username, email, password ) credentials = ('%s:%s' % (username, password)) base64_credentials = base64.b64encode( credentials.encode('utf-8') ).decode(HTTP_HEADER_ENCODING) auth = 'Basic %s' % base64_credentials response = self.csrf_client.post( '/basic/', {'example': 'example'}, HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_200_OK @override_settings(ROOT_URLCONF=__name__) class SessionAuthTests(TestCase): """User session authentication""" def setUp(self): self.csrf_client = APIClient(enforce_csrf_checks=True) self.non_csrf_client = APIClient(enforce_csrf_checks=False) self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user = User.objects.create_user( self.username, self.email, self.password ) def tearDown(self): self.csrf_client.logout() def test_login_view_renders_on_get(self): """ Ensure the login template renders for a basic GET. cf. [#1810](https://github.com/encode/django-rest-framework/pull/1810) """ response = self.csrf_client.get('/auth/login/') content = response.content.decode() assert '' in content def test_post_form_session_auth_failing_csrf(self): """ Ensure POSTing form over session authentication without CSRF token fails. """ self.csrf_client.login(username=self.username, password=self.password) response = self.csrf_client.post('/session/', {'example': 'example'}) assert response.status_code == status.HTTP_403_FORBIDDEN def test_post_form_session_auth_passing_csrf(self): """ Ensure POSTing form over session authentication with CSRF token succeeds. Regression test for #6088 """ self.csrf_client.login(username=self.username, password=self.password) # Set the csrf_token cookie so that CsrfViewMiddleware._get_token() works from django.middleware.csrf import ( _get_new_csrf_string, _mask_cipher_secret ) token = _mask_cipher_secret(_get_new_csrf_string()) self.csrf_client.cookies[settings.CSRF_COOKIE_NAME] = token # Post the token matching the cookie value response = self.csrf_client.post('/session/', { 'example': 'example', 'csrfmiddlewaretoken': token, }) assert response.status_code == status.HTTP_200_OK def test_post_form_session_auth_passing(self): """ Ensure POSTing form over session authentication with logged in user and CSRF token passes. """ self.non_csrf_client.login( username=self.username, password=self.password ) response = self.non_csrf_client.post( '/session/', {'example': 'example'} ) assert response.status_code == status.HTTP_200_OK def test_put_form_session_auth_passing(self): """ Ensure PUTting form over session authentication with logged in user and CSRF token passes. """ self.non_csrf_client.login( username=self.username, password=self.password ) response = self.non_csrf_client.put( '/session/', {'example': 'example'} ) assert response.status_code == status.HTTP_200_OK def test_post_form_session_auth_failing(self): """ Ensure POSTing form over session authentication without logged in user fails. """ response = self.csrf_client.post('/session/', {'example': 'example'}) assert response.status_code == status.HTTP_403_FORBIDDEN class BaseTokenAuthTests: """Token authentication""" model = None path = None header_prefix = 'Token ' def setUp(self): self.csrf_client = APIClient(enforce_csrf_checks=True) self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user = User.objects.create_user( self.username, self.email, self.password ) self.key = 'abcd1234' self.token = self.model.objects.create(key=self.key, user=self.user) def test_post_form_passing_token_auth(self): """ Ensure POSTing json over token auth with correct credentials passes and does not require CSRF """ auth = self.header_prefix + self.key response = self.csrf_client.post( self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_200_OK def test_fail_authentication_if_user_is_not_active(self): user = User.objects.create_user('foo', 'bar', 'baz') user.is_active = False user.save() self.model.objects.create(key='foobar_token', user=user) response = self.csrf_client.post( self.path, {'example': 'example'}, HTTP_AUTHORIZATION=self.header_prefix + 'foobar_token' ) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_fail_post_form_passing_nonexistent_token_auth(self): # use a nonexistent token key auth = self.header_prefix + 'wxyz6789' response = self.csrf_client.post( self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_fail_post_if_token_is_missing(self): response = self.csrf_client.post( self.path, {'example': 'example'}, HTTP_AUTHORIZATION=self.header_prefix) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_fail_post_if_token_contains_spaces(self): response = self.csrf_client.post( self.path, {'example': 'example'}, HTTP_AUTHORIZATION=self.header_prefix + 'foo bar' ) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_fail_post_form_passing_invalid_token_auth(self): # add an 'invalid' unicode character auth = self.header_prefix + self.key + "¸" response = self.csrf_client.post( self.path, {'example': 'example'}, HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_post_json_passing_token_auth(self): """ Ensure POSTing form over token auth with correct credentials passes and does not require CSRF """ auth = self.header_prefix + self.key response = self.csrf_client.post( self.path, {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth ) assert response.status_code == status.HTTP_200_OK def test_post_json_makes_one_db_query(self): """ Ensure that authenticating a user using a token performs only one DB query """ auth = self.header_prefix + self.key def func_to_test(): return self.csrf_client.post( self.path, {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth ) self.assertNumQueries(1, func_to_test) def test_post_form_failing_token_auth(self): """ Ensure POSTing form over token auth without correct credentials fails """ response = self.csrf_client.post(self.path, {'example': 'example'}) assert response.status_code == status.HTTP_401_UNAUTHORIZED def test_post_json_failing_token_auth(self): """ Ensure POSTing json over token auth without correct credentials fails """ response = self.csrf_client.post( self.path, {'example': 'example'}, format='json' ) assert response.status_code == status.HTTP_401_UNAUTHORIZED @override_settings(ROOT_URLCONF=__name__) class TokenAuthTests(BaseTokenAuthTests, TestCase): model = Token path = '/token/' def test_token_has_auto_assigned_key_if_none_provided(self): """Ensure creating a token with no key will auto-assign a key""" self.token.delete() token = self.model.objects.create(user=self.user) assert bool(token.key) def test_generate_key_returns_string(self): """Ensure generate_key returns a string""" token = self.model() key = token.generate_key() assert isinstance(key, str) def test_generate_key_accessible_as_classmethod(self): key = self.model.generate_key() assert isinstance(key, str) def test_generate_key_returns_valid_format(self): """Ensure generate_key returns a valid token format""" key = self.model.generate_key() assert len(key) == 40 # Should contain only valid hexadecimal characters assert all(c in '0123456789abcdef' for c in key) def test_generate_key_produces_unique_values(self): """Ensure generate_key produces unique values across multiple calls""" keys = set() for _ in range(100): key = self.model.generate_key() assert key not in keys, f"Duplicate key generated: {key}" keys.add(key) def test_generate_key_collision_resistance(self): """Test collision resistance with reasonable sample size""" keys = set() for _ in range(500): key = self.model.generate_key() assert key not in keys, f"Collision found: {key}" keys.add(key) assert len(keys) == 500, f"Expected 500 unique keys, got {len(keys)}" def test_generate_key_randomness_quality(self): """Test basic randomness properties of generated keys""" keys = [self.model.generate_key() for _ in range(10)] # Consecutive keys should be different for i in range(len(keys) - 1): assert keys[i] != keys[i + 1], "Consecutive keys should be different" # Keys should not follow obvious patterns for key in keys: # Should not be all same character assert not all(c == key[0] for c in key), f"Key has all same characters: {key}" def test_token_login_json(self): """Ensure token login view using JSON POST works.""" client = APIClient(enforce_csrf_checks=True) response = client.post( '/auth-token/', {'username': self.username, 'password': self.password}, format='json' ) assert response.status_code == status.HTTP_200_OK assert response.data['token'] == self.key def test_token_login_json_bad_creds(self): """ Ensure token login view using JSON POST fails if bad credentials are used """ client = APIClient(enforce_csrf_checks=True) response = client.post( '/auth-token/', {'username': self.username, 'password': "badpass"}, format='json' ) assert response.status_code == 400 def test_token_login_json_missing_fields(self): """Ensure token login view using JSON POST fails if missing fields.""" client = APIClient(enforce_csrf_checks=True) response = client.post('/auth-token/', {'username': self.username}, format='json') assert response.status_code == 400 def test_token_login_form(self): """Ensure token login view using form POST works.""" client = APIClient(enforce_csrf_checks=True) response = client.post( '/auth-token/', {'username': self.username, 'password': self.password} ) assert response.status_code == status.HTTP_200_OK assert response.data['token'] == self.key @override_settings(ROOT_URLCONF=__name__) class CustomTokenAuthTests(BaseTokenAuthTests, TestCase): model = CustomToken path = '/customtoken/' @override_settings(ROOT_URLCONF=__name__) class CustomKeywordTokenAuthTests(BaseTokenAuthTests, TestCase): model = Token path = '/customkeywordtoken/' header_prefix = 'Bearer ' class IncorrectCredentialsTests(TestCase): def test_incorrect_credentials(self): """ If a request contains bad authentication credentials, then authentication should run and error, even if no permissions are set on the view. """ class IncorrectCredentialsAuth(BaseAuthentication): def authenticate(self, request): raise exceptions.AuthenticationFailed('Bad credentials') request = factory.get('/') view = MockView.as_view( authentication_classes=(IncorrectCredentialsAuth,), permission_classes=() ) response = view(request) assert response.status_code == status.HTTP_403_FORBIDDEN assert response.data == {'detail': 'Bad credentials'} class FailingAuthAccessedInRenderer(TestCase): def setUp(self): class AuthAccessingRenderer(renderers.BaseRenderer): media_type = 'text/plain' format = 'txt' def render(self, data, media_type=None, renderer_context=None): request = renderer_context['request'] if request.user.is_authenticated: return b'authenticated' return b'not authenticated' class FailingAuth(BaseAuthentication): def authenticate(self, request): raise exceptions.AuthenticationFailed('authentication failed') class ExampleView(APIView): authentication_classes = (FailingAuth,) renderer_classes = (AuthAccessingRenderer,) def get(self, request): return Response({'foo': 'bar'}) self.view = ExampleView.as_view() def test_failing_auth_accessed_in_renderer(self): """ When authentication fails the renderer should still be able to access `request.user` without raising an exception. Particularly relevant to HTML responses that might reasonably access `request.user`. """ request = factory.get('/') response = self.view(request) content = response.render().content assert content == b'not authenticated' class NoAuthenticationClassesTests(TestCase): def test_permission_message_with_no_authentication_classes(self): """ An unauthenticated request made against a view that contains no `authentication_classes` but do contain `permissions_classes` the error code returned should be 403 with the exception's message. """ class DummyPermission(permissions.BasePermission): message = 'Dummy permission message' def has_permission(self, request, view): return False request = factory.get('/') view = MockView.as_view( authentication_classes=(), permission_classes=(DummyPermission,), ) response = view(request) assert response.status_code == status.HTTP_403_FORBIDDEN assert response.data == {'detail': 'Dummy permission message'} class BasicAuthenticationUnitTests(TestCase): def test_base_authentication_abstract_method(self): with pytest.raises(NotImplementedError): BaseAuthentication().authenticate({}) def test_basic_authentication_raises_error_if_user_not_found(self): auth = BasicAuthentication() with pytest.raises(exceptions.AuthenticationFailed): auth.authenticate_credentials('invalid id', 'invalid password') def test_basic_authentication_raises_error_if_user_not_active(self): from rest_framework import authentication class MockUser: is_active = False old_authenticate = authentication.authenticate authentication.authenticate = lambda **kwargs: MockUser() try: auth = authentication.BasicAuthentication() with pytest.raises(exceptions.AuthenticationFailed) as exc_info: auth.authenticate_credentials('foo', 'bar') assert 'User inactive or deleted.' in str(exc_info.value) finally: authentication.authenticate = old_authenticate @override_settings(ROOT_URLCONF=__name__, AUTHENTICATION_BACKENDS=('django.contrib.auth.backends.RemoteUserBackend',)) class RemoteUserAuthenticationUnitTests(TestCase): def setUp(self): self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user = User.objects.create_user( self.username, self.email, self.password ) def test_remote_user_works(self): response = self.client.post('/remote-user/', REMOTE_USER=self.username) self.assertEqual(response.status_code, status.HTTP_200_OK) ================================================ FILE: tests/browsable_api/__init__.py ================================================ ================================================ FILE: tests/browsable_api/auth_urls.py ================================================ from django.urls import include, path from .views import MockView urlpatterns = [ path('', MockView.as_view()), path('auth/', include('rest_framework.urls', namespace='rest_framework')), ] ================================================ FILE: tests/browsable_api/no_auth_urls.py ================================================ from django.urls import path from .views import BasicModelWithUsersViewSet, MockView urlpatterns = [ path('', MockView.as_view()), path('basicviewset', BasicModelWithUsersViewSet.as_view({'get': 'list'})), ] ================================================ FILE: tests/browsable_api/serializers.py ================================================ from rest_framework.serializers import ModelSerializer from tests.models import BasicModelWithUsers class BasicSerializer(ModelSerializer): class Meta: model = BasicModelWithUsers fields = '__all__' ================================================ FILE: tests/browsable_api/test_browsable_api.py ================================================ from django.contrib.auth.models import User from django.test import TestCase, override_settings from rest_framework.permissions import IsAuthenticated from rest_framework.test import APIClient from .views import BasicModelWithUsersViewSet, OrganizationPermissions @override_settings(ROOT_URLCONF='tests.browsable_api.no_auth_urls') class AnonymousUserTests(TestCase): """Tests correct handling of anonymous user request on endpoints with IsAuthenticated permission class.""" def setUp(self): self.client = APIClient(enforce_csrf_checks=True) def tearDown(self): self.client.logout() def test_get_raises_typeerror_when_anonymous_user_in_queryset_filter(self): with self.assertRaises(TypeError): self.client.get('/basicviewset') def test_get_returns_http_forbidden_when_anonymous_user(self): old_permissions = BasicModelWithUsersViewSet.permission_classes BasicModelWithUsersViewSet.permission_classes = [IsAuthenticated, OrganizationPermissions] response = self.client.get('/basicviewset') BasicModelWithUsersViewSet.permission_classes = old_permissions self.assertEqual(response.status_code, 403) @override_settings(ROOT_URLCONF='tests.browsable_api.auth_urls') class DropdownWithAuthTests(TestCase): """Tests correct dropdown behavior with Auth views enabled.""" def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user = User.objects.create_user( self.username, self.email, self.password ) def tearDown(self): self.client.logout() def test_name_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode() assert 'john' in content def test_logout_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode() assert '>Log out<' in content def test_login_shown_when_logged_out(self): response = self.client.get('/') content = response.content.decode() assert '>Log in<' in content def test_dropdown_contains_logout_form(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode() assert '
    ' in content @override_settings(ROOT_URLCONF='tests.browsable_api.no_auth_urls') class NoDropdownWithoutAuthTests(TestCase): """Tests correct dropdown behavior with Auth views NOT enabled.""" def setUp(self): self.client = APIClient(enforce_csrf_checks=True) self.username = 'john' self.email = 'lennon@thebeatles.com' self.password = 'password' self.user = User.objects.create_user( self.username, self.email, self.password ) def tearDown(self): self.client.logout() def test_name_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode() assert 'john' in content def test_dropdown_not_shown_when_logged_in(self): self.client.login(username=self.username, password=self.password) response = self.client.get('/') content = response.content.decode() assert '