From 70e54f45add6a96f92bbadbcff30fc211f2ce0c3 Mon Sep 17 00:00:00 2001 From: Ryan Date: Sun, 6 Jul 2025 07:39:52 -0700 Subject: [PATCH 01/16] Revert docs back to djangorestframework-guardian (#9734) --- docs/api-guide/permissions.md | 4 ++-- docs/community/third-party-packages.md | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/api-guide/permissions.md b/docs/api-guide/permissions.md index 775888fb6..c6d9f9338 100644 --- a/docs/api-guide/permissions.md +++ b/docs/api-guide/permissions.md @@ -201,7 +201,7 @@ As with `DjangoModelPermissions` you can use custom model permissions by overrid --- -**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian2` package][django-rest-framework-guardian2]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions. +**Note**: If you need object level `view` permissions for `GET`, `HEAD` and `OPTIONS` requests and are using django-guardian for your object-level permissions backend, you'll want to consider using the `DjangoObjectPermissionsFilter` class provided by the [`djangorestframework-guardian` package][django-rest-framework-guardian]. It ensures that list endpoints only return results including objects for which the user has appropriate view permissions. --- @@ -356,6 +356,6 @@ The [Django Rest Framework PSQ][drf-psq] package is an extension that gives supp [rest-framework-roles]: https://github.com/Pithikos/rest-framework-roles [djangorestframework-api-key]: https://florimondmanca.github.io/djangorestframework-api-key/ [django-rest-framework-role-filters]: https://github.com/allisson/django-rest-framework-role-filters -[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2 +[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian [drf-access-policy]: https://github.com/rsinger86/drf-access-policy [drf-psq]: https://github.com/drf-psq/drf-psq diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index d213cac3d..a48cbd606 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -126,7 +126,7 @@ To submit new content, [create a pull request][drf-create-pr]. * [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters. * [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF. * [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values. -* [django-rest-framework-guardian2][django-rest-framework-guardian2] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF. +* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF. ### Misc @@ -242,7 +242,7 @@ To submit new content, [create a pull request][drf-create-pr]. [djangorestframework-dataclasses]: https://github.com/oxan/djangorestframework-dataclasses [django-restql]: https://github.com/yezyilomo/django-restql [djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt -[django-rest-framework-guardian2]: https://github.com/johnthagen/django-rest-framework-guardian2 +[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian [drf-viewset-profiler]: https://github.com/fvlima/drf-viewset-profiler [djangorestframework-features]: https://github.com/cloudcode-hungary/django-rest-framework-features/ [django-elasticsearch-dsl-drf]: https://github.com/barseghyanartur/django-elasticsearch-dsl-drf From 2ae8c117dae5d7912760492a1df397e2fcd8c7a4 Mon Sep 17 00:00:00 2001 From: Ali Hassan <124016531+alihassancods@users.noreply.github.com> Date: Mon, 7 Jul 2025 16:11:24 +0500 Subject: [PATCH 02/16] Add note to tutorial about required request in serializer context when using `HyperlinkedModelSerializer` (#9732) * Fix : Updated documentation in tutorial 5 leading to error * Updated docs/tutorial/5-relationships-and-hyperlinked-apis.md Co-authored-by: Bruno Alla * Missing newline --------- Co-authored-by: Bruno Alla --- .../5-relationships-and-hyperlinked-apis.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/tutorial/5-relationships-and-hyperlinked-apis.md b/docs/tutorial/5-relationships-and-hyperlinked-apis.md index f999fdf50..f5aaee2bb 100644 --- a/docs/tutorial/5-relationships-and-hyperlinked-apis.md +++ b/docs/tutorial/5-relationships-and-hyperlinked-apis.md @@ -94,6 +94,22 @@ Notice that we've also added a new `'highlight'` field. This field is of the sa Because we've included format suffixed URLs such as `'.json'`, we also need to indicate on the `highlight` field that any format suffixed hyperlinks it returns should use the `'.html'` suffix. +--- + +**Note:** + +When you are manually instantiating these serializers inside your views (e.g., in `SnippetDetail` or `SnippetList`), you **must** pass `context={'request': request}` so the serializer knows how to build absolute URLs. For example, instead of: + + serializer = SnippetSerializer(snippet) + +You must write: + + serializer = SnippetSerializer(snippet, context={'request': request}) + +If your view is a subclass of `GenericAPIView`, you may use the `get_serializer_context()` as a convenience method. + +--- + ## Making sure our URL patterns are named If we're going to have a hyperlinked API, we need to make sure we name our URL patterns. Let's take a look at which URL patterns we need to name. From 853969c69c815be69513c2f63a41285858a45352 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Kul=C3=ADk?= Date: Thu, 24 Jul 2025 09:47:47 +0200 Subject: [PATCH 03/16] Fix test with Django 5 when pytz is available (#9715) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fix test with Django 5 when pytz is available * fix formatting * remove original condition Co-authored-by: Ülgen Sarıkavak * remove trailing whitespace * further improvements * let's not skip the pytz test - it should always be executed when testing against Django 4 * add comment to test requirements Co-authored-by: Bruno Alla * simplify the pytz import as it should always be available * make isort happy --------- Co-authored-by: Ülgen Sarıkavak Co-authored-by: Bruno Alla --- requirements/requirements-testing.txt | 1 + tests/test_fields.py | 28 +++++++++++++-------------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/requirements/requirements-testing.txt b/requirements/requirements-testing.txt index 2b39316a0..b1e3c82ec 100644 --- a/requirements/requirements-testing.txt +++ b/requirements/requirements-testing.txt @@ -5,3 +5,4 @@ pytest-django>=4.5.2,<5.0 importlib-metadata<5.0 # temporary pin of attrs attrs==22.1.0 +pytz # Remove when dropping support for Django<5.0 diff --git a/tests/test_fields.py b/tests/test_fields.py index d574b07eb..56693ed7a 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -9,13 +9,9 @@ from enum import auto from unittest.mock import patch from zoneinfo import ZoneInfo +import django import pytest - -try: - import pytz -except ImportError: - pytz = None - +import pytz from django.core.exceptions import ValidationError as DjangoValidationError from django.db.models import IntegerChoices, TextChoices from django.http import QueryDict @@ -1624,7 +1620,10 @@ class TestCustomTimezoneForDateTimeField(TestCase): assert rendered_date == rendered_date_in_timezone -@pytest.mark.skipif(pytz is None, reason="Django 5.0 has removed pytz; this test should eventually be able to get removed.") +@pytest.mark.skipif( + condition=django.VERSION >= (5,), + reason="Django 5.0 has removed pytz; this test should eventually be able to get removed.", +) class TestPytzNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues): """ Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST. @@ -1638,16 +1637,15 @@ class TestPytzNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues): } outputs = {} - if pytz: - class MockTimezone(pytz.BaseTzInfo): - @staticmethod - def localize(value, is_dst): - raise pytz.InvalidTimeError() + class MockTimezone(pytz.BaseTzInfo): + @staticmethod + def localize(value, is_dst): + raise pytz.InvalidTimeError() - def __str__(self): - return 'America/New_York' + def __str__(self): + return 'America/New_York' - field = serializers.DateTimeField(default_timezone=MockTimezone()) + field = serializers.DateTimeField(default_timezone=MockTimezone()) @patch('rest_framework.utils.timezone.datetime_ambiguous', return_value=True) From a7d050f5b3388ed9dc69c7770fdbd9654d4639ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sezer=20Bozk=C4=B1r?= <6623948+Natgho@users.noreply.github.com> Date: Fri, 1 Aug 2025 18:33:52 +0300 Subject: [PATCH 04/16] Turkish Translation updates (#9749) --- .../locale/tr/LC_MESSAGES/django.mo | Bin 10073 -> 12731 bytes .../locale/tr/LC_MESSAGES/django.po | 65 +++++++++--------- 2 files changed, 33 insertions(+), 32 deletions(-) diff --git a/rest_framework/locale/tr/LC_MESSAGES/django.mo b/rest_framework/locale/tr/LC_MESSAGES/django.mo index 6386aab5236ae56a95525a2b2c525baa555c3963..10233c89043c78b78b97724f3543b982d7ada9db 100644 GIT binary patch delta 4619 zcmbW2du$xV9mmHZ5XT`e=VcsHCJ7|aBnM3(flv}BI3xj*xCE02k1%&PwwK%6HM@Iu zY-28!5TXyL+AV#k4K7uMDJi1nq68^vq4=o!ptMwN0ihO9TY&@=Dyj+uE&crV_R=8n zN7a#k`F`2-m(8IA)YY&XF6Ml7m`*bj z&qIm8>&XkH8fVA?4urCC2b6=p2+xL3LW#($kh9g)nTbbgK9u>zP!8S-FNSx(_3%gV za`-Qp;e54$)481Lg|e^=&xen}bKz@nA)Gl&sZYXHP}biB<=`T`01m+n`~lnwUxb&z zb7t4p=U^-2ARXTg%i`g;>4@h~KuN_P)3KgYi@;^@6y^=&F3Q4B!2M7*{5s@MJ<3D0 z@G~g6e+ABklX+;UA$L+6ATm>(bBVu9>}5hk;z0@B0F(%fz()A%l+Q!{)GItrgYUw5 z@IxrMoyR~Tu>-Dx2cS517>b6TO~+?&ONr>}7UIvG+RcP4?1iGQt%OG|sv-JTOW`uO3VsUiE7RFS=gUw+@;cTM{V zH*t!LXTcS41zZWQhm+wwkTO!=fD*y)Kng`2f^zU<>G<)KPeakn3y>_U@~i2K58!;QTf>jw3FA-~lOsU;aw9v;x#CI=bD^*STGTh7f11J~Ubr$)D zc}N+S)dO@yrOwx& z@GbBTDAn^TC=R>}7fJokpqRzORVjO*YCGglO`+@nGPN^;6TdHL(#&w zpj`atP(=4{C>PjpUTys#Bsl5|P*V3WTn-;k=ih+k?MzG~E*jnl*+bn9C&5uDIeP>W z1a%zB&0m4&Q#BxE(ZHFIz0_Jrp{P8RgNLDrZ3H&LhoNZW2$X$)yNvkDjb36xLUuZX z$?ytz8ti~XP3?lG!rP&Q`VQCz?}L}Ym!MR|0>XmMR0nK_K9pP^hH~)JP$Kynly&c| zApX*6LAn>gHBeGfOvm>_+2A=Sp1lP%Y$QLTh4Ww=G*CSJE}Q}n!6tYV5-jy3lzrcX zSHp$mS=M`HIug2mC^x$wO6VSi@`3mrBsl6c1`>glP*QU-lnAv!IdC(a1$U<7Za9^3 znDVnwQuZY%=R5=(U>U6?7XT{4#H$YMCQNR4IVPMp`=%P+yF2%NCqTnt}+MF5^ zk;=D0+C*$q(yKl8r~P>+&CRC24_k;W5KY?jrKop0CMuP0KwJFRN!!-;nr^GTQZZ`- z-S0#_j;Es@tC@B@6WP2DY*=z59oi_PHUJakdURxiVw`F0JVy`p8MkEjMFYKdSUY*^ zMNZd%<8`x(6Y3$)6zy<)pz-}yHjA91)yaD8mm=+V>A-m1wz7Y6e?xqOx+ZIKrbY*g7eFQE8sCV8ZTA`+IFpu4ej-H%>In1#`Za=l zQ7EgTz~~LR$nm|fl9~EI!;*acqFsKFghFmT=zCT#8mf1P7sbDrc3`68^_D8@r{CF- z>AdD@LKgL8bh~du?fH=|nutIdZ$S6iAY^|nu?Txj&c;8S@y&CyRvQV1lh>V{TiY{g zTPck6NwZnscdhZ_jWf&Z>np=3AhsE`oddf3k~q4(mOBY%lBrNfKHaDkc)FLQN`m8` z&Kz95vlIk=H{R)7j|mJB3_@)Jvd?D5b^U&uU#mNp4dwj2-Ph|oUbJ@iaJ;U0%~g)) zM2>L@bKdUPU4dWJ{XLH8;KWfPn)Cu0b?tu@B#!4wK}ax@%*TGS+mv^bh?`&_{`;(! z%8SjvY-l0|y5?T|z1ijuY&YKPGW}wTs#w%9Go*L1i@0G?!bz%HCd6&@XtP|)^)=0&XgRnZ5Q5%`0 zUo=uxPSJ^m{9u|9sZHr*=EITXFTB4cj)KSd!G} z09utw&O3vIn{Z_G7Mzo;op^8f?2us`!&7aa8ga3rxEH^@@PRe89bG3$wbXSI2l9|n zA9fn}P`iY!5IPyPGpz+~9H4E7#O0jC9}bJ(T%4U3jvpCx$B!3u*5_8Dm!c@P za^>02@;Q*$6>a1>mDVM*8ZOwG6jOR4xq5y*lH!`2DI^Jsmo3edO+d-0 zMBz?BnL+uDG9I@PX)wj7!09%jBz}Cflr2?9O3Dc%;wWE*dLKb|JE5a;w$JpE+1e;; Yy}_EkB2!G_UH49Tyn=zW{nlQt3Hge%3tiw$1@)&NyYCMg#IE9_vTk3fu4+ z-islhF?ra88sIk6^|SDou5kjz(C1cXEc+s0YNb22bJ!oWzGQH^-P&*p2*| zgBNfvgLnWF`E<_ENy872ESrm1j-MgRWoA4r z?yehTVFrdUfMKk_I@D4Qp$2;1`~13h{wu0hvU%u(xICZyYYlgJ7sgOC{~YzjX$)f8 z!sLKTP({>@s?U?CfsEryoWRvMi9ML=Pfjd`_i(-wHK9@O{E(mgKfr}IxiD@S^Chav zhnSYu?gVOvmpClLuTiO;K@Bj#R*+GA0y~g$GH+u&zK?A&T-` z;s%`>I&)byZ=Y8T#*dr-x86qT|QxDMY%t?6&5C8%T+ znt2umRj`=v)QKVBH;}bG;jML*2ZG z&{k7%sj2$e-tLm9K9nh~zh32f_#*^~a$A>You1DYch^NJyR)eV7`R(Jt=Le4J2?+-gO1^y&^06@)1sd1m0*_&)p9tOk2Qc9;Ef_KY*` z+h^G=IhD?PIldI9Aa}yDYx8~fe|dYHc>aiGNBsxwpZw3K_YKAecH3_(8n!zERrXhb zJ}0*LvSn8;nYFhUM4il~e^_>X;a2D4!V1e-7Cd6vH$&~tNb$K8=WIz%iX99G?2PaW z&av>YWye;WvDd5|&1{JG#|L`%_U^Xlm5tfom94i2BTqXwBUdcvQhA, 2015 # Recep KIRMIZI , 2015 # Ülgen Sarıkavak , 2015 +# Sezer BOZKIR , 2025 msgid "" msgstr "" "Project-Id-Version: Django REST framework\n" @@ -108,7 +109,7 @@ msgstr "Sunucu hatası oluştu." #: exceptions.py:142 msgid "Invalid input." -msgstr "" +msgstr "Geçersiz girdi." #: exceptions.py:161 msgid "Malformed request." @@ -151,12 +152,12 @@ msgstr "Üst üste çok fazla istek yapıldı." #: exceptions.py:224 #, python-brace-format msgid "Expected available in {wait} second." -msgstr "" +msgstr "{wait} saniye içinde erişilebilir olması bekleniyor." #: exceptions.py:225 #, python-brace-format msgid "Expected available in {wait} seconds." -msgstr "" +msgstr "{wait} saniye içinde erişilebilir olması bekleniyor." #: fields.py:316 relations.py:245 relations.py:279 validators.py:90 #: validators.py:183 @@ -169,11 +170,11 @@ msgstr "Bu alan boş bırakılmamalı." #: fields.py:701 msgid "Must be a valid boolean." -msgstr "" +msgstr "Geçerli bir boolean olmalı." #: fields.py:766 msgid "Not a valid string." -msgstr "" +msgstr "Geçerli bir string değil." #: fields.py:767 msgid "This field may not be blank." @@ -215,7 +216,7 @@ msgstr "Geçerli bir URL girin." #: fields.py:867 msgid "Must be a valid UUID." -msgstr "" +msgstr "Geçerli bir UUID olmalı." #: fields.py:903 msgid "Enter a valid IPv4 or IPv6 address." @@ -273,11 +274,11 @@ msgstr "Datetime değeri bekleniyor, ama date değeri geldi." #: fields.py:1150 #, python-brace-format msgid "Invalid datetime for the timezone \"{timezone}\"." -msgstr "" +msgstr "\"{timezone}\" zaman dilimi için geçersiz datetime." #: fields.py:1151 msgid "Datetime value out of range." -msgstr "" +msgstr "Datetime değeri aralığın dışında." #: fields.py:1236 #, python-brace-format @@ -358,12 +359,12 @@ msgstr "Bu liste boş olmamalı." #: fields.py:1605 #, python-brace-format msgid "Ensure this field has at least {min_length} elements." -msgstr "" +msgstr "Bu alanın en az {min_length} eleman içerdiğinden emin olun." #: fields.py:1606 #, python-brace-format msgid "Ensure this field has no more than {max_length} elements." -msgstr "" +msgstr "Bu alanın en fazla {max_length} eleman içerdiğinden emin olun." #: fields.py:1682 #, python-brace-format @@ -372,7 +373,7 @@ msgstr "Sözlük tipi bir değişken beklenirken \"{input_type}\" tipi bir deği #: fields.py:1683 msgid "This dictionary may not be empty." -msgstr "" +msgstr "Bu sözlük boş olmamalı." #: fields.py:1755 msgid "Value must be valid JSON." @@ -384,7 +385,7 @@ msgstr "Arama" #: filters.py:50 msgid "A search term." -msgstr "" +msgstr "Bir arama terimi." #: filters.py:180 templates/rest_framework/filters/ordering.html:3 msgid "Ordering" @@ -392,23 +393,23 @@ msgstr "Sıralama" #: filters.py:181 msgid "Which field to use when ordering the results." -msgstr "" +msgstr "Sonuçların sıralanmasında kullanılacak alan." #: filters.py:287 msgid "ascending" -msgstr "" +msgstr "artan" #: filters.py:288 msgid "descending" -msgstr "" +msgstr "azalan" #: pagination.py:174 msgid "A page number within the paginated result set." -msgstr "" +msgstr "Sayfalanmış sonuç kümesinde bir sayfa numarası." #: pagination.py:179 pagination.py:372 pagination.py:590 msgid "Number of results to return per page." -msgstr "" +msgstr "Her sayfada döndürülecek sonuç sayısı." #: pagination.py:189 msgid "Invalid page." @@ -416,11 +417,11 @@ msgstr "Geçersiz sayfa." #: pagination.py:374 msgid "The initial index from which to return the results." -msgstr "" +msgstr "Döndürülecek sonuçların başlangıç indeksi." #: pagination.py:581 msgid "The pagination cursor value." -msgstr "" +msgstr "Sayfalandırma imleci değeri." #: pagination.py:583 msgid "Invalid cursor" @@ -464,20 +465,20 @@ msgstr "Geçersiz değer." #: schemas/utils.py:32 msgid "unique integer value" -msgstr "" +msgstr "benzersiz tamsayı değeri" #: schemas/utils.py:34 msgid "UUID string" -msgstr "" +msgstr "UUID metni" #: schemas/utils.py:36 msgid "unique value" -msgstr "" +msgstr "benzersiz değer" #: schemas/utils.py:38 #, python-brace-format msgid "A {value_type} identifying this {name}." -msgstr "" +msgstr "Bir {name} öğesini tanımlayan {value_type}." #: serializers.py:337 #, python-brace-format @@ -487,7 +488,7 @@ msgstr "Geçersiz veri. Sözlük bekleniyordu fakat {datatype} geldi. " #: templates/rest_framework/admin.html:116 #: templates/rest_framework/base.html:136 msgid "Extra Actions" -msgstr "" +msgstr "Ekstra Eylemler" #: templates/rest_framework/admin.html:130 #: templates/rest_framework/base.html:150 @@ -496,27 +497,27 @@ msgstr "Filtreler" #: templates/rest_framework/base.html:37 msgid "navbar" -msgstr "" +msgstr "navigasyon çubuğu" #: templates/rest_framework/base.html:75 msgid "content" -msgstr "" +msgstr "içerik" #: templates/rest_framework/base.html:78 msgid "request form" -msgstr "" +msgstr "istek formu" #: templates/rest_framework/base.html:157 msgid "main content" -msgstr "" +msgstr "ana içerik" #: templates/rest_framework/base.html:173 msgid "request info" -msgstr "" +msgstr "istek bilgisi" #: templates/rest_framework/base.html:177 msgid "response info" -msgstr "" +msgstr "cevap bilgisi" #: templates/rest_framework/horizontal/radio.html:4 #: templates/rest_framework/inline/radio.html:3 @@ -542,7 +543,7 @@ msgstr "{field_names} hep birlikte eşsiz bir küme oluşturmalılar." #: validators.py:171 #, python-brace-format msgid "Surrogate characters are not allowed: U+{code_point:X}." -msgstr "" +msgstr "Yerine konulmuş karakterlere izin verilmiyor: U+{code_point:X}." #: validators.py:243 #, python-brace-format @@ -569,7 +570,7 @@ msgstr "URL dizininde geçersiz versiyon." #: versioning.py:116 msgid "Invalid version in URL path. Does not match any version namespace." -msgstr "" +msgstr "Geçersiz versiyon URL dizininde. Hiçbir versiyon ad alanı ile eşleşmiyor." #: versioning.py:148 msgid "Invalid version in hostname." From de018df2aaacb1d2d947c0cfbfaa6d08fb50557d Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Wed, 6 Aug 2025 18:40:31 +0100 Subject: [PATCH 05/16] Prepare 3.16.1 release (#9752) --- docs/community/release-notes.md | 75 ++++++++++++++++++++++++++++++--- rest_framework/__init__.py | 2 +- 2 files changed, 70 insertions(+), 7 deletions(-) diff --git a/docs/community/release-notes.md b/docs/community/release-notes.md index c7b82e985..ae59ae000 100644 --- a/docs/community/release-notes.md +++ b/docs/community/release-notes.md @@ -38,20 +38,83 @@ You can determine your currently installed version using `pip show`: ## 3.16.x series +### 3.16.1 + +**Date**: 6th August 2025 + +This release fixes a few bugs, clean-up some old code paths for unsupported Python versions and improve translations. + +#### Minor changes + +* Cleanup optional `backports.zoneinfo` dependency and conditions on unsupported Python 3.8 and lower in [#9681](https://github.com/encode/django-rest-framework/pull/9681). Python versions prior to 3.9 were already unsupported so this shouldn't be a breaking change. + +#### Bug fixes + +* Fix regression in `unique_together` validation with `SerializerMethodField` in [#9712](https://github.com/encode/django-rest-framework/pull/9712) +* Fix `UniqueTogetherValidator` to handle fields with `source` attribute in [#9688](https://github.com/encode/django-rest-framework/pull/9688) +* Drop HTML line breaks on long headers in browsable API in [#9438](https://github.com/encode/django-rest-framework/pull/9438) + +#### Translations + +* Add Kazakh locale support in [#9713](https://github.com/encode/django-rest-framework/pull/9713) +* Update translations for Korean translations in [#9571](https://github.com/encode/django-rest-framework/pull/9571) +* Update German translations in [#9676](https://github.com/encode/django-rest-framework/pull/9676) +* Update Chinese translations in [#9675](https://github.com/encode/django-rest-framework/pull/9675) +* Update Arabic translations-sal in [#9595](https://github.com/encode/django-rest-framework/pull/9595) +* Update Persian translations in [#9576](https://github.com/encode/django-rest-framework/pull/9576) +* Update Spanish translations in [#9701](https://github.com/encode/django-rest-framework/pull/9701) +* Update Turkish Translations in [#9749](https://github.com/encode/django-rest-framework/pull/9749) +* Fix some typos in Brazilian Portuguese translations in [#9673](https://github.com/encode/django-rest-framework/pull/9673) + +#### Documentation + +* Removed reference to GitHub Issues and Discussions in [#9660](https://github.com/encode/django-rest-framework/pull/9660) +* Add `drf-restwind` and update outdated images in `browsable-api.md` in [#9680](https://github.com/encode/django-rest-framework/pull/9680) +* Updated funding page to represent current scope in [#9686](https://github.com/encode/django-rest-framework/pull/9686) +* Fix broken Heroku JSON Schema link in [#9693](https://github.com/encode/django-rest-framework/pull/9693) +* Update Django documentation links to use stable version in [#9698](https://github.com/encode/django-rest-framework/pull/9698) +* Expand docs on unique constraints cause 'required=True' in [#9725](https://github.com/encode/django-rest-framework/pull/9725) +* Revert extension back from `djangorestframework-guardian2` to `djangorestframework-guardian` in [#9734](https://github.com/encode/django-rest-framework/pull/9734) +* Add note to tutorial about required `request` in serializer context when using `HyperlinkedModelSerializer` in [#9732](https://github.com/encode/django-rest-framework/pull/9732) + +#### Internal changes + +* Update GitHub Actions to use Ubuntu 24.04 for testing in [#9677](https://github.com/encode/django-rest-framework/pull/9677) +* Update test matrix to use Django 5.2 stable version in [#9679](https://github.com/encode/django-rest-framework/pull/9679) +* Add `pyupgrade` to `pre-commit` hooks in [#9682](https://github.com/encode/django-rest-framework/pull/9682) +* Fix test with Django 5 when `pytz` is available in [#9715](https://github.com/encode/django-rest-framework/pull/9715) + +#### New Contributors + +* [`@araggohnxd`](https://github.com/araggohnxd) made their first contribution in [#9673](https://github.com/encode/django-rest-framework/pull/9673) +* [`@mbeijen`](https://github.com/mbeijen) made their first contribution in [#9660](https://github.com/encode/django-rest-framework/pull/9660) +* [`@stefan6419846`](https://github.com/stefan6419846) made their first contribution in [#9676](https://github.com/encode/django-rest-framework/pull/9676) +* [`@ren000thomas`](https://github.com/ren000thomas) made their first contribution in [#9675](https://github.com/encode/django-rest-framework/pull/9675) +* [`@ulgens`](https://github.com/ulgens) made their first contribution in [#9682](https://github.com/encode/django-rest-framework/pull/9682) +* [`@bukh-sal`](https://github.com/bukh-sal) made their first contribution in [#9595](https://github.com/encode/django-rest-framework/pull/9595) +* [`@rezatn0934`](https://github.com/rezatn0934) made their first contribution in [#9576](https://github.com/encode/django-rest-framework/pull/9576) +* [`@Rohit10jr`](https://github.com/Rohit10jr) made their first contribution in [#9693](https://github.com/encode/django-rest-framework/pull/9693) +* [`@kushibayev`](https://github.com/kushibayev) made their first contribution in [#9713](https://github.com/encode/django-rest-framework/pull/9713) +* [`@alihassancods`](https://github.com/alihassancods) made their first contribution in [#9732](https://github.com/encode/django-rest-framework/pull/9732) +* [`@kulikjak`](https://github.com/kulikjak) made their first contribution in [#9715](https://github.com/encode/django-rest-framework/pull/9715) +* [`@Natgho`](https://github.com/Natgho) made their first contribution in [#9749](https://github.com/encode/django-rest-framework/pull/9749) + +**Full Changelog**: https://github.com/encode/django-rest-framework/compare/3.16.0...3.16.1 + ### 3.16.0 **Date**: 28th March 2025 This release is considered a significant release to improve upstream support with Django and Python. Some of these may change the behaviour of existing features and pre-existing behaviour. Specifically, some fixes were added to around the support of `UniqueConstraint` with nullable fields which will improve built-in serializer validation. -## Features +#### Features * Add official support for Django 5.1 and its new `LoginRequiredMiddleware` in [#9514](https://github.com/encode/django-rest-framework/pull/9514) and [#9657](https://github.com/encode/django-rest-framework/pull/9657) * Add official Django 5.2a1 support in [#9634](https://github.com/encode/django-rest-framework/pull/9634) * Add support for Python 3.13 in [#9527](https://github.com/encode/django-rest-framework/pull/9527) and [#9556](https://github.com/encode/django-rest-framework/pull/9556) * Support Django 2.1+ test client JSON data automatically serialized in [#6511](https://github.com/encode/django-rest-framework/pull/6511) and fix a regression in [#9615](https://github.com/encode/django-rest-framework/pull/9615) -## Bug fixes +#### Bug fixes * Fix unique together validator to respect condition's fields from `UniqueConstraint` in [#9360](https://github.com/encode/django-rest-framework/pull/9360) * Fix raising on nullable fields part of `UniqueConstraint` in [#9531](https://github.com/encode/django-rest-framework/pull/9531) @@ -62,19 +125,19 @@ This release is considered a significant release to improve upstream support wit * Fix noisy warning and accept integers as min/max values of `DecimalField` in [#9515](https://github.com/encode/django-rest-framework/pull/9515) * Fix usages of `open()` in `setup.py` in [#9661](https://github.com/encode/django-rest-framework/pull/9661) -## Translations +#### Translations * Add some missing Chinese translations in [#9505](https://github.com/encode/django-rest-framework/pull/9505) * Fix spelling mistakes in Farsi language were corrected in [#9521](https://github.com/encode/django-rest-framework/pull/9521) * Fixing and adding missing Brazilian Portuguese translations in [#9535](https://github.com/encode/django-rest-framework/pull/9535) -## Removals +#### Removals * Remove support for Python 3.8 in [#9670](https://github.com/encode/django-rest-framework/pull/9670) * Remove long deprecated code from request wrapper in [#9441](https://github.com/encode/django-rest-framework/pull/9441) * Remove deprecated `AutoSchema._get_reference` method in [#9525](https://github.com/encode/django-rest-framework/pull/9525) -## Documentation and internal changes +#### Documentation and internal changes * Provide tests for hashing of `OperandHolder` in [#9437](https://github.com/encode/django-rest-framework/pull/9437) * Update documentation: Add `adrf` third party package in [#9198](https://github.com/encode/django-rest-framework/pull/9198) @@ -94,7 +157,7 @@ This release is considered a significant release to improve upstream support wit * Fix a number of typos in the test suite in the docs in [#9662](https://github.com/encode/django-rest-framework/pull/9662) * Add `django-pyoidc` as a third party authentication library in [#9667](https://github.com/encode/django-rest-framework/pull/9667) -## New Contributors +#### New Contributors * [`@maerteijn`](https://github.com/maerteijn) made their first contribution in [#9198](https://github.com/encode/django-rest-framework/pull/9198) * [`@FraCata00`](https://github.com/FraCata00) made their first contribution in [#9444](https://github.com/encode/django-rest-framework/pull/9444) diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 692ce9cb1..9b9bb6eda 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -8,7 +8,7 @@ ______ _____ _____ _____ __ """ __title__ = 'Django REST framework' -__version__ = '3.16.0' +__version__ = '3.16.1' __author__ = 'Tom Christie' __license__ = 'BSD 3-Clause' __copyright__ = 'Copyright 2011-2023 Encode OSS Ltd' From 64c3d9ef63bc073d01063934ab952cd1b990ecf2 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Sat, 9 Aug 2025 07:44:46 +0100 Subject: [PATCH 06/16] Restore references to GitHub Issues and Discussions (#9757) * Revert "Removed reference to GitHub Issues and Discussions (#9660)" This reverts commit ffadde930ef23983f123477964d201c278f107e9. * Remove issue template * Update discussions description * Remove recommendations to open issues from the docs * Change a few non-breakable spaces to regular ones for better syntax highlighting in the editors --- .github/ISSUE_TEMPLATE/config.yml | 7 +++++++ CONTRIBUTING.md | 2 ++ docs/api-guide/throttling.md | 3 ++- docs/api-guide/validators.md | 8 ++++---- docs/community/contributing.md | 15 +++++++++++++++ docs/community/project-management.md | 2 ++ 6 files changed, 32 insertions(+), 5 deletions(-) create mode 100644 .github/ISSUE_TEMPLATE/config.yml diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..0ba2c5d9d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 644a719c8..af7d55f13 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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. diff --git a/docs/api-guide/throttling.md b/docs/api-guide/throttling.md index e6d7774a6..0ea8b4158 100644 --- a/docs/api-guide/throttling.md +++ b/docs/api-guide/throttling.md @@ -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 diff --git a/docs/api-guide/validators.md b/docs/api-guide/validators.md index 57bcb8628..e3407e8a3 100644 --- a/docs/api-guide/validators.md +++ b/docs/api-guide/validators.md @@ -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). --- diff --git a/docs/community/contributing.md b/docs/community/contributing.md index 5a9188943..b47059f29 100644 --- a/docs/community/contributing.md +++ b/docs/community/contributing.md @@ -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 diff --git a/docs/community/project-management.md b/docs/community/project-management.md index daf2cda8d..4f203e13b 100644 --- a/docs/community/project-management.md +++ b/docs/community/project-management.md @@ -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 From edc055da78fabebef80851fe71dc2221e3120d92 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Sat, 9 Aug 2025 15:20:07 +0100 Subject: [PATCH 07/16] Fix a number of broken links in the docs (#9758) As reported by pylinkvalidate.py script --- docs/api-guide/schemas.md | 2 +- docs/community/3.1-announcement.md | 2 +- docs/community/3.3-announcement.md | 2 +- docs/community/3.4-announcement.md | 12 ++++++------ docs/community/3.5-announcement.md | 6 +++--- docs/community/third-party-packages.md | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index 0eee3c99f..345442182 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -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. diff --git a/docs/community/3.1-announcement.md b/docs/community/3.1-announcement.md index 641f313d0..2b4b83d57 100644 --- a/docs/community/3.1-announcement.md +++ b/docs/community/3.1-announcement.md @@ -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. --- diff --git a/docs/community/3.3-announcement.md b/docs/community/3.3-announcement.md index 24f493dcd..3f6427c53 100644 --- a/docs/community/3.3-announcement.md +++ b/docs/community/3.3-announcement.md @@ -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 diff --git a/docs/community/3.4-announcement.md b/docs/community/3.4-announcement.md index 2954b36b8..03ef6fc41 100644 --- a/docs/community/3.4-announcement.md +++ b/docs/community/3.4-announcement.md @@ -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 diff --git a/docs/community/3.5-announcement.md b/docs/community/3.5-announcement.md index 43a628dd4..de558fead 100644 --- a/docs/community/3.5-announcement.md +++ b/docs/community/3.5-announcement.md @@ -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 diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index a48cbd606..6d4791b70 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -177,7 +177,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 From 97a771c4053922d891e363ea63879963ffd7fe29 Mon Sep 17 00:00:00 2001 From: Mahdi Rahimi <31624047+mahdirahimi1999@users.noreply.github.com> Date: Sun, 10 Aug 2025 07:12:52 +0330 Subject: [PATCH 08/16] Refactor token generation to use secrets module (#9760) * Refactor token generation to use secrets module * test: Add focused tests for Token.generate_key() method - Add test for valid token format (40 hex characters) - Add collision resistance test with 500 sample size - Add basic randomness quality validation - Ensure generated keys are unique and properly formatted --- rest_framework/authtoken/models.py | 5 ++- tests/authentication/test_authentication.py | 39 +++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/rest_framework/authtoken/models.py b/rest_framework/authtoken/models.py index 6a17c2452..80a4dad69 100644 --- a/rest_framework/authtoken/models.py +++ b/rest_framework/authtoken/models.py @@ -1,5 +1,4 @@ -import binascii -import os +import secrets from django.conf import settings from django.db import models @@ -34,7 +33,7 @@ class Token(models.Model): @classmethod def generate_key(cls): - return binascii.hexlify(os.urandom(20)).decode() + return secrets.token_hex(20) def __str__(self): return self.key diff --git a/tests/authentication/test_authentication.py b/tests/authentication/test_authentication.py index 2f05ce7d1..3b6c633ee 100644 --- a/tests/authentication/test_authentication.py +++ b/tests/authentication/test_authentication.py @@ -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: From 92a2c4d3cbff9dc5878941e47e534718d967cb0f Mon Sep 17 00:00:00 2001 From: Khaled Sukkar Date: Sun, 10 Aug 2025 07:12:11 +0300 Subject: [PATCH 09/16] add a new third-party package in serializers.md (#9717) * Update serializers.md add a new third-party package in serializers section * Update third-party-packages.md add drf-shapeless-serializers to the serializers section. * Update docs/community/third-party-packages.md Co-authored-by: Bruno Alla --------- Co-authored-by: Bruno Alla --- docs/api-guide/serializers.md | 5 +++++ docs/community/third-party-packages.md | 2 ++ 2 files changed, 7 insertions(+) diff --git a/docs/api-guide/serializers.md b/docs/api-guide/serializers.md index 8d56d36f5..3ce8f887f 100644 --- a/docs/api-guide/serializers.md +++ b/docs/api-guide/serializers.md @@ -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 diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index 6d4791b70..96e7033ad 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -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 @@ -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 From c0166d95bb6455b7819d8de3d68a8eff4fc12e8f Mon Sep 17 00:00:00 2001 From: Mahdi Rahimi <31624047+mahdirahimi1999@users.noreply.github.com> Date: Sun, 10 Aug 2025 14:22:32 +0330 Subject: [PATCH 10/16] Prevent small risk of `Token` overwrite (#9754) * Fix #9250: Prevent token overwrite and improve security - Fix key collision issue that could overwrite existing tokens - Use force_insert=True only for new token instances - Replace os.urandom with secrets.token_hex for better security - Add comprehensive test suite to verify fix and backward compatibility - Ensure existing tokens can still be updated without breaking changes * Fix code style: remove trailing whitespace and unused imports * Fix #9250: Prevent token overwrite with minimal changes - Add force_insert=True to Token.save() for new objects to prevent overwriting existing tokens - Revert generate_key method to original implementation (os.urandom + binascii) - Update tests to work with original setUp() approach - Remove verbose comments and unrelated changes per reviewer feedback * Fix flake8 violations: remove extra blank lines and trailing whitespace * Update tests/test_authtoken.py Co-authored-by: Bruno Alla * Update tests/test_authtoken.py Co-authored-by: Bruno Alla * Update tests/test_authtoken.py Co-authored-by: Bruno Alla * Fix token key regeneration behavior and add test * Update tests/test_authtoken.py Co-authored-by: Bruno Alla --------- Co-authored-by: Bruno Alla --- rest_framework/authtoken/models.py | 9 +++++++ tests/test_authtoken.py | 40 ++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/rest_framework/authtoken/models.py b/rest_framework/authtoken/models.py index 80a4dad69..b75d1a842 100644 --- a/rest_framework/authtoken/models.py +++ b/rest_framework/authtoken/models.py @@ -27,8 +27,17 @@ 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 diff --git a/tests/test_authtoken.py b/tests/test_authtoken.py index 30e416d65..3cfcbb394 100644 --- a/tests/test_authtoken.py +++ b/tests/test_authtoken.py @@ -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): From 317ca8244d803ad208fa1d9f6530027f1e523883 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Sun, 10 Aug 2025 18:06:29 +0100 Subject: [PATCH 11/16] Automate docs deployment (#9759) On pushes to master, when the content of the docs or its config chnages --- .github/workflows/mkdocs-deploy.yml | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/workflows/mkdocs-deploy.yml diff --git a/.github/workflows/mkdocs-deploy.yml b/.github/workflows/mkdocs-deploy.yml new file mode 100644 index 000000000..56fc24d1e --- /dev/null +++ b/.github/workflows/mkdocs-deploy.yml @@ -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@v4 + - 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 From c73dddfadac383d900ac1684b8d370a4a7b172a3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 12 Aug 2025 13:08:20 +0600 Subject: [PATCH 12/16] Bump actions/checkout from 4 to 5 in the github-actions group (#9763) Bumps the github-actions group with 1 update: [actions/checkout](https://github.com/actions/checkout). Updates `actions/checkout` from 4 to 5 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '5' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/main.yml | 4 ++-- .github/workflows/mkdocs-deploy.yml | 2 +- .github/workflows/pre-commit.yml | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index bf158311a..2608ffe6c 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -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: diff --git a/.github/workflows/mkdocs-deploy.yml b/.github/workflows/mkdocs-deploy.yml index 56fc24d1e..2f400af9b 100644 --- a/.github/workflows/mkdocs-deploy.yml +++ b/.github/workflows/mkdocs-deploy.yml @@ -20,7 +20,7 @@ jobs: concurrency: group: ${{ github.workflow }}-${{ github.ref }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - run: git fetch --no-tags --prune --depth=1 origin gh-pages - uses: actions/setup-python@v5 with: diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 892235175..b6ad43038 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 with: fetch-depth: 0 From c8b6d3dcdf0a9fe04eb914e29e18efa42fe59a6c Mon Sep 17 00:00:00 2001 From: Devid <13779643+sevdog@users.noreply.github.com> Date: Tue, 12 Aug 2025 16:21:01 +0200 Subject: [PATCH 13/16] DurationField output format (#8532) * Allow format duration as ISO-8601 * Update tests/test_fields.py Co-authored-by: Bruno Alla * Update tests/test_fields.py Co-authored-by: Bruno Alla * Add validation for DurationField format, add more tests for it and improve related docs * Add more precise validation check for duration field format and adjust docs * Adjust typo in duration field docs --------- Co-authored-by: Asif Saif Uddin Co-authored-by: Bruno Alla --- docs/api-guide/fields.md | 7 +++-- docs/api-guide/settings.md | 9 ++++++ rest_framework/__init__.py | 1 + rest_framework/fields.py | 40 +++++++++++++++++++++--- rest_framework/settings.py | 4 ++- tests/test_fields.py | 62 +++++++++++++++++++++++++++++++++++++- 6 files changed, 115 insertions(+), 8 deletions(-) diff --git a/docs/api-guide/fields.md b/docs/api-guide/fields.md index 888996eec..8278e2a2f 100644 --- a/docs/api-guide/fields.md +++ b/docs/api-guide/fields.md @@ -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 diff --git a/docs/api-guide/settings.md b/docs/api-guide/settings.md index 7bee3166d..2a070b77e 100644 --- a/docs/api-guide/settings.md +++ b/docs/api-guide/settings.md @@ -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 diff --git a/rest_framework/__init__.py b/rest_framework/__init__.py index 9b9bb6eda..413f32606 100644 --- a/rest_framework/__init__.py +++ b/rest_framework/__init__.py @@ -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): diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 89c0a714c..847ee7b19 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -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... diff --git a/rest_framework/settings.py b/rest_framework/settings.py index b0d7bacec..50e3ad40e 100644 --- a/rest_framework/settings.py +++ b/rest_framework/settings.py @@ -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, diff --git a/tests/test_fields.py b/tests/test_fields.py index 56693ed7a..b52442a2c 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -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`. From 513ddb4ffbfaef9d0117b281121ffc7319106f2f Mon Sep 17 00:00:00 2001 From: Nicolas Delaby Date: Wed, 13 Aug 2025 06:53:25 +0200 Subject: [PATCH 14/16] Condition of UniqueTogetherValidator can be read-only (#9764) * Condition of UniqueValidator can be read-only We can't always expect to find the value of the condition in the serializer if the field is read-only. * Reproducible test --- rest_framework/validators.py | 7 ++++++- tests/test_validators.py | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/rest_framework/validators.py b/rest_framework/validators.py index 4c444cf01..76d2a2159 100644 --- a/rest_framework/validators.py +++ b/rest_framework/validators.py @@ -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) diff --git a/tests/test_validators.py b/tests/test_validators.py index c594eecbe..ea5bf3a4d 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -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` # ---------------------------------- From 0d0be8467d184fd503c10d5335d0aba1a2694205 Mon Sep 17 00:00:00 2001 From: Bruno Alla Date: Fri, 15 Aug 2025 13:28:05 +0200 Subject: [PATCH 15/16] Rename 'master' branch to 'main' (#9761) --- .github/workflows/main.yml | 2 +- .github/workflows/mkdocs-deploy.yml | 2 +- .github/workflows/pre-commit.yml | 2 +- README.md | 24 ++++++++++++------------ docs/api-guide/schemas.md | 10 +++++----- docs/api-guide/testing.md | 2 +- docs/community/3.0-announcement.md | 2 +- docs/community/contributing.md | 2 +- docs/community/project-management.md | 6 +++--- docs/community/third-party-packages.md | 2 +- docs/topics/internationalization.md | 2 +- docs_theme/main.html | 2 +- docs_theme/nav.html | 2 +- rest_framework/schemas/openapi.py | 4 ++-- 14 files changed, 32 insertions(+), 32 deletions(-) diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 2608ffe6c..845121197 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -3,7 +3,7 @@ name: CI on: push: branches: - - master + - main pull_request: jobs: diff --git a/.github/workflows/mkdocs-deploy.yml b/.github/workflows/mkdocs-deploy.yml index 2f400af9b..9d1560fe6 100644 --- a/.github/workflows/mkdocs-deploy.yml +++ b/.github/workflows/mkdocs-deploy.yml @@ -3,7 +3,7 @@ name: mkdocs on: push: branches: - - master + - main paths: - docs/** - docs_theme/** diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index b6ad43038..82d5e0b6a 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -3,7 +3,7 @@ name: pre-commit on: push: branches: - - master + - main pull_request: jobs: diff --git a/README.md b/README.md index be6619b4e..1427b274b 100644 --- a/README.md +++ b/README.md @@ -179,8 +179,8 @@ 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/master.svg -[codecov]: https://codecov.io/github/encode/django-rest-framework?branch=master +[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 @@ -188,16 +188,16 @@ Please see the [security policy][security-policy]. [funding]: https://fund.django-rest-framework.org/topics/funding/ [sponsors]: https://fund.django-rest-framework.org/topics/funding/#our-sponsors -[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/sentry-readme.png -[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/stream-readme.png -[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/spacinov-readme.png -[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/retool-readme.png -[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/bitio-readme.png -[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/posthog-readme.png -[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/cryptapi-readme.png -[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/fezto-readme.png -[svix-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/svix-premium.png -[zuplo-img]: https://raw.githubusercontent.com/encode/django-rest-framework/master/docs/img/premium/zuplo-readme.png +[sentry-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/sentry-readme.png +[stream-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/stream-readme.png +[spacinov-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/spacinov-readme.png +[retool-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/retool-readme.png +[bitio-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/bitio-readme.png +[posthog-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/posthog-readme.png +[cryptapi-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/cryptapi-readme.png +[fezto-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/fezto-readme.png +[svix-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/svix-premium.png +[zuplo-img]: https://raw.githubusercontent.com/encode/django-rest-framework/main/docs/img/premium/zuplo-readme.png [sentry-url]: https://getsentry.com/welcome/ [stream-url]: https://getstream.io/?utm_source=DjangoRESTFramework&utm_medium=Webpage_Logo_Ad&utm_content=Developer&utm_campaign=DjangoRESTFramework_Jan2022_HomePage diff --git a/docs/api-guide/schemas.md b/docs/api-guide/schemas.md index 345442182..c74d00cb7 100644 --- a/docs/api-guide/schemas.md +++ b/docs/api-guide/schemas.md @@ -453,12 +453,12 @@ create a base `AutoSchema` subclass for your project that takes additional [cite]: https://www.heroku.com/blog/json_schema_for_heroku_platform_api/ [openapi]: https://github.com/OAI/OpenAPI-Specification -[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#specification-extensions -[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#operationObject +[openapi-specification-extensions]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#specification-extensions +[openapi-operation]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#operationObject [openapi-tags]: https://swagger.io/specification/#tagObject -[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#fixed-fields-17 -[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#componentsObject -[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#referenceObject +[openapi-operationid]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#fixed-fields-17 +[openapi-components]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#componentsObject +[openapi-reference]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.2.md#referenceObject [openapi-generator]: https://github.com/OpenAPITools/openapi-generator [swagger-codegen]: https://github.com/swagger-api/swagger-codegen [info-object]: https://swagger.io/specification/#infoObject diff --git a/docs/api-guide/testing.md b/docs/api-guide/testing.md index ed585faf2..c340bf03d 100644 --- a/docs/api-guide/testing.md +++ b/docs/api-guide/testing.md @@ -417,5 +417,5 @@ For example, to add support for using `format='html'` in test requests, you migh [requestfactory]: https://docs.djangoproject.com/en/stable/topics/testing/advanced/#django.test.client.RequestFactory [configuration]: #configuration [refresh_from_db_docs]: https://docs.djangoproject.com/en/stable/ref/models/instances/#django.db.models.Model.refresh_from_db -[session_objects]: https://requests.readthedocs.io/en/master/user/advanced/#session-objects +[session_objects]: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects [provided_test_case_classes]: https://docs.djangoproject.com/en/stable/topics/testing/tools/#provided-test-case-classes diff --git a/docs/community/3.0-announcement.md b/docs/community/3.0-announcement.md index 0cb79fc2e..cec61f337 100644 --- a/docs/community/3.0-announcement.md +++ b/docs/community/3.0-announcement.md @@ -961,5 +961,5 @@ You can follow development on the GitHub site, where we use [milestones to indic [kickstarter]: https://www.kickstarter.com/projects/tomchristie/django-rest-framework-3 [sponsors]: https://www.django-rest-framework.org/community/kickstarter-announcement/#sponsors -[mixins.py]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/mixins.py +[mixins.py]: https://github.com/encode/django-rest-framework/blob/main/rest_framework/mixins.py [django-localization]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#localization-how-to-create-language-files diff --git a/docs/community/contributing.md b/docs/community/contributing.md index b47059f29..aceff45ac 100644 --- a/docs/community/contributing.md +++ b/docs/community/contributing.md @@ -209,7 +209,7 @@ If you want to draw attention to a note or warning, use a pair of enclosing line [pull-requests]: https://help.github.com/articles/using-pull-requests [tox]: https://tox.readthedocs.io/en/latest/ [markdown]: https://daringfireball.net/projects/markdown/basics -[docs]: https://github.com/encode/django-rest-framework/tree/master/docs +[docs]: https://github.com/encode/django-rest-framework/tree/main/docs [mou]: http://mouapp.com/ [repo]: https://github.com/encode/django-rest-framework [how-to-fork]: https://help.github.com/articles/fork-a-repo/ diff --git a/docs/community/project-management.md b/docs/community/project-management.md index 4f203e13b..bf591d5ef 100644 --- a/docs/community/project-management.md +++ b/docs/community/project-management.md @@ -31,7 +31,7 @@ Team members have the following responsibilities. Further notes for maintainers: -* Code changes should come in the form of a pull request - do not push directly to master. +* Code changes should come in the form of a pull request - do not push directly to main. * Maintainers should typically not merge their own pull requests. * Each issue/pull request should have exactly one label once triaged. * Search for un-triaged issues with [is:open no:label][un-triaged]. @@ -58,14 +58,14 @@ The following template should be used for the description of the issue, and serv Checklist: - - [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/master/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***). + - [ ] Create pull request for [release notes](https://github.com/encode/django-rest-framework/blob/mains/docs/topics/release-notes.md) based on the [*.*.* milestone](https://github.com/encode/django-rest-framework/milestones/***). - [ ] Update supported versions: - [ ] `setup.py` `python_requires` list - [ ] `setup.py` Python & Django version trove classifiers - [ ] `README` Python & Django versions - [ ] `docs` Python & Django versions - [ ] Update the translations from [transifex](https://www.django-rest-framework.org/topics/project-management/#translations). - - [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/master/rest_framework/__init__.py). + - [ ] Ensure the pull request increments the version to `*.*.*` in [`restframework/__init__.py`](https://github.com/encode/django-rest-framework/blob/main/rest_framework/__init__.py). - [ ] Ensure documentation validates - Build and serve docs `mkdocs serve` - Validate links `pylinkvalidate.py -P http://127.0.0.1:8000` diff --git a/docs/community/third-party-packages.md b/docs/community/third-party-packages.md index 96e7033ad..a4ad2db1e 100644 --- a/docs/community/third-party-packages.md +++ b/docs/community/third-party-packages.md @@ -173,7 +173,7 @@ To submit new content, [create a pull request][drf-create-pr]. [pypi-register]: https://pypi.org/account/register/ [semver]: https://semver.org/ [tox-docs]: https://tox.readthedocs.io/en/latest/ -[drf-compat]: https://github.com/encode/django-rest-framework/blob/master/rest_framework/compat.py +[drf-compat]: https://github.com/encode/django-rest-framework/blob/main/rest_framework/compat.py [rest-framework-grid]: https://www.djangopackages.com/grids/g/django-rest-framework/ [drf-create-pr]: https://github.com/encode/django-rest-framework/compare [authentication]: ../api-guide/authentication.md diff --git a/docs/topics/internationalization.md b/docs/topics/internationalization.md index 2f8f2abf0..b7387f772 100644 --- a/docs/topics/internationalization.md +++ b/docs/topics/internationalization.md @@ -106,7 +106,7 @@ For API clients the most appropriate of these will typically be to use the `Acce [django-translation]: https://docs.djangoproject.com/en/stable/topics/i18n/translation [custom-exception-handler]: ../api-guide/exceptions.md#custom-exception-handling [transifex-project]: https://explore.transifex.com/django-rest-framework-1/django-rest-framework/ -[django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/master/rest_framework/locale/en_US/LC_MESSAGES/django.po +[django-po-source]: https://raw.githubusercontent.com/encode/django-rest-framework/main/rest_framework/locale/en_US/LC_MESSAGES/django.po [django-language-preference]: https://docs.djangoproject.com/en/stable/topics/i18n/translation/#how-django-discovers-language-preference [django-locale-paths]: https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LOCALE_PATHS [django-locale-name]: https://docs.djangoproject.com/en/stable/topics/i18n/#term-locale-name diff --git a/docs_theme/main.html b/docs_theme/main.html index b4e894781..e37309595 100644 --- a/docs_theme/main.html +++ b/docs_theme/main.html @@ -110,7 +110,7 @@ {% block content %} {% if page.meta.source %} {% for filename in page.meta.source %} - + {{ filename }} {% endfor %} diff --git a/docs_theme/nav.html b/docs_theme/nav.html index d30348756..df2fd97d0 100644 --- a/docs_theme/nav.html +++ b/docs_theme/nav.html @@ -1,7 +1,7 @@