Full Code of encode/django-rest-framework for AI

main 30d58a75eeef cached
438 files
3.3 MB
873.3k tokens
3623 symbols
1 requests
Download .txt
Showing preview only (3,483K chars total). Download the full file or copy to clipboard to get everything.
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/<lang>/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.
>
> &mdash; 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 <username>

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 <username>


### 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.
>
> &mdash; [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.
>
> &mdash; 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 &mdash; normalizing it to a consistent format.
>
> &mdash; [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.<FieldName>`.

## 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 <input type="password"> 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://<host>/<path>`.

Corresponds to `django.db.models.fields.URLField`.  Uses Django's `django.core.validators.URLValidator` for validation.

**Signature:** `URLField(max_length=200, min_length=None, 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=<A_FIELD_INSTANCE>, 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=<A_FIELD_INSTANCE>, 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=<A_FIELD_INSTANCE>, 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=<Django ModelField instance>)`

The `ModelField` class is generally intended for internal use, but can be used by your API if needed.  In order to properly instantiate a `ModelField`, it must be passed a field that is attached to an instantiated model.  For example: `ModelField(model_field=MyModel()._meta.get_field('custom_field'))`

### SerializerMethodField

This is a read-only field. It gets its value by calling a method on the serializer class it is attached to. It can be used to add any sort of data to the serialized representation of your object.

**Signature**: `SerializerMethodField(method_name=None)`

* `method_name` - The name of the method on the serializer to be called. If not included this defaults to `get_<field_name>`.

The serializer method referred to by the `method_name` argument should accept a single argument (in addition to `self`), which is the object being serialized. It should return whatever you want to be included in the serialized representation of the object. For example:

    from django.contrib.auth.models import User
    from django.utils.timezone import now
    from rest_framework import serializers

    class UserSerializer(serializers.ModelSerializer):
        days_since_joined = serializers.SerializerMethodField()

        class Meta:
            model = User
            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.
>
> &mdash; [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<username>.+)/$', 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 `__<lookup>` 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.
>
> &mdash; Roy Fielding, [REST discuss mailing list][cite]

A common pattern for Web APIs is to use filename extensions on URLs to provide an endpoint for a given media type.  For example, 'http://example.com/api/users.json' to serve a JSON representation.

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/<int:pk>/', 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:

&ldquo;That's why I always prefer extensions.  Neither choice has anything to do with REST.&rdquo; &mdash; Roy Fielding, [REST discuss mailing list][cite2]

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.
>
> &mdash; [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.
>
> &mdash; [RFC7231, Section 4.3.7.][cite]

REST framework includes a configurable mechanism for determining how your API should respond to `OPTIONS` requests. This allows you to return API schema or other resource information.

There are not currently any widely adopted conventions for exactly what style of response should be returned for HTTP `OPTIONS` requests, so we provide an ad-hoc style that returns some useful information.

Here's an example response that demonstrates the information that is returned by default.

    HTTP 200 OK
    Allow: GET, POST, HEAD, OPTIONS
    Content-Type: application/json

    {
        "name": "To Do List",
        "description": "List existing 'To Do' items, or create a new item.",
        "renders": [
            "application/json",
            "text/html"
        ],
        "parses": [
            "application/json",
            "application/x-www-form-urlencoded",
            "multipart/form-data"
        ],
        "actions": {
            "POST": {
                "note": {
                    "type": "string",
                    "required": false,
                    "read_only": false,
                    "label": "title",
                    "max_length": 100
                }
            }
        }
    }

## Setting the metadata scheme

You can set the metadata class globally using the `'DEFAULT_METADATA_CLASS'` settings key:

    REST_FRAMEWORK = {
        'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata'
    }

Or you can set the metadata class individually for a view:

    class APIRoot(APIView):
        metadata_class = APIRootMetadata

        def get(self, request, format=None):
            return Response({
                ...
            })

The REST framework package only includes a single metadata class implementation, named `SimpleMetadata`. If you want to use an alternative style you'll need to implement a custom metadata class.

## Creating schema endpoints

If you have specific requirements for creating schema endpoints that are accessed with regular `GET` requests, you might consider 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.
>
> &mdash; [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
>
> &mdash; 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<filename>[^/]+)$', 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.
>
> &mdash; [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. *&mdash; 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. *&mdash; 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. *&mdash; 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.
* `DE
Download .txt
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
Download .txt
Showing preview only (311K chars total). Download the full file or copy to clipboard to get everything.
SYMBOL INDEX (3623 symbols across 138 files)

FILE: docs/theme/js/prettify-1.0.js
  function L (line 2) | function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var...
  function M (line 6) | function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.classN...
  function B (line 7) | function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}
  function x (line 7) | function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(...
  function u (line 9) | function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''...
  function D (line 12) | function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.clas...
  function k (line 15) | function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(...
  function C (line 15) | function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-m...
  function E (line 15) | function E(a){var m=
  function m (line 25) | function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Inf...

FILE: rest_framework/apps.py
  class RestFrameworkConfig (line 4) | class RestFrameworkConfig(AppConfig):
    method ready (line 8) | def ready(self):

FILE: rest_framework/authentication.py
  function get_authorization_header (line 14) | def get_authorization_header(request):
  class CSRFCheck (line 27) | class CSRFCheck(CsrfViewMiddleware):
    method _reject (line 28) | def _reject(self, request, reason):
  class BaseAuthentication (line 33) | class BaseAuthentication:
    method authenticate (line 38) | def authenticate(self, request):
    method authenticate_header (line 44) | def authenticate_header(self, request):
  class BasicAuthentication (line 53) | class BasicAuthentication(BaseAuthentication):
    method authenticate (line 59) | def authenticate(self, request):
    method authenticate_credentials (line 89) | def authenticate_credentials(self, userid, password, request=None):
    method authenticate_header (line 108) | def authenticate_header(self, request):
  class SessionAuthentication (line 112) | class SessionAuthentication(BaseAuthentication):
    method authenticate (line 117) | def authenticate(self, request):
    method enforce_csrf (line 135) | def enforce_csrf(self, request):
  class TokenAuthentication (line 151) | class TokenAuthentication(BaseAuthentication):
    method get_model (line 164) | def get_model(self):
    method authenticate (line 177) | def authenticate(self, request):
    method authenticate_credentials (line 198) | def authenticate_credentials(self, key):
    method authenticate_header (line 210) | def authenticate_header(self, request):
  class RemoteUserAuthentication (line 214) | class RemoteUserAuthentication(BaseAuthentication):
    method authenticate (line 229) | def authenticate(self, request):

FILE: rest_framework/authtoken/admin.py
  class TokenChangeList (line 14) | class TokenChangeList(ChangeList):
    method url_for_result (line 16) | def url_for_result(self, result):
  class TokenAdmin (line 24) | class TokenAdmin(admin.ModelAdmin):
    method get_changelist (line 33) | def get_changelist(self, request, **kwargs):
    method get_object (line 36) | def get_object(self, request, object_id, from_field=None):
    method delete_model (line 49) | def delete_model(self, request, obj):

FILE: rest_framework/authtoken/apps.py
  class AuthTokenConfig (line 5) | class AuthTokenConfig(AppConfig):

FILE: rest_framework/authtoken/management/commands/drf_create_token.py
  class Command (line 9) | class Command(BaseCommand):
    method create_user_token (line 12) | def create_user_token(self, username, reset_token):
    method add_arguments (line 21) | def add_arguments(self, parser):
    method handle (line 33) | def handle(self, *args, **options):

FILE: rest_framework/authtoken/migrations/0001_initial.py
  class Migration (line 5) | class Migration(migrations.Migration):

FILE: rest_framework/authtoken/migrations/0002_auto_20160226_1747.py
  class Migration (line 5) | class Migration(migrations.Migration):

FILE: rest_framework/authtoken/migrations/0003_tokenproxy.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: rest_framework/authtoken/migrations/0004_alter_tokenproxy_options.py
  class Migration (line 6) | class Migration(migrations.Migration):

FILE: rest_framework/authtoken/models.py
  class Token (line 8) | class Token(models.Model):
    class Meta (line 19) | class Meta:
    method save (line 29) | def save(self, *args, **kwargs):
    method generate_key (line 44) | def generate_key(cls):
    method __str__ (line 47) | def __str__(self):
  class TokenProxy (line 51) | class TokenProxy(Token):
    method pk (line 56) | def pk(self):
    class Meta (line 59) | class Meta:

FILE: rest_framework/authtoken/serializers.py
  class AuthTokenSerializer (line 7) | class AuthTokenSerializer(serializers.Serializer):
    method validate (line 23) | def validate(self, attrs):

FILE: rest_framework/authtoken/views.py
  class ObtainAuthToken (line 8) | class ObtainAuthToken(APIView):
    method get_serializer_context (line 15) | def get_serializer_context(self):
    method get_serializer (line 22) | def get_serializer(self, *args, **kwargs):
    method post (line 26) | def post(self, request, *args, **kwargs):

FILE: rest_framework/checks.py
  function pagination_system_check (line 5) | def pagination_system_check(app_configs, **kwargs):

FILE: rest_framework/compat.py
  function unicode_http_header (line 12) | def unicode_http_header(value):
  function apply_markdown (line 65) | def apply_markdown(text):
  function pygments_highlight (line 91) | def pygments_highlight(text, lang, style):
  function pygments_css (line 96) | def pygments_css(style):
  function pygments_highlight (line 103) | def pygments_highlight(text, lang, style):
  function pygments_css (line 106) | def pygments_css(style):
  class CodeBlockPreprocessor (line 117) | class CodeBlockPreprocessor(Preprocessor):
    method run (line 123) | def run(self, lines):
  function md_filter_add_syntax_highlight (line 136) | def md_filter_add_syntax_highlight(md):
  function md_filter_add_syntax_highlight (line 140) | def md_filter_add_syntax_highlight(md):
  function get_referenced_base_fields_from_q (line 151) | def get_referenced_base_fields_from_q(q):
  function ip_address_validators (line 159) | def ip_address_validators(protocol, unpack_ipv4):
  function _get_paths_from_expression (line 164) | def _get_paths_from_expression(expr):
  function _get_children_from_q (line 174) | def _get_children_from_q(q):
  function get_referenced_base_fields_from_q (line 186) | def get_referenced_base_fields_from_q(q):

FILE: rest_framework/decorators.py
  function api_view (line 16) | def api_view(http_method_names=None):
  function _check_decorator_order (line 90) | def _check_decorator_order(func, decorator_name):
  function renderer_classes (line 107) | def renderer_classes(renderer_classes):
  function parser_classes (line 115) | def parser_classes(parser_classes):
  function authentication_classes (line 123) | def authentication_classes(authentication_classes):
  function throttle_classes (line 131) | def throttle_classes(throttle_classes):
  function permission_classes (line 139) | def permission_classes(permission_classes):
  function content_negotiation_class (line 147) | def content_negotiation_class(content_negotiation_class):
  function metadata_class (line 155) | def metadata_class(metadata_class):
  function versioning_class (line 163) | def versioning_class(versioning_class):
  function schema (line 171) | def schema(view_inspector):
  function action (line 179) | def action(methods=None, detail=None, url_path=None, url_name=None, **kw...
  class MethodMapper (line 233) | class MethodMapper(dict):
    method __init__ (line 251) | def __init__(self, action, methods):
    method _map (line 256) | def _map(self, method, func):
    method get (line 267) | def get(self, func):
    method post (line 270) | def post(self, func):
    method put (line 273) | def put(self, func):
    method patch (line 276) | def patch(self, func):
    method delete (line 279) | def delete(self, func):
    method head (line 282) | def head(self, func):
    method options (line 285) | def options(self, func):
    method trace (line 288) | def trace(self, func):

FILE: rest_framework/exceptions.py
  function _get_error_details (line 18) | def _get_error_details(data, default_code=None):
  function _get_codes (line 44) | def _get_codes(detail):
  function _get_full_details (line 52) | def _get_full_details(detail):
  class ErrorDetail (line 63) | class ErrorDetail(str):
    method __new__ (line 69) | def __new__(cls, string, code=None):
    method __eq__ (line 74) | def __eq__(self, other):
    method __ne__ (line 83) | def __ne__(self, other):
    method __repr__ (line 89) | def __repr__(self):
    method __hash__ (line 95) | def __hash__(self):
  class APIException (line 99) | class APIException(Exception):
    method __init__ (line 108) | def __init__(self, detail=None, code=None):
    method __str__ (line 116) | def __str__(self):
    method get_codes (line 119) | def get_codes(self):
    method get_full_details (line 127) | def get_full_details(self):
  class ValidationError (line 143) | class ValidationError(APIException):
    method __init__ (line 148) | def __init__(self, detail=None, code=None):
  class ParseError (line 164) | class ParseError(APIException):
  class AuthenticationFailed (line 170) | class AuthenticationFailed(APIException):
  class NotAuthenticated (line 176) | class NotAuthenticated(APIException):
  class PermissionDenied (line 182) | class PermissionDenied(APIException):
  class NotFound (line 188) | class NotFound(APIException):
  class MethodNotAllowed (line 194) | class MethodNotAllowed(APIException):
    method __init__ (line 199) | def __init__(self, method, detail=None, code=None):
  class NotAcceptable (line 205) | class NotAcceptable(APIException):
    method __init__ (line 210) | def __init__(self, detail=None, code=None, available_renderers=None):
  class UnsupportedMediaType (line 215) | class UnsupportedMediaType(APIException):
    method __init__ (line 220) | def __init__(self, media_type, detail=None, code=None):
  class Throttled (line 226) | class Throttled(APIException):
    method __init__ (line 233) | def __init__(self, wait=None, detail=None, code=None):
  function server_error (line 247) | def server_error(request, *args, **kwargs):
  function bad_request (line 257) | def bad_request(request, exception, *args, **kwargs):

FILE: rest_framework/fields.py
  class empty (line 48) | class empty:
  class BuiltinSignatureError (line 58) | class BuiltinSignatureError(Exception):
  function is_simple_callable (line 66) | def is_simple_callable(obj):
  function get_attribute (line 92) | def get_attribute(instance, attrs):
  function to_choices_dict (line 119) | def to_choices_dict(choices):
  function flatten_choices_dict (line 147) | def flatten_choices_dict(choices):
  function iter_options (line 166) | def iter_options(grouped_choices, cutoff=None, cutoff_text=None):
  function get_error_detail (line 213) | def get_error_detail(exc_info):
  class CreateOnlyDefault (line 236) | class CreateOnlyDefault:
    method __init__ (line 244) | def __init__(self, default):
    method __call__ (line 247) | def __call__(self, serializer_field):
    method __repr__ (line 258) | def __repr__(self):
  class CurrentUserDefault (line 262) | class CurrentUserDefault:
    method __call__ (line 265) | def __call__(self, serializer_field):
    method __repr__ (line 268) | def __repr__(self):
  class SkipField (line 272) | class SkipField(Exception):
  class Field (line 288) | class Field:
    method __init__ (line 299) | def __init__(self, *, read_only=False, write_only=False,
    method __class_getitem__ (line 346) | def __class_getitem__(cls, *args, **kwargs):
    method bind (line 349) | def bind(self, field_name, parent):
    method validators (line 386) | def validators(self):
    method validators (line 392) | def validators(self, validators):
    method get_validators (line 395) | def get_validators(self):
    method get_initial (line 398) | def get_initial(self):
    method get_value (line 407) | def get_value(self, dictionary):
    method get_attribute (line 431) | def get_attribute(self, instance):
    method get_default (line 472) | def get_default(self):
    method validate_empty_values (line 492) | def validate_empty_values(self, data):
    method run_validation (line 525) | def run_validation(self, data=empty):
    method run_validators (line 542) | def run_validators(self, value):
    method to_internal_value (line 566) | def to_internal_value(self, data):
    method to_representation (line 579) | def to_representation(self, value):
    method fail (line 590) | def fail(self, key, **kwargs):
    method root (line 604) | def root(self):
    method context (line 614) | def context(self):
    method __new__ (line 620) | def __new__(cls, *args, **kwargs):
    method __deepcopy__ (line 630) | def __deepcopy__(self, memo):
    method __repr__ (line 648) | def __repr__(self):
  class BooleanField (line 659) | class BooleanField(Field):
    method __init__ (line 688) | def __init__(self, **kwargs):
    method _lower_if_str (line 695) | def _lower_if_str(value):
    method to_internal_value (line 700) | def to_internal_value(self, data):
    method to_representation (line 710) | def to_representation(self, value):
  class CharField (line 722) | class CharField(Field):
    method __init__ (line 731) | def __init__(self, **kwargs):
    method run_validation (line 749) | def run_validation(self, data=empty):
    method to_internal_value (line 759) | def to_internal_value(self, data):
    method to_representation (line 768) | def to_representation(self, value):
  class EmailField (line 772) | class EmailField(CharField):
    method __init__ (line 777) | def __init__(self, **kwargs):
  class RegexField (line 783) | class RegexField(CharField):
    method __init__ (line 788) | def __init__(self, regex, **kwargs):
  class SlugField (line 794) | class SlugField(CharField):
    method __init__ (line 800) | def __init__(self, allow_unicode=False, **kwargs):
  class URLField (line 810) | class URLField(CharField):
    method __init__ (line 815) | def __init__(self, **kwargs):
  class UUIDField (line 821) | class UUIDField(Field):
    method __init__ (line 828) | def __init__(self, **kwargs):
    method to_internal_value (line 837) | def to_internal_value(self, data):
    method to_representation (line 850) | def to_representation(self, value):
  class IPAddressField (line 857) | class IPAddressField(CharField):
    method __init__ (line 864) | def __init__(self, protocol='both', **kwargs):
    method to_internal_value (line 871) | def to_internal_value(self, data):
  class IntegerField (line 887) | class IntegerField(Field):
    method __init__ (line 897) | def __init__(self, **kwargs):
    method to_internal_value (line 910) | def to_internal_value(self, data):
    method to_representation (line 920) | def to_representation(self, value):
  class BigIntegerField (line 924) | class BigIntegerField(IntegerField):
    method __init__ (line 933) | def __init__(self, coerce_to_string=None, **kwargs):
    method to_representation (line 939) | def to_representation(self, value):
  class FloatField (line 946) | class FloatField(Field):
    method __init__ (line 956) | def __init__(self, **kwargs):
    method to_internal_value (line 969) | def to_internal_value(self, data):
    method to_representation (line 981) | def to_representation(self, value):
  class DecimalField (line 985) | class DecimalField(Field):
    method __init__ (line 997) | def __init__(self, max_digits, decimal_places, coerce_to_string=None, ...
    method validate_empty_values (line 1038) | def validate_empty_values(self, data):
    method to_internal_value (line 1043) | def to_internal_value(self, data):
    method validate_precision (line 1071) | def validate_precision(self, value):
    method to_representation (line 1106) | def to_representation(self, value):
    method quantize (line 1130) | def quantize(self, value):
  class DateTimeField (line 1149) | class DateTimeField(Field):
    method __init__ (line 1158) | def __init__(self, format=empty, input_formats=None, default_timezone=...
    method enforce_timezone (line 1167) | def enforce_timezone(self, value):
    method default_timezone (line 1195) | def default_timezone(self):
    method to_internal_value (line 1198) | def to_internal_value(self, value):
    method to_representation (line 1220) | def to_representation(self, value):
  class DateField (line 1239) | class DateField(Field):
    method __init__ (line 1246) | def __init__(self, format=empty, input_formats=None, **kwargs):
    method to_internal_value (line 1253) | def to_internal_value(self, value):
    method to_representation (line 1282) | def to_representation(self, value):
  class TimeField (line 1306) | class TimeField(Field):
    method __init__ (line 1312) | def __init__(self, format=empty, input_formats=None, **kwargs):
    method to_internal_value (line 1319) | def to_internal_value(self, value):
    method to_representation (line 1345) | def to_representation(self, value):
  class DurationField (line 1368) | class DurationField(Field):
    method __init__ (line 1376) | def __init__(self, *, format=empty, **kwargs):
    method to_internal_value (line 1402) | def to_internal_value(self, value):
    method to_representation (line 1413) | def to_representation(self, value):
  class ChoiceField (line 1438) | class ChoiceField(Field):
    method __init__ (line 1445) | def __init__(self, choices, **kwargs):
    method to_internal_value (line 1454) | def to_internal_value(self, data):
    method to_representation (line 1464) | def to_representation(self, value):
    method iter_options (line 1471) | def iter_options(self):
    method _get_choices (line 1481) | def _get_choices(self):
    method _set_choices (line 1484) | def _set_choices(self, choices):
  class MultipleChoiceField (line 1498) | class MultipleChoiceField(ChoiceField):
    method __init__ (line 1506) | def __init__(self, **kwargs):
    method get_value (line 1510) | def get_value(self, dictionary):
    method to_internal_value (line 1520) | def to_internal_value(self, data):
    method to_representation (line 1535) | def to_representation(self, value):
  class FilePathField (line 1544) | class FilePathField(ChoiceField):
    method __init__ (line 1549) | def __init__(self, path, match=None, recursive=False, allow_files=True,
  class FileField (line 1564) | class FileField(Field):
    method __init__ (line 1573) | def __init__(self, **kwargs):
    method to_internal_value (line 1580) | def to_internal_value(self, data):
    method to_representation (line 1597) | def to_representation(self, value):
  class ImageField (line 1615) | class ImageField(FileField):
    method __init__ (line 1622) | def __init__(self, **kwargs):
    method to_internal_value (line 1626) | def to_internal_value(self, data):
  class _UnvalidatedField (line 1638) | class _UnvalidatedField(Field):
    method __init__ (line 1639) | def __init__(self, **kwargs):
    method to_internal_value (line 1644) | def to_internal_value(self, data):
    method to_representation (line 1647) | def to_representation(self, value):
  class ListField (line 1651) | class ListField(Field):
    method __init__ (line 1661) | def __init__(self, **kwargs):
    method get_value (line 1682) | def get_value(self, dictionary):
    method to_internal_value (line 1697) | def to_internal_value(self, data):
    method to_representation (line 1709) | def to_representation(self, data):
    method run_child_validation (line 1715) | def run_child_validation(self, data):
  class DictField (line 1732) | class DictField(Field):
    method __init__ (line 1740) | def __init__(self, **kwargs):
    method get_value (line 1753) | def get_value(self, dictionary):
    method to_internal_value (line 1760) | def to_internal_value(self, data):
    method to_representation (line 1773) | def to_representation(self, value):
    method run_child_validation (line 1779) | def run_child_validation(self, data):
  class HStoreField (line 1796) | class HStoreField(DictField):
    method __init__ (line 1799) | def __init__(self, **kwargs):
  class JSONField (line 1807) | class JSONField(Field):
    method __init__ (line 1815) | def __init__(self, **kwargs):
    method get_value (line 1821) | def get_value(self, dictionary):
    method to_internal_value (line 1833) | def to_internal_value(self, data):
    method to_representation (line 1845) | def to_representation(self, value):
  class ReadOnlyField (line 1854) | class ReadOnlyField(Field):
    method __init__ (line 1867) | def __init__(self, **kwargs):
    method to_representation (line 1871) | def to_representation(self, value):
  class HiddenField (line 1875) | class HiddenField(Field):
    method __init__ (line 1884) | def __init__(self, **kwargs):
    method get_value (line 1889) | def get_value(self, dictionary):
    method to_internal_value (line 1894) | def to_internal_value(self, data):
  class SerializerMethodField (line 1898) | class SerializerMethodField(Field):
    method __init__ (line 1914) | def __init__(self, method_name=None, **kwargs):
    method bind (line 1920) | def bind(self, field_name, parent):
    method to_representation (line 1927) | def to_representation(self, value):
  class ModelField (line 1932) | class ModelField(Field):
    method __init__ (line 1943) | def __init__(self, model_field, **kwargs):
    method to_internal_value (line 1954) | def to_internal_value(self, data):
    method get_attribute (line 1960) | def get_attribute(self, obj):
    method to_representation (line 1965) | def to_representation(self, obj):

FILE: rest_framework/filters.py
  function search_smart_split (line 20) | def search_smart_split(search_terms):
  class BaseFilterBackend (line 37) | class BaseFilterBackend:
    method filter_queryset (line 42) | def filter_queryset(self, request, queryset, view):
    method get_schema_operation_parameters (line 48) | def get_schema_operation_parameters(self, view):
  class SearchFilter (line 52) | class SearchFilter(BaseFilterBackend):
    method get_search_fields (line 65) | def get_search_fields(self, view, request):
    method get_search_terms (line 73) | def get_search_terms(self, request):
    method construct_search (line 83) | def construct_search(self, field_name, queryset):
    method must_call_distinct (line 111) | def must_call_distinct(self, queryset, search_fields):
    method filter_queryset (line 137) | def filter_queryset(self, request, queryset, view):
    method to_html (line 168) | def to_html(self, request, queryset, view):
    method get_schema_operation_parameters (line 179) | def get_schema_operation_parameters(self, view):
  class OrderingFilter (line 193) | class OrderingFilter(BaseFilterBackend):
    method get_ordering (line 201) | def get_ordering(self, request, queryset, view):
    method get_default_ordering (line 219) | def get_default_ordering(self, view):
    method get_default_valid_fields (line 225) | def get_default_valid_fields(self, queryset, view, context=None):
    method get_valid_fields (line 264) | def get_valid_fields(self, queryset, view, context=None):
    method remove_invalid_fields (line 290) | def remove_invalid_fields(self, queryset, fields, view, request):
    method filter_queryset (line 300) | def filter_queryset(self, request, queryset, view):
    method get_template_context (line 308) | def get_template_context(self, request, queryset, view):
    method to_html (line 323) | def to_html(self, request, queryset, view):
    method get_schema_operation_parameters (line 328) | def get_schema_operation_parameters(self, view):

FILE: rest_framework/generics.py
  function get_object_or_404 (line 13) | def get_object_or_404(queryset, *filter_args, **filter_kwargs):
  class GenericAPIView (line 24) | class GenericAPIView(views.APIView):
    method __class_getitem__ (line 49) | def __class_getitem__(cls, *args, **kwargs):
    method get_queryset (line 52) | def get_queryset(self):
    method get_object (line 79) | def get_object(self):
    method get_serializer (line 107) | def get_serializer(self, *args, **kwargs):
    method get_serializer_class (line 116) | def get_serializer_class(self):
    method get_serializer_context (line 134) | def get_serializer_context(self):
    method filter_queryset (line 144) | def filter_queryset(self, queryset):
    method paginator (line 158) | def paginator(self):
    method paginate_queryset (line 169) | def paginate_queryset(self, queryset):
    method get_paginated_response (line 177) | def get_paginated_response(self, data):
  class CreateAPIView (line 188) | class CreateAPIView(mixins.CreateModelMixin,
    method post (line 193) | def post(self, request, *args, **kwargs):
  class ListAPIView (line 197) | class ListAPIView(mixins.ListModelMixin,
    method get (line 202) | def get(self, request, *args, **kwargs):
  class RetrieveAPIView (line 206) | class RetrieveAPIView(mixins.RetrieveModelMixin,
    method get (line 211) | def get(self, request, *args, **kwargs):
  class DestroyAPIView (line 215) | class DestroyAPIView(mixins.DestroyModelMixin,
    method delete (line 220) | def delete(self, request, *args, **kwargs):
  class UpdateAPIView (line 224) | class UpdateAPIView(mixins.UpdateModelMixin,
    method put (line 229) | def put(self, request, *args, **kwargs):
    method patch (line 232) | def patch(self, request, *args, **kwargs):
  class ListCreateAPIView (line 236) | class ListCreateAPIView(mixins.ListModelMixin,
    method get (line 242) | def get(self, request, *args, **kwargs):
    method post (line 245) | def post(self, request, *args, **kwargs):
  class RetrieveUpdateAPIView (line 249) | class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
    method get (line 255) | def get(self, request, *args, **kwargs):
    method put (line 258) | def put(self, request, *args, **kwargs):
    method patch (line 261) | def patch(self, request, *args, **kwargs):
  class RetrieveDestroyAPIView (line 265) | class RetrieveDestroyAPIView(mixins.RetrieveModelMixin,
    method get (line 271) | def get(self, request, *args, **kwargs):
    method delete (line 274) | def delete(self, request, *args, **kwargs):
  class RetrieveUpdateDestroyAPIView (line 278) | class RetrieveUpdateDestroyAPIView(mixins.RetrieveModelMixin,
    method get (line 285) | def get(self, request, *args, **kwargs):
    method put (line 288) | def put(self, request, *args, **kwargs):
    method patch (line 291) | def patch(self, request, *args, **kwargs):
    method delete (line 294) | def delete(self, request, *args, **kwargs):

FILE: rest_framework/management/commands/generateschema.py
  class Command (line 8) | class Command(BaseCommand):
    method add_arguments (line 11) | def add_arguments(self, parser):
    method handle (line 21) | def handle(self, *args, **options):
    method get_renderer (line 43) | def get_renderer(self, format):

FILE: rest_framework/metadata.py
  class BaseMetadata (line 18) | class BaseMetadata:
    method determine_metadata (line 19) | def determine_metadata(self, request, view):
  class SimpleMetadata (line 27) | class SimpleMetadata(BaseMetadata):
    method determine_metadata (line 59) | def determine_metadata(self, request, view):
    method determine_actions (line 72) | def determine_actions(self, request, view):
    method get_serializer_info (line 99) | def get_serializer_info(self, serializer):
    method get_field_info (line 114) | def get_field_info(self, field):

FILE: rest_framework/mixins.py
  class CreateModelMixin (line 12) | class CreateModelMixin:
    method create (line 16) | def create(self, request, *args, **kwargs):
    method perform_create (line 23) | def perform_create(self, serializer):
    method get_success_headers (line 26) | def get_success_headers(self, data):
  class ListModelMixin (line 33) | class ListModelMixin:
    method list (line 37) | def list(self, request, *args, **kwargs):
  class RetrieveModelMixin (line 49) | class RetrieveModelMixin:
    method retrieve (line 53) | def retrieve(self, request, *args, **kwargs):
  class UpdateModelMixin (line 59) | class UpdateModelMixin:
    method update (line 63) | def update(self, request, *args, **kwargs):
    method perform_update (line 77) | def perform_update(self, serializer):
    method partial_update (line 80) | def partial_update(self, request, *args, **kwargs):
  class DestroyModelMixin (line 85) | class DestroyModelMixin:
    method destroy (line 89) | def destroy(self, request, *args, **kwargs):
    method perform_destroy (line 94) | def perform_destroy(self, instance):

FILE: rest_framework/negotiation.py
  class BaseContentNegotiation (line 14) | class BaseContentNegotiation:
    method select_parser (line 15) | def select_parser(self, request, parsers):
    method select_renderer (line 18) | def select_renderer(self, request, renderers, format_suffix=None):
  class DefaultContentNegotiation (line 22) | class DefaultContentNegotiation(BaseContentNegotiation):
    method select_parser (line 25) | def select_parser(self, request, parsers):
    method select_renderer (line 35) | def select_renderer(self, request, renderers, format_suffix=None):
    method filter_renderers (line 80) | def filter_renderers(self, renderers, format):
    method get_accept_list (line 91) | def get_accept_list(self, request):

FILE: rest_framework/pagination.py
  function _positive_int (line 23) | def _positive_int(integer_string, strict=False, cutoff=None):
  function _divide_with_ceil (line 35) | def _divide_with_ceil(a, b):
  function _get_displayed_page_numbers (line 45) | def _get_displayed_page_numbers(current, final):
  function _get_page_links (line 96) | def _get_page_links(page_numbers, current, url_func):
  function _reverse_ordering (line 116) | def _reverse_ordering(ordering_tuple):
  class BasePagination (line 133) | class BasePagination:
    method paginate_queryset (line 136) | def paginate_queryset(self, queryset, request, view=None):  # pragma: ...
    method get_paginated_response (line 139) | def get_paginated_response(self, data):  # pragma: no cover
    method get_paginated_response_schema (line 142) | def get_paginated_response_schema(self, schema):
    method to_html (line 145) | def to_html(self):  # pragma: no cover
    method get_results (line 148) | def get_results(self, data):
    method get_schema_operation_parameters (line 151) | def get_schema_operation_parameters(self, view):
  class PageNumberPagination (line 155) | class PageNumberPagination(BasePagination):
    method paginate_queryset (line 188) | def paginate_queryset(self, queryset, request, view=None):
    method get_page_number (line 215) | def get_page_number(self, request, paginator):
    method get_paginated_response (line 221) | def get_paginated_response(self, data):
    method get_paginated_response_schema (line 229) | def get_paginated_response_schema(self, schema):
    method get_page_size (line 256) | def get_page_size(self, request):
    method get_next_link (line 266) | def get_next_link(self):
    method get_previous_link (line 273) | def get_previous_link(self):
    method get_html_context (line 282) | def get_html_context(self):
    method to_html (line 302) | def to_html(self):
    method get_schema_operation_parameters (line 307) | def get_schema_operation_parameters(self, view):
  class LimitOffsetPagination (line 334) | class LimitOffsetPagination(BasePagination):
    method paginate_queryset (line 349) | def paginate_queryset(self, queryset, request, view=None):
    method get_paginated_response (line 364) | def get_paginated_response(self, data):
    method get_paginated_response_schema (line 372) | def get_paginated_response_schema(self, schema):
    method get_limit (line 399) | def get_limit(self, request):
    method get_offset (line 409) | def get_offset(self, request):
    method get_next_link (line 417) | def get_next_link(self):
    method get_previous_link (line 427) | def get_previous_link(self):
    method get_html_context (line 440) | def get_html_context(self):
    method to_html (line 480) | def to_html(self):
    method get_count (line 485) | def get_count(self, queryset):
    method get_schema_operation_parameters (line 494) | def get_schema_operation_parameters(self, view):
  class CursorPagination (line 518) | class CursorPagination(BasePagination):
    method paginate_queryset (line 546) | def paginate_queryset(self, queryset, request, view=None):
    method get_page_size (line 623) | def get_page_size(self, request):
    method get_next_link (line 633) | def get_next_link(self):
    method get_previous_link (line 686) | def get_previous_link(self):
    method get_ordering (line 739) | def get_ordering(self, request, queryset, view):
    method decode_cursor (line 781) | def decode_cursor(self, request):
    method encode_cursor (line 806) | def encode_cursor(self, cursor):
    method _get_position_from_instance (line 822) | def _get_position_from_instance(self, instance, ordering):
    method get_paginated_response (line 830) | def get_paginated_response(self, data):
    method get_paginated_response_schema (line 837) | def get_paginated_response_schema(self, schema):
    method get_html_context (line 860) | def get_html_context(self):
    method to_html (line 866) | def to_html(self):
    method get_schema_operation_parameters (line 871) | def get_schema_operation_parameters(self, view):

FILE: rest_framework/parsers.py
  class DataAndFiles (line 26) | class DataAndFiles:
    method __init__ (line 27) | def __init__(self, data, files):
  class BaseParser (line 32) | class BaseParser:
    method parse (line 39) | def parse(self, stream, media_type=None, parser_context=None):
  class JSONParser (line 48) | class JSONParser(BaseParser):
    method parse (line 56) | def parse(self, stream, media_type=None, parser_context=None):
  class FormParser (line 71) | class FormParser(BaseParser):
    method parse (line 77) | def parse(self, stream, media_type=None, parser_context=None):
  class MultiPartParser (line 87) | class MultiPartParser(BaseParser):
    method parse (line 93) | def parse(self, stream, media_type=None, parser_context=None):
  class FileUploadParser (line 116) | class FileUploadParser(BaseParser):
    method parse (line 126) | def parse(self, stream, media_type=None, parser_context=None):
    method get_filename (line 193) | def get_filename(self, stream, media_type, parser_context):

FILE: rest_framework/permissions.py
  class OperationHolderMixin (line 11) | class OperationHolderMixin:
    method __and__ (line 12) | def __and__(self, other):
    method __or__ (line 15) | def __or__(self, other):
    method __rand__ (line 18) | def __rand__(self, other):
    method __ror__ (line 21) | def __ror__(self, other):
    method __invert__ (line 24) | def __invert__(self):
  class SingleOperandHolder (line 28) | class SingleOperandHolder(OperationHolderMixin):
    method __init__ (line 29) | def __init__(self, operator_class, op1_class):
    method __call__ (line 33) | def __call__(self, *args, **kwargs):
  class OperandHolder (line 38) | class OperandHolder(OperationHolderMixin):
    method __init__ (line 39) | def __init__(self, operator_class, op1_class, op2_class):
    method __call__ (line 44) | def __call__(self, *args, **kwargs):
    method __eq__ (line 49) | def __eq__(self, other):
    method __hash__ (line 57) | def __hash__(self):
  class AND (line 61) | class AND:
    method __init__ (line 62) | def __init__(self, op1, op2):
    method has_permission (line 66) | def has_permission(self, request, view):
    method has_object_permission (line 72) | def has_object_permission(self, request, view, obj):
  class OR (line 79) | class OR:
    method __init__ (line 80) | def __init__(self, op1, op2):
    method has_permission (line 84) | def has_permission(self, request, view):
    method has_object_permission (line 90) | def has_object_permission(self, request, view, obj):
  class NOT (line 100) | class NOT:
    method __init__ (line 101) | def __init__(self, op1):
    method has_permission (line 104) | def has_permission(self, request, view):
    method has_object_permission (line 107) | def has_object_permission(self, request, view, obj):
  class BasePermissionMetaclass (line 111) | class BasePermissionMetaclass(OperationHolderMixin, type):
  class BasePermission (line 115) | class BasePermission(metaclass=BasePermissionMetaclass):
    method has_permission (line 120) | def has_permission(self, request, view):
    method has_object_permission (line 126) | def has_object_permission(self, request, view, obj):
  class AllowAny (line 133) | class AllowAny(BasePermission):
    method has_permission (line 141) | def has_permission(self, request, view):
  class IsAuthenticated (line 145) | class IsAuthenticated(BasePermission):
    method has_permission (line 150) | def has_permission(self, request, view):
  class IsAdminUser (line 154) | class IsAdminUser(BasePermission):
    method has_permission (line 159) | def has_permission(self, request, view):
  class IsAuthenticatedOrReadOnly (line 163) | class IsAuthenticatedOrReadOnly(BasePermission):
    method has_permission (line 168) | def has_permission(self, request, view):
  class DjangoModelPermissions (line 176) | class DjangoModelPermissions(BasePermission):
    method get_required_permissions (line 203) | def get_required_permissions(self, method, model_cls):
    method _queryset (line 218) | def _queryset(self, view):
    method has_permission (line 233) | def has_permission(self, request, view):
  class DjangoModelPermissionsOrAnonReadOnly (line 249) | class DjangoModelPermissionsOrAnonReadOnly(DjangoModelPermissions):
  class DjangoObjectPermissions (line 257) | class DjangoObjectPermissions(DjangoModelPermissions):
    method get_required_object_permissions (line 278) | def get_required_object_permissions(self, method, model_cls):
    method has_object_permission (line 289) | def has_object_permission(self, request, view, obj):

FILE: rest_framework/relations.py
  function method_overridden (line 21) | def method_overridden(method_name, klass, instance):
  class ObjectValueError (line 30) | class ObjectValueError(ValueError):
  class ObjectTypeError (line 37) | class ObjectTypeError(TypeError):
  class Hyperlink (line 44) | class Hyperlink(str):
    method __new__ (line 50) | def __new__(cls, url, obj):
    method __getnewargs__ (line 55) | def __getnewargs__(self):
    method name (line 59) | def name(self):
  class PKOnlyObject (line 68) | class PKOnlyObject:
    method __init__ (line 75) | def __init__(self, pk):
    method __str__ (line 78) | def __str__(self):
  class RelatedField (line 91) | class RelatedField(Field):
    method __init__ (line 96) | def __init__(self, **kwargs):
    method __new__ (line 121) | def __new__(cls, *args, **kwargs):
    method many_init (line 129) | def many_init(cls, *args, **kwargs):
    method run_validation (line 151) | def run_validation(self, data=empty):
    method get_queryset (line 157) | def get_queryset(self):
    method use_pk_only_optimization (line 169) | def use_pk_only_optimization(self):
    method get_attribute (line 172) | def get_attribute(self, instance):
    method get_choices (line 191) | def get_choices(self, cutoff=None):
    method choices (line 206) | def choices(self):
    method grouped_choices (line 210) | def grouped_choices(self):
    method iter_options (line 213) | def iter_options(self):
    method display_value (line 220) | def display_value(self, instance):
  class StringRelatedField (line 224) | class StringRelatedField(RelatedField):
    method __init__ (line 230) | def __init__(self, **kwargs):
    method to_representation (line 234) | def to_representation(self, value):
  class PrimaryKeyRelatedField (line 238) | class PrimaryKeyRelatedField(RelatedField):
    method __init__ (line 245) | def __init__(self, **kwargs):
    method use_pk_only_optimization (line 249) | def use_pk_only_optimization(self):
    method to_internal_value (line 252) | def to_internal_value(self, data):
    method to_representation (line 265) | def to_representation(self, value):
  class HyperlinkedRelatedField (line 271) | class HyperlinkedRelatedField(RelatedField):
    method __init__ (line 283) | def __init__(self, view_name=None, **kwargs):
    method use_pk_only_optimization (line 298) | def use_pk_only_optimization(self):
    method get_object (line 301) | def get_object(self, view_name, view_args, view_kwargs):
    method get_url (line 321) | def get_url(self, obj, view_name, request, format):
    method to_internal_value (line 336) | def to_internal_value(self, data):
    method to_representation (line 372) | def to_representation(self, value):
  class HyperlinkedIdentityField (line 419) | class HyperlinkedIdentityField(HyperlinkedRelatedField):
    method __init__ (line 427) | def __init__(self, view_name=None, **kwargs):
    method use_pk_only_optimization (line 433) | def use_pk_only_optimization(self):
  class SlugRelatedField (line 439) | class SlugRelatedField(RelatedField):
    method __init__ (line 449) | def __init__(self, slug_field=None, **kwargs):
    method to_internal_value (line 454) | def to_internal_value(self, data):
    method to_representation (line 463) | def to_representation(self, obj):
  class ManyRelatedField (line 471) | class ManyRelatedField(Field):
    method __init__ (line 492) | def __init__(self, child_relation=None, *args, **kwargs):
    method get_value (line 509) | def get_value(self, dictionary):
    method to_internal_value (line 521) | def to_internal_value(self, data):
    method get_attribute (line 532) | def get_attribute(self, instance):
    method to_representation (line 563) | def to_representation(self, iterable):
    method get_choices (line 569) | def get_choices(self, cutoff=None):
    method choices (line 573) | def choices(self):
    method grouped_choices (line 577) | def grouped_choices(self):
    method iter_options (line 580) | def iter_options(self):

FILE: rest_framework/renderers.py
  function zero_as_none (line 35) | def zero_as_none(value):
  class BaseRenderer (line 39) | class BaseRenderer:
    method render (line 49) | def render(self, data, accepted_media_type=None, renderer_context=None):
  class JSONRenderer (line 53) | class JSONRenderer(BaseRenderer):
    method get_indent (line 70) | def get_indent(self, accepted_media_type, renderer_context):
    method render (line 82) | def render(self, data, accepted_media_type=None, renderer_context=None):
  class TemplateHTMLRenderer (line 110) | class TemplateHTMLRenderer(BaseRenderer):
    method render (line 138) | def render(self, data, accepted_media_type=None, renderer_context=None):
    method resolve_template (line 166) | def resolve_template(self, template_names):
    method get_template_context (line 169) | def get_template_context(self, data, renderer_context):
    method get_template_names (line 179) | def get_template_names(self, response, view):
    method get_exception_template (line 192) | def get_exception_template(self, response):
  class StaticHTMLRenderer (line 207) | class StaticHTMLRenderer(TemplateHTMLRenderer):
    method render (line 224) | def render(self, data, accepted_media_type=None, renderer_context=None):
  class HTMLFormRenderer (line 240) | class HTMLFormRenderer(BaseRenderer):
    method render_field (line 329) | def render_field(self, field, parent_style):
    method render (line 375) | def render(self, data, accepted_media_type=None, renderer_context=None):
  class BrowsableAPIRenderer (line 397) | class BrowsableAPIRenderer(BaseRenderer):
    method get_default_renderer (line 409) | def get_default_renderer(self, view):
    method get_content (line 425) | def get_content(self, renderer, data,
    method show_form_for_method (line 445) | def show_form_for_method(self, view, method, request, obj):
    method _get_serializer (line 460) | def _get_serializer(self, serializer_class, view_instance, request, *a...
    method get_rendered_html_form (line 468) | def get_rendered_html_form(self, data, view, method, request):
    method render_form_for_serializer (line 532) | def render_form_for_serializer(self, serializer):
    method get_raw_data_form (line 546) | def get_raw_data_form(self, data, view, method, request):
    method get_name (line 620) | def get_name(self, view):
    method get_description (line 623) | def get_description(self, view, status_code):
    method get_breadcrumbs (line 628) | def get_breadcrumbs(self, request):
    method get_extra_actions (line 631) | def get_extra_actions(self, view, status_code):
    method get_filter_form (line 639) | def get_filter_form(self, data, view, request):
    method get_context (line 670) | def get_context(self, data, accepted_media_type, renderer_context):
    method render (line 741) | def render(self, data, accepted_media_type=None, renderer_context=None):
  class AdminRenderer (line 762) | class AdminRenderer(BrowsableAPIRenderer):
    method render (line 766) | def render(self, data, accepted_media_type=None, renderer_context=None):
    method get_context (line 806) | def get_context(self, data, accepted_media_type, renderer_context):
    method get_result_url (line 850) | def get_result_url(self, result, view):
  class MultiPartRenderer (line 871) | class MultiPartRenderer(BaseRenderer):
    method render (line 877) | def render(self, data, accepted_media_type=None, renderer_context=None):
  class OpenAPIRenderer (line 891) | class OpenAPIRenderer(BaseRenderer):
    method __init__ (line 896) | def __init__(self):
    method render (line 899) | def render(self, data, media_type=None, renderer_context=None):
  class JSONOpenAPIRenderer (line 909) | class JSONOpenAPIRenderer(BaseRenderer):
    method render (line 916) | def render(self, data, media_type=None, renderer_context=None):

FILE: rest_framework/request.py
  function is_form_media_type (line 25) | def is_form_media_type(media_type):
  class override_method (line 34) | class override_method:
    method __init__ (line 45) | def __init__(self, view, request, method):
    method __enter__ (line 51) | def __enter__(self):
    method __exit__ (line 58) | def __exit__(self, *args, **kwarg):
  class WrappedAttributeError (line 63) | class WrappedAttributeError(Exception):
  function wrap_attributeerrors (line 68) | def wrap_attributeerrors():
  class Empty (line 81) | class Empty:
  function _hasattr (line 89) | def _hasattr(obj, name):
  function clone_request (line 93) | def clone_request(request, method):
  class ForcedAuthentication (line 126) | class ForcedAuthentication:
    method __init__ (line 132) | def __init__(self, force_user, force_token):
    method authenticate (line 136) | def authenticate(self, request):
  class Request (line 140) | class Request:
    method __init__ (line 152) | def __init__(self, request, parsers=None, authenticators=None,
    method __repr__ (line 182) | def __repr__(self):
    method __class_getitem__ (line 190) | def __class_getitem__(cls, *args, **kwargs):
    method _default_negotiator (line 193) | def _default_negotiator(self):
    method content_type (line 197) | def content_type(self):
    method stream (line 202) | def stream(self):
    method query_params (line 211) | def query_params(self):
    method data (line 218) | def data(self):
    method user (line 225) | def user(self):
    method user (line 236) | def user(self, value):
    method auth (line 249) | def auth(self):
    method auth (line 260) | def auth(self, value):
    method successful_authenticator (line 269) | def successful_authenticator(self):
    method _load_data_and_files (line 279) | def _load_data_and_files(self):
    method _load_stream (line 297) | def _load_stream(self):
    method _supports_form_parsing (line 316) | def _supports_form_parsing(self):
    method _parse (line 326) | def _parse(self):
    method _authenticate (line 378) | def _authenticate(self):
    method _not_authenticated (line 397) | def _not_authenticated(self):
    method __getattr__ (line 415) | def __getattr__(self, attr):
    method POST (line 427) | def POST(self):
    method FILES (line 437) | def FILES(self):
    method force_plaintext_errors (line 446) | def force_plaintext_errors(self, value):

FILE: rest_framework/response.py
  class Response (line 14) | class Response(SimpleTemplateResponse):
    method __init__ (line 20) | def __init__(self, data=None, status=None,
    method __class_getitem__ (line 50) | def __class_getitem__(cls, *args, **kwargs):
    method rendered_content (line 54) | def rendered_content(self):
    method status_text (line 88) | def status_text(self):
    method __getstate__ (line 95) | def __getstate__(self):

FILE: rest_framework/reverse.py
  function preserve_builtin_query_params (line 12) | def preserve_builtin_query_params(url, request=None):
  function reverse (line 32) | def reverse(viewname, args=None, kwargs=None, request=None, format=None,...
  function _reverse (line 52) | def _reverse(viewname, args=None, kwargs=None, request=None, format=None...

FILE: rest_framework/routers.py
  function escape_curly_brackets (line 34) | def escape_curly_brackets(url_path):
  function flatten (line 41) | def flatten(list_of_lists):
  class BaseRouter (line 48) | class BaseRouter:
    method __init__ (line 49) | def __init__(self):
    method register (line 52) | def register(self, prefix, viewset, basename=None):
    method is_already_registered (line 67) | def is_already_registered(self, new_basename):
    method get_default_basename (line 73) | def get_default_basename(self, viewset):
    method get_urls (line 80) | def get_urls(self):
    method urls (line 87) | def urls(self):
  class SimpleRouter (line 93) | class SimpleRouter(BaseRouter):
    method __init__ (line 138) | def __init__(self, trailing_slash=True, use_regex_path=True):
    method get_default_basename (line 163) | def get_default_basename(self, viewset):
    method get_routes (line 176) | def get_routes(self, viewset):
    method _get_dynamic_route (line 212) | def _get_dynamic_route(self, route, action):
    method get_method_map (line 226) | def get_method_map(self, viewset, method_map):
    method get_lookup_regex (line 238) | def get_lookup_regex(self, viewset, lookup_prefix=''):
    method get_urls (line 266) | def get_urls(self):
  class APIRootView (line 314) | class APIRootView(views.APIView):
    method get (line 322) | def get(self, request, *args, **kwargs):
  class DefaultRouter (line 344) | class DefaultRouter(SimpleRouter):
    method __init__ (line 357) | def __init__(self, *args, **kwargs):
    method get_api_root_view (line 364) | def get_api_root_view(self, api_urls=None):
    method get_urls (line 375) | def get_urls(self):

FILE: rest_framework/schemas/__init__.py
  function get_schema_view (line 29) | def get_schema_view(

FILE: rest_framework/schemas/generators.py
  function get_pk_name (line 21) | def get_pk_name(model):
  function is_api_view (line 26) | def is_api_view(callback):
  function endpoint_ordering (line 36) | def endpoint_ordering(endpoint):
  class EndpointEnumerator (line 53) | class EndpointEnumerator:
    method __init__ (line 57) | def __init__(self, patterns=None, urlconf=None):
    method get_api_endpoints (line 72) | def get_api_endpoints(self, patterns=None, prefix=''):
    method get_path_from_regex (line 100) | def get_path_from_regex(self, path_regex):
    method should_include_endpoint (line 113) | def should_include_endpoint(self, path, callback):
    method get_allowed_methods (line 132) | def get_allowed_methods(self, callback):
  class BaseSchemaGenerator (line 146) | class BaseSchemaGenerator:
    method __init__ (line 154) | def __init__(self, title=None, url=None, description=None, patterns=No...
    method _initialise_endpoints (line 168) | def _initialise_endpoints(self):
    method _get_paths_and_endpoints (line 173) | def _get_paths_and_endpoints(self, request):
    method create_view (line 187) | def create_view(self, callback, method, request=None):
    method coerce_path (line 210) | def coerce_path(self, path, method, view):
    method get_schema (line 225) | def get_schema(self, request=None, public=False):
    method has_view_permissions (line 228) | def has_view_permissions(self, path, method, view):

FILE: rest_framework/schemas/inspectors.py
  class ViewInspector (line 15) | class ViewInspector:
    method __init__ (line 25) | def __init__(self):
    method __get__ (line 28) | def __get__(self, instance, owner):
    method __set__ (line 50) | def __set__(self, instance, other):
    method view (line 56) | def view(self):
    method view (line 65) | def view(self, value):
    method view (line 69) | def view(self):
    method get_description (line 72) | def get_description(self, path, method):
    method _get_description_section (line 91) | def _get_description_section(self, view, header, description):
  class DefaultSchema (line 113) | class DefaultSchema(ViewInspector):
    method __get__ (line 115) | def __get__(self, instance, owner):

FILE: rest_framework/schemas/openapi.py
  class SchemaGenerator (line 24) | class SchemaGenerator(BaseSchemaGenerator):
    method get_info (line 26) | def get_info(self):
    method check_duplicate_operation_id (line 38) | def check_duplicate_operation_id(self, paths):
    method get_schema (line 64) | def get_schema(self, request=None, public=False):
  class AutoSchema (line 116) | class AutoSchema(ViewInspector):
    method __init__ (line 118) | def __init__(self, tags=None, operation_id_base=None, component_name=N...
    method get_operation (line 141) | def get_operation(self, path, method):
    method get_component_name (line 161) | def get_component_name(self, serializer):
    method get_components (line 184) | def get_components(self, path, method):
    method _to_camel_case (line 209) | def _to_camel_case(self, snake_str):
    method get_operation_id_base (line 215) | def get_operation_id_base(self, path, method, action):
    method get_operation_id (line 253) | def get_operation_id(self, path, method):
    method get_path_parameters (line 269) | def get_path_parameters(self, path, method):
    method get_filter_parameters (line 305) | def get_filter_parameters(self, path, method):
    method allows_filters (line 313) | def allows_filters(self, path, method):
    method get_pagination_parameters (line 326) | def get_pagination_parameters(self, path, method):
    method map_choicefield (line 338) | def map_choicefield(self, field):
    method map_field (line 366) | def map_field(self, field):
    method _map_min_max (line 510) | def _map_min_max(self, field, content):
    method map_serializer (line 516) | def map_serializer(self, serializer):
    method map_field_validators (line 552) | def map_field_validators(self, field, schema):
    method get_field_name (line 592) | def get_field_name(self, field):
    method get_paginator (line 599) | def get_paginator(self):
    method map_parsers (line 605) | def map_parsers(self, path, method):
    method map_renderers (line 608) | def map_renderers(self, path, method):
    method get_serializer (line 617) | def get_serializer(self, path, method):
    method get_request_serializer (line 632) | def get_request_serializer(self, path, method):
    method get_response_serializer (line 639) | def get_response_serializer(self, path, method):
    method get_reference (line 646) | def get_reference(self, serializer):
    method get_request_body (line 649) | def get_request_body(self, path, method):
    method get_responses (line 669) | def get_responses(self, path, method):
    method get_tags (line 710) | def get_tags(self, path, method):

FILE: rest_framework/schemas/utils.py
  function is_list_view (line 12) | def is_list_view(path, method, view):
  function get_pk_description (line 30) | def get_pk_description(model, model_field):

FILE: rest_framework/schemas/views.py
  class SchemaView (line 12) | class SchemaView(APIView):
    method __init__ (line 19) | def __init__(self, *args, **kwargs):
    method get (line 29) | def get(self, request, *args, **kwargs):
    method handle_exception (line 35) | def handle_exception(self, exc):

FILE: rest_framework/serializers.py
  class BaseSerializer (line 89) | class BaseSerializer(Field):
    method __init__ (line 114) | def __init__(self, instance=None, data=empty, **kwargs):
    method __new__ (line 123) | def __new__(cls, *args, **kwargs):
    method __class_getitem__ (line 131) | def __class_getitem__(cls, *args, **kwargs):
    method many_init (line 135) | def many_init(cls, *args, **kwargs):
    method to_internal_value (line 165) | def to_internal_value(self, data):
    method to_representation (line 168) | def to_representation(self, instance):
    method update (line 171) | def update(self, instance, validated_data):
    method create (line 174) | def create(self, validated_data):
    method save (line 177) | def save(self, **kwargs):
    method is_valid (line 217) | def is_valid(self, *, raise_exception=False):
    method data (line 238) | def data(self):
    method errors (line 259) | def errors(self):
    method validated_data (line 266) | def validated_data(self):
  class SerializerMetaclass (line 276) | class SerializerMetaclass(type):
    method _get_declared_fields (line 286) | def _get_declared_fields(cls, bases, attrs):
    method __new__ (line 309) | def __new__(cls, name, bases, attrs):
  function as_serializer_error (line 314) | def as_serializer_error(exc):
  class Serializer (line 352) | class Serializer(BaseSerializer, metaclass=SerializerMetaclass):
    method set_value (line 357) | def set_value(self, dictionary, keys, value):
    method fields (line 378) | def fields(self):
    method _writable_fields (line 391) | def _writable_fields(self):
    method _readable_fields (line 397) | def _readable_fields(self):
    method get_fields (line 402) | def get_fields(self):
    method get_validators (line 411) | def get_validators(self):
    method get_initial (line 420) | def get_initial(self):
    method get_value (line 439) | def get_value(self, dictionary):
    method run_validation (line 446) | def run_validation(self, data=empty):
    method _read_only_defaults (line 466) | def _read_only_defaults(self):
    method run_validators (line 482) | def run_validators(self, value):
    method to_internal_value (line 493) | def to_internal_value(self, data):
    method to_representation (line 530) | def to_representation(self, instance):
    method validate (line 556) | def validate(self, attrs):
    method __repr__ (line 559) | def __repr__(self):
    method __iter__ (line 566) | def __iter__(self):
    method __getitem__ (line 570) | def __getitem__(self, key):
    method data (line 584) | def data(self):
    method errors (line 589) | def errors(self):
  class ListSerializer (line 602) | class ListSerializer(BaseSerializer):
    method __init__ (line 613) | def __init__(self, *args, **kwargs):
    method get_initial (line 623) | def get_initial(self):
    method get_value (line 628) | def get_value(self, dictionary):
    method run_validation (line 638) | def run_validation(self, data=empty):
    method run_child_validation (line 658) | def run_child_validation(self, data):
    method to_internal_value (line 669) | def to_internal_value(self, data):
    method to_representation (line 719) | def to_representation(self, data):
    method validate (line 731) | def validate(self, attrs):
    method update (line 734) | def update(self, instance, validated_data):
    method create (line 743) | def create(self, validated_data):
    method save (line 748) | def save(self, **kwargs):
    method is_valid (line 779) | def is_valid(self, *, raise_exception=False):
    method __repr__ (line 801) | def __repr__(self):
    method data (line 808) | def data(self):
    method errors (line 813) | def errors(self):
  function raise_errors_on_nested_writes (line 828) | def raise_errors_on_nested_writes(method_name, serializer, validated_data):
  class ModelSerializer (line 910) | class ModelSerializer(Serializer):
    method create (line 976) | def create(self, validated_data):
    method update (line 1040) | def update(self, instance, validated_data):
    method get_fields (line 1068) | def get_fields(self):
    method get_field_names (line 1151) | def get_field_names(self, declared_fields, info):
    method get_default_field_names (line 1243) | def get_default_field_names(self, declared_fields, model_info):
    method build_field (line 1257) | def build_field(self, field_name, info, model_class, nested_depth):
    method build_standard_field (line 1280) | def build_standard_field(self, field_name, model_field):
    method build_relational_field (line 1341) | def build_relational_field(self, field_name, relation_info):
    method build_nested_field (line 1359) | def build_nested_field(self, field_name, relation_info, nested_depth):
    method build_property_field (line 1374) | def build_property_field(self, field_name, model_class):
    method build_url_field (line 1383) | def build_url_field(self, field_name, model_class):
    method build_unknown_field (line 1392) | def build_unknown_field(self, field_name, model_class):
    method include_extra_kwargs (line 1401) | def include_extra_kwargs(self, kwargs, extra_kwargs):
    method get_extra_kwargs (line 1425) | def get_extra_kwargs(self):
    method get_unique_together_constraints (line 1455) | def get_unique_together_constraints(self, model):
    method get_uniqueness_extra_kwargs (line 1472) | def get_uniqueness_extra_kwargs(self, field_names, declared_fields, ex...
    method _get_model_fields (line 1549) | def _get_model_fields(self, field_names, declared_fields, extra_kwargs):
    method get_validators (line 1584) | def get_validators(self):
    method _get_constraint_violation_error_message (line 1599) | def _get_constraint_violation_error_message(self, constraint):
    method get_unique_together_validators (line 1610) | def get_unique_together_validators(self):
    method get_unique_for_date_validators (line 1684) | def get_unique_for_date_validators(self):
  class HyperlinkedModelSerializer (line 1726) | class HyperlinkedModelSerializer(ModelSerializer):
    method get_default_field_names (line 1736) | def get_default_field_names(self, declared_fields, model_info):
    method build_nested_field (line 1748) | def build_nested_field(self, field_name, relation_info, nested_depth):

FILE: rest_framework/settings.py
  function perform_import (line 163) | def perform_import(val, setting_name):
  function import_from_string (line 177) | def import_from_string(val, setting_name):
  class APISettings (line 188) | class APISettings:
    method __init__ (line 204) | def __init__(self, user_settings=None, defaults=None, import_strings=N...
    method user_settings (line 212) | def user_settings(self):
    method __getattr__ (line 217) | def __getattr__(self, attr):
    method __check_user_settings (line 237) | def __check_user_settings(self, user_settings):
    method reload (line 244) | def reload(self):
  function reload_api_settings (line 255) | def reload_api_settings(*args, **kwargs):

FILE: rest_framework/static/rest_framework/js/ajax-form.js
  function replaceDocument (line 1) | function replaceDocument(docString) {
  function doAjaxSubmit (line 14) | function doAjaxSubmit(e) {
  function captureSubmittingElement (line 119) | function captureSubmittingElement(e) {

FILE: rest_framework/static/rest_framework/js/csrf.js
  function getCookie (line 1) | function getCookie(name) {
  function csrfSafeMethod (line 21) | function csrfSafeMethod(method) {
  function sameOrigin (line 26) | function sameOrigin(url) {

FILE: rest_framework/static/rest_framework/js/prettify-min.js
  function L (line 2) | function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92)return f;var...
  function M (line 6) | function M(a){function m(a){switch(a.nodeType){case 1:if(e.test(a.classN...
  function B (line 7) | function B(a,m,e,h){m&&(a={a:m,d:a},e(a),h.push.apply(h,a.e))}
  function x (line 7) | function x(a,m){function e(a){for(var l=a.d,p=[l,"pln"],d=0,g=a.a.match(...
  function u (line 9) | function u(a){var m=[],e=[];a.tripleQuotedStrings?m.push(["str",/^(?:'''...
  function D (line 12) | function D(a,m){function e(a){switch(a.nodeType){case 1:if(k.test(a.clas...
  function k (line 15) | function k(a,m){for(var e=m.length;--e>=0;){var h=m[e];A.hasOwnProperty(...
  function C (line 15) | function C(a,m){if(!a||!A.hasOwnProperty(a))a=/^\s*</.test(m)?"default-m...
  function E (line 15) | function E(a){var m=
  function m (line 25) | function m(){for(var e=window.PR_SHOULD_USE_CONTINUATION?l.now()+250:Inf...

FILE: rest_framework/status.py
  function is_informational (line 10) | def is_informational(code):
  function is_success (line 14) | def is_success(code):
  function is_redirect (line 18) | def is_redirect(code):
  function is_client_error (line 22) | def is_client_error(code):
  function is_server_error (line 26) | def is_server_error(code):

FILE: rest_framework/templatetags/rest_framework.py
  function highlight_code (line 21) | def highlight_code(parser, token):
  class CodeNode (line 28) | class CodeNode(template.Node):
    method __init__ (line 31) | def __init__(self, lang, code):
    method render (line 35) | def render(self, context):
  function render_markdown (line 41) | def render_markdown(markdown_text):
  function get_pagination_html (line 48) | def get_pagination_html(pager):
  function render_form (line 53) | def render_form(serializer, template_pack=None):
  function render_field (line 60) | def render_field(field, style):
  function optional_login (line 66) | def optional_login(request):
  function optional_docs_login (line 82) | def optional_docs_login(request):
  function optional_logout (line 98) | def optional_logout(request, user, csrf_token):
  function add_query_param (line 128) | def add_query_param(request, key, val):
  function as_string (line 138) | def as_string(value):
  function as_list_of_strings (line 145) | def as_list_of_strings(value):
  function add_class (line 153) | def add_class(value, css_class):
  function format_value (line 182) | def format_value(value):
  function items (line 213) | def items(value):
  function add_nested_class (line 228) | def add_nested_class(value):
  function smart_urlquote_wrapper (line 246) | def smart_urlquote_wrapper(matched_url):

FILE: rest_framework/test.py
  function force_authenticate (line 20) | def force_authenticate(request, user=None, token=None):
  class HeaderDict (line 26) | class HeaderDict(requests.packages.urllib3._collections.HTTPHeaderDict):
    method get_all (line 27) | def get_all(self, key, default):
  class MockOriginalResponse (line 30) | class MockOriginalResponse:
    method __init__ (line 31) | def __init__(self, headers):
    method isclosed (line 35) | def isclosed(self):
    method close (line 38) | def close(self):
  class DjangoTestAdapter (line 41) | class DjangoTestAdapter(requests.adapters.HTTPAdapter):
    method __init__ (line 46) | def __init__(self):
    method get_environ (line 50) | def get_environ(self, request):
    method send (line 76) | def send(self, request, *args, **kwargs):
    method close (line 102) | def close(self):
  class RequestsClient (line 105) | class RequestsClient(requests.Session):
    method __init__ (line 106) | def __init__(self, *args, **kwargs):
    method request (line 112) | def request(self, method, url, *args, **kwargs):
  function RequestsClient (line 118) | def RequestsClient(*args, **kwargs):
    method __init__ (line 106) | def __init__(self, *args, **kwargs):
    method request (line 112) | def request(self, method, url, *args, **kwargs):
  class APIRequestFactory (line 122) | class APIRequestFactory(DjangoRequestFactory):
    method __init__ (line 126) | def __init__(self, enforce_csrf_checks=False, **defaults):
    method _encode_data (line 133) | def _encode_data(self, data, format=None, content_type=None):
    method get (line 182) | def get(self, path, data=None, **extra):
    method post (line 195) | def post(self, path, data=None, format=None, content_type=None, **extra):
    method put (line 199) | def put(self, path, data=None, format=None, content_type=None, **extra):
    method patch (line 203) | def patch(self, path, data=None, format=None, content_type=None, **ext...
    method delete (line 207) | def delete(self, path, data=None, format=None, content_type=None, **ex...
    method options (line 211) | def options(self, path, data=None, format=None, content_type=None, **e...
    method generic (line 215) | def generic(self, method, path, data='',
    method request (line 224) | def request(self, **kwargs):
  class ForceAuthClientHandler (line 230) | class ForceAuthClientHandler(ClientHandler):
    method __init__ (line 236) | def __init__(self, *args, **kwargs):
    method get_response (line 241) | def get_response(self, request):
  class APIClient (line 248) | class APIClient(APIRequestFactory, DjangoClient):
    method __init__ (line 249) | def __init__(self, enforce_csrf_checks=False, **defaults):
    method credentials (line 254) | def credentials(self, **kwargs):
    method force_authenticate (line 260) | def force_authenticate(self, user=None, token=None):
    method request (line 270) | def request(self, **kwargs):
    method get (line 275) | def get(self, path, data=None, follow=False, **extra):
    method post (line 281) | def post(self, path, data=None, format=None, content_type=None,
    method put (line 289) | def put(self, path, data=None, format=None, content_type=None,
    method patch (line 297) | def patch(self, path, data=None, format=None, content_type=None,
    method delete (line 305) | def delete(self, path, data=None, format=None, content_type=None,
    method options (line 313) | def options(self, path, data=None, format=None, content_type=None,
    method logout (line 321) | def logout(self):
  class APITransactionTestCase (line 332) | class APITransactionTestCase(testcases.TransactionTestCase):
  class APITestCase (line 336) | class APITestCase(testcases.TestCase):
  class APISimpleTestCase (line 340) | class APISimpleTestCase(testcases.SimpleTestCase):
  class APILiveServerTestCase (line 344) | class APILiveServerTestCase(testcases.LiveServerTestCase):
  function cleanup_url_patterns (line 348) | def cleanup_url_patterns(cls):
  class URLPatternsTestCase (line 355) | class URLPatternsTestCase(testcases.SimpleTestCase):
    method setUpClass (line 372) | def setUpClass(cls):

FILE: rest_framework/throttling.py
  class BaseThrottle (line 12) | class BaseThrottle:
    method allow_request (line 17) | def allow_request(self, request, view):
    method get_ident (line 23) | def get_ident(self, request):
    method wait (line 42) | def wait(self):
  class SimpleRateThrottle (line 50) | class SimpleRateThrottle(BaseThrottle):
    method __init__ (line 68) | def __init__(self):
    method get_cache_key (line 73) | def get_cache_key(self, request, view):
    method get_rate (line 82) | def get_rate(self):
    method parse_rate (line 97) | def parse_rate(self, rate):
    method allow_request (line 109) | def allow_request(self, request, view):
    method throttle_success (line 134) | def throttle_success(self):
    method throttle_failure (line 143) | def throttle_failure(self):
    method wait (line 149) | def wait(self):
  class AnonRateThrottle (line 165) | class AnonRateThrottle(SimpleRateThrottle):
    method get_cache_key (line 173) | def get_cache_key(self, request, view):
  class UserRateThrottle (line 183) | class UserRateThrottle(SimpleRateThrottle):
    method get_cache_key (line 193) | def get_cache_key(self, request, view):
  class ScopedRateThrottle (line 205) | class ScopedRateThrottle(SimpleRateThrottle):
    method __init__ (line 214) | def __init__(self):
    method allow_request (line 219) | def allow_request(self, request, view):
    method get_cache_key (line 235) | def get_cache_key(self, request, view):

FILE: rest_framework/urlpatterns.py
  function _get_format_path_converter (line 8) | def _get_format_path_converter(allowed):
  function _generate_converter_name (line 30) | def _generate_converter_name(allowed):
  function apply_suffix_patterns (line 37) | def apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required, ...
  function format_suffix_patterns (line 85) | def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=N...

FILE: rest_framework/utils/breadcrumbs.py
  function get_breadcrumbs (line 4) | def get_breadcrumbs(url, request=None):

FILE: rest_framework/utils/encoders.py
  class JSONEncoder (line 18) | class JSONEncoder(json.JSONEncoder):
    method default (line 23) | def default(self, obj):
  class CustomScalar (line 73) | class CustomScalar:
    method represent_timedelta (line 79) | def represent_timedelta(cls, dumper, data):

FILE: rest_framework/utils/field_mapping.py
  class ClassLookupDict (line 19) | class ClassLookupDict:
    method __init__ (line 26) | def __init__(self, mapping):
    method __getitem__ (line 29) | def __getitem__(self, key):
    method __setitem__ (line 42) | def __setitem__(self, key, value):
  function needs_label (line 46) | def needs_label(model_field, field_name):
  function get_detail_view_name (line 55) | def get_detail_view_name(model):
  function get_unique_validators (line 65) | def get_unique_validators(field_name, model_field):
  function get_field_kwargs (line 88) | def get_field_kwargs(field_name, model_field):
  function get_relation_kwargs (line 250) | def get_relation_kwargs(field_name, relation_info):
  function get_nested_relation_kwargs (line 307) | def get_nested_relation_kwargs(relation_info):
  function get_url_kwargs (line 314) | def get_url_kwargs(model_field):
  function get_unique_error_message (line 320) | def get_unique_error_message(model_field):

FILE: rest_framework/utils/formatting.py
  function remove_trailing_string (line 13) | def remove_trailing_string(content, trailing):
  function dedent (line 23) | def dedent(content):
  function camelcase_to_spaces (line 48) | def camelcase_to_spaces(content):
  function markup_description (line 58) | def markup_description(description):
  class lazy_format (line 70) | class lazy_format:
    method __init__ (line 80) | def __init__(self, format_string, *args, **kwargs):
    method __str__ (line 86) | def __str__(self):
    method __mod__ (line 92) | def __mod__(self, value):

FILE: rest_framework/utils/html.py
  function is_html_input (line 9) | def is_html_input(dictionary):
  function parse_html_list (line 15) | def parse_html_list(dictionary, prefix='', default=None):
  function parse_html_dict (line 69) | def parse_html_dict(dictionary, prefix=''):

FILE: rest_framework/utils/humanize_datetime.py
  function datetime_formats (line 7) | def datetime_formats(formats):
  function date_formats (line 15) | def date_formats(formats):
  function time_formats (line 20) | def time_formats(formats):
  function humanize_strptime (line 25) | def humanize_strptime(format_string):

FILE: rest_framework/utils/json.py
  function strict_constant (line 12) | def strict_constant(o):
  function dump (line 17) | def dump(*args, **kwargs):
  function dumps (line 23) | def dumps(*args, **kwargs):
  function load (line 29) | def load(*args, **kwargs):
  function loads (line 35) | def loads(*args, **kwargs):

FILE: rest_framework/utils/mediatypes.py
  function media_type_matches (line 9) | def media_type_matches(lhs, rhs):
  function order_by_precedence (line 27) | def order_by_precedence(media_type_lst):
  class _MediaType (line 44) | class _MediaType:
    method __init__ (line 45) | def __init__(self, media_type_str):
    method match (line 50) | def match(self, other):
    method precedence (line 65) | def precedence(self):
    method __str__ (line 77) | def __str__(self):

FILE: rest_framework/utils/model_meta.py
  function get_field_info (line 29) | def get_field_info(model):
  function _get_pk (line 48) | def _get_pk(opts):
  function _get_fields (line 60) | def _get_fields(opts):
  function _get_to_field (line 68) | def _get_to_field(field):
  function _get_forward_relationships (line 72) | def _get_forward_relationships(opts):
  function _get_reverse_relationships (line 104) | def _get_reverse_relationships(opts):
  function _merge_fields_and_pk (line 141) | def _merge_fields_and_pk(pk, fields):
  function _merge_relationships (line 148) | def _merge_relationships(forward_relations, reverse_relations):
  function is_abstract_model (line 152) | def is_abstract_model(model):

FILE: rest_framework/utils/representation.py
  function manager_repr (line 12) | def manager_repr(value):
  function smart_repr (line 26) | def smart_repr(value):
  function field_repr (line 47) | def field_repr(field, force_many=False):
  function serializer_repr (line 70) | def serializer_repr(serializer, indent, force_many=None):
  function list_repr (line 97) | def list_repr(serializer, indent):

FILE: rest_framework/utils/serializer_helpers.py
  class ReturnDict (line 9) | class ReturnDict(dict):
    method __init__ (line 16) | def __init__(self, *args, **kwargs):
    method copy (line 20) | def copy(self):
    method __repr__ (line 23) | def __repr__(self):
    method __reduce__ (line 26) | def __reduce__(self):
    method __or__ (line 32) | def __or__(self, other):
    method __ror__ (line 39) | def __ror__(self, other):
  class ReturnList (line 47) | class ReturnList(list):
    method __init__ (line 54) | def __init__(self, *args, **kwargs):
    method __repr__ (line 58) | def __repr__(self):
    method __reduce__ (line 61) | def __reduce__(self):
  class BoundField (line 67) | class BoundField:
    method __init__ (line 74) | def __init__(self, field, value, errors, prefix=''):
    method __getattr__ (line 81) | def __getattr__(self, attr_name):
    method _proxy_class (line 85) | def _proxy_class(self):
    method __repr__ (line 88) | def __repr__(self):
    method as_form_field (line 93) | def as_form_field(self):
  class JSONBoundField (line 98) | class JSONBoundField(BoundField):
    method as_form_field (line 99) | def as_form_field(self):
  class NestedBoundField (line 114) | class NestedBoundField(BoundField):
    method __init__ (line 121) | def __init__(self, field, value, errors, prefix=''):
    method __iter__ (line 126) | def __iter__(self):
    method __getitem__ (line 130) | def __getitem__(self, key):
    method as_form_field (line 140) | def as_form_field(self):
  class BindingDict (line 150) | class BindingDict(MutableMapping):
    method __init__ (line 159) | def __init__(self, serializer):
    method __setitem__ (line 163) | def __setitem__(self, key, field):
    method __getitem__ (line 167) | def __getitem__(self, key):
    method __delitem__ (line 170) | def __delitem__(self, key):
    method __iter__ (line 173) | def __iter__(self):
    method __len__ (line 176) | def __len__(self):
    method __repr__ (line 179) | def __repr__(self):

FILE: rest_framework/utils/timezone.py
  function datetime_exists (line 4) | def datetime_exists(dt):
  function datetime_ambiguous (line 12) | def datetime_ambiguous(dt: datetime):
  function valid_datetime (line 21) | def valid_datetime(dt):

FILE: rest_framework/utils/urls.py
  function replace_query_param (line 6) | def replace_query_param(url, key, val):
  function remove_query_param (line 18) | def remove_query_param(url, key):

FILE: rest_framework/validators.py
  function qs_exists (line 21) | def qs_exists(queryset):
  function qs_exists_with_condition (line 28) | def qs_exists_with_condition(queryset, condition, against):
  function qs_filter (line 39) | def qs_filter(queryset, **kwargs):
  class UniqueValidator (line 46) | class UniqueValidator:
    method __init__ (line 55) | def __init__(self, queryset, message=None, lookup='exact'):
    method filter_queryset (line 60) | def filter_queryset(self, value, queryset, field_name):
    method exclude_current_instance (line 67) | def exclude_current_instance(self, queryset, instance):
    method __call__ (line 76) | def __call__(self, value, serializer_field):
    method __repr__ (line 89) | def __repr__(self):
    method __eq__ (line 95) | def __eq__(self, other):
  class UniqueTogetherValidator (line 105) | class UniqueTogetherValidator:
    method __init__ (line 116) | def __init__(self, queryset, fields, message=None, condition_fields=No...
    method enforce_required_fields (line 124) | def enforce_required_fields(self, attrs, serializer):
    method filter_queryset (line 140) | def filter_queryset(self, attrs, queryset, serializer):
    method exclude_current_instance (line 164) | def exclude_current_instance(self, attrs, queryset, instance):
    method __call__ (line 173) | def __call__(self, attrs, serializer):
    method __repr__ (line 205) | def __repr__(self):
    method __eq__ (line 214) | def __eq__(self, other):
  class ProhibitSurrogateCharactersValidator (line 226) | class ProhibitSurrogateCharactersValidator:
    method __call__ (line 230) | def __call__(self, value):
    method __eq__ (line 236) | def __eq__(self, other):
  class BaseUniqueForValidator (line 244) | class BaseUniqueForValidator:
    method __init__ (line 249) | def __init__(self, queryset, field, date_field, message=None):
    method enforce_required_fields (line 255) | def enforce_required_fields(self, attrs):
    method filter_queryset (line 268) | def filter_queryset(self, attrs, queryset, field_name, date_field_name):
    method exclude_current_instance (line 271) | def exclude_current_instance(self, attrs, queryset, instance):
    method __call__ (line 280) | def __call__(self, attrs, serializer):
    method __eq__ (line 296) | def __eq__(self, other):
    method __repr__ (line 307) | def __repr__(self):
  class UniqueForDateValidator (line 316) | class UniqueForDateValidator(BaseUniqueForValidator):
    method filter_queryset (line 319) | def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  class UniqueForMonthValidator (line 331) | class UniqueForMonthValidator(BaseUniqueForValidator):
    method filter_queryset (line 334) | def filter_queryset(self, attrs, queryset, field_name, date_field_name):
  class UniqueForYearValidator (line 344) | class UniqueForYearValidator(BaseUniqueForValidator):
    method filter_queryset (line 347) | def filter_queryset(self, attrs, queryset, field_name, date_field_name):

FILE: rest_framework/versioning.py
  class BaseVersioning (line 13) | class BaseVersioning:
    method determine_version (line 18) | def determine_version(self, request, *args, **kwargs):
    method reverse (line 24) | def reverse(self, viewname, args=None, kwargs=None, request=None, form...
    method is_allowed_version (line 27) | def is_allowed_version(self, version):
  class AcceptHeaderVersioning (line 34) | class AcceptHeaderVersioning(BaseVersioning):
    method determine_version (line 42) | def determine_version(self, request, *args, **kwargs):
  class URLPathVersioning (line 54) | class URLPathVersioning(BaseVersioning):
    method determine_version (line 73) | def determine_version(self, request, *args, **kwargs):
    method reverse (line 82) | def reverse(self, viewname, args=None, kwargs=None, request=None, form...
  class NamespaceVersioning (line 94) | class NamespaceVersioning(BaseVersioning):
    method determine_version (line 120) | def determine_version(self, request, *args, **kwargs):
    method reverse (line 132) | def reverse(self, viewname, args=None, kwargs=None, request=None, form...
    method get_versioned_viewname (line 139) | def get_versioned_viewname(self, viewname, request):
  class HostNameVersioning (line 143) | class HostNameVersioning(BaseVersioning):
    method determine_version (line 152) | def determine_version(self, request, *args, **kwargs):
  class QueryParameterVersioning (line 166) | class QueryParameterVersioning(BaseVersioning):
    method determine_version (line 174) | def determine_version(self, request, *args, **kwargs):
    method reverse (line 180) | def reverse(self, viewname, args=None, kwargs=None, request=None, form...

FILE: rest_framework/views.py
  function get_view_name (line 23) | def get_view_name(view):
  function get_view_description (line 48) | def get_view_description(view, html=False):
  function set_rollback (line 66) | def set_rollback():
  function exception_handler (line 72) | def exception_handler(exc, context):
  class APIView (line 105) | class APIView(View):
    method as_view (line 123) | def as_view(cls, **initkwargs):
    method allowed_methods (line 153) | def allowed_methods(self):
    method default_response_headers (line 160) | def default_response_headers(self):
    method http_method_not_allowed (line 168) | def http_method_not_allowed(self, request, *args, **kwargs):
    method permission_denied (line 175) | def permission_denied(self, request, message=None, code=None):
    method throttled (line 183) | def throttled(self, request, wait):
    method get_authenticate_header (line 189) | def get_authenticate_header(self, request):
    method get_parser_context (line 198) | def get_parser_context(self, http_request):
    method get_renderer_context (line 211) | def get_renderer_context(self):
    method get_exception_handler_context (line 225) | def get_exception_handler_context(self):
    method get_view_name (line 237) | def get_view_name(self):
    method get_view_description (line 245) | def get_view_description(self, html=False):
    method get_format_suffix (line 255) | def get_format_suffix(self, **kwargs):
    method get_renderers (line 262) | def get_renderers(self):
    method get_parsers (line 268) | def get_parsers(self):
    method get_authenticators (line 274) | def get_authenticators(self):
    method get_permissions (line 280) | def get_permissions(self):
    method get_throttles (line 286) | def get_throttles(self):
    method get_content_negotiator (line 292) | def get_content_negotiator(self):
    method get_exception_handler (line 300) | def get_exception_handler(self):
    method perform_content_negotiation (line 308) | def perform_content_negotiation(self, request, force=False):
    method perform_authentication (line 322) | def perform_authentication(self, request):
    method check_permissions (line 332) | def check_permissions(self, request):
    method check_object_permissions (line 345) | def check_object_permissions(self, request, obj):
    method check_throttles (line 358) | def check_throttles(self, request):
    method determine_version (line 379) | def determine_version(self, request, *args, **kwargs):
    method initialize_request (line 391) | def initialize_request(self, request, *args, **kwargs):
    method initial (line 405) | def initial(self, request, *args, **kwargs):
    method finalize_response (line 424) | def finalize_response(self, request, response, *args, **kwargs):
    method handle_exception (line 454) | def handle_exception(self, exc):
    method raise_uncaught_exception (line 480) | def raise_uncaught_exception(self, exc):
    method dispatch (line 491) | def dispatch(self, request, *args, **kwargs):
    method options (line 520) | def options(self, request, *args, **kwargs):

FILE: rest_framework/viewsets.py
  function _is_extra_action (line 32) | def _is_extra_action(attr):
  function _check_attr_name (line 36) | def _check_attr_name(func, name):
  class ViewSetMixin (line 45) | class ViewSetMixin:
    method as_view (line 59) | def as_view(cls, actions=None, **initkwargs):
    method initialize_request (line 148) | def initialize_request(self, request, *args, **kwargs):
    method reverse_action (line 163) | def reverse_action(self, url_name, *args, **kwargs):
    method get_extra_actions (line 178) | def get_extra_actions(cls):
    method get_extra_action_url_map (line 186) | def get_extra_action_url_map(self):
  class ViewSet (line 220) | class ViewSet(ViewSetMixin, views.APIView):
  class GenericViewSet (line 227) | class GenericViewSet(ViewSetMixin, generics.GenericAPIView):
  class ReadOnlyModelViewSet (line 236) | class ReadOnlyModelViewSet(mixins.RetrieveModelMixin,
  class ModelViewSet (line 245) | class ModelViewSet(mixins.CreateModelMixin,

FILE: runtests.py
  function split_class_and_function (line 8) | def split_class_and_function(string):
  function is_function (line 13) | def is_function(string):
  function is_class (line 18) | def is_class(string):

FILE: tests/authentication/migrations/0001_initial.py
  class Migration (line 5) | class Migration(migrations.Migration):

FILE: tests/authentication/models.py
  class CustomToken (line 5) | class CustomToken(models.Model):

FILE: tests/authentication/test_authentication.py
  class CustomTokenAuthentication (line 28) | class CustomTokenAuthentication(TokenAuthentication):
  class CustomKeywordTokenAuthentication (line 32) | class CustomKeywordTokenAuthentication(TokenAuthentication):
  class MockView (line 36) | class MockView(APIView):
    method get (line 39) | def get(self, request):
    method post (line 42) | def post(self, request):
    method put (line 45) | def put(self, request):
  class BasicAuthTests (line 82) | class BasicAuthTests(TestCase):
    method setUp (line 85) | def setUp(self):
    method test_post_form_passing_basic_auth (line 94) | def test_post_form_passing_basic_auth(self):
    method test_post_json_passing_basic_auth (line 108) | def test_post_json_passing_basic_auth(self):
    method test_post_json_without_password_failing_basic_auth (line 123) | def test_post_json_without_password_failing_basic_auth(self):
    method test_regression_handle_bad_base64_basic_auth_header (line 139) | def test_regression_handle_bad_base64_basic_auth_header(self):
    method test_post_form_failing_basic_auth (line 152) | def test_post_form_failing_basic_auth(self):
    method test_post_json_failing_basic_auth (line 157) | def test_post_json_failing_basic_auth(self):
    method test_fail_post_if_credentials_are_missing (line 167) | def test_fail_post_if_credentials_are_missing(self):
    method test_fail_post_if_credentials_contain_spaces (line 172) | def test_fail_post_if_credentials_contain_spaces(self):
    method test_decoding_of_utf8_credentials (line 179) | def test_decoding_of_utf8_credentials(self):
  class SessionAuthTests (line 200) | class SessionAuthTests(TestCase):
    method setUp (line 203) | def setUp(self):
    method tearDown (line 213) | def tearDown(self):
    method test_login_view_renders_on_get (line 216) | def test_login_view_renders_on_get(self):
    method test_post_form_session_auth_failing_csrf (line 226) | def test_post_form_session_auth_failing_csrf(self):
    method test_post_form_session_auth_passing_csrf (line 234) | def test_post_form_session_auth_passing_csrf(self):
    method test_post_form_session_auth_passing (line 255) | def test_post_form_session_auth_passing(self):
    method test_put_form_session_auth_passing (line 268) | def test_put_form_session_auth_passing(self):
    method test_post_form_session_auth_failing (line 281) | def test_post_form_session_auth_failing(self):
  class BaseTokenAuthTests (line 289) | class BaseTokenAuthTests:
    method setUp (line 295) | def setUp(self):
    method test_post_form_passing_token_auth (line 307) | def test_post_form_passing_token_auth(self):
    method test_fail_authentication_if_user_is_not_active (line 318) | def test_fail_authentication_if_user_is_not_active(self):
    method test_fail_post_form_passing_nonexistent_token_auth (line 329) | def test_fail_post_form_passing_nonexistent_token_auth(self):
    method test_fail_post_if_token_is_missing (line 337) | def test_fail_post_if_token_is_missing(self):
    method test_fail_post_if_token_contains_spaces (line 343) | def test_fail_post_if_token_contains_spaces(self):
    method test_fail_post_form_passing_invalid_token_auth (line 350) | def test_fail_post_form_passing_invalid_token_auth(self):
    method test_post_json_passing_token_auth (line 358) | def test_post_json_passing_token_auth(self):
    method test_post_json_makes_one_db_query (line 370) | def test_post_json_makes_one_db_query(self):
    method test_post_form_failing_token_auth (line 385) | def test_post_form_failing_token_auth(self):
    method test_post_json_failing_token_auth (line 392) | def test_post_json_failing_token_auth(self):
  class TokenAuthTests (line 403) | class TokenAuthTests(BaseTokenAuthTests, TestCase):
    method test_token_has_auto_assigned_key_if_none_provided (line 407) | def test_token_has_auto_assigned_key_if_none_provided(self):
    method test_generate_key_returns_string (line 413) | def test_generate_key_returns_string(self):
    method test_generate_key_accessible_as_classmethod (line 419) | def test_generate_key_accessible_as_classmethod(self):
    method test_generate_key_returns_valid_format (line 423) | def test_generate_key_returns_valid_format(self):
    method test_generate_key_produces_unique_values (line 430) | def test_generate_key_produces_unique_values(self):
    method test_generate_key_collision_resistance (line 438) | def test_generate_key_collision_resistance(self):
    method test_generate_key_randomness_quality (line 447) | def test_generate_key_randomness_quality(self):
    method test_token_login_json (line 458) | def test_token_login_json(self):
    method test_token_login_json_bad_creds (line 469) | def test_token_login_json_bad_creds(self):
    method test_token_login_json_missing_fields (line 482) | def test_token_login_json_missing_fields(self):
    method test_token_login_form (line 489) | def test_token_login_form(self):
  class CustomTokenAuthTests (line 501) | class CustomTokenAuthTests(BaseTokenAuthTests, TestCase):
  class CustomKeywordTokenAuthTests (line 507) | class CustomKeywordTokenAuthTests(BaseTokenAuthTests, TestCase):
  class IncorrectCredentialsTests (line 513) | class IncorrectCredentialsTests(TestCase):
    method test_incorrect_credentials (line 514) | def test_incorrect_credentials(self):
  class FailingAuthAccessedInRenderer (line 535) | class FailingAuthAccessedInRenderer(TestCase):
    method setUp (line 536) | def setUp(self):
    method test_failing_auth_accessed_in_renderer (line 560) | def test_failing_auth_accessed_in_renderer(self):
  class NoAuthenticationClassesTests (line 572) | class NoAuthenticationClassesTests(TestCase):
    method test_permission_message_with_no_authentication_classes (line 573) | def test_permission_message_with_no_authentication_classes(self):
  class BasicAuthenticationUnitTests (line 596) | class BasicAuthenticationUnitTests(TestCase):
    method test_base_authentication_abstract_method (line 598) | def test_base_authentication_abstract_method(self):
    method test_basic_authentication_raises_error_if_user_not_found (line 602) | def test_basic_authentication_raises_error_if_user_not_found(self):
    method test_basic_authentication_raises_error_if_user_not_active (line 607) | def test_basic_authentication_raises_error_if_user_not_active(self):
  class RemoteUserAuthenticationUnitTests (line 626) | class RemoteUserAuthenticationUnitTests(TestCase):
    method setUp (line 627) | def setUp(self):
    method test_remote_user_works (line 635) | def test_remote_user_works(self):

FILE: tests/browsable_api/serializers.py
  class BasicSerializer (line 5) | class BasicSerializer(ModelSerializer):
    class Meta (line 6) | class Meta:

FILE: tests/browsable_api/test_browsable_api.py
  class AnonymousUserTests (line 11) | class AnonymousUserTests(TestCase):
    method setUp (line 14) | def setUp(self):
    method tearDown (line 17) | def tearDown(self):
    method test_get_raises_typeerror_when_anonymous_user_in_queryset_filter (line 20) | def test_get_raises_typeerror_when_anonymous_user_in_queryset_filter(s...
    method test_get_returns_http_forbidden_when_anonymous_user (line 24) | def test_get_returns_http_forbidden_when_anonymous_user(self):
  class DropdownWithAuthTests (line 35) | class DropdownWithAuthTests(TestCase):
    method setUp (line 37) | def setUp(self):
    method tearDown (line 48) | def tearDown(self):
    method test_name_shown_when_logged_in (line 51) | def test_name_shown_when_logged_in(self):
    method test_logout_shown_when_logged_in (line 57) | def test_logout_shown_when_logged_in(self):
    method test_login_shown_when_logged_out (line 63) | def test_login_shown_when_logged_out(self):
    method test_dropdown_contains_logout_form (line 68) | def test_dropdown_contains_logout_form(self):
  class NoDropdownWithoutAuthTests (line 76) | class NoDropdownWithoutAuthTests(TestCase):
    method setUp (line 78) | def setUp(self):
    method tearDown (line 89) | def tearDown(self):
    method test_name_shown_when_logged_in (line 92) | def test_name_shown_when_logged_in(self):
    method test_dropdown_not_shown_when_logged_in (line 98) | def test_dropdown_not_shown_when_logged_in(self):
    method test_dropdown_not_shown_when_logged_out (line 104) | def test_dropdown_not_shown_when_logged_out(self):

FILE: tests/browsable_api/test_browsable_nested_api.py
  class NestedSerializer (line 10) | class NestedSerializer(serializers.Serializer):
  class NestedSerializerTestSerializer (line 15) | class NestedSerializerTestSerializer(serializers.Serializer):
  class NestedSerializersView (line 19) | class NestedSerializersView(ListCreateAPIView):
  class DropdownWithAuthTests (line 30) | class DropdownWithAuthTests(TestCase):
    method test_login (line 34) | def test_login(self):

FILE: tests/browsable_api/test_form_rendering.py
  class BasicSerializer (line 11) | class BasicSerializer(serializers.ModelSerializer):
    class Meta (line 12) | class Meta:
  class StandardPostView (line 17) | class StandardPostView(generics.CreateAPIView):
  class ManyPostView (line 21) | class ManyPostView(generics.GenericAPIView):
    method post (line 26) | def post(self, request, *args, **kwargs):
  class TestPostingListData (line 31) | class TestPostingListData(TestCase):
    method test_json_response (line 39) | def test_json_response(self):
    method test_browsable_api (line 48) | def test_browsable_api(self):
  class TestManyPostView (line 57) | class TestManyPostView(TestCase):
    method setUp (line 58) | def setUp(self):
    method test_post_many_post_view (line 72) | def test_post_many_post_view(self):

FILE: tests/browsable_api/views.py
  class OrganizationPermissions (line 11) | class OrganizationPermissions(BasePermission):
    method has_object_permission (line 12) | def has_object_permission(self, request, view, obj):
  class MockView (line 16) | class MockView(APIView):
    method get (line 20) | def get(self, request):
  class BasicModelWithUsersViewSet (line 24) | class BasicModelWithUsersViewSet(ModelViewSet):
    method get_queryset (line 31) | def get_queryset(self):

FILE: tests/conftest.py
  function pytest_addoption (line 7) | def pytest_addoption(parser):
  function pytest_configure (line 13) | def pytest_configure(config):

FILE: tests/generic_relations/migrations/0001_initial.py
  class Migration (line 4) | class Migration(migrations.Migration):

FILE: tests/generic_relations/models.py
  class Tag (line 8) | class Tag(models.Model):
    method __str__ (line 17) | def __str__(self):
  class Bookmark (line 21) | class Bookmark(models.Model):
    method __str__ (line 28) | def __str__(self):
  class Note (line 32) | class Note(models.Model):
    method __str__ (line 39) | def __str__(self):

FILE: tests/generic_relations/test_generic_relations.py
  class TestGenericRelations (line 8) | class TestGenericRelations(TestCase):
    method setUp (line 9) | def setUp(self):
    method test_generic_relation (line 16) | def test_generic_relation(self):
    method test_generic_fk (line 36) | def test_generic_fk(self):

FILE: tests/importable/__init__.py
  class ExampleSerializer (line 10) | class ExampleSerializer(serializers.Serializer):

FILE: tests/importable/test_installed.py
  function test_installed (line 6) | def test_installed():
  function test_compat (line 11) | def test_compat():
  function test_serializer_fields_initialization (line 15) | def test_serializer_fields_initialization():

FILE: tests/models.py
  class RESTFrameworkModel (line 10) | class RESTFrameworkModel(models.Model):
    class Meta (line 15) | class Meta:
  class BasicModel (line 20) | class BasicModel(RESTFrameworkModel):
  class ManyToManyTarget (line 30) | class ManyToManyTarget(RESTFrameworkModel):
  class ManyToManySource (line 34) | class ManyToManySource(RESTFrameworkModel):
  class BasicModelWithUsers (line 39) | class BasicModelWithUsers(RESTFrameworkModel):
  class ForeignKeyTarget (line 44) | class ForeignKeyTarget(RESTFrameworkModel):
    method get_first_source (line 47) | def get_first_source(self):
    method first_source (line 52) | def first_source(self):
  class UUIDForeignKeyTarget (line 57) | class UUIDForeignKeyTarget(RESTFrameworkModel):
  class ForeignKeySource (line 62) | class ForeignKeySource(RESTFrameworkModel):
  class ForeignKeySourceWithLimitedChoices (line 69) | class ForeignKeySourceWithLimitedChoices(RESTFrameworkModel):
  class ForeignKeySourceWithQLimitedChoices (line 76) | class ForeignKeySourceWithQLimitedChoices(RESTFrameworkModel):
  class NullableForeignKeySource (line 84) | class NullableForeignKeySource(RESTFrameworkModel):
  class NullableUUIDForeignKeySource (line 92) | class NullableUUIDForeignKeySource(RESTFrameworkModel):
  class NestedForeignKeySource (line 100) | class NestedForeignKeySource(RESTFrameworkModel):
  class OneToOneTarget (line 112) | class OneToOneTarget(RESTFrameworkModel):
  class NullableOneToOneSource (line 116) | class NullableOneToOneSource(RESTFrameworkModel):
  class OneToOnePKSource (line 123) | class OneToOnePKSource(RESTFrameworkModel):
  class CustomManagerModel (line 131) | class CustomManagerModel(RESTFrameworkModel):
    class CustomManager (line 132) | class CustomManager:
      method __new__ (line 133) | def __new__(cls, *args, **kwargs):

FILE: tests/schemas/test_get_schema_view.py
  class GetSchemaViewTests (line 7) | class GetSchemaViewTests(TestCase):
    method test_openapi (line 9) | def test_openapi(self):

FILE: tests/schemas/test_managementcommand.py
  class FooView (line 16) | class FooView(APIView):
    method get (line 17) | def get(self, request):
  class CustomSchemaGenerator (line 26) | class CustomSchemaGenerator:
    method __init__ (line 29) | def __init__(self, *args, **kwargs):
    method get_schema (line 32) | def get_schema(self, **kwargs):
  class GenerateSchemaTests (line 38) | class GenerateSchemaTests(TestCase):
    method setUp (line 41) | def setUp(self):
    method test_renders_default_schema_with_custom_title_url_and_description (line 45) | def test_renders_default_schema_with_custom_title_url_and_description(...
    method test_renders_openapi_json_schema (line 55) | def test_renders_openapi_json_schema(self):
    method test_accepts_custom_schema_generator (line 63) | def test_accepts_custom_schema_generator(self):
    method test_writes_schema_to_file_on_parameter (line 70) | def test_writes_schema_to_file_on_parameter(self):

FILE: tests/schemas/test_openapi.py
  function create_request (line 26) | def create_request(path):
  function create_view (line 32) | def create_view(view_cls, method, request):
  class TestBasics (line 38) | class TestBasics(TestCase):
    method dummy_view (line 39) | def dummy_view(request):
    method test_filters (line 42) | def test_filters(self):
    method test_pagination (line 48) | def test_pagination(self):
  class TestFieldMapping (line 55) | class TestFieldMapping(TestCase):
    method test_list_field_mapping (line 56) | def test_list_field_mapping(self):
    method test_lazy_string_field (line 94) | def test_lazy_string_field(self):
    method test_boolean_default_field (line 103) | def test_boolean_default_field(self):
    method test_custom_field_name (line 116) | def test_custom_field_name(self):
    method test_nullable_fields (line 130) | def test_nullable_fields(self):
    method test_primary_key_related_field (line 148) | def test_primary_key_related_field(self):
  class TestOperationIntrospection (line 166) | class TestOperationIntrospection(TestCase):
    method test_path_without_parameters (line 168) | def test_path_without_parameters(self):
    method test_path_with_id_parameter (line 201) | def test_path_with_id_parameter(self):
    method test_request_body (line 240) | def test_request_body(self):
    method test_invalid_serializer_class_name (line 266) | def test_invalid_serializer_class_name(self):
    method test_empty_required (line 291) | def test_empty_required(self):
    method test_empty_required_with_patch_method (line 318) | def test_empty_required_with_patch_method(self):
    method test_response_body_generation (line 344) | def test_response_body_generation(self):
    method test_response_body_nested_serializer (line 371) | def test_response_body_nested_serializer(self):
    method test_response_body_partial_serializer (line 405) | def test_response_body_partial_serializer(self):
    method test_list_response_body_generation (line 455) | def test_list_response_body_generation(self):
    method test_paginated_list_response_body_generation (line 503) | def test_paginated_list_response_body_generation(self):
    method test_delete_response_body_generation (line 562) | def test_delete_response_body_generation(self):
    method test_parser_mapping (line 585) | def test_parser_mapping(self):
    method test_renderer_mapping (line 608) | def test_renderer_mapping(self):
    method test_openapi_yaml_rendering_without_aliases (line 640) | def test_openapi_yaml_rendering_without_aliases(self):
    method test_openapi_yaml_safestring_render (line 653) | def test_openapi_yaml_safestring_render(self):
    method test_serializer_filefield (line 658) | def test_serializer_filefield(self):
    method test_retrieve_response_body_generation (line 681) | def test_retrieve_response_body_generation(self):
    method test_operation_id_generation (line 739) | def test_operation_id_generation(self):
    method test_operation_id_custom_operation_id_base (line 754) | def test_operation_id_custom_operation_id_base(self):
    method test_operation_id_custom_name (line 769) | def test_operation_id_custom_name(self):
    method test_operation_id_plural (line 784) | def test_operation_id_plural(self):
    method test_operation_id_override_get (line 799) | def test_operation_id_override_get(self):
    method test_operation_id_override_base (line 817) | def test_operation_id_override_base(self):
    method test_different_request_response_objects (line 835) | def test_different_request_response_objects(self):
    method test_repeat_operation_ids (line 920) | def test_repeat_operation_ids(self):
    method test_duplicate_operation_id (line 934) | def test_duplicate_operation_id(self):
    method test_operation_id_viewset (line 951) | def test_operation_id_viewset(self):
    method test_serializer_datefield (line 967) | def test_serializer_datefield(self):
    method test_serializer_hstorefield (line 985) | def test_serializer_hstorefield(self):
    method test_serializer_callable_default (line 1001) | def test_serializer_callable_default(self):
    method test_serializer_validators (line 1017) | def test_serializer_validators(self):
    method test_overridden_tags (line 1084) | def test_overridden_tags(self):
    method test_overridden_get_tags_method (line 1095) | def test_overridden_get_tags_method(self):
    method test_auto_generated_apiview_tags (line 1117) | def test_auto_generated_apiview_tags(self):
  class TestGenerator (line 1137) | class TestGenerator(TestCase):
    method test_override_settings (line 1139) | def test_override_settings(self):
    method test_paths_construction (line 1142) | def test_paths_construction(self):
    method test_prefixed_paths_construction (line 1158) | def test_prefixed_paths_construction(self):
    method test_mount_url_prefixed_to_paths (line 1172) | def test_mount_url_prefixed_to_paths(self):
    method test_schema_construction (line 1185) | def test_schema_construction(self):
    method test_schema_rendering_to_json (line 1198) | def test_schema_rendering_to_json(self):
    method test_schema_rendering_to_yaml (line 1211) | def test_schema_rendering_to_yaml(self):
    method test_schema_rendering_timedelta_to_yaml_with_validator (line 1223) | def test_schema_rendering_timedelta_to_yaml_with_validator(self):
    method test_schema_with_no_paths (line 1236) | def test_schema_with_no_paths(self):
    method test_schema_information (line 1245) | def test_schema_information(self):
    method test_schema_information_empty (line 1259) | def test_schema_information_empty(self):
    method test_serializer_model (line 1272) | def test_serializer_model(self):
    method test_authtoken_serializer (line 1287) | def test_authtoken_serializer(self):
    method test_component_name (line 1312) | def test_component_name(self):
    method test_duplicate_component_name (line 1326) | def test_duplicate_component_name(self):
    method test_component_should_not_be_generated_for_delete_method (line 1347) | def test_component_should_not_be_generated_for_delete_method(self):

FILE: tests/schemas/views.py
  class ExampleListView (line 18) | class ExampleListView(APIView):
    method get (line 21) | def get(self, *args, **kwargs):
    method post (line 24) | def post(self, request, *args, **kwargs):
  class ExampleDetailView (line 28) | class ExampleDetailView(APIView):
    method get (line 31) | def get(self, *args, **kwargs):
  class DocStringExampleListView (line 35) | class DocStringExampleListView(APIView):
    method get (line 42) | def get(self, *args, **kwargs):
    method post (line 45) | def post(self, request, *args, **kwargs):
  class DocStringExampleDetailView (line 49) | class DocStringExampleDetailView(APIView):
    method get (line 52) | def get(self, *args, **kwargs):
  class ExampleSerializer (line 60) | class ExampleSerializer(serializers.Serializer):
  class ExampleGenericAPIView (line 68) | class ExampleGenericAPIView(generics.GenericAPIView):
    method get (line 71) | def get(self, *args, **kwargs):
  class ExampleGenericViewSet (line 79) | class ExampleGenericViewSet(GenericViewSet):
    method get (line 82) | def get(self, *args, **kwargs):
    method new (line 90) | def new(self, *args, **kwargs):
    method old (line 94) | def old(self, *args, **kwargs):
  class ExampleValidatedSerializer (line 99) | class ExampleValidatedSerializer(serializers.Serializer):
  class ExampleValidatedAPIView (line 144) | class ExampleValidatedAPIView(generics.GenericAPIView):
    method get (line 147) | def get(self, *args, **kwargs):
  class OpenAPIExample (line 156) | class OpenAPIExample(models.Model):
  class ExampleSerializerModel (line 160) | class ExampleSerializerModel(serializers.Serializer):
    class Meta (line 166) | class Meta:
  class ExampleOperationIdDuplicate1 (line 170) | class ExampleOperationIdDuplicate1(generics.GenericAPIView):
    method get (line 173) | def get(self, *args, **kwargs):
  class ExampleOperationIdDuplicate2 (line 177) | class ExampleOperationIdDuplicate2(generics.GenericAPIView):
    method get (line 180) | def get(self, *args, **kwargs):
  class ExampleGenericAPIViewModel (line 184) | class ExampleGenericAPIViewModel(generics.GenericAPIView):
    method get (line 187) | def get(self, *args, **kwargs):
  class ExampleAutoSchemaComponentName (line 195) | class ExampleAutoSchemaComponentName(generics.GenericAPIView):
    method get (line 199) | def get(self, *args, **kwargs):
  class ExampleAutoSchemaDuplicate1 (line 207) | class ExampleAutoSchemaDuplicate1(generics.GenericAPIView):
    method get (line 211) | def get(self, *args, **kwargs):
  class ExampleAutoSchemaDuplicate2 (line 219) | class ExampleAutoSchemaDuplicate2(generics.GenericAPIView):
    method get (line 223) | def get(self, *args, **kwargs):
  class ExampleViewSet (line 231) | class ExampleViewSet(ViewSet):
    method list (line 234) | def list(self, request):
    method create (line 237) | def create(self, request):
    method retrieve (line 240) | def retrieve(self, request, pk=None):
    method update (line 243) | def update(self, request, pk=None):
    method partial_update (line 246) | def partial_update(self, request, pk=None):
    method destroy (line 249) | def destroy(self, request, pk=None):

FILE: tests/test_atomic_requests.py
  class BasicView (line 18) | class BasicView(APIView):
    method post (line 19) | def post(self, request, *args, **kwargs):
  class ErrorView (line 24) | class ErrorView(APIView):
    method post (line 25) | def post(self, request, *args, **kwargs):
  class APIExceptionView (line 30) | class APIExceptionView(APIView):
    method post (line 31) | def post(self, request, *args, **kwargs):
  class NonAtomicAPIExceptionView (line 36) | class NonAtomicAPIExceptionView(APIView):
    method dispatch (line 38) | def dispatch(self, *args, **kwargs):
    method get (line 41) | def get(self, request, *args, **kwargs):
  class DBTransactionTests (line 55) | class DBTransactionTests(TestCase):
    method setUp (line 56) | def setUp(self):
    method tearDown (line 60) | def tearDown(self):
    method test_no_exception_commit_transaction (line 63) | def test_no_exception_commit_transaction(self):
  class DBTransactionErrorTests (line 77) | class DBTransactionErrorTests(TestCase):
    method setUp (line 78) | def setUp(self):
    method tearDown (line 82) | def tearDown(self):
    method test_generic_exception_delegate_transaction_management (line 85) | def test_generic_exception_delegate_transaction_management(self):
  class DBTransactionAPIExceptionTests (line 107) | class DBTransactionAPIExceptionTests(TestCase):
    method setUp (line 108) | def setUp(self):
    method tearDown (line 112) | def tearDown(self):
    method test_api_exception_rollback_transaction (line 115) | def test_api_exception_rollback_transaction(self):
  class MultiDBTransactionAPIExceptionTests (line 137) | class MultiDBTransactionAPIExceptionTests(TestCase):
    method setUp (line 140) | def setUp(self):
    method tearDown (line 145) | def tearDown(self):
    method test_api_exception_rollback_transaction (line 149) | def test_api_exception_rollback_transaction(self):
  class NonAtomicDBTransactionAPIExceptionTests (line 173) | class NonAtomicDBTransactionAPIExceptionTests(TransactionTestCase):
    method setUp (line 174) | def setUp(self):
    method tearDown (line 177) | def tearDown(self):
    method test_api_exception_rollback_transaction_non_atomic_view (line 180) | def test_api_exception_rollback_transaction_non_atomic_view(self):

FILE: tests/test_authtoken.py
  class AuthTokenTests (line 20) | class AuthTokenTests(TestCase):
    method setUp (line 22) | def setUp(self):
    method test_authtoken_can_be_imported_when_not_included_in_installed_apps (line 27) | def test_authtoken_can_be_imported_when_not_included_in_installed_apps...
    method test_model_admin_displayed_fields (line 35) | def test_model_admin_displayed_fields(self):
    method test_model_admin__username_field (line 41) | def test_model_admin__username_field(self, mock_register):
    method test_token_string_representation (line 63) | def test_token_string_representation(self):
    method test_validate_raise_error_if_no_credentials_provided (line 66) | def test_validate_raise_error_if_no_credentials_provided(self):
    method test_whitespace_in_password (line 70) | def test_whitespace_in_password(self):
    method test_token_creation_collision_raises_integrity_error (line 76) | def test_token_creation_collision_raises_integrity_error(self):
    method test_key_generated_on_save_when_cleared (line 84) | def test_key_generated_on_save_when_cleared(self):
    method test_clearing_key_on_existing_token_raises_integrity_error (line 97) | def test_clearing_key_on_existing_token_raises_integrity_error(self):
    method test_saving_existing_token_without_changes_does_not_alter_key (line 109) | def test_saving_existing_token_without_changes_does_not_alter_key(self):
  class AuthTokenCommandTests (line 116) | class AuthTokenCommandTests(TestCase):
    method setUp (line 118) | def setUp(self):
    method test_command_create_user_token (line 122) | def test_command_create_user_token(self):
    method test_command_create_user_token_invalid_user (line 128) | def test_command_create_user_token_invalid_user(self):
    method test_command_reset_user_token (line 132) | def test_command_reset_user_token(self):
    method test_command_do_not_reset_user_token (line 140) | def test_command_do_not_reset_user_token(self):
    method test_command_raising_error_for_invalid_user (line 148) | def test_command_raising_error_for_invalid_user(self):
    method test_command_output (line 153) | def test_command_output(self):

FILE: tests/test_bound_fields.py
  class TestSimpleBoundField (line 7) | class TestSimpleBoundField:
    method test_empty_bound_field (line 8) | def test_empty_bound_field(self):
    method test_populated_bound_field (line 22) | def test_populated_bound_field(self):
    method test_error_bound_field (line 36) | def test_error_bound_field(self):
    method test_delete_field (line 51) | def test_delete_field(self):
    method test_as_form_fields (line 60) | def test_as_form_fields(self):
    method test_rendering_boolean_field (line 70) | def test_rendering_boolean_field(self):
  class CustomJSONField (line 95) | class CustomJSONField(serializers.JSONField):
  class TestNestedBoundField (line 99) | class TestNestedBoundField:
    method test_nested_empty_bound_field (line 100) | def test_nested_empty_bound_field(self):
    method test_as_form_fields (line 121) | def test_as_form_fields(self):
    method test_rendering_nested_fields_with_none_value (line 151) | def test_rendering_nested_fields_with_none_value(self):
    method test_rendering_nested_fields_with_not_mappable_value (line 188) | def test_rendering_nested_fields_with_not_mappable_value(self):
    method test_child_bound_field_after_parent_validation_error (line 215) | def test_child_bound_field_after_parent_validation_error(self):
  class TestJSONBoundField (line 238) | class TestJSONBoundField:
    method test_as_form_fields (line 239) | def test_as_form_fields(self):

FILE: tests/test_decorators.py
  class DecoratorTestCase (line 25) | class DecoratorTestCase(TestCase):
    method setUp (line 27) | def setUp(self):
    method test_api_view_incorrect (line 30) | def test_api_view_incorrect(self):
    method test_api_view_incorrect_arguments (line 42) | def test_api_view_incorrect_arguments(self):
    method test_calling_method (line 52) | def test_calling_method(self):
    method test_calling_put_method (line 66) | def test_calling_put_method(self):
    method test_calling_patch_method (line 80) | def test_calling_patch_method(self):
    method test_renderer_classes (line 94) | def test_renderer_classes(self):
    method test_parser_classes (line 105) | def test_parser_classes(self):
    method test_authentication_classes (line 117) | def test_authentication_classes(self):
    method test_permission_classes (line 129) | def test_permission_classes(self):
    method test_throttle_classes (line 140) | def test_throttle_classes(self):
    method test_versioning_class (line 156) | def test_versioning_class(self):
    method test_metadata_class (line 166) | def test_metadata_class(self):
    method test_content_negotiation (line 178) | def test_content_negotiation(self):
    method test_schema (line 193) | def test_schema(self):
    method test_incorrect_decorator_order_permission_classes (line 207) | def test_incorrect_decorator_order_permission_classes(self):
    method test_incorrect_decorator_order_renderer_classes (line 219) | def test_incorrect_decorator_order_renderer_classes(self):
    method test_incorrect_decorator_order_parser_classes (line 231) | def test_incorrect_decorator_order_parser_classes(self):
    method test_incorrect_decorator_order_authentication_classes (line 243) | def test_incorrect_decorator_order_authentication_classes(self):
    method test_incorrect_decorator_order_throttle_classes (line 255) | def test_incorrect_decorator_order_throttle_classes(self):
    method test_incorrect_decorator_order_versioning_class (line 270) | def test_incorrect_decorator_order_versioning_class(self):
    method test_incorrect_decorator_order_metadata_class (line 282) | def test_incorrect_decorator_order_metadata_class(self):
    method test_incorrect_decorator_order_content_negotiation_class (line 294) | def test_incorrect_decorator_order_content_negotiation_class(self):
    method test_incorrect_decorator_order_schema (line 310) | def test_incorrect_decorator_order_schema(self):
  class ActionDecoratorTestCase (line 326) | class ActionDecoratorTestCase(TestCase):
    method test_defaults (line 328) | def test_defaults(self):
    method test_detail_required (line 342) | def test_detail_required(self):
    method test_method_mapping_http_method (line 351) | def test_method_mapping_http_method(self):
    method test_method_mapping_http_methods (line 364) | def test_method_mapping_http_methods(self):
    method test_view_name_kwargs (line 381) | def test_view_name_kwargs(self):
    method test_method_mapping (line 422) | def test_method_mapping(self):
    method test_method_mapping_already_mapped (line 435) | def test_method_mapping_already_mapped(self):
    method test_method_mapping_overwrite (line 446) | def test_method_mapping_overwrite(self):

FILE: tests/test_description.py
  class TestViewNamesAndDescriptions (line 48) | class TestViewNamesAndDescriptions(TestCase):
    method test_view_name_uses_class_name (line 49) | def test_view_name_uses_class_name(self):
    method test_view_name_uses_name_attribute (line 57) | def test_view_name_uses_name_attribute(self):
    method test_view_name_uses_suffix_attribute (line 62) | def test_view_name_uses_suffix_attribute(self):
    method test_view_name_preferences_name_over_suffix (line 67) | def test_view_name_preferences_name_over_suffix(self):
    method test_view_description_uses_docstring (line 73) | def test_view_description_uses_docstring(self):
    method test_view_description_uses_description_attribute (line 100) | def test_view_description_uses_description_attribute(self):
    method test_view_description_allows_empty_description (line 105) | def test_view_description_allows_empty_description(self):
    method test_view_description_can_be_empty (line 111) | def test_view_description_can_be_empty(self):
    method test_view_description_can_be_promise (line 120) | def test_view_description_can_be_promise(self):
    method test_markdown (line 143) | def test_markdown(self):
  function test_dedent_tabs (line 150) | def test_dedent_tabs():

FILE: tests/test_encoders.py
  class MockList (line 15) | class MockList:
    method tolist (line 16) | def tolist(self):
  class JSONEncoderTests (line 20) | class JSONEncoderTests(TestCase):
    method setUp (line 25) | def setUp(self):
    method test_encode_decimal (line 28) | def test_encode_decimal(self):
    method test_encode_datetime (line 35) | def test_encode_datetime(self):
    method test_encode_time (line 44) | def test_encode_time(self):
    method test_encode_time_tz (line 51) | def test_encode_time_tz(self):
    method test_encode_date (line 60) | def test_encode_date(self):
    method test_encode_timedelta (line 67) | def test_encode_timedelta(self):
    method test_encode_uuid (line 74) | def test_encode_uuid(self):
    method test_encode_ipaddress_ipv4address (line 81) | def test_encode_ipaddress_ipv4address(self):
    method test_encode_ipaddress_ipv6address (line 88) | def test_encode_ipaddress_ipv6address(self):
    method test_encode_ipaddress_ipv4network (line 95) | def test_encode_ipaddress_ipv4network(self):
    method test_encode_ipaddress_ipv6network (line 102) | def test_encode_ipaddress_ipv6network(self):
    method test_encode_ipaddress_ipv4interface (line 109) | def test_encode_ipaddress_ipv4interface(self):
    method test_encode_ipaddress_ipv6interface (line 116) | def test_encode_ipaddress_ipv6interface(self):
    method test_encode_object_with_tolist (line 123) | def test_encode_object_with_tolist(self):
    method test_encode_empty_returnlist (line 130) | def test_encode_empty_returnlist(self):

FILE: tests/test_exceptions.py
  class ExceptionTestCase (line 11) | class ExceptionTestCase(TestCase):
    method test_get_error_details (line 13) | def test_get_error_details(self):
    method test_get_full_details_with_throttling (line 39) | def test_get_full_details_with_throttling(self):
  class ErrorDetailTests (line 55) | class ErrorDetailTests(TestCase):
    method test_eq (line 57) | def test_eq(self):
    method test_ne (line 64) | def test_ne(self):
    method test_repr (line 71) | def test_repr(self):
    method test_str (line 77) | def test_str(self):
    method test_hash (line 81) | def test_hash(self):
  class TranslationTests (line 86) | class TranslationTests(TestCase):
    method test_message (line 89) | def test_message(self):
  function test_server_error (line 95) | def test_server_error():
  function test_bad_request (line 102) | def test_bad_request():

FILE: tests/test_fields.py
  class TestIsSimpleCallable (line 36) | class TestIsSimpleCallable:
    method test_method (line 38) | def test_method(self):
    method test_function (line 70) | def test_function(self):
    method test_not_callable (line 89) | def test_not_callable(self, obj):
    method test_4602_regression (line 92) | def test_4602_regression(self):
    method test_builtin_function (line 106) | def test_builtin_function(self):
    method test_type_annotation (line 118) | def test_type_annotation(self):
  class TestEmpty (line 130) | class TestEmpty:
    method test_required (line 134) | def test_required(self):
    method test_not_required (line 143) | def test_not_required(self):
    method test_disallow_null (line 151) | def test_disallow_null(self):
    method test_allow_null (line 160) | def test_allow_null(self):
    method test_disallow_blank (line 168) | def test_disallow_blank(self):
    method test_allow_blank (line 177) | def test_allow_blank(self):
    method test_default (line 185) | def test_default(self):
  class TestSource (line 194) | class TestSource:
    method test_source (line 195) | def test_source(self):
    method test_redundant_source (line 202) | def test_redundant_source(self):
    method test_callable_source (line 213) | def test_callable_source(self):
    method test_callable_source_raises (line 224) | def test_callable_source_raises(self):
    method test_builtin_callable_source_raises (line 238) | def test_builtin_callable_source_raises(self):
  class TestReadOnly (line 251) | class TestReadOnly:
    method setup_method (line 252) | def setup_method(self):
    method test_writable_fields (line 258) | def test_writable_fields(self):
    method test_validate_read_only (line 265) | def test_validate_read_only(self):
    method test_serialize_read_only (line 274) | def test_serialize_read_only(self):
  class TestWriteOnly (line 283) | class TestWriteOnly:
    method setup_method (line 284) | def setup_method(self):
    method test_validate_write_only (line 290) | def test_validate_write_only(self):
    method test_serialize_write_only (line 299) | def test_serialize_write_only(self):
  class TestInitial (line 308) | class TestInitial:
    method setup_method (line 309) | def setup_method(self):
    method test_initial (line 315) | def test_initial(self):
  class TestInitialWithCallable (line 325) | class TestInitialWithCallable:
    method setup_method (line 326) | def setup_method(self):
    method test_initial_should_accept_callable (line 334) | def test_initial_should_accept_callable(self):
  class TestLabel (line 343) | class TestLabel:
    method setup_method (line 344) | def setup_method(self):
    method test_label (line 349) | def test_label(self):
  class TestInvalidErrorKey (line 357) | class TestInvalidErrorKey:
    method setup_method (line 358) | def setup_method(self):
    method test_invalid_error_key (line 364) | def test_invalid_error_key(self):
  class TestBooleanHTMLInput (line 378) | class TestBooleanHTMLInput:
    method test_empty_html_checkbox (line 379) | def test_empty_html_checkbox(self):
    method test_empty_html_checkbox_not_required (line 391) | def test_empty_html_checkbox_not_required(self):
    method test_empty_html_checkbox_allow_null (line 404) | def test_empty_html_checkbox_allow_null(self):
    method test_empty_html_checkbox_allow_null_with_default (line 416) | def test_empty_html_checkbox_allow_null_with_default(self):
  class TestHTMLInput (line 433) | class TestHTMLInput:
    method test_empty_html_charfield_with_default (line 434) | def test_empty_html_charfield_with_default(self):
    method test_empty_html_charfield_without_default (line 442) | def test_empty_html_charfield_without_default(self):
    method test_empty_html_charfield_without_default_not_required (line 450) | def test_empty_html_charfield_without_default_not_required(self):
    method test_empty_html_integerfield (line 458) | def test_empty_html_integerfield(self):
    method test_empty_html_uuidfield_with_default (line 466) | def test_empty_html_uuidfield_with_default(self):
    method test_empty_html_uuidfield_with_optional (line 474) | def test_empty_html_uuidfield_with_optional(self):
    method test_empty_html_charfield_allow_null (line 482) | def test_empty_html_charfield_allow_null(self):
    method test_empty_html_datefield_allow_null (line 490) | def test_empty_html_datefield_allow_null(self):
    method test_empty_html_charfield_allow_null_allow_blank (line 498) | def test_empty_html_charfield_allow_null_allow_blank(self):
    method test_empty_html_charfield_required_false (line 506) | def test_empty_html_charfield_required_false(self):
    method test_querydict_list_input (line 514) | def test_querydict_list_input(self):
    method test_querydict_list_input_only_one_input (line 522) | def test_querydict_list_input_only_one_input(self):
    method test_querydict_list_input_no_values_uses_default (line 530) | def test_querydict_list_input_no_values_uses_default(self):
    method test_querydict_list_input_supports_indexed_keys (line 543) | def test_querydict_list_input_supports_indexed_keys(self):
    method test_querydict_list_input_no_values_no_default_and_not_required (line 555) | def test_querydict_list_input_no_values_no_default_and_not_required(se...
    method test_querydict_list_input_posts_key_but_no_values (line 567) | def test_querydict_list_input_posts_key_but_no_values(self):
  class TestCreateOnlyDefault (line 580) | class TestCreateOnlyDefault:
    method setup_method (line 581) | def setup_method(self):
    method test_create_only_default_is_provided (line 589) | def test_create_only_default_is_provided(self):
    method test_create_only_default_is_not_provided_on_update (line 596) | def test_create_only_default_is_not_provided_on_update(self):
    method test_create_only_default_callable_sets_context (line 606) | def test_create_only_default_callable_sets_context(self):
  class Test5087Regression (line 625) | class Test5087Regression:
    method test_parent_binding (line 626) | def test_parent_binding(self):
  class TestTyping (line 635) | class TestTyping(TestCase):
    method test_field_is_subscriptable (line 636) | def test_field_is_subscriptable(self):
  function get_items (line 643) | def get_items(mapping_or_list_of_two_tuples):
  class FieldValues (line 652) | class FieldValues:
    method test_valid_inputs (line 656) | def test_valid_inputs(self, *args):
    method test_invalid_inputs (line 664) | def test_invalid_inputs(self, *args):
    method test_outputs (line 674) | def test_outputs(self, *args):
  class TestBooleanField (line 682) | class TestBooleanField(FieldValues):
    method test_disallow_unhashable_collection_types (line 745) | def test_disallow_unhashable_collection_types(self):
  class TestNullableBooleanField (line 758) | class TestNullableBooleanField(TestBooleanField):
  class TestCharField (line 787) | class TestCharField(FieldValues):
    method test_trim_whitespace_default (line 806) | def test_trim_whitespace_default(self):
    method test_trim_whitespace_disabled (line 810) | def test_trim_whitespace_disabled(self):
    method test_disallow_blank_with_trim_whitespace (line 814) | def test_disallow_blank_with_trim_whitespace(self):
    method test_null_bytes (line 821) | def test_null_bytes(self):
    method test_surrogate_characters (line 831) | def test_surrogate_characters(self):
    method test_iterable_validators (line 846) | def test_iterable_validators(self):
  class TestEmailField (line 866) | class TestEmailField(FieldValues):
  class TestRegexField (line 881) | class TestRegexField(FieldValues):
  class TestiCompiledRegexField (line 895) | class TestiCompiledRegexField(FieldValues):
  class TestSlugField (line 909) | class TestSlugField(FieldValues):
    method test_allow_unicode_true (line 922) | def test_allow_unicode_true(self):
  class TestURLField (line 934) | class TestURLField(FieldValues):
  class TestUUIDField (line 948) | class TestUUIDField(FieldValues):
    method _test_format (line 967) | def _test_format(self, uuid_format, formatted_uuid_0):
    method test_formats (line 972) | def test_formats(self):
  class TestIPAddressField (line 979) | class TestIPAddressField(FieldValues):
  class TestIPv4AddressField (line 1001) | class TestIPv4AddressField(FieldValues):
  class TestIPv6AddressField (line 1017) | class TestIPv6AddressField(FieldValues):
  class TestFilePathField (line 1034) | class TestFilePathField(FieldValues):
  class TestIntegerField (line 1054) | class TestIntegerField(FieldValues):
  class TestMinMaxIntegerField (line 1083) | class TestMinMaxIntegerField(FieldValues):
  class TestBigIntegerField (line 1103) | class TestBigIntegerField(FieldValues):
  class TestMinMaxBigIntegerField (line 1138) | class TestMinMaxBigIntegerField(FieldValues):
  class TestCoercionBigIntegerField (line 1158) | class TestCoercionBigIntegerField(TestCase):
    method test_force_coerce_to_string (line 1160) | def test_force_coerce_to_string(self):
  class TestFloatField (line 1167) | class TestFloatField(FieldValues):
  class TestMinMaxFloatField (line 1193) | class TestMinMaxFloatField(FieldValues):
  class TestFloatFieldOverFlowError (line 1215) | class TestFloatFieldOverFlowError(TestCase):
    method test_overflow_error_float_field (line 1216) | def test_overflow_error_float_field(self):
  class TestDecimalField (line 1223) | class TestDecimalField(FieldValues):
  class TestAllowNullDecimalField (line 1265) | class TestAllowNullDecimalField(FieldValues):
  class TestAllowNullNoStringCoercionDecimalField (line 1278) | class TestAllowNullNoStringCoercionDecimalField(FieldValues):
  class TestMinMaxDecimalField (line 1291) | class TestMinMaxDecimalField(FieldValues):
    method test_warning_when_not_decimal_types (line 1309) | def test_warning_when_not_decimal_types(self, caplog):
  class TestAllowEmptyStrDecimalFieldWithValidators (line 1325) | class TestAllowEmptyStrDecimalFieldWithValidators(FieldValues):
  class TestNoMaxDigitsDecimalField (line 1349) | class TestNoMaxDigitsDecimalField(FieldValues):
  class TestNoStringCoercionDecimalField (line 1361) | class TestNoStringCoercionDecimalField(FieldValues):
  class TestLocalizedDecimalField (line 1381) | class TestLocalizedDecimalField(TestCase):
    method test_to_internal_value (line 1383) | def test_to_internal_value(self):
    method test_to_representation (line 1388) | def test_to_representation(self):
    method test_localize_forces_coerce_to_string (line 1392) | def test_localize_forces_coerce_to_string(self):
  class TestQuantizedValueForDecimal (line 1397) | class TestQuantizedValueForDecimal(TestCase):
    method test_int_quantized_value_for_decimal (line 1398) | def test_int_quantized_value_for_decimal(self):
    method test_string_quantized_value_for_decimal (line 1404) | def test_string_quantized_value_for_decimal(self):
    method test_part_precision_string_quantized_value_for_decimal (line 1410) | def test_part_precision_string_quantized_value_for_decimal(self):
  class TestNormalizedOutputValueDecimalField (line 1417) | class TestNormalizedOutputValueDecimalField(TestCase):
    method test_normalize_output (line 1422) | def test_normalize_output(self):
    method test_non_normalize_output (line 1427) | def test_non_normalize_output(self):
    method test_normalize_coeherce_to_string (line 1432) | def test_normalize_coeherce_to_string(self):
  class TestNoDecimalPlaces (line 1438) | class TestNoDecimalPlaces(FieldValues):
  class TestRoundingDecimalField (line 1453) | class TestRoundingDecimalField(TestCase):
    method test_valid_rounding (line 1454) | def test_valid_rounding(self):
    method test_invalid_rounding (line 1461) | def test_invalid_rounding(self):
  class TestDateField (line 1468) | class TestDateField(FieldValues):
  class TestCustomInputFormatDateField (line 1493) | class TestCustomInputFormatDateField(FieldValues):
  class TestCustomOutputFormatDateField (line 1507) | class TestCustomOutputFormatDateField(FieldValues):
  class TestNoOutputFormatDateField (line 1519) | class TestNoOutputFormatDateField(FieldValues):
  class TestDateTimeField (line 1531) | class TestDateTimeField(FieldValues):
  class TestCustomInputFormatDateTimeField (line 1560) | class TestCustomInputFormatDateTimeField(FieldValues):
  class TestCustomOutputFormatDateTimeField (line 1574) | class TestCustomOutputFormatDateTimeField(FieldValues):
  class TestNoOutputFormatDateTimeField (line 1586) | class TestNoOutputFormatDateTimeField(FieldValues):
  class TestNaiveDateTimeField (line 1599) | class TestNaiveDateTimeField(FieldValues, TestCase):
  class TestTZWithDateTimeField (line 1615) | class TestTZWithDateTimeField(FieldValues):
    method setup_class (line 1620) | def setup_class(cls):
  class TestDefaultTZDateTimeField (line 1638) | class TestDefaultTZDateTimeField(TestCase):
    method setup_class (line 1644) | def setup_class(cls):
    method assertUTC (line 1648) | def assertUTC(self, tzinfo):
    method test_default_timezone (line 1657) | def test_default_timezone(self):
    method test_current_timezone (line 1660) | def test_current_timezone(self):
  class TestCustomTimezoneForDateTimeField (line 1669) | class TestCustomTimezoneForDateTimeField(TestCase):
    method setup_class (line 1672) | def setup_class(cls):
    method test_should_render_date_time_in_default_timezone (line 1676) | def test_should_render_date_time_in_default_timezone(self):
  class TestPytzNaiveDayLightSavingTimeTimeZoneDateTimeField (line 1692) | class TestPytzNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
    class MockTimezone (line 1705) | class MockTimezone(pytz.BaseTzInfo):
      method localize (line 1707) | def localize(value, is_dst):
      method __str__ (line 1710) | def __str__(self):
  class TestNaiveDayLightSavingTimeTimeZoneDateTimeField (line 1717) | class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
    class MockZoneInfoTimezone (line 1730) | class MockZoneInfoTimezone(datetime.tzinfo):
      method __str__ (line 1731) | def __str__(self):
  class TestTimeField (line 1737) | class TestTimeField(FieldValues):
  class TestCustomInputFormatTimeField (line 1759) | class TestCustomInputFormatTimeField(FieldValues):
  class TestCustomOutputFormatTimeField (line 1773) | class TestCustomOutputFormatTimeField(FieldValues):
  class TestNoOutputFormatTimeField (line 1785) | class TestNoOutputFormatTimeField(FieldValues):
  class TestMinMaxDurationField (line 1797) | class TestMinMaxDurationField(FieldValues):
  class TestDurationField (line 1814) | class TestDurationField(FieldValues):
    method test_invalid_format (line 1838) | def test_invalid_format(self):
    method test_invalid_format_in_config (line 1851) | def test_invalid_format_in_config(self):
  class TestNoOutputFormatDurationField (line 1870) | class TestNoOutputFormatDurationField(FieldValues):
  class TestISOOutputFormatDurationField (line 1882) | class TestISOOutputFormatDurationField(FieldValues):
  class TestChoiceField (line 1901) | class TestChoiceField(FieldValues):
    method test_allow_blank (line 1926) | def test_allow_blank(self):
    method test_allow_null (line 1941) | def test_allow_null(self):
    method test_iter_options (line 1957) | def test_iter_options(self):
    method test_edit_choices (line 1985) | def test_edit_choices(self):
    method test_enum_integer_choices (line 1998) | def test_enum_integer_choices(self):
    method test_integer_choices (line 2023) | def test_integer_choices(self):
    method test_text_choices (line 2048) | def test_text_choices(self):
  class TestChoiceFieldWithType (line 2072) | class TestChoiceFieldWithType(FieldValues):
  class TestChoiceFieldWithListChoices (line 2098) | class TestChoiceFieldWithListChoices(FieldValues):
  class TestChoiceFieldWithGroupedChoices (line 2117) | class TestChoiceFieldWithGroupedChoices(FieldValues):
  class TestChoiceFieldWithMixedChoices (line 2147) | class TestChoiceFieldWithMixedChoices(FieldValues):
  class TestMultipleChoiceField (line 2177) | class TestMultipleChoiceField(FieldValues):
    method test_against_partial_and_full_updates (line 2205) | def test_against_partial_and_full_updates(self):
    method test_valid_inputs_is_json_serializable (line 2212) | def test_valid_inputs_is_json_serializable(self):
    method test_output_is_json_serializable (line 2221) | def test_output_is_json_serializable(self):
  class TestEmptyMultipleChoiceField (line 2234) | class TestEmptyMultipleChoiceField(FieldValues):
  class MockFile (line 2257) | class MockFile:
    method __init__ (line 2258) | def __init__(self, name='', size=0, url=''):
    method __eq__ (line 2263) | def __eq__(self, other):
  class TestFileField (line 2272) | class TestFileField(FieldValues):
  class TestFieldFieldWithName (line 2292) | class TestFieldFieldWithName(FieldValues):
  function ext_validator (line 2304) | def ext_validator(value):
  class PassImageValidation (line 2311) | class PassImageValidation(DjangoImageField):
    method to_python (line 2314) | def to_python(self, value):
  class FailImageValidation (line 2318) | class FailImageValidation(PassImageValidation):
    method to_python (line 2319) | def to_python(self, value):
  class TestInvalidImageField (line 2325) | class TestInvalidImageField(FieldValues):
  class TestValidImageField (line 2338) | class TestValidImageField(FieldValues):
  class TestListField (line 2352) | class TestListField(FieldValues):
    method test_no_source_on_child (line 2372) | def test_no_source_on_child(self):
    method test_collection_types_are_invalid_input (line 2381) | def test_collection_types_are_invalid_input(self):
    method test_constructor_misuse_raises (line 2389) | def test_constructor_misuse_raises(self):
  class TestNestedListField (line 2395) | class TestNestedListField(FieldValues):
  class TestListFieldWithDjangoValidationErrors (line 2414) | class TestListFieldWithDjangoValidationErrors(FieldValues, TestCase):
  class TestEmptyListField (line 2443) | class TestEmptyListField(FieldValues):
  class TestListFieldLengthLimit (line 2455) | class TestListFieldLengthLimit(FieldValues):
  class TestUnvalidatedListField (line 2465) | class TestUnvalidatedListField(FieldValues):
  class TestDictField (line 2481) | class TestDictField(FieldValues):
    method test_no_source_on_child (line 2498) | def test_no_source_on_child(self):
    method test_allow_null (line 2507) | def test_allow_null(self):
    method test_allow_empty_disallowed (line 2515) | def test_allow_empty_disallowed(self):
  class TestNestedDictField (line 2526) | class TestNestedDictField(FieldValues):
  class TestDictFieldWithNullChild (line 2543) | class TestDictFieldWithNullChild(FieldValues):
  class TestUnvalidatedDictField (line 2558) | class TestUnvalidatedDictField(FieldValues):
  class TestHStoreField (line 2574) | class TestHStoreField(FieldValues):
    method test_child_is_charfield (line 2590) | def test_child_is_charfield(self):
    method test_no_source_on_child (line 2599) | def test_no_source_on_child(self):
    method test_allow_null (line 2608) | def test_allow_null(self):
  class TestJSONField (line 2617) | class TestJSONField(FieldValues):
    method test_html_input_as_json_string (line 2649) | def test_html_input_as_json_string(self):
  class TestBinaryJSONField (line 2663) | class TestBinaryJSONField(FieldValues):
  class MockRequest (line 2686) | class MockRequest:
    method build_absolute_uri (line 2687) | def build_absolute_uri(self, value):
  class TestFileFieldContext (line 2691) | class TestFileFieldContext:
    method test_fully_qualified_when_request_in_context (line 2692) | def test_fully_qualified_when_request_in_context(self):
  class TestFilePathFieldRequired (line 2703) | class TestFilePathFieldRequired:
    method test_required_passed_to_both_django_file_path_field_and_base (line 2704) | def test_required_passed_to_both_django_file_path_field_and_base(self):
  class TestSerializerMethodField (line 2718) | class TestSerializerMethodField:
    method test_serializer_method_field (line 2719) | def test_serializer_method_field(self):
    method test_redundant_method_name (line 2731) | def test_redundant_method_name(self):
  class TestModelField (line 2744) | class TestModelField:
    method test_max_length_init (line 2745) | def test_max_length_init(self):
  class TestValidationErrorCode (line 2756) | class TestValidationErrorCode:
    method test_validationerror_code_with_msg (line 2758) | def test_validationerror_code_with_msg(self, use_list):
    method test_validationerror_code_with_msg_including_percent (line 2777) | def test_validationerror_code_with_msg_including_percent(self, use_list):
    method test_validationerror_code_with_dict (line 2795) | def test_validationerror_code_with_dict(self, use_list, code):
    method test_validationerror_code_with_dict_list_same_code (line 2833) | def test_validationerror_code_with_dict_list_same_code(self, code):

FILE: tests/test_filters.py
  class SearchSplitTests (line 19) | class SearchSplitTests(SimpleTestCase):
    method test_keep_quoted_together_regardless_of_commas (line 21) | def test_keep_quoted_together_regardless_of_commas(self):
    method test_strips_commas_around_quoted (line 24) | def test_strips_commas_around_quoted(self):
    method test_splits_by_comma (line 29) | def test_splits_by_comma(self):
    method test_splits_quotes_followed_by_comma_and_sentence (line 34) | def test_splits_quotes_followed_by_comma_and_sentence(self):
  class BaseFilterTests (line 38) | class BaseFilterTests(TestCase):
    method setUp (line 39) | def setUp(self):
    method test_filter_queryset_raises_error (line 42) | def test_filter_queryset_raises_error(self):
  class SearchFilterModel (line 47) | class SearchFilterModel(models.Model):
  class SearchFilterSerializer (line 52) | class SearchFilterSerializer(serializers.ModelSerializer):
    class Meta (line 53) | class Meta:
  class SearchFilterTests (line 58) | class SearchFilterTests(TestCase):
    method setUpTestData (line 60) | def setUpTestData(cls):
    method test_search (line 79) | def test_search(self):
    method test_search_returns_same_queryset_if_no_search_fields_or_terms_provided (line 94) | def test_search_returns_same_queryset_if_no_search_fields_or_terms_pro...
    method test_exact_search (line 107) | def test_exact_search(self):
    method test_startswith_search (line 121) | def test_startswith_search(self):
    method test_regexp_search (line 135) | def test_regexp_search(self):
    method test_search_with_nonstandard_search_param (line 149) | def test_search_with_nonstandard_search_param(self):
    method test_search_with_filter_subclass (line 169) | def test_search_with_filter_subclass(self):
    method test_search_field_with_null_characters (line 194) | def test_search_field_with_null_characters(self):
    method test_search_field_with_custom_lookup (line 202) | def test_search_field_with_custom_lookup(self):
    method test_search_field_with_additional_transforms (line 215) | def test_search_field_with_additional_transforms(self):
    method test_search_field_with_multiple_words (line 250) | def test_search_field_with_multiple_words(self):
    method test_search_field_with_escapes (line 267) | def test_search_field_with_escapes(self):
    method test_search_field_with_quotes (line 280) | def test_search_field_with_quotes(self):
  class AttributeModel (line 294) | class AttributeModel(models.Model):
  class SearchFilterModelFk (line 298) | class SearchFilterModelFk(models.Model):
  class SearchFilterFkSerializer (line 303) | class SearchFilterFkSerializer(serializers.ModelSerializer):
    class Meta (line 304) | class Meta:
  class SearchFilterFkTests (line 309) | class SearchFilterFkTests(TestCase):
    method test_must_call_distinct (line 311) | def test_must_call_distinct(self):
    method test_must_call_distinct_restores_meta_for_each_field (line 324) | def test_must_call_distinct_restores_meta_for_each_field(self):
    method test_custom_lookup_to_related_model (line 335) | def test_custom_lookup_to_related_model(self):
  class SearchFilterModelM2M (line 343) | class SearchFilterModelM2M(models.Model):
  class SearchFilterM2MSerializer (line 349) | class SearchFilterM2MSerializer(serializers.ModelSerializer):
    class Meta (line 350) | class Meta:
  class SearchFilterM2MTests (line 355) | class SearchFilterM2MTests(TestCase):
    method setUp (line 356) | def setUp(self):
    method test_m2m_search (line 377) | def test_m2m_search(self):
    method test_must_call_distinct (line 389) | def test_must_call_distinct(self):
  class Blog (line 404) | class Blog(models.Model):
  class Entry (line 408) | class Entry(models.Model):
  class BlogSerializer (line 414) | class BlogSerializer(serializers.ModelSerializer):
    class Meta (line 415) | class Meta:
  class SearchFilterToManyTests (line 420) | class SearchFilterToManyTests(TestCase):
    method setUpTestData (line 423) | def setUpTestData(cls):
    method test_multiple_filter_conditions (line 435) | def test_multiple_filter_conditions(self):
  class SearchFilterAnnotatedSerializer (line 448) | class SearchFilterAnnotatedSerializer(serializers.ModelSerializer):
    class Meta (line 451) | class Meta:
  class SearchFilterAnnotatedFieldTests (line 456) | class SearchFilterAnnotatedFieldTests(TestCase):
    method setUpTestData (line 458) | def setUpTestData(cls):
    method test_search_in_annotated_field (line 462) | def test_search_in_annotated_field(self):
    method test_must_call_distinct_subsequent_m2m_fields (line 479) | def test_must_call_distinct_subsequent_m2m_fields(self):
  class OrderingFilterModel (line 495) | class OrderingFilterModel(models.Model):
    method description (line 500) | def description(self):
  class OrderingFilterRelatedModel (line 504) | class OrderingFilterRelatedModel(models.Model):
  class OrderingFilterSerializer (line 509) | class OrderingFilterSerializer(serializers.ModelSerializer):
    class Meta (line 510) | class Meta:
  class OrderingFilterSerializerWithModelProperty (line 515) | class OrderingFilterSerializerWithModelProperty(serializers.ModelSeriali...
    class Meta (line 516) | class Meta:
  class OrderingDottedRelatedSerializer (line 526) | class OrderingDottedRelatedSerializer(serializers.ModelSerializer):
    class Meta (line 530) | class Meta:
  class DjangoFilterOrderingModel (line 539) | class DjangoFilterOrderingModel(models.Model):
    class Meta (line 543) | class Meta:
  class DjangoFilterOrderingSerializer (line 547) | class DjangoFilterOrderingSerializer(serializers.ModelSerializer):
    class Meta (line 548) | class Meta:
  class OrderingFilterTests (line 553) | class OrderingFilterTests(TestCase):
    method setUp (line 554) | def setUp(self):
    method test_ordering (line 573) | def test_ordering(self):
    method test_reverse_ordering (line 590) | def test_reverse_ordering(self):
    method test_incorrecturl_extrahyphens_ordering (line 607) | def test_incorrecturl_extrahyphens_ordering(self):
    method test_incorrectfield_ordering (line 624) | def test_incorrectfield_ordering(self):
    method test_ordering_without_ordering_fields (line 641) | def test_ordering_without_ordering_fields(self):
    method test_default_ordering (line 677) | def test_default_ordering(self):
    method test_default_ordering_using_string (line 694) | def test_default_ordering_using_string(self):
    method test_ordering_by_aggregate_field (line 711) | def test_ordering_by_aggregate_field(self):
    method test_ordering_by_dotted_source (line 739) | def test_ordering_by_dotted_source(self):
    method test_ordering_with_nonstandard_ordering_param (line 769) | def test_ordering_with_nonstandard_ordering_param(self):
    method test_get_template_context (line 791) | def test_get_template_context(self):
    method test_ordering_with_overridden_get_serializer_class (line 804) | def test_ordering_with_overridden_get_serializer_class(self):
    method test_ordering_with_improper_configuration (line 824) | def test_ordering_with_improper_configuration(self):
  class SensitiveOrderingFilterModel (line 838) | class SensitiveOrderingFilterModel(models.Model):
  class SensitiveDataSerializer1 (line 845) | class SensitiveDataSerializer1(serializers.ModelSerializer):
    class Meta (line 848) | class Meta:
  class SensitiveDataSerializer2 (line 853) | class SensitiveDataSerializer2(serializers.ModelSerializer):
    class Meta (line 857) | class Meta:
  class SensitiveDataSerializer3 (line 862) | class SensitiveDataSerializer3(serializers.ModelSerializer):
    class Meta (line 865) | class Meta:
  class SensitiveOrderingFilterTests (line 870) | class SensitiveOrderingFilterTests(TestCase):
    method setUp (line 871) | def setUp(self):
    method test_order_by_serializer_fields (line 877) | def test_order_by_serializer_fields(self):
    method test_cannot_order_by_non_serializer_fields (line 904) | def test_cannot_order_by_non_serializer_fields(self):

FILE: tests/test_generics.py
  class SlugBasedModel (line 20) | class SlugBasedModel(RESTFrameworkModel):
  class Comment (line 26) | class Comment(RESTFrameworkModel):
  class BasicSerializer (line 33) | class BasicSerializer(serializers.ModelSerializer):
    class Meta (line 34) | class Meta:
  class ForeignKeySerializer (line 39) | class ForeignKeySerializer(serializers.ModelSerializer):
    class Meta (line 40) | class Meta:
  class SlugSerializer (line 45) | class SlugSerializer(serializers.ModelSerializer):
    class Meta (line 48) | class Meta:
  class RootView (line 54) | class RootView(generics.ListCreateAPIView):
  class InstanceView (line 59) | class InstanceView(generics.RetrieveUpdateDestroyAPIView):
  class FKInstanceView (line 64) | class FKInstanceView(generics.RetrieveUpdateDestroyAPIView):
  class SlugBasedInstanceView (line 69) | class SlugBasedInstanceView(InstanceView):
  class TestRootView (line 79) | class TestRootView(TestCase):
    method setUp (line 80) | def setUp(self):
    method test_get_root_view (line 94) | def test_get_root_view(self):
    method test_head_root_view (line 104) | def test_head_root_view(self):
    method test_post_root_view (line 113) | def test_post_root_view(self):
    method test_put_root_view (line 126) | def test_put_root_view(self):
    method test_delete_root_view (line 137) | def test_delete_root_view(self):
    method test_post_cannot_set_id (line 147) | def test_post_cannot_set_id(self):
    method test_post_error_root_view (line 160) | def test_post_error_root_view(self):
  class TestInstanceView (line 174) | class TestInstanceView(TestCase):
    method setUp (line 175) | def setUp(self):
    method test_get_instance_view (line 190) | def test_get_instance_view(self):
    method test_post_instance_view (line 200) | def test_post_instance_view(self):
    method test_put_instance_view (line 211) | def test_put_instance_view(self):
    method test_patch_instance_view (line 224) | def test_patch_instance_view(self):
    method test_delete_instance_view (line 238) | def test_delete_instance_view(self):
    method test_get_instance_view_incorrect_arg (line 250) | def test_get_instance_view_incorrect_arg(self):
    method test_put_cannot_set_id (line 260) | def test_put_cannot_set_id(self):
    method test_put_to_deleted_instance (line 273) | def test_put_to_deleted_instance(self):
    method test_put_to_filtered_out_instance (line 285) | def test_put_to_filtered_out_instance(self):
    method test_patch_cannot_create_an_object (line 296) | def test_patch_cannot_create_an_object(self):
    method test_put_error_instance_view (line 307) | def test_put_error_instance_view(self):
  class TestFKInstanceView (line 318) | class TestFKInstanceView(TestCase):
    method setUp (line 319) | def setUp(self):
  class TestOverriddenGetObject (line 337) | class TestOverriddenGetObject(TestCase):
    method setUp (line 343) | def setUp(self):
    method test_overridden_get_object_view (line 368) | def test_overridden_get_object_view(self):
  class CommentSerializer (line 381) | class CommentSerializer(serializers.ModelSerializer):
    class Meta (line 382) | class Meta:
  class CommentView (line 387) | class CommentView(generics.ListCreateAPIView):
  class TestCreateModelWithAutoNowAddField (line 392) | class TestCreateModelWithAutoNowAddField(TestCase):
    method setUp (line 393) | def setUp(self):
    method test_create_model_with_auto_now_add_field (line 397) | def test_create_model_with_auto_now_add_field(self):
  class ClassB (line 412) | class ClassB(models.Model):
  class ClassA (line 416) | class ClassA(models.Model):
  class ClassASerializer (line 421) | class ClassASerializer(serializers.ModelSerializer):
    class Meta (line 426) | class Meta:
  class ExampleView (line 431) | class ExampleView(generics.ListCreateAPIView):
  class TestM2MBrowsableAPI (line 436) | class TestM2MBrowsableAPI(TestCase):
    method test_m2m_in_browsable_api (line 437) | def test_m2m_in_browsable_api(self):
  class InclusiveFilterBackend (line 447) | class InclusiveFilterBackend:
    method filter_queryset (line 448) | def filter_queryset(self, request, queryset, view):
  class ExclusiveFilterBackend (line 452) | class ExclusiveFilterBackend:
    method filter_queryset (line 453) | def filter_queryset(self, request, queryset, view):
  class TwoFieldModel (line 457) | class TwoFieldModel(models.Model):
  class DynamicSerializerView (line 462) | class DynamicSerializerView(generics.ListCreateAPIView):
    method get_serializer_class (line 466) | def get_serializer_class(self):
  class TestFilterBackendAppliedToViews (line 480) | class TestFilterBackendAppliedToViews(TestCase):
    method setUp (line 481) | def setUp(self):
    method test_get_root_view_filters_by_name_with_filter_backend (line 494) | def test_get_root_view_filters_by_name_with_filter_backend(self):
    method test_get_root_view_filters_out_all_models_with_exclusive_filter_backend (line 505) | def test_get_root_view_filters_out_all_models_with_exclusive_filter_ba...
    method test_get_instance_view_filters_out_name_with_filter_backend (line 515) | def test_get_instance_view_filters_out_name_with_filter_backend(self):
    method test_get_instance_view_will_return_single_object_when_filter_does_not_exclude_it (line 530) | def test_get_instance_view_will_return_single_object_when_filter_does_...
    method test_dynamic_serializer_form_in_browsable_api (line 540) | def test_dynamic_serializer_form_in_browsable_api(self):
  class TestGuardedQueryset (line 552) | class TestGuardedQueryset(TestCase):
    method test_guarded_queryset (line 553) | def test_guarded_queryset(self):
  class ApiViewsTests (line 566) | class ApiViewsTests(TestCase):
    method test_create_api_view_post (line 568) | def test_create_api_view_post(self):
    method test_destroy_api_view_delete (line 579) | def test_destroy_api_view_delete(self):
    method test_update_api_view_partial_update (line 590) | def test_update_api_view_partial_update(self):
    method test_retrieve_update_api_view_get (line 601) | def test_retrieve_update_api_view_get(self):
    method test_retrieve_update_api_view_put (line 612) | def test_retrieve_update_api_view_put(self):
    method test_retrieve_update_api_view_patch (line 623) | def test_retrieve_update_api_view_patch(self):
    method test_retrieve_destroy_api_view_get (line 634) | def test_retrieve_destroy_api_view_get(self):
    method test_retrieve_destroy_api_view_delete (line 645) | def test_retrieve_destroy_api_view_delete(self):
  class GetObjectOr404Tests (line 657) | class GetObjectOr404Tests(TestCase):
    method setUp (line 658) | def setUp(self):
    method test_get_object_or_404_with_valid_uuid (line 662) | def test_get_object_or_404_with_valid_uuid(self):
    method test_get_object_or_404_with_invalid_string_for_uuid (line 668) | def test_get_object_or_404_with_invalid_string_for_uuid(self):
  class TestSerializer (line 673) | class TestSerializer(TestCase):
    method test_serializer_class_not_provided (line 675) | def test_serializer_class_not_provided(self):
    method test_given_context_not_overridden (line 686) | def test_given_context_not_overridden(self):
  class TestTyping (line 703) | class TestTyping(TestCase):
    method test_genericview_is_subscriptable (line 704) | def test_genericview_is_subscriptable(self):
    method test_listview_is_subscriptable (line 707) | def test_listview_is_subscriptable(self):
    method test_instanceview_is_subscriptable (line 710) | def test_instanceview_is_subscriptable(self):

FILE: tests/test_htmlrenderer.py
  function example (line 18) | def example(request):
  function permission_denied (line 28) | def permission_denied(request):
  function not_found (line 34) | def not_found(request):
  function validation_error (line 40) | def validation_error(request):
  class TemplateHTMLRendererTests (line 53) | class TemplateHTMLRendererTests(TestCase):
    method setUp (line 54) | def setUp(self):
    method _monkey_patch_get_template (line 60) | def _monkey_patch_get_template(self):
    method tearDown (line 79) | def tearDown(self):
    method test_simple_html_view (line 85) | def test_simple_html_view(self):
    method test_not_found_html_view (line 90) | def test_not_found_html_view(self):
    method test_permission_denied_html_view (line 96) | def test_permission_denied_html_view(self):
    method test_validation_error_html_view (line 102) | def test_validation_error_html_view(self):
    method test_get_template_names_returns_own_template_name (line 110) | def test_get_template_names_returns_own_template_name(self):
    method test_get_template_names_returns_view_template_name (line 116) | def test_get_template_names_returns_view_template_name(self):
    method test_get_template_names_raises_error_if_no_template_found (line 137) | def test_get_template_names_raises_error_if_no_template_found(self):
  class TemplateHTMLRendererExceptionTests (line 144) | class TemplateHTMLRendererExceptionTests(TestCase):
    method setUp (line 145) | def setUp(self):
    method tearDown (line 160) | def tearDown(self):
    method test_not_found_html_view_with_template (line 166) | def test_not_found_html_view_with_template(self):
    method test_permission_denied_html_view_with_template (line 173) | def test_permission_denied_html_view_with_template(self):

FILE: tests/test_lazy_hyperlinks.py
  class Example (line 12) | class Example(models.Model):
    method __str__ (line 15) | def __str__(self):
  class ExampleSerializer (line 21) | class ExampleSerializer(serializers.HyperlinkedModelSerializer):
    class Meta (line 22) | class Meta:
  function dummy_view (line 27) | def dummy_view(request):
  class TestLazyHyperlinkNames (line 37) | class TestLazyHyperlinkNames(TestCase):
    method setUp (line 38) | def setUp(self):
    method test_lazy_hyperlink_names (line 41) | def test_lazy_hyperlink_names(self):

FILE: tests/test_metadata.py
  class TestMetadata (line 17) | class TestMetadata:
    method test_determine_metadata_abstract_method_raises_proper_error (line 19) | def test_determine_metadata_abstract_method_raises_proper_error(self):
    method test_metadata (line 23) | def test_metadata(self):
    method test_none_metadata (line 49) | def test_none_metadata(self):
    method test_actions (line 62) | def test_actions(self):
    method test_global_permissions (line 187) | def test_global_permissions(self):
    method test_object_permissions (line 217) | def test_object_permissions(self):
    method test_bug_2455_clone_request (line 247) | def test_bug_2455_clone_request(self):
    method test_bug_2477_clone_request (line 261) | def test_bug_2477_clone_request(self):
    method test_dont_show_hidden_fields (line 276) | def test_dont_show_hidden_fields(self):
    method test_list_serializer_metadata_returns_info_about_fields_of_child_serializer (line 297) | def test_list_serializer_metadata_returns_info_about_fields_of_child_s...
  class TestSimpleMetadataFieldInfo (line 311) | class TestSimpleMetadataFieldInfo(TestCase):
    method test_null_boolean_field_info_type (line 312) | def test_null_boolean_field_info_type(self):
    method test_related_field_choices (line 318) | def test_related_field_choices(self):
    method test_decimal_field_info_type (line 327) | def test_decimal_field_info_type(self):
  class TestModelSerializerMetadata (line 335) | class TestModelSerializerMetadata(TestCase):
    method test_read_only_primary_key_related_field (line 336) | def test_read_only_primary_key_related_field(self):

FILE: tests/test_middleware.py
  class PostView (line 21) | class PostView(APIView):
    method post (line 22) | def post(self, request):
  class GetAPIView (line 26) | class GetAPIView(APIView):
    method get (line 27) | def get(self, request):
  function get_func_view (line 32) | def get_func_view(request):
  class ListViewSet (line 36) | class ListViewSet(GenericViewSet):
    method list (line 38) | def list(self, request, *args, **kwargs):
    method list_action (line 44) | def list_action(self, request, *args, **kwargs):
  class RequestUserMiddleware (line 62) | class RequestUserMiddleware:
    method __init__ (line 63) | def __init__(self, get_response):
    method __call__ (line 66) | def __call__(self, request):
  class RequestPOSTMiddleware (line 74) | class RequestPOSTMiddleware:
    method __init__ (line 75) | def __init__(self, get_response):
    method __call__ (line 78) | def __call__(self, request):
  class TestMiddleware (line 97) | class TestMiddleware(APITestCase):
    method test_middleware_can_access_user_when_processing_response (line 100) | def test_middleware_can_access_user_when_processing_response(self):
    method test_middleware_can_access_request_post_when_processing_response (line 108) | def test_middleware_can_access_request_post_when_processing_response(s...
  class TestLoginRequiredMiddlewareCompat (line 127) | class TestLoginRequiredMiddlewareCompat(APITestCase):
    method test_class_based_view (line 134) | def test_class_based_view(self):
    method test_function_based_view (line 138) | def test_function_based_view(self):
    method test_viewset_list (line 142) | def test_viewset_list(self):
    method test_viewset_list_action (line 146) | def test_viewset_list_action(self):

FILE: tests/test_model_serializer.py
  function dedent (line 32) | def dedent(blocktext):
  class CustomField (line 39) | class CustomField(models.Field):
  class OneFieldModel (line 46) | class OneFieldModel(models.Model):
  class RegularFieldsModel (line 50) | class RegularFieldsModel(models.Model):
    method method (line 77) | def method(self):
  class FieldOptionsModel (line 85) | class FieldOptionsModel(models.Model):
  class ChoicesModel (line 96) | class ChoicesModel(models.Model):
  class Issue3674ParentModel (line 100) | class Issue3674ParentModel(models.Model):
  class Issue3674ChildModel (line 104) | class Issue3674ChildModel(models.Model):
  class UniqueChoiceModel (line 109) | class UniqueChoiceModel(models.Model):
  class TestModelSerializer (line 118) | class TestModelSerializer(TestCase):
    method test_create_method (line 119) | def test_create_method(self):
    method test_abstract_model (line 137) | def test_abstract_model(self):
  class TestRegularFieldMappings (line 162) | class TestRegularFieldMappings(TestCase):
    method test_regular_fields (line 164) | def test_regular_fields(self):
    method test_field_options (line 200) | def test_field_options(self):
    method test_nullable_boolean_field_choices (line 220) | def test_nullable_boolean_field_choices(self):
    method test_method_field (line 241) | def test_method_field(self):
    method test_pk_fields (line 258) | def test_pk_fields(self):
    method test_extra_field_kwargs (line 274) | def test_extra_field_kwargs(self):
    method test_extra_field_kwargs_required (line 291) | def test_extra_field_kwargs_required(self):
    method test_invalid_field (line 308) | def test_invalid_field(self):
    method test_missing_field (line 323) | def test_missing_field(self):
    method test_missing_superclass_field (line 342) | def test_missing_superclass_field(self):
    method test_choices_with_nonstandard_args (line 357) | def test_choices_with_nonstandard_args(self):
  class TestDurationFieldMapping (line 366) | class TestDurationFieldMapping(TestCase):
    method test_duration_field (line 367) | def test_duration_field(self):
    method test_duration_field_with_validators (line 386) | def test_duration_field_with_validators(self):
  class TestGenericIPAddressFieldValidation (line 408) | class TestGenericIPAddressFieldValidation(TestCase):
    method test_ip_address_validation (line 409) | def test_ip_address_validation(self):
  class TestPosgresFieldsMapping (line 426) | class TestPosgresFieldsMapping(TestCase):
    method test_hstore_field (line 427) | def test_hstore_field(self):
    method test_array_field (line 442) | def test_array_field(self):
    method test_json_field (line 460) | def test_json_field(self):
  class CustomJSONDecoder (line 478) | class CustomJSONDecoder(json.JSONDecoder):
  class TestDjangoJSONFieldMapping (line 483) | class TestDjangoJSONFieldMapping(TestCase):
    method test_json_field (line 484) | def test_json_field(self):
  class ForeignKeyTargetModel (line 505) | class ForeignKeyTargetModel(models.Model):
  class ManyToManyTargetModel (line 509) | class ManyToManyTargetModel(models.Model):
  class OneToOneTargetModel (line 513) | class OneToOneTargetModel(models.Model):
  class ThroughTargetModel (line 517) | class ThroughTargetModel(models.Model):
  class Supplementary (line 521) | class Supplementary(models.Model):
  class RelationalModel (line 527) | class RelationalModel(models.Model):
  class UniqueTogetherModel (line 534) | class UniqueTogetherModel(models.Model):
    class Meta (line 538) | class Meta:
  class TestRelationalFieldMappings (line 542) | class TestRelationalFieldMappings(TestCase):
    method test_pk_relations (line 543) | def test_pk_relations(self):
    method test_nested_relations (line 559) | def test_nested_relations(self):
    method test_hyperlinked_relations (line 584) | def test_hyperlinked_relations(self):
    method test_nested_hyperlinked_relations (line 600) | def test_nested_hyperlinked_relations(self):
    method test_nested_hyperlinked_relations_starred_source (line 625) | def test_nested_hyperlinked_relations_starred_source(self):
    method test_nested_unique_together_relations (line 656) | def test_nested_unique_together_relations(self):
    method test_pk_reverse_foreign_key (line 675) | def test_pk_reverse_foreign_key(self):
    method test_pk_reverse_one_to_one (line 689) | def test_pk_reverse_one_to_one(self):
    method test_pk_reverse_many_to_many (line 703) | def test_pk_reverse_many_to_many(self):
    method test_pk_reverse_through (line 717) | def test_pk_reverse_through(self):
  class DisplayValueTargetModel (line 732) | class DisplayValueTargetModel(models.Model):
    method __str__ (line 735) | def __str__(self):
  class DisplayValueModel (line 739) | class DisplayValueModel(models.Model):
  class TestRelationalFieldDisplayValue (line 743) | class TestRelationalFieldDisplayValue(TestCase):
    method setUp (line 744) | def setUp(self):
    method test_default_display_value (line 751) | def test_default_display_value(self):
    method test_custom_display_value (line 761) | def test_custom_display_value(self):
  class TestIntegration (line 778) | class TestIntegration(TestCase):
    method setUp (line 779) | def setUp(self):
    method test_pk_retrieval (line 797) | def test_pk_retrieval(self):
    method test_pk_create (line 813) | def test_pk_create(self):
    method test_pk_update (line 861) | def test_pk_update(self):
  class BulkCreateModel (line 912) | class BulkCreateModel(models.Model):
  class TestBulkCreate (line 916) | class TestBulkCreate(TestCase):
    method test_bulk_create (line 917) | def test_bulk_create(self):
  class MetaClassTestModel (line 943) | class MetaClassTestModel(models.Model):
  class TestSerializerMetaClass (line 947) | class TestSerializerMetaClass(TestCase):
    method test_meta_class_fields_option (line 948) | def test_meta_class_fields_option(self):
    method test_meta_class_exclude_option (line 958) | def test_meta_class_exclude_option(self):
    method test_meta_class_fields_and_exclude_options (line 968) | def test_meta_class_fields_and_exclude_options(self):
    method test_declared_fields_with_exclude_option (line 979) | def test_declared_fields_with_exclude_option(self):
  class Issue2704TestCase (line 996) | class Issue2704TestCase(TestCase):
    method test_queryset_all (line 997) | def test_queryset_all(self):
  class Issue7550FooModel (line 1021) | class Issue7550FooModel(models.Model):
  class Issue7550BarModel (line 1028) | class Issue7550BarModel(models.Model):
  class Issue7550TestCase (line 1032) | class Issue7550TestCase(TestCase):
    method test_dotted_source (line 1034) | def test_dotted_source(self):
    method test_dotted_source_with_default (line 1066) | def test_dotted_source_with_default(self):
  class DecimalFieldModel (line 1088) | class DecimalFieldModel(models.Model):
  class TestDecimalFieldMappings (line 1096) | class TestDecimalFieldMappings(TestCase):
    method test_decimal_field_has_decimal_validator (line 1097) | def test_decimal_field_has_decimal_validator(self):
    method test_min_value_is_passed (line 1110) | def test_min_value_is_passed(self):
    method test_max_value_is_passed (line 1124) | def test_max_value_is_passed(self):
  class TestMetaInheritance (line 1139) | class TestMetaInheritance(TestCase):
    method test_extra_kwargs_not_altered (line 1140) | def test_extra_kwargs_not_altered(self):
  class OneToOneTargetTestModel (line 1170) | class OneToOneTargetTestModel(models.Model):
  class OneToOneSourceTestModel (line 1174) | class OneToOneSourceTestModel(models.Model):
  class TestModelFieldValues (line 1178) | class TestModelFieldValues(TestCase):
    method test_model_field (line 1179) | def test_model_field(self):
  class TestUniquenessOverride (line 1191) | class TestUniquenessOverride(TestCase):
    method test_required_not_overwritten (line 1192) | def test_required_not_overwritten(self):
  class Issue3674Test (line 1211) | class Issue3674Test(TestCase):
    method test_nonPK_foreignkey_model_serializer (line 1212) | def test_nonPK_foreignkey_model_serializer(self):
    method test_nonID_PK_foreignkey_model_serializer (line 1245) | def test_nonID_PK_foreignkey_model_serializer(self):
  class Issue4897TestCase (line 1270) | class Issue4897TestCase(TestCase):
    method test_should_assert_if_writing_readonly_fields (line 1271) | def test_should_assert_if_writing_readonly_fields(self):
  class Test5004UniqueChoiceField (line 1285) | class Test5004UniqueChoiceField(TestCase):
    method test_unique_choice_field (line 1286) | def test_unique_choice_field(self):
  class TestFieldSource (line 1298) | class TestFieldSource(TestCase):
    method test_traverse_nullable_fk (line 1299) | def test_traverse_nullable_fk(self):
    method test_named_field_source (line 1318) | def test_named_field_source(self):
  class Issue6110TestModel (line 1338) | class Issue6110TestModel(models.Model):
  class Issue6110ModelSerializer (line 1345) | class Issue6110ModelSerializer(serializers.ModelSerializer):
    class Meta (line 1346) | class Meta:
  class Issue6110Test (line 1351) | class Issue6110Test(TestCase):
    method test_model_serializer_custom_manager (line 1352) | def test_model_serializer_custom_manager(self):
    method test_model_serializer_custom_manager_error_message (line 1356) | def test_model_serializer_custom_manager_error_message(self):
  class Issue6751Model (line 1362) | class Issue6751Model(models.Model):
  function process_issue6751model_m2m_changed (line 1369) | def process_issue6751model_m2m_changed(action, instance, **_):
  class Issue6751Test (line 1375) | class Issue6751Test(TestCase):
    method test_model_serializer_save_m2m_after_instance (line 1376) | def test_model_serializer_save_m2m_after_instance(self):

FILE: tests/test_multitable_inheritance.py
  class ParentModel (line 9) | class ParentModel(RESTFrameworkModel):
  class ChildModel (line 13) | class ChildModel(ParentModel):
  class AssociatedModel (line 17) | class AssociatedModel(RESTFrameworkModel):
  class DerivedModelSerializer (line 23) | class DerivedModelSerializer(serializers.ModelSerializer):
    class Meta (line 24) | class Meta:
  class AssociatedModelSerializer (line 29) | class AssociatedModelSerializer(serializers.ModelSerializer):
    class Meta (line 30) | class Meta:
  class InheritedModelSerializationTests (line 36) | class InheritedModelSerializationTests(TestCase):
    method test_multitable_inherited_model_fields_as_expected (line 38) | def test_multitable_inherited_model_fields_as_expected(self):
    method test_onetoone_primary_key_model_fields_as_expected (line 47) | def test_onetoone_primary_key_model_fields_as_expected(self):
    method test_data_is_valid_without_parent_ptr (line 57) | def test_data_is_valid_without_parent_ptr(self):

FILE: tests/test_negotiation.py
  class MockOpenAPIRenderer (line 16) | class MockOpenAPIRenderer(BaseRenderer):
  class MockJSONRenderer (line 21) | class MockJSONRenderer(BaseRenderer):
  class MockHTMLRenderer (line 25) | class MockHTMLRenderer(BaseRenderer):
  class NoCharsetSpecifiedRenderer (line 29) | class NoCharsetSpecifiedRenderer(BaseRenderer):
  class TestAcceptedMediaType (line 33) | class TestAcceptedMediaType(TestCase):
    method setUp (line 34) | def setUp(self):
    method select_renderer (line 38) | def select_renderer(self, request):
    method test_client_without_accept_use_renderer (line 41) | def test_client_without_accept_use_renderer(self):
    method test_client_underspecifies_accept_use_renderer (line 46) | def test_client_underspecifies_accept_use_renderer(self):
    method test_client_overspecifies_accept_use_client (line 51) | def test_client_overspecifies_accept_use_client(self):
    method test_client_specifies_parameter (line 56) | def test_client_specifies_parameter(self):
    method test_match_is_false_if_main_types_not_match (line 62) | def test_match_is_false_if_main_types_not_match(self):
    method test_mediatype_match_is_false_if_keys_not_match (line 67) | def test_mediatype_match_is_false_if_keys_not_match(self):
    method test_mediatype_precedence_with_wildcard_subtype (line 72) | def test_mediatype_precedence_with_wildcard_subtype(self):
    method test_mediatype_string_representation (line 76) | def test_mediatype_string_representation(self):
    method test_raise_error_if_no_suitable_renderers_found (line 80) | def test_raise_error_if_no_suitable_renderers_found(self):
  class BaseContentNegotiationTests (line 88) | class BaseContentNegotiationTests(TestCase):
    method setUp (line 90) | def setUp(self):
    method test_raise_error_for_abstract_select_parser_method (line 93) | def test_raise_error_for_abstract_select_parser_method(self):
    method test_raise_error_for_abstract_select_renderer_method (line 97) | def test_raise_error_for_abstract_select_renderer_method(self):

FILE: tests/test_one_to_one_with_inheritance.py
  class ChildAssociatedModel (line 11) | class ChildAssociatedModel(RESTFrameworkModel):
  class DerivedModelSerializer (line 17) | class DerivedModelSerializer(serializers.ModelSerializer):
    class Meta (line 18) | class Meta:
  class ChildAssociatedModelSerializer (line 23) | class ChildAssociatedModelSerializer(serializers.ModelSerializer):
    class Meta (line 25) | class Meta:
  class InheritedModelSerializationTests (line 31) | class InheritedModelSerializationTests(TestCase):
    method test_multitable_inherited_model_fields_as_expected (line 33) | def test_multitable_inherited_model_fields_as_expected(self):

FILE: tests/test_pagination.py
  class TestPaginationIntegration (line 16) | class TestPaginationIntegration:
    method setup_method (line 21) | def setup_method(self):
    method test_filtered_items_are_paginated (line 42) | def test_filtered_items_are_paginated(self):
    method test_setting_page_size (line 53) | def test_setting_page_size(self):
    method test_setting_page_size_over_maximum (line 67) | def test_setting_page_size_over_maximum(self):
    method test_setting_page_size_to_zero (line 85) | def test_setting_page_size_to_zero(self):
    method test_additional_query_params_are_preserved (line 99) | def test_additional_query_params_are_preserved(self):
    method test_empty_query_params_are_preserved (line 110) | def test_empty_query_params_are_preserved(self):
    method test_404_not_found_for_zero_page (line 121) | def test_404_not_found_for_zero_page(self):
    method test_404_not_found_for_invalid_page (line 129) | def test_404_not_found_for_invalid_page(self):
  class TestPaginationDisabledIntegration (line 138) | class TestPaginationDisabledIntegration:
    method setup_method (line 143) | def setup_method(self):
    method test_unpaginated_list (line 154) | def test_unpaginated_list(self):
  class TestPageNumberPagination (line 161) | class TestPageNumberPagination:
    method setup_method (line 166) | def setup_method(self):
    method paginate_queryset (line 173) | def paginate_queryset(self, request):
    method get_paginated_content (line 176) | def get_paginated_content(self, queryset):
    method get_html_context (line 180) | def get_html_context(self):
    method test_no_page_number (line 184) | def test_no_page_number(self, url):
    method test_second_page (line 210) | def test_second_page(self):
    method test_last_page (line 234) | def test_last_page(self):
    method test_invalid_page (line 258) | def test_invalid_page(self):
    method test_get_paginated_response_schema (line 263) | def test_get_paginated_response_schema(self):
  class TestPageNumberPaginationOverride (line 300) | class TestPageNumberPaginationOverride:
    method setup_method (line 307) | def setup_method(self):
    method paginate_queryset (line 320) | def paginate_queryset(self, request):
    method get_paginated_content (line 323) | def get_paginated_content(self, queryset):
    method get_html_context (line 327) | def get_html_context(self):
    method test_no_page_number (line 330) | def test_no_page_number(self):
    method test_invalid_page (line 352) | def test_invalid_page(self):
  class TestLimitOffset (line 358) | class TestLimitOffset:
    method setup_method (line 363) | def setup_method(self):
    method paginate_queryset (line 371) | def paginate_queryset(self, request):
    method get_paginated_content (line 374) | def get_paginated_content(self, queryset):
    method get_html_context (line 378) | def get_html_context(self):
    method test_no_offset (line 381) | def test_no_offset(self):
    method test_pagination_not_applied_if_limit_or_default_limit_not_set (line 407) | def test_pagination_not_applied_if_limit_or_default_limit_not_set(self):
    method test_single_offset (line 414) | def test_single_offset(self):
    method test_first_offset (line 443) | def test_first_offset(self):
    method test_middle_offset (line 467) | def test_middle_offset(self):
    method test_ending_offset (line 492) | def test_ending_offset(self):
    method test_erroneous_offset (line 516) | def test_erroneous_offset(self):
    method test_invalid_offset (line 522) | def test_invalid_offset(self):
    method test_invalid_limit (line 530) | def test_invalid_limit(self):
    method test_zero_limit (line 543) | def test_zero_limit(self):
    method test_max_limit (line 556) | def test_max_limit(self):
    method test_get_paginated_response_schema (line 575) | def test_get_paginated_response_schema(self):
  class CursorPaginationTestsMixin (line 612) | class CursorPaginationTestsMixin:
    method test_invalid_cursor (line 614) | def test_invalid_cursor(self):
    method test_use_with_ordering_filter (line 619) | def test_use_with_ordering_filter(self):
    method test_use_with_ordering_filter_without_ordering_default_value (line 637) | def test_use_with_ordering_filter_without_ordering_default_value(self):
    method test_cursor_pagination (line 655) | def test_cursor_pagination(self):
    method test_cursor_pagination_current_page_empty_forward (line 724) | def test_cursor_pagination_current_page_empty_forward(self):
    method test_cursor_pagination_current_page_empty_reverse (line 747) | def test_cursor_pagination_current_page_empty_reverse(self):
    method test_cursor_pagination_with_page_size (line 770) | def test_cursor_pagination_with_page_size(self):
    method test_cursor_pagination_with_page_size_over_limit (line 782) | def test_cursor_pagination_with_page_size_over_limit(self):
    method test_cursor_pagination_with_page_size_zero (line 794) | def test_cursor_pagination_with_page_size_zero(self):
    method test_cursor_pagination_with_page_size_negative (line 861) | def test_cursor_pagination_with_page_size_negative(self):
    method test_get_paginated_response_schema (line 928) | def test_get_paginated_response_schema(self):
  class TestCursorPagination (line 961) | class TestCursorPagination(CursorPaginationTestsMixin):
    method setup_method (line 966) | def setup_method(self):
    method get_pages (line 1014) | def get_pages(self, url):
  class CursorPaginationModel (line 1044) | class CursorPaginationModel(models.Model):
  class TestCursorPaginationWithValueQueryset (line 1048) | class TestCursorPaginationWithValueQueryset(CursorPaginationTestsMixin, ...
    method setUp (line 1053) | def setUp(self):
    method get_pages (line 1074) | def get_pages(self, url):
  function test_get_displayed_page_numbers (line 1104) | def test_get_displayed_page_numbers():

FILE: tests/test_parsers.py
  class Form (line 20) | class Form(forms.Form):
  class TestFormParser (line 25) | class TestFormParser(TestCase):
    method setUp (line 26) | def setUp(self):
    method test_parse (line 29) | def test_parse(self):
  class TestFileUploadParser (line 39) | class TestFileUploadParser(TestCase):
    method setUp (line 40) | def setUp(self):
    method test_parse (line 52) | def test_parse(self):
    method test_parse_missing_filename (line 62) | def test_parse_missing_filename(self):
    method test_parse_missing_filename_multiple_upload_handlers (line 73) | def test_parse_missing_filename_multiple_upload_handlers(self):
    method test_parse_missing_filename_large_file (line 89) | def test_parse_missing_filename_large_file(self):
    method test_get_filename (line 103) | def test_get_filename(self):
    method test_get_encoded_filename (line 108) | def test_get_encoded_filename(self):
    method __replace_content_disposition (line 123) | def __replace_content_disposition(self, disposition):
  class TestJSONParser (line 127) | class TestJSONParser(TestCase):
    method bytes (line 128) | def bytes(self, value):
    method test_float_strictness (line 131) | def test_float_strictness(self):
  class TestPOSTAccessed (line 145) | class TestPOSTAccessed(TestCase):
    method setUp (line 146) | def setUp(self):
    method test_post_accessed_in_post_method (line 149) | def test_post_accessed_in_post_method(self):
    method test_post_accessed_in_post_method_with_json_parser (line 156) | def test_post_accessed_in_post_method_with_json_parser(self):
    method test_post_accessed_in_put_method (line 163) | def test_post_accessed_in_put_method(self):
    method test_request_read_before_parsing (line 170) | def test_request_read_before_parsing(self):

FILE: tests/test_permissions.py
  class BasicSerializer (line 22) | class BasicSerializer(serializers.ModelSerializer):
    class Meta (line 23) | class Meta:
  class RootView (line 28) | class RootView(generics.ListCreateAPIView):
  class InstanceView (line 35) | class InstanceView(generics.RetrieveUpdateDestroyAPIView):
  class GetQuerySetListView (line 42) | class GetQuerySetListView(generics.ListCreateAPIView):
    method get_queryset (line 47) | def get_queryset(self):
  class EmptyListView (line 51) | class EmptyListView(generics.ListCreateAPIView):
  class IgnoredGetQuerySetListView (line 58) | class IgnoredGetQuerySetListView(GetQuerySetListView):
  function basic_auth_header (line 70) | def basic_auth_header(username, password):
  class ModelPermissionsIntegrationTests (line 76) | class ModelPermissionsIntegrationTests(TestCase):
    method setUp (line 77) | def setUp(self):
    method test_has_create_permissions (line 97) | def test_has_create_permissions(self):
    method test_api_root_view_discard_default_django_model_permission (line 103) | def test_api_root_view_discard_default_django_model_permission(self):
    method test_ignore_model_permissions_with_unauthenticated_user (line 115) | def test_ignore_model_permissions_with_unauthenticated_user(self):
    method test_ignore_model_permissions_with_authenticated_user (line 125) | def test_ignore_model_permissions_with_authenticated_user(self):
    method test_get_queryset_has_create_permissions (line 136) | def test_get_queryset_has_create_permissions(self):
    method test_has_put_permissions (line 142) | def test_has_put_permissions(self):
    method test_has_delete_permissions (line 148) | def test_has_delete_permissions(self):
    method test_does_not_have_create_permissions (line 153) | def test_does_not_have_create_permissions(self):
    method test_does_not_have_put_permissions (line 159) | def test_does_not_have_put_permissions(self):
    method test_does_not_have_delete_permissions (line 165) | def test_does_not_have_delete_permissions(self):
    method test_options_permitted (line 170) | def test_options_permitted(self):
    method test_options_disallowed (line 189) | def test_options_disallowed(self):
    method test_options_updateonly (line 206) | def test_options_updateonly(self):
    method test_empty_view_does_not_assert (line 224) | def test_empty_view_does_not_assert(self):
    method test_calling_method_not_allowed (line 229) | def test_calling_method_not_allowed(self):
    method test_check_auth_before_queryset_call (line 238) | def test_check_auth_before_queryset_call(self):
    method test_queryset_assertions (line 248) | def test_queryset_assertions(self):
  class BasicPermModel (line 270) | class BasicPermModel(models.Model):
    class Meta (line 273) | class Meta:
  class BasicPermSerializer (line 277) | class BasicPermSerializer(serializers.ModelSerializer):
    class Meta (line 278) | class Meta:
  class ViewObjectPermissions (line 284) | class ViewObjectPermissions(permissions.DjangoObjectPermissions):
  class ObjectPermissionInstanceView (line 296) | class ObjectPermissionInstanceView(generics.RetrieveUpdateDestroyAPIView):
  class ObjectPermissionListView (line 306) | class ObjectPermissionListView(generics.ListAPIView):
  class GetQuerysetObjectPermissionInstanceView (line 316) | class GetQuerysetObjectPermissionInstanceView(generics.RetrieveUpdateDes...
    method get_queryset (line 321) | def get_queryset(self):
  class ObjectPermissionsIntegrationTests (line 329) | class ObjectPermissionsIntegrationTests(TestCase):
    method setUp (line 333) | def setUp(self):
    method test_can_delete_permissions (line 380) | def test_can_delete_permissions(self):
    method test_cannot_delete_permissions (line 385) | def test_cannot_delete_permissions(self):
    method test_can_update_permissions (line 391) | def test_can_update_permissions(self):
    method test_cannot_update_permissions (line 400) | def test_cannot_update_permissions(self):
    method test_cannot_update_permissions_non_existing (line 408) | def test_cannot_update_permissions_non_existing(self):
    method test_can_read_permissions (line 417) | def test_can_read_permissions(self):
    method test_cannot_read_permissions (line 422) | def test_cannot_read_permissions(self):
    method test_can_read_get_queryset_permissions (line 427) | def test_can_read_get_queryset_permissions(self):
    method test_can_read_list_permissions (line 439) | def test_can_read_list_permissions(self):
    method test_cannot_method_not_allowed (line 445) | def test_cannot_method_not_allowed(self):
  class BasicPerm (line 451) | class BasicPerm(permissions.BasePermission):
    method has_permission (line 452) | def has_permission(self, request, view):
  class BasicPermWithDetail (line 456) | class BasicPermWithDetail(permissions.BasePermission):
    method has_permission (line 460) | def has_permission(self, request, view):
  class BasicObjectPerm (line 464) | class BasicObjectPerm(permissions.BasePermission):
    method has_object_permission (line 465) | def has_object_permission(self, request, view, obj):
  class BasicObjectPermWithDetail (line 469) | class BasicObjectPermWithDetail(permissions.BasePermission):
    method has_object_permission (line 473) | def has_object_permission(self, request, view, obj):
  class PermissionInstanceView (line 477) | class PermissionInstanceView(generics.RetrieveUpdateDestroyAPIView):
  class DeniedView (line 482) | class DeniedView(PermissionInstanceView):
  class DeniedViewWithDetail (line 486) | class DeniedViewWithDetail(PermissionInstanceView):
  class DeniedObjectView (line 490) | class DeniedObjectView(PermissionInstanceView):
  class DeniedObjectViewWithDetail (line 494) | class DeniedObjectViewWithDetail(PermissionInstanceView):
  class CustomPermissionsTests (line 507) | class CustomPermissionsTests(TestCase):
    method setUp (line 508) | def setUp(self):
    method test_permission_denied (line 516) | def test_permission_denied(self):
    method test_permission_denied_with_custom_detail (line 523) | def test_permission_denied_with_custom_detail(self):
    method test_permission_denied_for_object (line 530) | def test_permission_denied_for_object(self):
    method test_permission_denied_for_object_with_custom_detail (line 537) | def test_permission_denied_for_object_with_custom_detail(self):
  class PermissionsCompositionTests (line 545) | class PermissionsCompositionTests(TestCase):
    method setUp (line 547) | def setUp(self):
    method test_and_false (line 558) | def test_and_false(self):
    method test_and_true (line 564) | def test_and_true(self):
    method test_or_false (line 570) | def test_or_false(self):
    method test_or_true (line 576) | def test_or_true(self):
    method test_not_false (line 582) | def test_not_false(self):
    method test_not_true (line 588) | def test_not_true(self):
    method test_several_levels_without_negation (line 594) | def test_several_levels_without_negation(self):
    method test_several_levels_and_precedence_with_negation (line 605) | def test_several_levels_and_precedence_with_negation(self):
    method test_several_levels_and_precedence (line 616) | def test_several_levels_and_precedence(self):
    method test_or_laziness (line 627) | def test_or_laziness(self):
    method test_object_or_laziness (line 647) | def test_object_or_laziness(self):
    method test_and_laziness (line 667) | def test_and_laziness(self):
    method test_object_and_laziness (line 687) | def test_object_and_laziness(self):
    method test_unimplemented_has_object_permission (line 707) | def test_unimplemented_has_object_permission(self):
    method test_operand_holder_is_hashable (line 720) | def test_operand_holder_is_hashable(self):
    method test_operand_holder_hash_same_for_same_operands_and_operator (line 723) | def test_operand_holder_hash_same_for_same_operands_and_operator(self):
    method test_operand_holder_hash_differs_for_different_operands (line 733) | def test_operand_holder_hash_differs_for_different_operands(self):
    method test_operand_holder_hash_differs_for_different_operators (line 748) | def test_operand_holder_hash_differs_for_different_operators(self):
    method test_filtering_permissions (line 758) | def test_filtering_permissions(self):

FILE: tests/test_prefetch_related.py
  class UserSerializer (line 10) | class UserSerializer(serializers.ModelSerializer):
    class Meta (line 11) | class Meta:
  class UserUpdate (line 16) | class UserUpdate(generics.UpdateAPIView):
  class TestPrefetchRelatedUpdates (line 21) | class TestPrefetchRelatedUpdates(TestCase):
    method setUp (line 22) | def setUp(self):
    method test_prefetch_related_updates (line 27) | def test_prefetch_related_updates(self):
    method test_prefetch_related_excluding_instance_from_original_queryset (line 42) | def test_prefetch_related_excluding_instance_from_original_queryset(se...
    method test_can_update_without_queryset_on_class_view (line 60) | def test_can_update_without_queryset_on_class_view(self):

FILE: tests/test_relations.py
  class TestStringRelatedField (line 19) | class TestStringRelatedField(APISimpleTestCase):
    method setUp (line 20) | def setUp(self):
    method test_string_related_representation (line 24) | def test_string_related_representation(self):
  class MockApiSettings (line 29) | class MockApiSettings:
    method __init__ (line 30) | def __init__(self, cutoff, cutoff_text):
  class TestRelatedFieldHTMLCutoff (line 35) | class TestRelatedFieldHTMLCutoff(APISimpleTestCase):
    method setUp (line 36) | def setUp(self):
    method test_no_settings (line 42) | def test_no_settings(self):
    method test_settings_cutoff (line 51) | def test_settings_cutoff(self):
    method test_settings_cutoff_none (line 61) | def test_settings_cutoff_none(self):
    method test_settings_kwargs_cutoff (line 71) | def test_settings_kwargs_cutoff(self):
  class TestPrimaryKeyRelatedField (line 84) | class TestPrimaryKeyRelatedField(APISimpleTestCase):
    method setUp (line 85) | def setUp(self):
    method test_pk_related_lookup_exists (line 94) | def test_pk_related_lookup_exists(self):
    method test_pk_related_lookup_does_not_exist (line 98) | def test_pk_related_lookup_does_not_exist(self):
    method test_pk_related_lookup_invalid_type (line 104) | def test_pk_related_lookup_invalid_type(self):
    method test_pk_related_lookup_bool (line 110) | def test_pk_related_lookup_bool(self):
    method test_pk_representation (line 116) | def test_pk_representation(self):
    method test_explicit_many_false (line 120) | def test_explicit_many_false(self):
  class TestProxiedPrimaryKeyRelatedField (l
Condensed preview — 438 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (3,588K chars).
[
  {
    "path": ".gitattributes",
    "chars": 65,
    "preview": "docs/theme/src/drf-logos.fig filter=lfs diff=lfs merge=lfs -text\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "chars": 62,
    "preview": "github: [browniebroke]\nopen_collective: django-rest-framework\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 309,
    "preview": "blank_issues_enabled: false\ncontact_links:\n- name: Discussions\n  url: https://github.com/encode/django-rest-framework/di"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 1191,
    "preview": "# Keep GitHub Actions up to date with GitHub's Dependabot...\n# https://docs.github.com/en/code-security/dependabot/worki"
  },
  {
    "path": ".github/release.yml",
    "chars": 525,
    "preview": "changelog:\n  exclude:\n    labels:\n      - dependencies\n      - Internal\n      - CI\n      - Documentation\n    authors:\n  "
  },
  {
    "path": ".github/stale.yml",
    "chars": 712,
    "preview": "# Documentation: https://github.com/probot/stale\n\n# Number of days of inactivity before an issue becomes stale\ndaysUntil"
  },
  {
    "path": ".github/workflows/main.yml",
    "chars": 2101,
    "preview": "name: CI\n\non:\n  push:\n    branches:\n    - main\n  pull_request:\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github."
  },
  {
    "path": ".github/workflows/mkdocs-deploy.yml",
    "chars": 634,
    "preview": "name: mkdocs\n\non:\n  push:\n    branches:\n      - main\n    paths:\n      - docs/**\n      - docs_theme/**\n      - pyproject."
  },
  {
    "path": ".github/workflows/release.yml",
    "chars": 3813,
    "preview": "name: Publish Release\n\nconcurrency:\n  # stop previous release runs if tag is recreated\n  group: release-${{ github.ref }"
  },
  {
    "path": ".gitignore",
    "chars": 172,
    "preview": "*.pyc\n*.db\n*~\n*.py.bak\n\n\n/site/\n/htmlcov/\n/coverage/\n/build/\n/dist/\n/*.egg-info/\n/env/\nMANIFEST\ncoverage.*\n.coverage\n.ca"
  },
  {
    "path": ".pre-commit-config.yaml",
    "chars": 1122,
    "preview": "repos:\n- repo: https://github.com/pre-commit/pre-commit-hooks\n  rev: v6.0.0\n  hooks:\n  - id: check-added-large-files\n  -"
  },
  {
    "path": ".readthedocs.yaml",
    "chars": 415,
    "preview": "# Read the Docs configuration file\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details\n\n# Requir"
  },
  {
    "path": ".tx/config",
    "chars": 295,
    "preview": "[main]\nhost = https://www.transifex.com\nlang_map = sr@latin:sr_Latn, zh-Hans:zh_Hans, zh-Hant:zh_Hant\n\n[django-rest-fram"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 728,
    "preview": "# Contributing to REST framework\n\nAt this point in its lifespan we consider Django REST framework to be essentially feat"
  },
  {
    "path": "LICENSE.md",
    "chars": 1536,
    "preview": "# License\n\nCopyright © 2011-present, [Encode OSS Ltd](https://www.encode.io/).\nAll rights reserved.\n\nRedistribution and "
  },
  {
    "path": "MANIFEST.in",
    "chars": 78,
    "preview": "recursive-include tests/ *\nglobal-exclude __pycache__\nglobal-exclude *.py[co]\n"
  },
  {
    "path": "PULL_REQUEST_TEMPLATE.md",
    "chars": 384,
    "preview": "*Note*: Before submitting a code change, please review our [contributing guidelines](https://www.django-rest-framework.o"
  },
  {
    "path": "README.md",
    "chars": 6422,
    "preview": "# [Django REST framework][docs]\n\n[![build-status-image]][build-status]\n[![coverage-status-image]][codecov]\n[![pypi-versi"
  },
  {
    "path": "SECURITY.md",
    "chars": 234,
    "preview": "# Security Policy\n\n## Reporting a Vulnerability\n\n**Please report security issues by emailing security@encode.io**.\n\nThe "
  },
  {
    "path": "codecov.yml",
    "chars": 131,
    "preview": "coverage:\n  precision: 2\n  round: down\n  range: \"80...100\"\n\n  status:\n    project: yes\n    patch: no\n    changes: no\n\nco"
  },
  {
    "path": "codespell-ignore-words.txt",
    "chars": 55,
    "preview": "Tim\nassertIn\nIAM\nendcode\ndeque\nthead\nlets\nfo\nmalcom\nser"
  },
  {
    "path": "docs/CNAME",
    "chars": 30,
    "preview": "www.django-rest-framework.org\n"
  },
  {
    "path": "docs/api-guide/authentication.md",
    "chars": 28252,
    "preview": "---\nsource:\n    - authentication.py\n---\n\n> Auth needs to be pluggable.\n>\n> &mdash; Jacob Kaplan-Moss, [\"REST worst pract"
  },
  {
    "path": "docs/api-guide/caching.md",
    "chars": 2992,
    "preview": "# Caching\n\n> A certain woman had a very sharp consciousness but almost no\n> memory ... She remembered enough to work, an"
  },
  {
    "path": "docs/api-guide/content-negotiation.md",
    "chars": 4714,
    "preview": "---\nsource:\n    - negotiation.py\n---\n\n> HTTP has provisions for several mechanisms for \"content negotiation\" - the proce"
  },
  {
    "path": "docs/api-guide/exceptions.md",
    "chars": 11971,
    "preview": "---\nsource:\n    - exceptions.py\n---\n\n# Exceptions\n\n> Exceptions… allow error handling to be organized cleanly in a centr"
  },
  {
    "path": "docs/api-guide/fields.md",
    "chars": 44037,
    "preview": "---\nsource:\n    - fields.py\n---\n\n# Serializer fields\n\n> Each field in a Form class is responsible not only for validatin"
  },
  {
    "path": "docs/api-guide/filtering.md",
    "chars": 17294,
    "preview": "---\nsource:\n    - filters.py\n---\n\n# Filtering\n\n> The root QuerySet provided by the Manager describes all objects in the "
  },
  {
    "path": "docs/api-guide/format-suffixes.md",
    "chars": 3986,
    "preview": "---\nsource:\n    - urlpatterns.py\n---\n\n# Format suffixes\n\n> Section 6.2.1 does not say that content negotiation should be"
  },
  {
    "path": "docs/api-guide/generic-views.md",
    "chars": 19623,
    "preview": "---\nsource:\n    - mixins.py\n    - generics.py\n---\n\n# Generic views\n\n> Django’s generic views... were developed as a shor"
  },
  {
    "path": "docs/api-guide/metadata.md",
    "chars": 4756,
    "preview": "---\nsource:\n    - metadata.py\n---\n\n# Metadata\n\n> [The `OPTIONS`] method allows a client to determine the options and/or "
  },
  {
    "path": "docs/api-guide/pagination.md",
    "chars": 18521,
    "preview": "---\nsource:\n    - pagination.py\n---\n\n# Pagination\n\n> Django provides a few classes that help you manage paginated data –"
  },
  {
    "path": "docs/api-guide/parsers.md",
    "chars": 9154,
    "preview": "---\nsource:\n    - parsers.py\n---\n\n# Parsers\n\n> Machine interacting web services tend to use more\nstructured formats for "
  },
  {
    "path": "docs/api-guide/permissions.md",
    "chars": 22550,
    "preview": "---\nsource:\n    - permissions.py\n---\n\n# Permissions\n\n> Authentication or identification by itself is not usually suffici"
  },
  {
    "path": "docs/api-guide/relations.md",
    "chars": 27983,
    "preview": "---\nsource:\n    - relations.py\n---\n\n# Serializer relations\n\n> Data structures, not algorithms, are central to programmin"
  },
  {
    "path": "docs/api-guide/renderers.md",
    "chars": 25135,
    "preview": "---\nsource:\n    - renderers.py\n---\n\n# Renderers\n\n> Before a TemplateResponse instance can be returned to the client, it "
  },
  {
    "path": "docs/api-guide/requests.md",
    "chars": 6737,
    "preview": "---\nsource:\n    - request.py\n---\n\n> If you're doing REST-based web service stuff ... you should ignore request.POST.\n>\n>"
  },
  {
    "path": "docs/api-guide/responses.md",
    "chars": 4680,
    "preview": "---\nsource:\n    - response.py\n---\n\n# Responses\n\n> Unlike basic HttpResponse objects, TemplateResponse objects retain the"
  },
  {
    "path": "docs/api-guide/reverse.md",
    "chars": 2520,
    "preview": "---\nsource:\n    - reverse.py\n---\n\n# Returning URLs\n\n> The central feature that distinguishes the REST architectural styl"
  },
  {
    "path": "docs/api-guide/routers.md",
    "chars": 17679,
    "preview": "---\nsource:\n    - routers.py\n---\n\n# Routers\n\n> Resource routing allows you to quickly declare all of the common routes f"
  },
  {
    "path": "docs/api-guide/schemas.md",
    "chars": 16589,
    "preview": "---\nsource:\n    - schemas\n---\n\n# Schema\n\n> A machine-readable [schema] describes what resources are available via the AP"
  },
  {
    "path": "docs/api-guide/serializers.md",
    "chars": 59766,
    "preview": "---\nsource:\n    - serializers.py\n---\n\n> Expanding the usefulness of the serializers is something that we would\nlike to a"
  },
  {
    "path": "docs/api-guide/settings.md",
    "chars": 16604,
    "preview": "---\nsource:\n    - settings.py\n---\n\n# Settings\n\n> Namespaces are one honking great idea - let's do more of those!\n>\n> &md"
  },
  {
    "path": "docs/api-guide/status-codes.md",
    "chars": 4714,
    "preview": "---\nsource:\n    - status.py\n---\n\n# Status Codes\n\n> 418 I'm a teapot - Any attempt to brew coffee with a teapot should re"
  },
  {
    "path": "docs/api-guide/testing.md",
    "chars": 17810,
    "preview": "---\nsource:\n    - test.py\n---\n\n# Testing\n\n> Code without tests is broken as designed.\n>\n> &mdash; [Jacob Kaplan-Moss][ci"
  },
  {
    "path": "docs/api-guide/throttling.md",
    "chars": 11348,
    "preview": "---\nsource:\n    - throttling.py\n---\n\n# Throttling\n\n> HTTP/1.1 420 Enhance Your Calm\n>\n> [Twitter API rate limiting respo"
  },
  {
    "path": "docs/api-guide/validators.md",
    "chars": 14266,
    "preview": "---\nsource:\n    - validators.py\n---\n\n# Validators\n\n> Validators can be useful for reusing validation logic between diffe"
  },
  {
    "path": "docs/api-guide/versioning.md",
    "chars": 10581,
    "preview": "---\nsource:\n    - versioning.py\n---\n\n# Versioning\n\n> Versioning an interface is just a \"polite\" way to kill deployed cli"
  },
  {
    "path": "docs/api-guide/views.md",
    "chars": 9108,
    "preview": "---\nsource:\n    - decorators.py\n    - views.py\n---\n\n## Class-based Views\n\n> Django's class-based views are a welcome dep"
  },
  {
    "path": "docs/api-guide/viewsets.md",
    "chars": 15507,
    "preview": "---\nsource:\n    - viewsets.py\n---\n\n# ViewSets\n\n> After routing has determined which controller to use for a request, you"
  },
  {
    "path": "docs/community/3.0-announcement.md",
    "chars": 49475,
    "preview": "# Django REST framework 3.0\n\nThe 3.0 release of Django REST framework is the result of almost four years of iteration an"
  },
  {
    "path": "docs/community/3.1-announcement.md",
    "chars": 10663,
    "preview": "# Django REST framework 3.1\n\nThe 3.1 release is an intermediate step in the Kickstarter project releases, and includes a"
  },
  {
    "path": "docs/community/3.10-announcement.md",
    "chars": 6145,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.11-announcement.md",
    "chars": 5413,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.12-announcement.md",
    "chars": 7315,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.13-announcement.md",
    "chars": 1499,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.14-announcement.md",
    "chars": 2300,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.15-announcement.md",
    "chars": 2131,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.16-announcement.md",
    "chars": 1640,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.2-announcement.md",
    "chars": 6225,
    "preview": "# Django REST framework 3.2\n\nThe 3.2 release is the first version to include an admin interface for the browsable API.\n\n"
  },
  {
    "path": "docs/community/3.3-announcement.md",
    "chars": 4167,
    "preview": "# Django REST framework 3.3\n\nThe 3.3 release marks the final work in the Kickstarter funded series. We'd like to offer a"
  },
  {
    "path": "docs/community/3.4-announcement.md",
    "chars": 8439,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.5-announcement.md",
    "chars": 10059,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.6-announcement.md",
    "chars": 8164,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.7-announcement.md",
    "chars": 5999,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.8-announcement.md",
    "chars": 3683,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/3.9-announcement.md",
    "chars": 8809,
    "preview": "<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align: center;\n    margin: 10px 30px"
  },
  {
    "path": "docs/community/contributing.md",
    "chars": 11583,
    "preview": "# Contributing to REST framework\n\n> The world can only really be changed one piece at a time.  The art is picking that p"
  },
  {
    "path": "docs/community/jobs.md",
    "chars": 2307,
    "preview": "# Jobs\n\nLooking for a new Django REST Framework related role? On this site we provide a list of job resources that may b"
  },
  {
    "path": "docs/community/kickstarter-announcement.md",
    "chars": 14406,
    "preview": "# Kickstarting Django REST framework 3\n\n---\n\n<iframe style=\"display: block; margin: 0 auto 0 auto\" width=\"480\" height=\"3"
  },
  {
    "path": "docs/community/mozilla-grant.md",
    "chars": 4912,
    "preview": "# Mozilla Grant\n\nWe have recently been [awarded a Mozilla grant](https://blog.mozilla.org/blog/2016/04/13/mozilla-open-s"
  },
  {
    "path": "docs/community/project-management.md",
    "chars": 4542,
    "preview": "# Project management\n\n> \"No one can whistle a symphony; it takes a whole orchestra to play it\"\n>\n> &mdash; Halford E. Lu"
  },
  {
    "path": "docs/community/release-notes.md",
    "chars": 176897,
    "preview": "# Release Notes\n\n## Versioning\n\n- **Minor** version numbers (0.0.x) are used for changes that are API compatible.  You s"
  },
  {
    "path": "docs/community/third-party-packages.md",
    "chars": 23724,
    "preview": "# Third Party Packages\n\n> Software ecosystems […] establish a community that further accelerates the sharing of knowledg"
  },
  {
    "path": "docs/community/tutorials-and-resources.md",
    "chars": 10381,
    "preview": "# Tutorials and Resources\n\nThere are a wide range of resources available for learning and using Django REST framework. W"
  },
  {
    "path": "docs/index.md",
    "chars": 9377,
    "preview": "---\nhide:\n  - navigation\n---\n\n<style>\n.promo li a {\n    float: left;\n    width: 130px;\n    height: 20px;\n    text-align:"
  },
  {
    "path": "docs/theme/js/prettify-1.0.js",
    "chars": 13632,
    "preview": "var q=null;window.PR_SHOULD_USE_CONTINUATION=!0;\n(function(){function L(a){function m(a){var f=a.charCodeAt(0);if(f!==92"
  },
  {
    "path": "docs/theme/main.html",
    "chars": 343,
    "preview": "{% extends \"base.html\" %}\n\n{% block scripts %}\n    {{ super() }}\n    <script>\n        document$.subscribe(function() {\n "
  },
  {
    "path": "docs/theme/src/README.md",
    "chars": 82,
    "preview": "# DRF logos\n\nThis folder contains the source file for the DRF logos as Figma file."
  },
  {
    "path": "docs/theme/src/drf-logos.fig",
    "chars": 132,
    "preview": "version https://git-lfs.github.com/spec/v1\noid sha256:762ff0dcedaa80a0ba95b9b8fc656d0c5fd2514a70d08335afe0eb06c9e14658\ns"
  },
  {
    "path": "docs/theme/stylesheets/extra.css",
    "chars": 1646,
    "preview": ":root  > * {\n  /* primary */\n  --md-primary-fg-color: #2c2c2c;\n  --md-primary-fg-color--light: #a8a8a8;\n  --md-primary-f"
  },
  {
    "path": "docs/theme/stylesheets/prettify.css",
    "chars": 968,
    "preview": ".com { color: #93a1a1; }\n.lit { color: #195f91; }\n.pun, .opn, .clo { color: #93a1a1; }\n.fun { color: #dc322f; }\n.str, .a"
  },
  {
    "path": "docs/topics/ajax-csrf-cors.md",
    "chars": 3138,
    "preview": "# Working with AJAX, CSRF & CORS\n\n> \"Take a close look at possible CSRF / XSRF vulnerabilities on your own websites.  Th"
  },
  {
    "path": "docs/topics/browsable-api.md",
    "chars": 10803,
    "preview": "# The Browsable API\n\n> It is a profoundly erroneous truism... that we should cultivate the habit of thinking of what we "
  },
  {
    "path": "docs/topics/browser-enhancements.md",
    "chars": 3945,
    "preview": "# Browser enhancements\n\n> \"There are two noncontroversial uses for overloaded POST.  The first is to *simulate* HTTP's u"
  },
  {
    "path": "docs/topics/documenting-your-api.md",
    "chars": 9789,
    "preview": "# Documenting your API\n\n> A REST API should spend almost all of its descriptive effort in defining the media type(s) use"
  },
  {
    "path": "docs/topics/html-and-forms.md",
    "chars": 8708,
    "preview": "# HTML & Forms\n\nREST framework is suitable for returning both API style responses, and regular HTML pages. Additionally,"
  },
  {
    "path": "docs/topics/internationalization.md",
    "chars": 6035,
    "preview": "# Internationalization\n\n> Supporting internationalization is not optional. It must be a core feature.\n>\n> &mdash; [Janni"
  },
  {
    "path": "docs/topics/rest-hypermedia-hateoas.md",
    "chars": 3505,
    "preview": "# REST, Hypermedia & HATEOAS\n\n> You keep using that word \"REST\". I do not think it means what you think it means.\n>\n> &m"
  },
  {
    "path": "docs/topics/writable-nested-serializers.md",
    "chars": 1742,
    "preview": "> To save HTTP requests, it may be convenient to send related documents along with the request.\n>\n> &mdash; [JSON API sp"
  },
  {
    "path": "docs/tutorial/1-serialization.md",
    "chars": 16543,
    "preview": "# Tutorial 1: Serialization\n\n## Introduction\n\nThis tutorial will cover creating a simple pastebin code highlighting Web "
  },
  {
    "path": "docs/tutorial/2-requests-and-responses.md",
    "chars": 8540,
    "preview": "# Tutorial 2: Requests and Responses\n\nFrom this point we're going to really start covering the core of REST framework.\nL"
  },
  {
    "path": "docs/tutorial/3-class-based-views.md",
    "chars": 6246,
    "preview": "# Tutorial 3: Class-based Views\n\nWe can also write our API views using class-based views, rather than function based vie"
  },
  {
    "path": "docs/tutorial/4-authentication-and-permissions.md",
    "chars": 10982,
    "preview": "# Tutorial 4: Authentication & Permissions\n\nCurrently our API doesn't have any restrictions on who can edit or delete co"
  },
  {
    "path": "docs/tutorial/5-relationships-and-hyperlinked-apis.md",
    "chars": 8520,
    "preview": "# Tutorial 5: Relationships & Hyperlinked APIs\n\nAt the moment relationships within our API are represented by using prim"
  },
  {
    "path": "docs/tutorial/6-viewsets-and-routers.md",
    "chars": 6705,
    "preview": "# Tutorial 6: ViewSets & Routers\n\nREST framework includes an abstraction for dealing with `ViewSets`, that allows the de"
  },
  {
    "path": "docs/tutorial/quickstart.md",
    "chars": 7713,
    "preview": "# Quickstart\n\nWe're going to create a simple API to allow admin users to view and edit the users and groups in the syste"
  },
  {
    "path": "licenses/bootstrap.md",
    "chars": 1107,
    "preview": "https://github.com/twbs/bootstrap/\n\nThe MIT License (MIT)\n\nCopyright (c) 2011-2016 Twitter, Inc.\n\nPermission is hereby g"
  },
  {
    "path": "licenses/jquery.json-view.md",
    "chars": 1141,
    "preview": "https://github.com/bazh/jquery.json-view/\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 bazh. (https://github.com/bazh)\n\nPe"
  },
  {
    "path": "mkdocs.yml",
    "chars": 5604,
    "preview": "site_name: Django REST framework\nsite_url: https://www.django-rest-framework.org/\nsite_description: Django REST framewor"
  },
  {
    "path": "pyproject.toml",
    "chars": 3786,
    "preview": "[build-system]\nbuild-backend = \"setuptools.build_meta\"\nrequires = [ \"setuptools>=77.0.3\" ]\n\n[project]\nname = \"djangorest"
  },
  {
    "path": "rest_framework/__init__.py",
    "chars": 821,
    "preview": "r\"\"\"\n______ _____ _____ _____    __\n| ___ \\  ___/  ___|_   _|  / _|                                           | |\n| |_/ "
  },
  {
    "path": "rest_framework/apps.py",
    "chars": 255,
    "preview": "from django.apps import AppConfig\n\n\nclass RestFrameworkConfig(AppConfig):\n    name = 'rest_framework'\n    verbose_name ="
  },
  {
    "path": "rest_framework/authentication.py",
    "chars": 7701,
    "preview": "\"\"\"\nProvides various authentication policies.\n\"\"\"\nimport base64\nimport binascii\n\nfrom django.contrib.auth import authent"
  },
  {
    "path": "rest_framework/authtoken/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "rest_framework/authtoken/admin.py",
    "chars": 1961,
    "preview": "from django.contrib import admin\nfrom django.contrib.admin.utils import quote\nfrom django.contrib.admin.views.main impor"
  },
  {
    "path": "rest_framework/authtoken/apps.py",
    "chars": 198,
    "preview": "from django.apps import AppConfig\nfrom django.utils.translation import gettext_lazy as _\n\n\nclass AuthTokenConfig(AppConf"
  },
  {
    "path": "rest_framework/authtoken/management/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "rest_framework/authtoken/management/commands/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "rest_framework/authtoken/management/commands/drf_create_token.py",
    "chars": 1370,
    "preview": "from django.contrib.auth import get_user_model\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom r"
  },
  {
    "path": "rest_framework/authtoken/migrations/0001_initial.py",
    "chars": 706,
    "preview": "from django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    "
  },
  {
    "path": "rest_framework/authtoken/migrations/0002_auto_20160226_1747.py",
    "chars": 994,
    "preview": "from django.conf import settings\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n    "
  },
  {
    "path": "rest_framework/authtoken/migrations/0003_tokenproxy.py",
    "chars": 552,
    "preview": "# Generated by Django 3.1.1 on 2020-09-28 09:34\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration"
  },
  {
    "path": "rest_framework/authtoken/migrations/0004_alter_tokenproxy_options.py",
    "chars": 379,
    "preview": "# Generated by Django 4.1.3 on 2022-11-24 21:07\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration"
  },
  {
    "path": "rest_framework/authtoken/migrations/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "rest_framework/authtoken/models.py",
    "chars": 1944,
    "preview": "import secrets\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django.utils.translation import gette"
  },
  {
    "path": "rest_framework/authtoken/serializers.py",
    "chars": 1384,
    "preview": "from django.contrib.auth import authenticate\nfrom django.utils.translation import gettext_lazy as _\n\nfrom rest_framework"
  },
  {
    "path": "rest_framework/authtoken/views.py",
    "chars": 1212,
    "preview": "from rest_framework import parsers, renderers\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.auth"
  },
  {
    "path": "rest_framework/checks.py",
    "chars": 970,
    "preview": "from django.core.checks import Tags, Warning, register\n\n\n@register(Tags.compatibility)\ndef pagination_system_check(app_c"
  },
  {
    "path": "rest_framework/compat.py",
    "chars": 6073,
    "preview": "\"\"\"\nThe `compat` module provides support for backwards compatibility with older\nversions of Django/Python, and compatibi"
  },
  {
    "path": "rest_framework/decorators.py",
    "chars": 9974,
    "preview": "\"\"\"\nThe most important decorator in this module is `@api_view`, which is used\nfor writing function-based views with REST"
  },
  {
    "path": "rest_framework/exceptions.py",
    "chars": 8159,
    "preview": "\"\"\"\nHandled exceptions raised by REST framework.\n\nIn addition, Django's built in 403 and 404 exceptions are handled.\n(`d"
  },
  {
    "path": "rest_framework/fields.py",
    "chars": 71109,
    "preview": "import contextlib\nimport copy\nimport datetime\nimport decimal\nimport functools\nimport inspect\nimport re\nimport uuid\nimpor"
  },
  {
    "path": "rest_framework/filters.py",
    "chars": 12899,
    "preview": "\"\"\"\nProvides generic filtering backends that can be used to filter the results\nreturned by list views.\n\"\"\"\nimport operat"
  },
  {
    "path": "rest_framework/generics.py",
    "chars": 10163,
    "preview": "\"\"\"\nGeneric views that provide commonly needed behavior.\n\"\"\"\nfrom django.core.exceptions import ValidationError\nfrom dja"
  },
  {
    "path": "rest_framework/locale/ach/LC_MESSAGES/django.po",
    "chars": 9444,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ar/LC_MESSAGES/django.po",
    "chars": 16703,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/az/LC_MESSAGES/django.po",
    "chars": 15820,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/be/LC_MESSAGES/django.po",
    "chars": 9586,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/bg/LC_MESSAGES/django.po",
    "chars": 16152,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ca/LC_MESSAGES/django.po",
    "chars": 15700,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ca_ES/LC_MESSAGES/django.po",
    "chars": 9459,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/cs/LC_MESSAGES/django.po",
    "chars": 16099,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/da/LC_MESSAGES/django.po",
    "chars": 15903,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/de/LC_MESSAGES/django.po",
    "chars": 17735,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/el/LC_MESSAGES/django.po",
    "chars": 16233,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/el_GR/LC_MESSAGES/django.po",
    "chars": 9458,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/en/LC_MESSAGES/django.po",
    "chars": 16559,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/en_AU/LC_MESSAGES/django.po",
    "chars": 9463,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/en_CA/LC_MESSAGES/django.po",
    "chars": 9460,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/en_US/LC_MESSAGES/django.po",
    "chars": 11971,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/es/LC_MESSAGES/django.po",
    "chars": 17689,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/et/LC_MESSAGES/django.po",
    "chars": 15922,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/fa/LC_MESSAGES/django.po",
    "chars": 16580,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/fa_IR/LC_MESSAGES/django.po",
    "chars": 15743,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/fi/LC_MESSAGES/django.po",
    "chars": 15946,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/fr/LC_MESSAGES/django.po",
    "chars": 17745,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/fr_CA/LC_MESSAGES/django.po",
    "chars": 9458,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/gl/LC_MESSAGES/django.po",
    "chars": 9446,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/gl_ES/LC_MESSAGES/django.po",
    "chars": 9543,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/he_IL/LC_MESSAGES/django.po",
    "chars": 9459,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/hu/LC_MESSAGES/django.po",
    "chars": 16403,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/hy/LC_MESSAGES/django.po",
    "chars": 15952,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/id/LC_MESSAGES/django.po",
    "chars": 14171,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/it/LC_MESSAGES/django.po",
    "chars": 16592,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ja/LC_MESSAGES/django.po",
    "chars": 14364,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/kk/LC_MESSAGES/django.po",
    "chars": 17167,
    "preview": "# This file is distributed under the same license as the Django REST framework package.\n# Translators:\n# Dulat Kushibaye"
  },
  {
    "path": "rest_framework/locale/ko_KR/LC_MESSAGES/django.po",
    "chars": 15660,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/lt/LC_MESSAGES/django.po",
    "chars": 14066,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/lv/LC_MESSAGES/django.po",
    "chars": 16046,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/mk/LC_MESSAGES/django.po",
    "chars": 15834,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/nb/LC_MESSAGES/django.po",
    "chars": 15879,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ne_NP/LC_MESSAGES/django.po",
    "chars": 16004,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/nl/LC_MESSAGES/django.po",
    "chars": 16329,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/nn/LC_MESSAGES/django.po",
    "chars": 9455,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/no/LC_MESSAGES/django.po",
    "chars": 9447,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/pl/LC_MESSAGES/django.po",
    "chars": 16457,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/pt/LC_MESSAGES/django.po",
    "chars": 16354,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/pt_BR/LC_MESSAGES/django.po",
    "chars": 17686,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/pt_PT/LC_MESSAGES/django.po",
    "chars": 9465,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ro/LC_MESSAGES/django.po",
    "chars": 16478,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ru/LC_MESSAGES/django.po",
    "chars": 16426,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/ru_RU/LC_MESSAGES/django.po",
    "chars": 13764,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/sk/LC_MESSAGES/django.po",
    "chars": 15900,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/sl/LC_MESSAGES/django.po",
    "chars": 15803,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/sv/LC_MESSAGES/django.po",
    "chars": 16018,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/th/LC_MESSAGES/django.po",
    "chars": 13982,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/tr/LC_MESSAGES/django.po",
    "chars": 17156,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/tr_TR/LC_MESSAGES/django.po",
    "chars": 15945,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/uk/LC_MESSAGES/django.po",
    "chars": 16371,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/vi/LC_MESSAGES/django.po",
    "chars": 12742,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/zh_CN/LC_MESSAGES/django.po",
    "chars": 13825,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/zh_Hans/LC_MESSAGES/django.po",
    "chars": 14140,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/zh_Hant/LC_MESSAGES/django.po",
    "chars": 12813,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/locale/zh_TW/LC_MESSAGES/django.po",
    "chars": 9453,
    "preview": "# SOME DESCRIPTIVE TITLE.\n# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER\n# This file is distributed under the same "
  },
  {
    "path": "rest_framework/management/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "rest_framework/management/commands/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "rest_framework/management/commands/generateschema.py",
    "chars": 2061,
    "preview": "from django.core.management.base import BaseCommand\nfrom django.utils.module_loading import import_string\n\nfrom rest_fra"
  },
  {
    "path": "rest_framework/metadata.py",
    "chars": 5862,
    "preview": "\"\"\"\nThe metadata API is used to allow customization of how `OPTIONS` requests\nare handled. We currently provide a single"
  },
  {
    "path": "rest_framework/mixins.py",
    "chars": 2936,
    "preview": "\"\"\"\nBasic building blocks for generic class based views.\n\nWe don't bind behavior to http method handlers yet,\nwhich allo"
  },
  {
    "path": "rest_framework/negotiation.py",
    "chars": 4034,
    "preview": "\"\"\"\nContent negotiation deals with selecting an appropriate renderer given the\nincoming request.  Typically this will be"
  },
  {
    "path": "rest_framework/pagination.py",
    "chars": 32694,
    "preview": "\"\"\"\nPagination serializers determine the structure of the output that should\nbe used for paginated responses.\n\"\"\"\n\nimpor"
  },
  {
    "path": "rest_framework/parsers.py",
    "chars": 7717,
    "preview": "\"\"\"\nParsers are used to parse the content of incoming HTTP requests.\n\nThey give us a generic way of being able to handle"
  },
  {
    "path": "rest_framework/permissions.py",
    "chars": 9588,
    "preview": "\"\"\"\nProvides a set of pluggable permission policies.\n\"\"\"\nfrom django.http import Http404\n\nfrom rest_framework import exc"
  },
  {
    "path": "rest_framework/relations.py",
    "chars": 21238,
    "preview": "import contextlib\nimport sys\nfrom operator import attrgetter\nfrom urllib import parse\n\nfrom django.core.exceptions impor"
  },
  {
    "path": "rest_framework/renderers.py",
    "chars": 35626,
    "preview": "\"\"\"\nRenderers are used to serialize a response into specific media types.\n\nThey give us a generic way of being able to h"
  },
  {
    "path": "rest_framework/request.py",
    "chars": 15121,
    "preview": "\"\"\"\nThe Request class is used as a wrapper around the standard request object.\n\nThe wrapped request then offers a richer"
  },
  {
    "path": "rest_framework/response.py",
    "chars": 3543,
    "preview": "\"\"\"\nThe Response class in REST framework is similar to HTTPResponse, except that\nit is initialized with unrendered data,"
  },
  {
    "path": "rest_framework/reverse.py",
    "chars": 2144,
    "preview": "\"\"\"\nProvide urlresolver functions that return fully qualified URLs or view names\n\"\"\"\nfrom django.urls import NoReverseMa"
  },
  {
    "path": "rest_framework/routers.py",
    "chars": 13923,
    "preview": "\"\"\"\nRouters provide a convenient and consistent way of automatically\ndetermining the URL conf for your API.\n\nThey are us"
  }
]

// ... and 238 more files (download for full content)

About this extraction

This page contains the full source code of the encode/django-rest-framework GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 438 files (3.3 MB), approximately 873.3k tokens, and a symbol index with 3623 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!