mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-13 16:54:47 +03:00
Compare commits
9 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
513ddb4ffb | ||
|
c8b6d3dcdf | ||
|
c73dddfada | ||
|
317ca8244d | ||
|
c0166d95bb | ||
|
92a2c4d3cb | ||
|
97a771c405 | ||
|
edc055da78 | ||
|
64c3d9ef63 |
7
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
7
.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
|
@ -0,0 +1,7 @@
|
|||
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.
|
4
.github/workflows/main.yml
vendored
4
.github/workflows/main.yml
vendored
|
@ -21,7 +21,7 @@ jobs:
|
|||
- '3.13'
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
|
@ -52,7 +52,7 @@ jobs:
|
|||
name: Test documentation links
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
|
|
29
.github/workflows/mkdocs-deploy.yml
vendored
Normal file
29
.github/workflows/mkdocs-deploy.yml
vendored
Normal file
|
@ -0,0 +1,29 @@
|
|||
name: mkdocs
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
paths:
|
||||
- docs/**
|
||||
- docs_theme/**
|
||||
- requirements/requirements-documentation.txt
|
||||
- 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@v5
|
||||
- run: git fetch --no-tags --prune --depth=1 origin gh-pages
|
||||
- uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: 3.x
|
||||
- run: pip install -r requirements/requirements-documentation.txt
|
||||
- run: mkdocs gh-deploy
|
2
.github/workflows/pre-commit.yml
vendored
2
.github/workflows/pre-commit.yml
vendored
|
@ -11,7 +11,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
|
|
|
@ -2,4 +2,6 @@
|
|||
|
||||
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.
|
||||
|
|
|
@ -377,13 +377,16 @@ A Duration representation.
|
|||
Corresponds to `django.db.models.fields.DurationField`
|
||||
|
||||
The `validated_data` for these fields will contain a `datetime.timedelta` instance.
|
||||
The representation is a string following this format `'[DD] [HH:[MM:]]ss[.uuuuuu]'`.
|
||||
|
||||
**Signature:** `DurationField(max_value=None, min_value=None)`
|
||||
**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
|
||||
|
|
|
@ -392,7 +392,7 @@ introspection.
|
|||
|
||||
#### `get_operation_id()`
|
||||
|
||||
There must be a unique [operationid](openapi-operationid) for each operation.
|
||||
There must be a unique [operationid][openapi-operationid] for each operation.
|
||||
By default the `operationId` is deduced from the model name, serializer name or
|
||||
view name. The operationId looks like "listItems", "retrieveItem",
|
||||
"updateItem", etc. The `operationId` is camelCase by convention.
|
||||
|
|
|
@ -1189,6 +1189,10 @@ The [drf-writable-nested][drf-writable-nested] package provides writable nested
|
|||
|
||||
The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your data, serialized through ModelSerializer. It also contains some helper functions. Which helps you to encrypt your data.
|
||||
|
||||
## Shapeless Serializers
|
||||
|
||||
The [drf-shapeless-serializers][drf-shapeless-serializers] package provides dynamic serializer configuration capabilities, allowing runtime field selection, renaming, attribute modification, and nested relationship configuration without creating multiple serializer classes. It helps eliminate serializer boilerplate while providing flexible API responses.
|
||||
|
||||
|
||||
[cite]: https://groups.google.com/d/topic/django-users/sVFaOfQi4wY/discussion
|
||||
[relations]: relations.md
|
||||
|
@ -1212,3 +1216,4 @@ The [drf-encrypt-content][drf-encrypt-content] package helps you encrypt your da
|
|||
[djangorestframework-queryfields]: https://djangorestframework-queryfields.readthedocs.io/
|
||||
[drf-writable-nested]: https://github.com/beda-software/drf-writable-nested
|
||||
[drf-encrypt-content]: https://github.com/oguzhancelikarslan/drf-encrypt-content
|
||||
[drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers
|
||||
|
|
|
@ -314,6 +314,15 @@ May be a list including the string `'iso-8601'` or Python [strftime format][strf
|
|||
|
||||
Default: `['iso-8601']`
|
||||
|
||||
|
||||
#### DURATION_FORMAT
|
||||
|
||||
Indicates the default format that should be used for rendering the output of `DurationField` serializer fields. If `None`, then `DurationField` serializer fields will return Python `timedelta` objects, and the duration encoding will be determined by the renderer.
|
||||
|
||||
May be any of `None`, `'iso-8601'` or `'django'` (the format accepted by `django.utils.dateparse.parse_duration`).
|
||||
|
||||
Default: `'django'`
|
||||
|
||||
---
|
||||
|
||||
## Encodings
|
||||
|
|
|
@ -110,7 +110,7 @@ You'll need to remember to also set your custom throttle class in the `'DEFAULT_
|
|||
|
||||
The built-in throttle implementations are open to [race conditions][race], so under high concurrency they may allow a few extra requests through.
|
||||
|
||||
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class.
|
||||
If your project relies on guaranteeing the number of requests during concurrent requests, you will need to implement your own throttle class. See [issue #5181][gh5181] for more details.
|
||||
|
||||
---
|
||||
|
||||
|
@ -220,4 +220,5 @@ The following is an example of a rate throttle, that will randomly throttle 1 in
|
|||
[identifying-clients]: http://oxpedia.org/wiki/index.php?title=AppSuite:Grizzly#Multiple_Proxies_in_front_of_the_cluster
|
||||
[cache-setting]: https://docs.djangoproject.com/en/stable/ref/settings/#caches
|
||||
[cache-docs]: https://docs.djangoproject.com/en/stable/topics/cache/#setting-up-the-cache
|
||||
[gh5181]: https://github.com/encode/django-rest-framework/issues/5181
|
||||
[race]: https://en.wikipedia.org/wiki/Race_condition#Data_race
|
||||
|
|
|
@ -13,7 +13,7 @@ Most of the time you're dealing with validation in REST framework you'll simply
|
|||
|
||||
However, sometimes you'll want to place your validation logic into reusable components, so that it can easily be reused throughout your codebase. This can be achieved by using validator functions and validator classes.
|
||||
|
||||
## Validation in REST framework
|
||||
## Validation in REST framework
|
||||
|
||||
Validation in Django REST framework serializers is handled a little differently to how validation works in Django's `ModelForm` class.
|
||||
|
||||
|
@ -75,7 +75,7 @@ This validator should be applied to *serializer fields*, like so:
|
|||
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
|
||||
)
|
||||
|
||||
## UniqueTogetherValidator
|
||||
## UniqueTogetherValidator
|
||||
|
||||
This validator can be used to enforce `unique_together` constraints on model instances.
|
||||
It has two required arguments, and a single optional `messages` argument:
|
||||
|
@ -92,7 +92,7 @@ The validator should be applied to *serializer classes*, like so:
|
|||
# ...
|
||||
class Meta:
|
||||
# ToDo items belong to a parent list, and have an ordering defined
|
||||
# by the 'position' field. No two items in a given list may share
|
||||
# by the 'position' field. No two items in a given list may share
|
||||
# the same position.
|
||||
validators = [
|
||||
UniqueTogetherValidator(
|
||||
|
@ -166,7 +166,7 @@ If you want the date field to be entirely hidden from the user, then use `Hidden
|
|||
|
||||
---
|
||||
|
||||
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
|
||||
**Note:** `HiddenField()` does not appear in `partial=True` serializer (when making `PATCH` request).
|
||||
|
||||
---
|
||||
|
||||
|
|
|
@ -46,7 +46,7 @@ The cursor based pagination renders a more simple style of control:
|
|||
|
||||
The pagination API was previously only able to alter the pagination style in the body of the response. The API now supports being able to write pagination information in response headers, making it possible to use pagination schemes that use the `Link` or `Content-Range` headers.
|
||||
|
||||
For more information, see the [custom pagination styles](../api-guide/pagination/#custom-pagination-styles) documentation.
|
||||
For more information, see the [custom pagination styles](../api-guide/pagination.md#custom-pagination-styles) documentation.
|
||||
|
||||
---
|
||||
|
||||
|
|
|
@ -54,7 +54,7 @@ The `ModelSerializer` and `HyperlinkedModelSerializer` classes should now includ
|
|||
|
||||
[forms-api]: ../topics/html-and-forms.md
|
||||
[ajax-form]: https://github.com/encode/ajax-form
|
||||
[jsonfield]: ../api-guide/fields#jsonfield
|
||||
[jsonfield]: ../api-guide/fields.md#jsonfield
|
||||
[accept-headers]: ../topics/browser-enhancements.md#url-based-accept-headers
|
||||
[method-override]: ../topics/browser-enhancements.md#http-header-based-method-overriding
|
||||
[django-supported-versions]: https://www.djangoproject.com/download/#supported-versions
|
||||
|
|
|
@ -179,16 +179,16 @@ The full set of itemized release notes [are available here][release-notes].
|
|||
[moss]: mozilla-grant.md
|
||||
[funding]: funding.md
|
||||
[core-api]: https://www.coreapi.org/
|
||||
[command-line-client]: api-clients#command-line-client
|
||||
[client-library]: api-clients#python-client-library
|
||||
[command-line-client]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/topics/api-clients.md#command-line-client
|
||||
[client-library]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/topics/api-clients.md#python-client-library
|
||||
[core-json]: https://www.coreapi.org/specification/encoding/#core-json-encoding
|
||||
[swagger]: https://openapis.org/specification
|
||||
[hyperschema]: https://json-schema.org/latest/json-schema-hypermedia.html
|
||||
[api-blueprint]: https://apiblueprint.org/
|
||||
[tut-7]: ../tutorial/7-schemas-and-client-libraries/
|
||||
[schema-generation]: ../api-guide/schemas/
|
||||
[tut-7]: https://github.com/encode/django-rest-framework/blob/3.4.7/docs/tutorial/7-schemas-and-client-libraries.md
|
||||
[schema-generation]: ../api-guide/schemas.md
|
||||
[api-clients]: https://github.com/encode/django-rest-framework/blob/3.14.0/docs/topics/api-clients.md
|
||||
[milestone]: https://github.com/encode/django-rest-framework/milestone/35
|
||||
[release-notes]: release-notes#34
|
||||
[metadata]: ../api-guide/metadata/#custom-metadata-classes
|
||||
[release-notes]: ./release-notes.md#34x-series
|
||||
[metadata]: ../api-guide/metadata.md#custom-metadata-classes
|
||||
[gh3751]: https://github.com/encode/django-rest-framework/issues/3751
|
||||
|
|
|
@ -254,9 +254,9 @@ in version 3.3 and raised a deprecation warning in 3.4. Its usage is now mandato
|
|||
[funding]: funding.md
|
||||
[uploads]: https://core-api.github.io/python-client/api-guide/utils/#file
|
||||
[downloads]: https://core-api.github.io/python-client/api-guide/codecs/#downloadcodec
|
||||
[schema-generation-api]: ../api-guide/schemas/#schemagenerator
|
||||
[schema-docs]: ../api-guide/schemas/#schemas-as-documentation
|
||||
[schema-view]: ../api-guide/schemas/#the-get_schema_view-shortcut
|
||||
[schema-generation-api]: ../api-guide/schemas.md#schemagenerator
|
||||
[schema-docs]: ../api-guide/schemas.md#schemas-as-documentation
|
||||
[schema-view]: ../api-guide/schemas.md#get_schema_view
|
||||
[django-rest-raml]: https://github.com/encode/django-rest-raml
|
||||
[raml-image]: ../img/raml.png
|
||||
[raml-codec]: https://github.com/core-api/python-raml-codec
|
||||
|
|
|
@ -4,6 +4,8 @@
|
|||
>
|
||||
> — [Tim Berners-Lee][cite]
|
||||
|
||||
There are many ways you can contribute to Django REST framework. We'd like it to be a community-led project, so please get involved and help shape the future of the project.
|
||||
|
||||
!!! note
|
||||
|
||||
At this point in its lifespan we consider Django REST framework to be feature-complete. We focus on pull requests that track the continued development of Django versions, and generally do not accept new features or code formatting changes.
|
||||
|
@ -28,9 +30,22 @@ The [Django code of conduct][code-of-conduct] gives a fuller set of guidelines f
|
|||
|
||||
# Issues
|
||||
|
||||
Our contribution process is that the [GitHub discussions page](https://github.com/encode/django-rest-framework/discussions) should generally be your starting point. Some tips on good potential issue reporting:
|
||||
|
||||
* Django REST framework is considered feature-complete. Please do not file requests to change behavior, unless it is required for security reasons or to maintain compatibility with upcoming Django or Python versions.
|
||||
* Search the GitHub project page for related items, and make sure you're running the latest version of REST framework before reporting an issue.
|
||||
* Feature requests will typically be closed with a recommendation that they be implemented outside the core REST framework library (e.g. as third-party libraries). This approach allows us to keep down the maintenance overhead of REST framework, so that the focus can be on continued stability and great documentation.
|
||||
|
||||
## Triaging issues
|
||||
|
||||
Getting involved in triaging incoming issues is a good way to start contributing. Every single ticket that comes into the ticket tracker needs to be reviewed in order to determine what the next steps should be. Anyone can help out with this, you just need to be willing to
|
||||
|
||||
* Read through the ticket - does it make sense, is it missing any context that would help explain it better?
|
||||
* Is the ticket reported in the correct place, would it be better suited as a discussion on the discussion group?
|
||||
* If the ticket is a bug report, can you reproduce it? Are you able to write a failing test case that demonstrates the issue and that can be submitted as a pull request?
|
||||
* If the ticket is a feature request, could the feature request instead be implemented as a third party package?
|
||||
* If a ticket hasn't had much activity and addresses something you need, then comment on the ticket and try to find out what's needed to get it moving again.
|
||||
|
||||
# Development
|
||||
|
||||
To start developing on Django REST framework, first create a Fork from the
|
||||
|
|
|
@ -34,6 +34,7 @@ Further notes for maintainers:
|
|||
* Code changes should come in the form of a pull request - do not push directly to master.
|
||||
* Maintainers should typically not merge their own pull requests.
|
||||
* Each issue/pull request should have exactly one label once triaged.
|
||||
* Search for un-triaged issues with [is:open no:label][un-triaged].
|
||||
|
||||
---
|
||||
|
||||
|
@ -156,6 +157,7 @@ The following issues still need to be addressed:
|
|||
* Document ownership and management of the security mailing list.
|
||||
|
||||
[bus-factor]: https://en.wikipedia.org/wiki/Bus_factor
|
||||
[un-triaged]: https://github.com/encode/django-rest-framework/issues?q=is%3Aopen+no%3Alabel
|
||||
[transifex-project]: https://www.transifex.com/projects/p/django-rest-framework/
|
||||
[transifex-client]: https://pypi.org/project/transifex-client/
|
||||
[translation-memory]: http://docs.transifex.com/guides/tm#let-tm-automatically-populate-translations
|
||||
|
|
|
@ -88,6 +88,7 @@ To submit new content, [create a pull request][drf-create-pr].
|
|||
* [djangorestframework-dataclasses][djangorestframework-dataclasses] - Serializer providing automatic field generation for Python dataclasses, like the built-in ModelSerializer does for models.
|
||||
* [django-restql][django-restql] - Turn your REST API into a GraphQL like API(It allows clients to control which fields will be sent in a response, uses GraphQL like syntax, supports read and write on both flat and nested fields).
|
||||
* [graphwrap][graphwrap] - Transform your REST API into a fully compliant GraphQL API with just two lines of code. Leverages [Graphene-Django](https://docs.graphene-python.org/projects/django/en/latest/) to dynamically build, at runtime, a GraphQL ObjectType for each view in your API.
|
||||
* [drf-shapeless-serializers][drf-shapeless-serializers] - Dynamically assemble, configure, and shape your Django Rest Framework serializers at runtime, much like connecting Lego bricks.
|
||||
|
||||
### Serializer fields
|
||||
|
||||
|
@ -177,7 +178,7 @@ To submit new content, [create a pull request][drf-create-pr].
|
|||
[drf-create-pr]: https://github.com/encode/django-rest-framework/compare
|
||||
[authentication]: ../api-guide/authentication.md
|
||||
[permissions]: ../api-guide/permissions.md
|
||||
[third-party-packages]: ../topics/third-party-packages/#existing-third-party-packages
|
||||
[third-party-packages]: #existing-third-party-packages
|
||||
[discussion-group]: https://groups.google.com/forum/#!forum/django-rest-framework
|
||||
[djangorestframework-digestauth]: https://github.com/juanriaza/django-rest-framework-digestauth
|
||||
[django-oauth-toolkit]: https://github.com/evonove/django-oauth-toolkit
|
||||
|
@ -259,3 +260,4 @@ To submit new content, [create a pull request][drf-create-pr].
|
|||
[drf-redesign]: https://github.com/youzarsiph/drf-redesign
|
||||
[drf-material]: https://github.com/youzarsiph/drf-material
|
||||
[django-pyoidc]: https://github.com/makinacorpus/django_pyoidc
|
||||
[drf-shapeless-serializers]: https://github.com/khaledsukkar2/drf-shapeless-serializers
|
||||
|
|
|
@ -21,6 +21,7 @@ HTTP_HEADER_ENCODING = 'iso-8859-1'
|
|||
|
||||
# Default datetime input and output formats
|
||||
ISO_8601 = 'iso-8601'
|
||||
DJANGO_DURATION_FORMAT = 'django'
|
||||
|
||||
|
||||
class RemovedInDRF317Warning(PendingDeprecationWarning):
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
import binascii
|
||||
import os
|
||||
import secrets
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import models
|
||||
|
@ -28,13 +27,22 @@ class Token(models.Model):
|
|||
verbose_name_plural = _("Tokens")
|
||||
|
||||
def save(self, *args, **kwargs):
|
||||
"""
|
||||
Save the token instance.
|
||||
|
||||
If no key is provided, generates a cryptographically secure key.
|
||||
For new tokens, ensures they are inserted as new (not updated).
|
||||
"""
|
||||
if not self.key:
|
||||
self.key = self.generate_key()
|
||||
# For new objects, force INSERT to prevent overwriting existing tokens
|
||||
if self._state.adding:
|
||||
kwargs['force_insert'] = True
|
||||
return super().save(*args, **kwargs)
|
||||
|
||||
@classmethod
|
||||
def generate_key(cls):
|
||||
return binascii.hexlify(os.urandom(20)).decode()
|
||||
return secrets.token_hex(20)
|
||||
|
||||
def __str__(self):
|
||||
return self.key
|
||||
|
|
|
@ -24,7 +24,7 @@ from django.utils import timezone
|
|||
from django.utils.dateparse import (
|
||||
parse_date, parse_datetime, parse_duration, parse_time
|
||||
)
|
||||
from django.utils.duration import duration_string
|
||||
from django.utils.duration import duration_iso_string, duration_string
|
||||
from django.utils.encoding import is_protected_type, smart_str
|
||||
from django.utils.formats import localize_input, sanitize_separators
|
||||
from django.utils.ipv6 import clean_ipv6_address
|
||||
|
@ -35,7 +35,7 @@ try:
|
|||
except ImportError:
|
||||
pytz = None
|
||||
|
||||
from rest_framework import ISO_8601
|
||||
from rest_framework import DJANGO_DURATION_FORMAT, ISO_8601
|
||||
from rest_framework.compat import ip_address_validators
|
||||
from rest_framework.exceptions import ErrorDetail, ValidationError
|
||||
from rest_framework.settings import api_settings
|
||||
|
@ -1351,9 +1351,22 @@ class DurationField(Field):
|
|||
'overflow': _('The number of days must be between {min_days} and {max_days}.'),
|
||||
}
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
def __init__(self, *, format=empty, **kwargs):
|
||||
self.max_value = kwargs.pop('max_value', None)
|
||||
self.min_value = kwargs.pop('min_value', None)
|
||||
if format is not empty:
|
||||
if format is None or (isinstance(format, str) and format.lower() in (ISO_8601, DJANGO_DURATION_FORMAT)):
|
||||
self.format = format
|
||||
elif isinstance(format, str):
|
||||
raise ValueError(
|
||||
f"Unknown duration format provided, got '{format}'"
|
||||
" while expecting 'django', 'iso-8601' or `None`."
|
||||
)
|
||||
else:
|
||||
raise TypeError(
|
||||
"duration format must be either str or `None`,"
|
||||
f" not {type(format).__name__}"
|
||||
)
|
||||
super().__init__(**kwargs)
|
||||
if self.max_value is not None:
|
||||
message = lazy_format(self.error_messages['max_value'], max_value=self.max_value)
|
||||
|
@ -1376,7 +1389,26 @@ class DurationField(Field):
|
|||
self.fail('invalid', format='[DD] [HH:[MM:]]ss[.uuuuuu]')
|
||||
|
||||
def to_representation(self, value):
|
||||
return duration_string(value)
|
||||
output_format = getattr(self, 'format', api_settings.DURATION_FORMAT)
|
||||
|
||||
if output_format is None:
|
||||
return value
|
||||
|
||||
if isinstance(output_format, str):
|
||||
if output_format.lower() == ISO_8601:
|
||||
return duration_iso_string(value)
|
||||
|
||||
if output_format.lower() == DJANGO_DURATION_FORMAT:
|
||||
return duration_string(value)
|
||||
|
||||
raise ValueError(
|
||||
f"Unknown duration format provided, got '{output_format}'"
|
||||
" while expecting 'django', 'iso-8601' or `None`."
|
||||
)
|
||||
raise TypeError(
|
||||
"duration format must be either str or `None`,"
|
||||
f" not {type(output_format).__name__}"
|
||||
)
|
||||
|
||||
|
||||
# Choice types...
|
||||
|
|
|
@ -24,7 +24,7 @@ from django.conf import settings
|
|||
from django.core.signals import setting_changed
|
||||
from django.utils.module_loading import import_string
|
||||
|
||||
from rest_framework import ISO_8601
|
||||
from rest_framework import DJANGO_DURATION_FORMAT, ISO_8601
|
||||
|
||||
DEFAULTS = {
|
||||
# Base API policies
|
||||
|
@ -109,6 +109,8 @@ DEFAULTS = {
|
|||
'TIME_FORMAT': ISO_8601,
|
||||
'TIME_INPUT_FORMATS': [ISO_8601],
|
||||
|
||||
'DURATION_FORMAT': DJANGO_DURATION_FORMAT,
|
||||
|
||||
# Encoding
|
||||
'UNICODE_JSON': True,
|
||||
'COMPACT_JSON': True,
|
||||
|
|
|
@ -189,7 +189,12 @@ class UniqueTogetherValidator:
|
|||
]
|
||||
|
||||
condition_sources = (serializer.fields[field_name].source for field_name in self.condition_fields)
|
||||
condition_kwargs = {source: attrs[source] for source in condition_sources}
|
||||
condition_kwargs = {
|
||||
source: attrs[source]
|
||||
if source in attrs
|
||||
else getattr(serializer.instance, source)
|
||||
for source in condition_sources
|
||||
}
|
||||
if checked_values and None not in checked_values and qs_exists_with_condition(queryset, self.condition, condition_kwargs):
|
||||
field_names = ', '.join(self.fields)
|
||||
message = self.message.format(field_names=field_names)
|
||||
|
|
|
@ -81,6 +81,7 @@ urlpatterns = [
|
|||
@override_settings(ROOT_URLCONF=__name__)
|
||||
class BasicAuthTests(TestCase):
|
||||
"""Basic authentication"""
|
||||
|
||||
def setUp(self):
|
||||
self.csrf_client = APIClient(enforce_csrf_checks=True)
|
||||
self.username = 'john'
|
||||
|
@ -198,6 +199,7 @@ class BasicAuthTests(TestCase):
|
|||
@override_settings(ROOT_URLCONF=__name__)
|
||||
class SessionAuthTests(TestCase):
|
||||
"""User session authentication"""
|
||||
|
||||
def setUp(self):
|
||||
self.csrf_client = APIClient(enforce_csrf_checks=True)
|
||||
self.non_csrf_client = APIClient(enforce_csrf_checks=False)
|
||||
|
@ -418,6 +420,41 @@ class TokenAuthTests(BaseTokenAuthTests, TestCase):
|
|||
key = self.model.generate_key()
|
||||
assert isinstance(key, str)
|
||||
|
||||
def test_generate_key_returns_valid_format(self):
|
||||
"""Ensure generate_key returns a valid token format"""
|
||||
key = self.model.generate_key()
|
||||
assert len(key) == 40
|
||||
# Should contain only valid hexadecimal characters
|
||||
assert all(c in '0123456789abcdef' for c in key)
|
||||
|
||||
def test_generate_key_produces_unique_values(self):
|
||||
"""Ensure generate_key produces unique values across multiple calls"""
|
||||
keys = set()
|
||||
for _ in range(100):
|
||||
key = self.model.generate_key()
|
||||
assert key not in keys, f"Duplicate key generated: {key}"
|
||||
keys.add(key)
|
||||
|
||||
def test_generate_key_collision_resistance(self):
|
||||
"""Test collision resistance with reasonable sample size"""
|
||||
keys = set()
|
||||
for _ in range(500):
|
||||
key = self.model.generate_key()
|
||||
assert key not in keys, f"Collision found: {key}"
|
||||
keys.add(key)
|
||||
assert len(keys) == 500, f"Expected 500 unique keys, got {len(keys)}"
|
||||
|
||||
def test_generate_key_randomness_quality(self):
|
||||
"""Test basic randomness properties of generated keys"""
|
||||
keys = [self.model.generate_key() for _ in range(10)]
|
||||
# Consecutive keys should be different
|
||||
for i in range(len(keys) - 1):
|
||||
assert keys[i] != keys[i + 1], "Consecutive keys should be different"
|
||||
# Keys should not follow obvious patterns
|
||||
for key in keys:
|
||||
# Should not be all same character
|
||||
assert not all(c == key[0] for c in key), f"Key has all same characters: {key}"
|
||||
|
||||
def test_token_login_json(self):
|
||||
"""Ensure token login view using JSON POST works."""
|
||||
client = APIClient(enforce_csrf_checks=True)
|
||||
|
@ -480,6 +517,7 @@ class IncorrectCredentialsTests(TestCase):
|
|||
authentication should run and error, even if no permissions
|
||||
are set on the view.
|
||||
"""
|
||||
|
||||
class IncorrectCredentialsAuth(BaseAuthentication):
|
||||
def authenticate(self, request):
|
||||
raise exceptions.AuthenticationFailed('Bad credentials')
|
||||
|
@ -571,6 +609,7 @@ class BasicAuthenticationUnitTests(TestCase):
|
|||
|
||||
class MockUser:
|
||||
is_active = False
|
||||
|
||||
old_authenticate = authentication.authenticate
|
||||
authentication.authenticate = lambda **kwargs: MockUser()
|
||||
try:
|
||||
|
|
|
@ -5,6 +5,7 @@ import pytest
|
|||
from django.contrib.admin import site
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.management import CommandError, call_command
|
||||
from django.db import IntegrityError
|
||||
from django.test import TestCase, modify_settings
|
||||
|
||||
from rest_framework.authtoken.admin import TokenAdmin
|
||||
|
@ -48,6 +49,45 @@ class AuthTokenTests(TestCase):
|
|||
self.user.save()
|
||||
assert AuthTokenSerializer(data=data).is_valid()
|
||||
|
||||
def test_token_creation_collision_raises_integrity_error(self):
|
||||
user2 = User.objects.create_user('user2', 'user2@example.com', 'p')
|
||||
existing_token = Token.objects.create(user=user2)
|
||||
|
||||
# Try to create another token with the same key
|
||||
with self.assertRaises(IntegrityError):
|
||||
Token.objects.create(key=existing_token.key, user=self.user)
|
||||
|
||||
def test_key_generated_on_save_when_cleared(self):
|
||||
# Create a new user for this test to avoid conflicts with setUp token
|
||||
user2 = User.objects.create_user('test_user2', 'test2@example.com', 'password')
|
||||
|
||||
# Create a token without a key - it should generate one automatically
|
||||
token = Token(user=user2)
|
||||
token.key = "" # Explicitly clear the key
|
||||
token.save()
|
||||
|
||||
# Verify the key was generated
|
||||
self.assertEqual(len(token.key), 40)
|
||||
self.assertEqual(token.user, user2)
|
||||
|
||||
def test_clearing_key_on_existing_token_raises_integrity_error(self):
|
||||
"""Test that clearing the key on an existing token raises IntegrityError."""
|
||||
user = User.objects.create_user('test_user3', 'test3@example.com', 'password')
|
||||
token = Token.objects.create(user=user)
|
||||
token.key = ""
|
||||
|
||||
# This should raise IntegrityError because:
|
||||
# 1. We're trying to update a record with an empty primary key
|
||||
# 2. The OneToOneField constraint would be violated
|
||||
with self.assertRaises(Exception): # Could be IntegrityError or DatabaseError
|
||||
token.save()
|
||||
|
||||
def test_saving_existing_token_without_changes_does_not_alter_key(self):
|
||||
original_key = self.token.key
|
||||
|
||||
self.token.save()
|
||||
self.assertEqual(self.token.key, original_key)
|
||||
|
||||
|
||||
class AuthTokenCommandTests(TestCase):
|
||||
|
||||
|
|
|
@ -1770,9 +1770,69 @@ class TestDurationField(FieldValues):
|
|||
}
|
||||
field = serializers.DurationField()
|
||||
|
||||
def test_invalid_format(self):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
serializers.DurationField(format='unknown')
|
||||
assert str(exc_info.value) == (
|
||||
"Unknown duration format provided, got 'unknown'"
|
||||
" while expecting 'django', 'iso-8601' or `None`."
|
||||
)
|
||||
with pytest.raises(TypeError) as exc_info:
|
||||
serializers.DurationField(format=123)
|
||||
assert str(exc_info.value) == (
|
||||
"duration format must be either str or `None`, not int"
|
||||
)
|
||||
|
||||
def test_invalid_format_in_config(self):
|
||||
field = serializers.DurationField()
|
||||
|
||||
with override_settings(REST_FRAMEWORK={'DURATION_FORMAT': 'unknown'}):
|
||||
with pytest.raises(ValueError) as exc_info:
|
||||
field.to_representation(datetime.timedelta(days=1))
|
||||
|
||||
assert str(exc_info.value) == (
|
||||
"Unknown duration format provided, got 'unknown'"
|
||||
" while expecting 'django', 'iso-8601' or `None`."
|
||||
)
|
||||
with override_settings(REST_FRAMEWORK={'DURATION_FORMAT': 123}):
|
||||
with pytest.raises(TypeError) as exc_info:
|
||||
field.to_representation(datetime.timedelta(days=1))
|
||||
assert str(exc_info.value) == (
|
||||
"duration format must be either str or `None`, not int"
|
||||
)
|
||||
|
||||
|
||||
class TestNoOutputFormatDurationField(FieldValues):
|
||||
"""
|
||||
Values for `DurationField` with a no output format.
|
||||
"""
|
||||
valid_inputs = {}
|
||||
invalid_inputs = {}
|
||||
outputs = {
|
||||
datetime.timedelta(1): datetime.timedelta(1)
|
||||
}
|
||||
field = serializers.DurationField(format=None)
|
||||
|
||||
|
||||
class TestISOOutputFormatDurationField(FieldValues):
|
||||
"""
|
||||
Values for `DurationField` with a custom output format.
|
||||
"""
|
||||
valid_inputs = {
|
||||
'13': datetime.timedelta(seconds=13),
|
||||
'P3DT08H32M01.000123S': datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123),
|
||||
'PT8H1M': datetime.timedelta(hours=8, minutes=1),
|
||||
'-P999999999D': datetime.timedelta(days=-999999999),
|
||||
'P999999999D': datetime.timedelta(days=999999999)
|
||||
}
|
||||
invalid_inputs = {}
|
||||
outputs = {
|
||||
datetime.timedelta(days=3, hours=8, minutes=32, seconds=1, microseconds=123): 'P3DT08H32M01.000123S'
|
||||
}
|
||||
field = serializers.DurationField(format='iso-8601')
|
||||
|
||||
|
||||
# Choice types...
|
||||
|
||||
class TestChoiceField(FieldValues):
|
||||
"""
|
||||
Valid and invalid values for `ChoiceField`.
|
||||
|
|
|
@ -589,6 +589,21 @@ class UniqueConstraintModel(models.Model):
|
|||
]
|
||||
|
||||
|
||||
class UniqueConstraintReadOnlyFieldModel(models.Model):
|
||||
state = models.CharField(max_length=100, default="new")
|
||||
position = models.IntegerField()
|
||||
something = models.IntegerField()
|
||||
|
||||
class Meta:
|
||||
constraints = [
|
||||
models.UniqueConstraint(
|
||||
name="unique_constraint_%(class)s",
|
||||
fields=("position", "something"),
|
||||
condition=models.Q(state="new"),
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
class UniqueConstraintNullableModel(models.Model):
|
||||
title = models.CharField(max_length=100)
|
||||
age = models.IntegerField(null=True)
|
||||
|
@ -738,6 +753,31 @@ class TestUniqueConstraintValidation(TestCase):
|
|||
)
|
||||
assert serializer.is_valid()
|
||||
|
||||
def test_uniq_constraint_condition_read_only_create(self):
|
||||
class UniqueConstraintReadOnlyFieldModelSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = UniqueConstraintReadOnlyFieldModel
|
||||
read_only_fields = ("state",)
|
||||
fields = ("position", "something", *read_only_fields)
|
||||
serializer = UniqueConstraintReadOnlyFieldModelSerializer(
|
||||
data={"position": 1, "something": 1}
|
||||
)
|
||||
assert serializer.is_valid()
|
||||
|
||||
def test_uniq_constraint_condition_read_only_partial(self):
|
||||
class UniqueConstraintReadOnlyFieldModelSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = UniqueConstraintReadOnlyFieldModel
|
||||
read_only_fields = ("state",)
|
||||
fields = ("position", "something", *read_only_fields)
|
||||
instance = UniqueConstraintReadOnlyFieldModel.objects.create(position=1, something=1)
|
||||
serializer = UniqueConstraintReadOnlyFieldModelSerializer(
|
||||
instance=instance,
|
||||
data={"position": 1, "something": 1},
|
||||
partial=True
|
||||
)
|
||||
assert serializer.is_valid()
|
||||
|
||||
|
||||
# Tests for `UniqueForDateValidator`
|
||||
# ----------------------------------
|
||||
|
|
Loading…
Reference in New Issue
Block a user