Datasets:
instance_id stringlengths 18 32 | repo stringclasses 8 values | base_commit stringlengths 40 40 | problem_statement stringlengths 68 11.2k | test_patch stringlengths 379 12.1k | human_patch stringlengths 442 16k | pr_number int64 5.92k 33.5k | pr_url stringlengths 41 55 | pr_merged_at stringdate 2026-01-02 13:01:58 2026-03-10 18:40:29 | issue_number int64 2.49k 37k | issue_url stringlengths 43 57 | human_changed_lines int64 7 512 | FAIL_TO_PASS stringlengths 23 304 | PASS_TO_PASS stringclasses 1 value | version stringclasses 8 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
django__django-20877 | django/django | 476e5def5fcbcf637945985a23675db0e1f59354 | # Fixed #36943 -- Preserved original URLconf exception in autoreloader.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36943
#### Branch description
Earlier, the autoreloader used to hide exceptions raised while loading the URLConf.
This change preserves the original exception using exception chaining
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [x] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period (see [guidelines](https://docs.djangoproject.com/en/dev/internals/contributing/committing-code/#committing-guidelines)).
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/utils_tests/test_autoreload.py b/tests/utils_tests/test_autoreload.py
index c9e6443c6fbf..2033728da809 100644
--- a/tests/utils_tests/test_autoreload.py
+++ b/tests/utils_tests/test_autoreload.py
@@ -434,6 +434,18 @@ def test_mutates_error_files(self):
autoreload._exception = None
self.assertEqual(mocked_error_files.append.call_count, 1)
+ def test_urlconf_exception_is_used_as_cause(self):
+ urlconf_exc = ValueError("Error")
+ fake_method = mock.MagicMock(side_effect=RuntimeError())
+ wrapped = autoreload.check_errors(fake_method)
+ with mock.patch.object(autoreload, "_url_module_exception", urlconf_exc):
+ try:
+ with self.assertRaises(RuntimeError) as cm:
+ wrapped()
+ finally:
+ autoreload._exception = None
+ self.assertIs(cm.exception.__cause__, urlconf_exc)
+
class TestRaiseLastException(SimpleTestCase):
@mock.patch("django.utils.autoreload._exception", None)
| diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py
index 99812979d73c..13019f7214b7 100644
--- a/django/utils/autoreload.py
+++ b/django/utils/autoreload.py
@@ -33,6 +33,8 @@
# file paths to allow watching them in the future.
_error_files = []
_exception = None
+# Exception raised while loading the URLConf.
+_url_module_exception = None
try:
import termios
@@ -62,7 +64,7 @@ def wrapper(*args, **kwargs):
global _exception
try:
fn(*args, **kwargs)
- except Exception:
+ except Exception as e:
_exception = sys.exc_info()
et, ev, tb = _exception
@@ -75,8 +77,10 @@ def wrapper(*args, **kwargs):
if filename not in _error_files:
_error_files.append(filename)
+ if _url_module_exception is not None:
+ raise e from _url_module_exception
- raise
+ raise e
return wrapper
@@ -339,6 +343,7 @@ def wait_for_apps_ready(self, app_reg, django_main_thread):
return False
def run(self, django_main_thread):
+ global _url_module_exception
logger.debug("Waiting for apps ready_event.")
self.wait_for_apps_ready(apps, django_main_thread)
from django.urls import get_resolver
@@ -347,10 +352,10 @@ def run(self, django_main_thread):
# reloader starts by accessing the urlconf_module property.
try:
get_resolver().urlconf_module
- except Exception:
+ except Exception as e:
# Loading the urlconf can result in errors during development.
- # If this occurs then swallow the error and continue.
- pass
+ # If this occurs then store the error and continue.
+ _url_module_exception = e
logger.debug("Apps ready_event triggered. Sending autoreload_started signal.")
autoreload_started.send(sender=self)
self.run_loop()
| 20,877 | https://github.com/django/django/pull/20877 | 2026-03-10 15:32:39 | 36,943 | https://github.com/django/django/pull/20877 | 27 | ["tests/utils_tests/test_autoreload.py"] | [] | 5.2 |
django__django-19999 | django/django | b33c31d992591bc8e8d20ac156809e4ae5b45375 | # Doc'd return values of as_sql() for Func and query expressions.
Mostly to make it clear that `params` may be a list or tuple. | diff --git a/tests/migrations/migrations_test_apps/unmigrated_app_syncdb/models.py b/tests/migrations/migrations_test_apps/unmigrated_app_syncdb/models.py
index 9f3179cd0d6d..c539b20d1184 100644
--- a/tests/migrations/migrations_test_apps/unmigrated_app_syncdb/models.py
+++ b/tests/migrations/migrations_test_apps/unmigrated_app_syncdb/models.py
@@ -7,3 +7,8 @@ class Classroom(models.Model):
class Lesson(models.Model):
classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE)
+
+
+class VeryLongNameModel(models.Model):
+ class Meta:
+ db_table = "long_db_table_that_should_be_truncated_before_checking"
diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py
index 6a0d9bd6d28d..e9929c1eafa9 100644
--- a/tests/migrations/test_commands.py
+++ b/tests/migrations/test_commands.py
@@ -25,6 +25,7 @@
connections,
models,
)
+from django.db.backends.base.introspection import BaseDatabaseIntrospection
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.backends.utils import truncate_name
from django.db.migrations.autodetector import MigrationAutodetector
@@ -1222,10 +1223,10 @@ def test_migrate_syncdb_deferred_sql_executed_with_schemaeditor(self):
create_table_count = len(
[call for call in execute.mock_calls if "CREATE TABLE" in str(call)]
)
- self.assertEqual(create_table_count, 2)
+ self.assertEqual(create_table_count, 3)
# There's at least one deferred SQL for creating the foreign key
# index.
- self.assertGreater(len(execute.mock_calls), 2)
+ self.assertGreater(len(execute.mock_calls), 3)
stdout = stdout.getvalue()
self.assertIn("Synchronize unmigrated apps: unmigrated_app_syncdb", stdout)
self.assertIn("Creating tables...", stdout)
@@ -1259,8 +1260,54 @@ def test_migrate_syncdb_app_label(self):
create_table_count = len(
[call for call in execute.mock_calls if "CREATE TABLE" in str(call)]
)
- self.assertEqual(create_table_count, 2)
+ self.assertEqual(create_table_count, 3)
+ self.assertGreater(len(execute.mock_calls), 3)
+ self.assertIn(
+ "Synchronize unmigrated app: unmigrated_app_syncdb", stdout.getvalue()
+ )
+
+ @override_settings(
+ INSTALLED_APPS=[
+ "migrations.migrations_test_apps.unmigrated_app_syncdb",
+ "migrations.migrations_test_apps.unmigrated_app_simple",
+ ]
+ )
+ def test_migrate_syncdb_installed_truncated_db_model(self):
+ """
+ Running migrate --run-syncdb doesn't try to create models with long
+ truncated name if already exist.
+ """
+ with connection.cursor() as cursor:
+ mock_existing_tables = connection.introspection.table_names(cursor)
+ # Add truncated name for the VeryLongNameModel to the list of
+ # existing table names.
+ table_name = truncate_name(
+ "long_db_table_that_should_be_truncated_before_checking",
+ connection.ops.max_name_length(),
+ )
+ mock_existing_tables.append(table_name)
+ stdout = io.StringIO()
+ with (
+ mock.patch.object(BaseDatabaseSchemaEditor, "execute") as execute,
+ mock.patch.object(
+ BaseDatabaseIntrospection,
+ "table_names",
+ return_value=mock_existing_tables,
+ ),
+ ):
+ call_command(
+ "migrate", "unmigrated_app_syncdb", run_syncdb=True, stdout=stdout
+ )
+ create_table_calls = [
+ str(call).upper()
+ for call in execute.mock_calls
+ if "CREATE TABLE" in str(call)
+ ]
+ self.assertEqual(len(create_table_calls), 2)
self.assertGreater(len(execute.mock_calls), 2)
+ self.assertFalse(
+ any([table_name.upper() in call for call in create_table_calls])
+ )
self.assertIn(
"Synchronize unmigrated app: unmigrated_app_syncdb", stdout.getvalue()
)
| diff --git a/django/core/management/commands/migrate.py b/django/core/management/commands/migrate.py
index 268f669ba257..62ad29e43d8a 100644
--- a/django/core/management/commands/migrate.py
+++ b/django/core/management/commands/migrate.py
@@ -6,6 +6,7 @@
from django.core.management.base import BaseCommand, CommandError, no_translations
from django.core.management.sql import emit_post_migrate_signal, emit_pre_migrate_signal
from django.db import DEFAULT_DB_ALIAS, connections, router
+from django.db.backends.utils import truncate_name
from django.db.migrations.autodetector import MigrationAutodetector
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.loader import AmbiguityError
@@ -447,8 +448,9 @@ def sync_apps(self, connection, app_labels):
def model_installed(model):
opts = model._meta
converter = connection.introspection.identifier_converter
+ max_name_length = connection.ops.max_name_length()
return not (
- (converter(opts.db_table) in tables)
+ (converter(truncate_name(opts.db_table, max_name_length)) in tables)
or (
opts.auto_created
and converter(opts.auto_created._meta.db_table) in tables
| 19,999 | https://github.com/django/django/pull/19999 | 2026-03-08 09:44:56 | 12,529 | https://github.com/django/django/pull/12529 | 62 | ["tests/migrations/migrations_test_apps/unmigrated_app_syncdb/models.py", "tests/migrations/test_commands.py"] | [] | 5.2 |
django__django-20749 | django/django | 864850b20f7ef89ed2f6bd8baf1a45acc9245a6c | # Fixed #36940 -- Improved ASGI script prefix path_info handling.
#### Trac ticket number
ticket-36940
#### Branch description
The current `ASGIRequest.__init__` uses `str.removeprefix()` to strip the script name from the request path to compute `path_info`. This is fragile because `removeprefix` is a pure string operation — it doesn't verify that the prefix is a proper path segment boundary.
For example, if `script_name` is `/myapp` and the path is `/myapplication/page`, `removeprefix` would incorrectly produce `lication/page`.
This patch replaces `removeprefix` with a check that ensures the script name is followed by `/` or is the exact path, before stripping it. This addresses the inline TODO comment.
#### AI Assistance Disclosure (REQUIRED)
- [x] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
AI tools (Claude) were used to understand the issue and guide the approach. The code was reviewed and verified manually.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch.
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [ ] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py
index 83dfd95713b8..625090a66d0c 100644
--- a/tests/handlers/tests.py
+++ b/tests/handlers/tests.py
@@ -346,6 +346,26 @@ def test_force_script_name(self):
self.assertEqual(request.script_name, "/FORCED_PREFIX")
self.assertEqual(request.path_info, "/somepath/")
+ def test_root_path_prefix_boundary(self):
+ async_request_factory = AsyncRequestFactory()
+ # When path shares a textual prefix with root_path but not at a
+ # segment boundary, path_info should be the full path.
+ request = async_request_factory.request(
+ **{"path": "/rootprefix/somepath/", "root_path": "/root"}
+ )
+ self.assertEqual(request.path, "/rootprefix/somepath/")
+ self.assertEqual(request.script_name, "/root")
+ self.assertEqual(request.path_info, "/rootprefix/somepath/")
+
+ def test_root_path_trailing_slash(self):
+ async_request_factory = AsyncRequestFactory()
+ request = async_request_factory.request(
+ **{"path": "/root/somepath/", "root_path": "/root/"}
+ )
+ self.assertEqual(request.path, "/root/somepath/")
+ self.assertEqual(request.script_name, "/root/")
+ self.assertEqual(request.path_info, "/somepath/")
+
async def test_sync_streaming(self):
response = await self.async_client.get("/streaming/")
self.assertEqual(response.status_code, 200)
| diff --git a/django/core/handlers/asgi.py b/django/core/handlers/asgi.py
index c8118e1691f9..9555860a7e21 100644
--- a/django/core/handlers/asgi.py
+++ b/django/core/handlers/asgi.py
@@ -54,10 +54,13 @@ def __init__(self, scope, body_file):
self.path = scope["path"]
self.script_name = get_script_prefix(scope)
if self.script_name:
- # TODO: Better is-prefix checking, slash handling?
- self.path_info = scope["path"].removeprefix(self.script_name)
+ script_name = self.script_name.rstrip("/")
+ if self.path.startswith(script_name + "/") or self.path == script_name:
+ self.path_info = self.path[len(script_name) :]
+ else:
+ self.path_info = self.path
else:
- self.path_info = scope["path"]
+ self.path_info = self.path
# HTTP basics.
self.method = self.scope["method"].upper()
# Ensure query string is encoded correctly.
| 20,749 | https://github.com/django/django/pull/20749 | 2026-03-06 22:32:33 | 36,940 | https://github.com/django/django/pull/20749 | 29 | ["tests/handlers/tests.py"] | [] | 5.2 |
django__django-20852 | django/django | f8665b1a7ff5e98d84f66ad0e958c3f175aa5d8b | # Fixed #36968 -- Improved error message when collectstatic can't find a referenced file.
#### Trac ticket number
ticket-36968
#### Branch description
A suggestion of how we could improve the message that is shown to people when the file referenced in a css/js is missing.
Wraps the ValueError for missing file when it comes from collectstatic in a 'CommandError' and updated the message to include a little more information. The CommandError will hide the traceback by default and it can still be accessed by providing --traceback
Example
<img width="1034" height="186" alt="image" src="https://github.com/user-attachments/assets/0f5d800e-4c30-45aa-ae51-4e0c1eaeedb5" />
<details><summary>Vs Old</summary>
<img width="1038" height="963" alt="image" src="https://github.com/user-attachments/assets/5b6a8d7e-5455-4363-a181-af3c7003401a" />
</details>
Open to feedback on wording. It's inspired by [whitenoise](https://github.com/evansd/whitenoise/blob/13997326100d37bc0b9edab01c886dea85bc05c3/src/whitenoise/storage.py#L190C18-L190C34)
The intent is to make it easier for people to find where the issue is in their files when things go wrong.
But where there is a suggestion on what to look for in whitenoise, I felt it was safer to give the person the information of the file missing, the file and line it was found in, and leave it for them to fix it from there.
It could be a number of things that need fixing, from most to least likely in my experience
1) An error in your code i.ie. a typo, wrong folder, or actual missing file
2) external lib references file you don't have/need, e.g. sourcemap file
3) confusion over relative paths and how storage resolves files
4) storage is not configured correctly and not picking up files you expect it to
Trying to call out any one of these could mislead people, calling out them all is too long, and it's probably not exhaustive anyway.
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [X] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [X] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [X] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [X] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [X] I have checked the "Has patch" ticket flag in the Trac system.
- [X] I have added or updated relevant tests.
- [X] I have added or updated relevant docs, including release notes if applicable. N/A
- [X] I have attached screenshots in both light and dark modes for any UI changes. N/A
| diff --git a/tests/staticfiles_tests/test_storage.py b/tests/staticfiles_tests/test_storage.py
index cdb6fd3c7e2e..9db449bf9df2 100644
--- a/tests/staticfiles_tests/test_storage.py
+++ b/tests/staticfiles_tests/test_storage.py
@@ -13,7 +13,7 @@
from django.contrib.staticfiles.management.commands.collectstatic import (
Command as CollectstaticCommand,
)
-from django.core.management import call_command
+from django.core.management import CommandError, call_command
from django.test import SimpleTestCase, override_settings
from .cases import CollectionTestCase
@@ -201,8 +201,10 @@ def test_template_tag_url(self):
def test_import_loop(self):
finders.get_finder.cache_clear()
err = StringIO()
- with self.assertRaisesMessage(RuntimeError, "Max post-process passes exceeded"):
+ msg = "Max post-process passes exceeded"
+ with self.assertRaisesMessage(CommandError, msg) as cm:
call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
+ self.assertIsInstance(cm.exception.__cause__, RuntimeError)
self.assertEqual(
"Post-processing 'bar.css, foo.css' failed!\n\n", err.getvalue()
)
@@ -367,9 +369,14 @@ def test_post_processing_failure(self):
"""
finders.get_finder.cache_clear()
err = StringIO()
- with self.assertRaises(Exception):
+ with self.assertRaises(CommandError) as cm:
call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
self.assertEqual("Post-processing 'faulty.css' failed!\n\n", err.getvalue())
+ self.assertIsInstance(cm.exception.__cause__, ValueError)
+ exc_message = str(cm.exception)
+ self.assertIn("faulty.css", exc_message)
+ self.assertIn("missing.css", exc_message)
+ self.assertIn("1:", exc_message) # line 1 reported
self.assertPostCondition()
@override_settings(
@@ -379,8 +386,9 @@ def test_post_processing_failure(self):
def test_post_processing_nonutf8(self):
finders.get_finder.cache_clear()
err = StringIO()
- with self.assertRaises(UnicodeDecodeError):
+ with self.assertRaises(CommandError) as cm:
call_command("collectstatic", interactive=False, verbosity=0, stderr=err)
+ self.assertIsInstance(cm.exception.__cause__, UnicodeDecodeError)
self.assertEqual("Post-processing 'nonutf8.css' failed!\n\n", err.getvalue())
self.assertPostCondition()
| diff --git a/django/contrib/staticfiles/management/commands/collectstatic.py b/django/contrib/staticfiles/management/commands/collectstatic.py
index 1c3f8ba26d53..6fcff46d93af 100644
--- a/django/contrib/staticfiles/management/commands/collectstatic.py
+++ b/django/contrib/staticfiles/management/commands/collectstatic.py
@@ -154,7 +154,11 @@ def collect(self):
# Add a blank line before the traceback, otherwise it's
# too easy to miss the relevant part of the error message.
self.stderr.write()
- raise processed
+ # Re-raise exceptions as CommandError and display notes.
+ message = str(processed)
+ if hasattr(processed, "__notes__"):
+ message += "\n" + "\n".join(processed.__notes__)
+ raise CommandError(message) from processed
if processed:
self.log(
"Post-processed '%s' as '%s'" % (original_path, processed_path),
diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py
index c889bcb4a495..e0af40638423 100644
--- a/django/contrib/staticfiles/storage.py
+++ b/django/contrib/staticfiles/storage.py
@@ -232,6 +232,16 @@ def url_converter(self, name, hashed_files, template=None, comment_blocks=None):
if template is None:
template = self.default_template
+ def _line_at_position(content, position):
+ start = content.rfind("\n", 0, position) + 1
+ end = content.find("\n", position)
+ end = end if end != -1 else len(content)
+ line_num = content.count("\n", 0, start) + 1
+ msg = f"\n{line_num}: {content[start:end]}"
+ if len(msg) > 79:
+ return f"\n{line_num}"
+ return msg
+
def converter(matchobj):
"""
Convert the matched URL to a normalized and hashed URL.
@@ -276,12 +286,18 @@ def converter(matchobj):
# Determine the hashed name of the target file with the storage
# backend.
- hashed_url = self._url(
- self._stored_name,
- unquote(target_name),
- force=True,
- hashed_files=hashed_files,
- )
+ try:
+ hashed_url = self._url(
+ self._stored_name,
+ unquote(target_name),
+ force=True,
+ hashed_files=hashed_files,
+ )
+ except ValueError as exc:
+ line = _line_at_position(matchobj.string, matchobj.start())
+ note = f"{name!r} contains this reference {matched!r} on line {line}"
+ exc.add_note(note)
+ raise exc
transformed_url = "/".join(
url_path.split("/")[:-1] + hashed_url.split("/")[-1:]
| 20,852 | https://github.com/django/django/pull/20852 | 2026-03-06 21:54:27 | 36,968 | https://github.com/django/django/pull/20852 | 50 | ["tests/staticfiles_tests/test_storage.py"] | [] | 5.2 |
django__django-20837 | django/django | 23931eb7ff562b44d78859f29ca81d77d212df06 | # Fixed #36679 -- Fixed Basque date formats to use parenthetical declension suffixes.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36679
#### Branch description
Basque (eu) grammar requires conditional suffixes on years and day articles that depend on the final sound of the preceding word. Since Django's format strings are static, the CLDR parenthetical convention ("(e)ko" instead of "ko") is used to express the optionality.
This is a revamp of #19988.
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [ ] **No AI tools were used** in preparing this PR.
- [X] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
Claude code with model Sonnet 4.6 was used to analyze and summarize the [forum post](https://forum.djangoproject.com/t/basque-date-declination/43205) and [related ticket](https://code.djangoproject.com/ticket/36679).
#### Checklist
- [X] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [X] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [X] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [X] I have checked the "Has patch" ticket flag in the Trac system.
- [X] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/i18n/tests.py b/tests/i18n/tests.py
index e593d97cba14..91e7c95f67a0 100644
--- a/tests/i18n/tests.py
+++ b/tests/i18n/tests.py
@@ -1179,6 +1179,26 @@ def test_uncommon_locale_formats(self):
with translation.override(locale, deactivate=True):
self.assertEqual(expected, format_function(*format_args))
+ def test_basque_date_formats(self):
+ # Basque locale uses parenthetical suffixes for conditional declension:
+ # (e)ko for years and declined month/day forms.
+ with translation.override("eu", deactivate=True):
+ self.assertEqual(date_format(self.d), "2009(e)ko abe.k 31")
+ self.assertEqual(
+ date_format(self.dt, "DATETIME_FORMAT"),
+ "2009(e)ko abe.k 31, 20:50",
+ )
+ self.assertEqual(
+ date_format(self.d, "YEAR_MONTH_FORMAT"), "2009(e)ko abendua"
+ )
+ self.assertEqual(date_format(self.d, "MONTH_DAY_FORMAT"), "abenduaren 31a")
+ # Day 11 (hamaika in Basque) ends in 'a' as a word, but the
+ # numeral form does not, so appending 'a' is correct here.
+ self.assertEqual(
+ date_format(datetime.date(2009, 12, 11), "MONTH_DAY_FORMAT"),
+ "abenduaren 11a",
+ )
+
def test_sub_locales(self):
"""
Check if sublocales fall back to the main locale
| diff --git a/django/conf/locale/eu/formats.py b/django/conf/locale/eu/formats.py
index 61b16fbc6f69..e707f931c70c 100644
--- a/django/conf/locale/eu/formats.py
+++ b/django/conf/locale/eu/formats.py
@@ -2,10 +2,10 @@
#
# The *_FORMAT strings use the Django date format syntax,
# see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
-DATE_FORMAT = r"Y\k\o N j\a"
+DATE_FORMAT = r"Y(\e)\k\o N\k j"
TIME_FORMAT = "H:i"
-DATETIME_FORMAT = r"Y\k\o N j\a, H:i"
-YEAR_MONTH_FORMAT = r"Y\k\o F"
+DATETIME_FORMAT = r"Y(\e)\k\o N\k j, H:i"
+YEAR_MONTH_FORMAT = r"Y(\e)\k\o F"
MONTH_DAY_FORMAT = r"F\r\e\n j\a"
SHORT_DATE_FORMAT = "Y-m-d"
SHORT_DATETIME_FORMAT = "Y-m-d H:i"
| 20,837 | https://github.com/django/django/pull/20837 | 2026-03-06 21:25:16 | 36,679 | https://github.com/django/django/pull/20837 | 26 | ["tests/i18n/tests.py"] | [] | 5.2 |
django__django-20028 | django/django | 23931eb7ff562b44d78859f29ca81d77d212df06 | # Refs #28877 -- Added special ordinal context when humanizing value 1.
In french we need to specialize 1st which does not work like 81st, it's 1<sup>er</sup> and 81<sup>ième</sup>. For zero is tricky but it's attested that some use 0<sup>ième</sup>.
Also fixed 101 that was tested to be `101er` while in french it's `101e` (sourced in my commit).
#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [ ] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py
index 7c2863d3c478..91e9127a65bf 100644
--- a/tests/humanize_tests/tests.py
+++ b/tests/humanize_tests/tests.py
@@ -1,4 +1,5 @@
import datetime
+import os
from decimal import Decimal
from django.contrib.humanize.templatetags import humanize
@@ -9,10 +10,10 @@
from django.utils.timezone import get_fixed_timezone
from django.utils.translation import gettext as _
+here = os.path.dirname(os.path.abspath(__file__))
# Mock out datetime in some tests so they don't fail occasionally when they
# run too slow. Use a fixed datetime for datetime.now(). DST change in
# America/Chicago (the default time zone) happened on March 11th in 2012.
-
now = datetime.datetime(2012, 3, 9, 22, 30)
@@ -83,6 +84,7 @@ def test_ordinal(self):
with translation.override("en"):
self.humanize_tester(test_list, result_list, "ordinal")
+ @override_settings(LOCALE_PATHS=[os.path.join(here, "locale")])
def test_i18n_html_ordinal(self):
"""Allow html in output on i18n strings"""
test_list = (
@@ -93,6 +95,8 @@ def test_i18n_html_ordinal(self):
"11",
"12",
"13",
+ "21",
+ "31",
"101",
"102",
"103",
@@ -108,7 +112,9 @@ def test_i18n_html_ordinal(self):
"11<sup>e</sup>",
"12<sup>e</sup>",
"13<sup>e</sup>",
- "101<sup>er</sup>",
+ "21<sup>e</sup>",
+ "31<sup>e</sup>",
+ "101<sup>e</sup>",
"102<sup>e</sup>",
"103<sup>e</sup>",
"111<sup>e</sup>",
| diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py
index 26a9dd3a3f68..79d2e1566721 100644
--- a/django/contrib/humanize/templatetags/humanize.py
+++ b/django/contrib/humanize/templatetags/humanize.py
@@ -32,7 +32,10 @@ def ordinal(value):
return value
if value < 0:
return str(value)
- if value % 100 in (11, 12, 13):
+ if value == 1:
+ # Translators: Ordinal format when value is 1 (1st).
+ value = pgettext("ordinal is 1", "{}st").format(value)
+ elif value % 100 in (11, 12, 13):
# Translators: Ordinal format for 11 (11th), 12 (12th), and 13 (13th).
value = pgettext("ordinal 11, 12, 13", "{}th").format(value)
else:
| 20,028 | https://github.com/django/django/pull/20028 | 2026-03-06 12:02:21 | 28,877 | https://github.com/django/django/pull/20028 | 89 | ["tests/humanize_tests/tests.py"] | [] | 5.2 |
django__django-20828 | django/django | 35dab0ad9ee2ed23101420cb0f253deda2818191 | # Fixed #21080 -- Ignored urls inside comments during collectstatic.
#### Trac ticket number
ticket-21080
#### Branch description
Follows on from the work in https://github.com/django/django/pull/11241/ by @tmszi and @n6g7, it ignores block comments in css/js files when considering url subustitutions. It also adds line // comments for javascript. This does not attempt to solve the wider problems in javascript around matches in strings. But comments will cover a lot if incremental cases.
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [X] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [X] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [X] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [X] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [X] I have checked the "Has patch" ticket flag in the Trac system.
- [X] I have added or updated relevant tests.
- [X] I have added or updated relevant docs, including release notes if applicable.
- [X] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/staticfiles_tests/test_storage.py b/tests/staticfiles_tests/test_storage.py
index e09f9eda1c90..cdb6fd3c7e2e 100644
--- a/tests/staticfiles_tests/test_storage.py
+++ b/tests/staticfiles_tests/test_storage.py
@@ -65,7 +65,7 @@ def test_template_tag_simple_content(self):
def test_path_ignored_completely(self):
relpath = self.hashed_file_path("cached/css/ignored.css")
- self.assertEqual(relpath, "cached/css/ignored.55e7c226dda1.css")
+ self.assertEqual(relpath, "cached/css/ignored.0e15ac4a4fb4.css")
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
self.assertIn(b"#foobar", content)
@@ -75,6 +75,22 @@ def test_path_ignored_completely(self):
self.assertIn(b"chrome:foobar", content)
self.assertIn(b"//foobar", content)
self.assertIn(b"url()", content)
+ self.assertIn(b'/* @import url("non_exist.css") */', content)
+ self.assertIn(b'/* url("non_exist.png") */', content)
+ self.assertIn(b'@import url("non_exist.css")', content)
+ self.assertIn(b'url("non_exist.png")', content)
+ self.assertIn(b"@import url(other.css)", content)
+ self.assertIn(
+ b'background: #d3d6d8 /*url("does.not.exist.png")*/ '
+ b'url("/static/cached/img/relative.acae32e4532b.png");',
+ content,
+ )
+ self.assertIn(
+ b'background: #d3d6d8 /* url("does.not.exist.png") */ '
+ b'url("/static/cached/img/relative.acae32e4532b.png") '
+ b'/*url("does.not.exist.either.png")*/',
+ content,
+ )
self.assertPostCondition()
def test_path_with_querystring(self):
@@ -698,7 +714,7 @@ class TestCollectionJSModuleImportAggregationManifestStorage(CollectionTestCase)
def test_module_import(self):
relpath = self.hashed_file_path("cached/module.js")
- self.assertEqual(relpath, "cached/module.4326210cf0bd.js")
+ self.assertEqual(relpath, "cached/module.eaa407b94311.js")
tests = [
# Relative imports.
b'import testConst from "./module_test.477bbebe77f0.js";',
@@ -721,6 +737,15 @@ def test_module_import(self):
b" firstVar1 as firstVarAlias,\n"
b" $second_var_2 as secondVarAlias\n"
b'} from "./module_test.477bbebe77f0.js";',
+ # Ignore block comments
+ b'/* export * from "./module_test_missing.js"; */',
+ b"/*\n"
+ b'import rootConst from "/static/absolute_root_missing.js";\n'
+ b'const dynamicModule = import("./module_test_missing.js");\n'
+ b"*/",
+ # Ignore line comments
+ b'// import testConst from "./module_test_missing.js";',
+ b'// const dynamicModule = import("./module_test_missing.js");',
]
with storage.staticfiles_storage.open(relpath) as relfile:
content = relfile.read()
@@ -730,7 +755,7 @@ def test_module_import(self):
def test_aggregating_modules(self):
relpath = self.hashed_file_path("cached/module.js")
- self.assertEqual(relpath, "cached/module.4326210cf0bd.js")
+ self.assertEqual(relpath, "cached/module.eaa407b94311.js")
tests = [
b'export * from "./module_test.477bbebe77f0.js";',
b'export { testConst } from "./module_test.477bbebe77f0.js";',
| diff --git a/django/contrib/staticfiles/storage.py b/django/contrib/staticfiles/storage.py
index b16c77757cd6..c889bcb4a495 100644
--- a/django/contrib/staticfiles/storage.py
+++ b/django/contrib/staticfiles/storage.py
@@ -11,6 +11,12 @@
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage, storages
from django.utils.functional import LazyObject
+from django.utils.regex_helper import _lazy_re_compile
+
+comment_re = _lazy_re_compile(r"\/\*[^*]*\*+([^/*][^*]*\*+)*\/", re.DOTALL)
+line_comment_re = _lazy_re_compile(
+ r"\/\*[^*]*\*+([^/*][^*]*\*+)*\/|\/\/[^\n]*", re.DOTALL
+)
class StaticFilesStorage(FileSystemStorage):
@@ -204,7 +210,22 @@ def url(self, name, force=False):
"""
return self._url(self.stored_name, name, force)
- def url_converter(self, name, hashed_files, template=None):
+ def get_comment_blocks(self, content, include_line_comments=False):
+ """
+ Return a list of (start, end) tuples for each comment block.
+ """
+ pattern = line_comment_re if include_line_comments else comment_re
+ return [(match.start(), match.end()) for match in re.finditer(pattern, content)]
+
+ def is_in_comment(self, pos, comments):
+ for start, end in comments:
+ if start < pos and pos < end:
+ return True
+ if pos < start:
+ return False
+ return False
+
+ def url_converter(self, name, hashed_files, template=None, comment_blocks=None):
"""
Return the custom URL converter for the given file name.
"""
@@ -222,6 +243,10 @@ def converter(matchobj):
matched = matches["matched"]
url = matches["url"]
+ # Ignore URLs in comments.
+ if comment_blocks and self.is_in_comment(matchobj.start(), comment_blocks):
+ return matched
+
# Ignore absolute/protocol-relative and data-uri URLs.
if re.match(r"^[a-z]+:", url) or url.startswith("//"):
return matched
@@ -375,7 +400,13 @@ def path_level(name):
if matches_patterns(path, (extension,)):
for pattern, template in patterns:
converter = self.url_converter(
- name, hashed_files, template
+ name,
+ hashed_files,
+ template,
+ self.get_comment_blocks(
+ content,
+ include_line_comments=path.endswith(".js"),
+ ),
)
try:
content = pattern.sub(converter, content)
| 20,828 | https://github.com/django/django/pull/20828 | 2026-03-04 21:15:49 | 21,080 | https://github.com/django/django/pull/20828 | 104 | ["tests/staticfiles_tests/test_storage.py"] | [] | 5.2 |
django__django-20789 | django/django | 3f21cb06e76044ad753055700395e54a1fc4f1e9 | # Fixed #36961 -- Fixed TypeError in deprecation warnings if Django is imported by namespace.
#### Trac ticket number
ticket-36961
#### Branch description
Found while testing #20300 -- I opened a shell, and tried to create a `Field.get_placeholder` method, but because my cwd was one level above my Django checkout, I had:
```py
>>> django.__file__ is None
True
```
Leading to a TypeError in this util.
#### AI Assistance Disclosure (REQUIRED)
- [x] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [x] I have added or updated relevant docs, including release notes if applicable.
- [x] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/deprecation/tests.py b/tests/deprecation/tests.py
index 2df9cc6fa219..ac610b492835 100644
--- a/tests/deprecation/tests.py
+++ b/tests/deprecation/tests.py
@@ -18,6 +18,10 @@ def setUp(self):
def test_no_file(self):
orig_file = django.__file__
try:
+ # Depending on the cwd, Python might give a local checkout
+ # precedence over installed Django, producing None.
+ django.__file__ = None
+ self.assertEqual(django_file_prefixes(), ())
del django.__file__
self.assertEqual(django_file_prefixes(), ())
finally:
| diff --git a/django/utils/deprecation.py b/django/utils/deprecation.py
index daa485eb35bf..4aa11832165e 100644
--- a/django/utils/deprecation.py
+++ b/django/utils/deprecation.py
@@ -13,9 +13,8 @@
@functools.cache
def django_file_prefixes():
- try:
- file = django.__file__
- except AttributeError:
+ file = getattr(django, "__file__", None)
+ if file is None:
return ()
return (os.path.dirname(file),)
| 20,789 | https://github.com/django/django/pull/20789 | 2026-03-02 19:08:11 | 36,961 | https://github.com/django/django/pull/20789 | 12 | ["tests/deprecation/tests.py"] | [] | 5.2 |
django__django-20788 | django/django | 97cab5fe6526ca175ae520711c61a25c4f8cbb11 | # Refs #35972 -- Returned params in a tuple in further expressions.
#### Trac ticket number
ticket-35972
#### Branch description
As [pointed out](https://github.com/django/django/pull/20300#discussion_r2643723457) by Simon, `Value.as_sql` still returned params in a list.
#### AI Assistance Disclosure (REQUIRED)
- [x] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [ ] I have checked the "Has patch" ticket flag in the Trac system.
- [ ] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py
index cb62d0fbd73f..5effc8ac0d17 100644
--- a/tests/expressions/tests.py
+++ b/tests/expressions/tests.py
@@ -2504,9 +2504,9 @@ def test_compile_unresolved(self):
# This test might need to be revisited later on if #25425 is enforced.
compiler = Time.objects.all().query.get_compiler(connection=connection)
value = Value("foo")
- self.assertEqual(value.as_sql(compiler, connection), ("%s", ["foo"]))
+ self.assertEqual(value.as_sql(compiler, connection), ("%s", ("foo",)))
value = Value("foo", output_field=CharField())
- self.assertEqual(value.as_sql(compiler, connection), ("%s", ["foo"]))
+ self.assertEqual(value.as_sql(compiler, connection), ("%s", ("foo",)))
def test_output_field_decimalfield(self):
Time.objects.create()
| diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index 63d0c1802b49..d0e91f13d278 100644
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -769,7 +769,7 @@ def as_sql(self, compiler, connection):
# order of precedence
expression_wrapper = "(%s)"
sql = connection.ops.combine_expression(self.connector, expressions)
- return expression_wrapper % sql, expression_params
+ return expression_wrapper % sql, tuple(expression_params)
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
@@ -835,7 +835,7 @@ def as_sql(self, compiler, connection):
# order of precedence
expression_wrapper = "(%s)"
sql = connection.ops.combine_duration_expression(self.connector, expressions)
- return expression_wrapper % sql, expression_params
+ return expression_wrapper % sql, tuple(expression_params)
def as_sqlite(self, compiler, connection, **extra_context):
sql, params = self.as_sql(compiler, connection, **extra_context)
@@ -1179,8 +1179,8 @@ def as_sql(self, compiler, connection):
# oracledb does not always convert None to the appropriate
# NULL type (like in case expressions using numbers), so we
# use a literal SQL NULL
- return "NULL", []
- return "%s", [val]
+ return "NULL", ()
+ return "%s", (val,)
def as_sqlite(self, compiler, connection, **extra_context):
sql, params = self.as_sql(compiler, connection, **extra_context)
@@ -1273,7 +1273,7 @@ def __repr__(self):
return "'*'"
def as_sql(self, compiler, connection):
- return "*", []
+ return "*", ()
class DatabaseDefault(Expression):
@@ -1313,7 +1313,7 @@ def resolve_expression(
def as_sql(self, compiler, connection):
if not connection.features.supports_default_keyword_in_insert:
return compiler.compile(self.expression)
- return "DEFAULT", []
+ return "DEFAULT", ()
class Col(Expression):
@@ -1398,7 +1398,7 @@ def as_sql(self, compiler, connection):
cols_sql.append(sql)
cols_params.extend(params)
- return ", ".join(cols_sql), cols_params
+ return ", ".join(cols_sql), tuple(cols_params)
def relabeled_clone(self, relabels):
return self.__class__(
@@ -1447,7 +1447,7 @@ def relabeled_clone(self, relabels):
return clone
def as_sql(self, compiler, connection):
- return connection.ops.quote_name(self.refs), []
+ return connection.ops.quote_name(self.refs), ()
def get_group_by_cols(self):
return [self]
@@ -1764,7 +1764,7 @@ def as_sql(
sql = template % template_params
if self._output_field_or_none is not None:
sql = connection.ops.unification_cast_sql(self.output_field) % sql
- return sql, sql_params
+ return sql, tuple(sql_params)
def get_group_by_cols(self):
if not self.cases:
@@ -2148,7 +2148,7 @@ def as_sql(self, compiler, connection):
"end": end,
"exclude": self.get_exclusion(),
},
- [],
+ (),
)
def __repr__(self):
| 20,788 | https://github.com/django/django/pull/20788 | 2026-02-27 22:06:47 | 35,972 | https://github.com/django/django/pull/20788 | 24 | ["tests/expressions/tests.py"] | [] | 5.2 |
django__django-20308 | django/django | f991a1883889a520679fe41112281435581211e1 | # Fixed #36750 -- Made ordering of M2M objects deterministic in serializers.
#### Trac ticket number
ticket-36750
#### Branch description
Following the implementation of `QuerySet.totally_ordered` in ticket [#36857](https://code.djangoproject.com/ticket/36857), this patch updates the Python and XML serializers to apply deterministic ordering for many-to-many relations using natural keys. The serializers check ``qs.totally_ordered`` and, when the ``queryset`` lacks a total ordering, they extract any existing ordering and simply append ``'pk'`` to break ties. This preserves any default model sorting while guaranteeing determinism, addressing the inconsistent fixture output on PostgreSQL without imposing redundant sorting.
A regression test in `tests/fixtures/tests.py` verifies this behavior for both formats.
#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/serializers/test_natural.py b/tests/serializers/test_natural.py
index b405dc3e284b..4dff100cc7af 100644
--- a/tests/serializers/test_natural.py
+++ b/tests/serializers/test_natural.py
@@ -1,5 +1,7 @@
+from unittest import mock
+
from django.core import serializers
-from django.db import connection
+from django.db import connection, models
from django.test import TestCase
from .models import (
@@ -336,6 +338,20 @@ def nullable_natural_key_m2m_test(self, format):
)
+def natural_key_m2m_totally_ordered_test(self, format):
+ t1 = NaturalKeyThing.objects.create(key="t1")
+ t2 = NaturalKeyThing.objects.create(key="t2")
+ t3 = NaturalKeyThing.objects.create(key="t3")
+ t1.other_things.add(t2, t3)
+
+ with mock.patch.object(models.QuerySet, "order_by") as mock_order_by:
+ serializers.serialize(format, [t1], use_natural_foreign_keys=True)
+ mock_order_by.assert_called_once_with("pk")
+ mock_order_by.reset_mock()
+ serializers.serialize(format, [t1], use_natural_foreign_keys=False)
+ mock_order_by.assert_called_once_with("pk")
+
+
# Dynamically register tests for each serializer
register_tests(
NaturalKeySerializerTests,
@@ -385,3 +401,8 @@ def nullable_natural_key_m2m_test(self, format):
"test_%s_nullable_natural_key_m2m",
nullable_natural_key_m2m_test,
)
+register_tests(
+ NaturalKeySerializerTests,
+ "test_%s_natural_key_m2m_totally_ordered",
+ natural_key_m2m_totally_ordered_test,
+)
| diff --git a/django/core/serializers/python.py b/django/core/serializers/python.py
index 53a73e19e51f..73ba24368b0b 100644
--- a/django/core/serializers/python.py
+++ b/django/core/serializers/python.py
@@ -77,7 +77,15 @@ def queryset_iterator(obj, field):
chunk_size = (
2000 if getattr(attr, "prefetch_cache_name", None) else None
)
- return attr.iterator(chunk_size)
+ query_set = attr.all()
+ if not query_set.totally_ordered:
+ current_ordering = (
+ query_set.query.order_by
+ or query_set.model._meta.ordering
+ or []
+ )
+ query_set = query_set.order_by(*current_ordering, "pk")
+ return query_set.iterator(chunk_size)
else:
@@ -86,6 +94,13 @@ def m2m_value(value):
def queryset_iterator(obj, field):
query_set = getattr(obj, field.name).select_related(None).only("pk")
+ if not query_set.totally_ordered:
+ current_ordering = (
+ query_set.query.order_by
+ or query_set.model._meta.ordering
+ or []
+ )
+ query_set = query_set.order_by(*current_ordering, "pk")
chunk_size = 2000 if query_set._prefetch_related_lookups else None
return query_set.iterator(chunk_size=chunk_size)
diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py
index d8ffbdf00a98..3d1f79ea0d00 100644
--- a/django/core/serializers/xml_serializer.py
+++ b/django/core/serializers/xml_serializer.py
@@ -177,7 +177,15 @@ def queryset_iterator(obj, field):
chunk_size = (
2000 if getattr(attr, "prefetch_cache_name", None) else None
)
- return attr.iterator(chunk_size)
+ query_set = attr.all()
+ if not query_set.totally_ordered:
+ current_ordering = (
+ query_set.query.order_by
+ or query_set.model._meta.ordering
+ or []
+ )
+ query_set = query_set.order_by(*current_ordering, "pk")
+ return query_set.iterator(chunk_size)
else:
@@ -186,6 +194,13 @@ def handle_m2m(value):
def queryset_iterator(obj, field):
query_set = getattr(obj, field.name).select_related(None).only("pk")
+ if not query_set.totally_ordered:
+ current_ordering = (
+ query_set.query.order_by
+ or query_set.model._meta.ordering
+ or []
+ )
+ query_set = query_set.order_by(*current_ordering, "pk")
chunk_size = 2000 if query_set._prefetch_related_lookups else None
return query_set.iterator(chunk_size=chunk_size)
| 20,308 | https://github.com/django/django/pull/20308 | 2026-02-26 12:46:35 | 36,750 | https://github.com/django/django/pull/20308 | 57 | ["tests/serializers/test_natural.py"] | [] | 5.2 |
django__django-20722 | django/django | bbc6818bc12f14c1764a7eb68556018195f56b59 | # Fixed #36951 -- Removed empty exc_info from log_task_finished signal handler.
#### Trac ticket number
N/A
#### Branch description
If no exception occurred, the logger in `django.tasks.signals.log_task_finished` would print `None Type: None`
Before:
Task id=191 path=tests.dummy.tasks.dummy_recurring_task state=RUNNING
dummy recurring task
Task id=191 path=tests.dummy.tasks.dummy_recurring_task state=SUCCESSFUL
NoneType: None
After:
Task id=193 path=tests.dummy.tasks.dummy_recurring_task state=RUNNING
dummy recurring task
Task id=193 path=tests.dummy.tasks.dummy_recurring_task state=SUCCESSFUL
Of course, if there is an exception, it is still printed:
Task id=195 path=tests.dummy.tasks.dummy_recurring_task state=RUNNING
Traceback (most recent call last):
File "/Users/elias/dev/steady_queue/steady_queue/models/claimed_execution.py", line 93, in perform
task.func(*args, **kwargs)
~~~~~~~~~^^^^^^^^^^^^^^^^^
File "/Users/elias/dev/steady_queue/tests/dummy/tasks.py", line 53, in dummy_recurring_task
return 1 / 0
~~^~~
ZeroDivisionError: division by zero
#### AI Assistance Disclosure (REQUIRED)
- [ ] **No AI tools were used** in preparing this PR.
- [x] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
AI tools used: `cursor-agent` with `Claude Opus 4.6 (thinking)`.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [ ] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/tasks/test_immediate_backend.py b/tests/tasks/test_immediate_backend.py
index 356e9ab2649d..36b63faff801 100644
--- a/tests/tasks/test_immediate_backend.py
+++ b/tests/tasks/test_immediate_backend.py
@@ -228,6 +228,15 @@ def test_failed_logs(self):
self.assertIn("state=FAILED", captured_logs.output[2])
self.assertIn(result.id, captured_logs.output[2])
+ def test_successful_task_no_none_in_logs(self):
+ with self.assertLogs("django.tasks", level="DEBUG") as captured_logs:
+ result = test_tasks.noop_task.enqueue()
+
+ self.assertEqual(result.status, TaskResultStatus.SUCCESSFUL)
+
+ for log_output in captured_logs.output:
+ self.assertNotIn("None", log_output)
+
def test_takes_context(self):
result = test_tasks.get_task_id.enqueue()
| diff --git a/django/tasks/signals.py b/django/tasks/signals.py
index 288fe08e328a..919dae022221 100644
--- a/django/tasks/signals.py
+++ b/django/tasks/signals.py
@@ -49,6 +49,8 @@ def log_task_started(sender, task_result, **kwargs):
@receiver(task_finished)
def log_task_finished(sender, task_result, **kwargs):
+ # Signal is sent inside exception handlers, so exc_info() is available.
+ exc_info = sys.exc_info()
logger.log(
(
logging.ERROR
@@ -59,6 +61,5 @@ def log_task_finished(sender, task_result, **kwargs):
task_result.id,
task_result.task.module_path,
task_result.status,
- # Signal is sent inside exception handlers, so exc_info() is available.
- exc_info=sys.exc_info(),
+ exc_info=exc_info if exc_info[0] else None,
)
| 20,722 | https://github.com/django/django/pull/20722 | 2026-02-25 18:52:24 | 36,951 | https://github.com/django/django/pull/20722 | 17 | ["tests/tasks/test_immediate_backend.py"] | [] | 5.2 |
django__django-20766 | django/django | 69d47f921979aba5ad5d876bff015b55121fc49c | # Fixed #36944 -- Removed MAX_LENGTH_HTML and related 5M chars limit references from HTML truncation docs.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36944
#### Branch description
Following up some security reports, we noticed the docs around HTML length limit enforcement was outdated. This work cleans that up.
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [X] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [X] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [X] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [X] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [X] I have checked the "Has patch" ticket flag in the Trac system.
- [ ] I have added or updated relevant tests.
- [X] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/utils_tests/test_text.py b/tests/utils_tests/test_text.py
index 11c01874cb5d..50e205a25449 100644
--- a/tests/utils_tests/test_text.py
+++ b/tests/utils_tests/test_text.py
@@ -1,6 +1,5 @@
import json
import sys
-from unittest.mock import patch
from django.core.exceptions import SuspiciousFileOperation
from django.test import SimpleTestCase
@@ -136,23 +135,6 @@ def test_truncate_chars_html(self):
truncator = text.Truncator("foo</p>")
self.assertEqual("foo</p>", truncator.chars(5, html=True))
- @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000)
- def test_truncate_chars_html_size_limit(self):
- max_len = text.Truncator.MAX_LENGTH_HTML
- bigger_len = text.Truncator.MAX_LENGTH_HTML + 1
- valid_html = "<p>Joel is a slug</p>" # 14 chars
- perf_test_values = [
- ("</a" + "\t" * (max_len - 6) + "//>", "</a>"),
- ("</p" + "\t" * bigger_len + "//>", "</p>"),
- ("&" * bigger_len, ""),
- ("_X<<<<<<<<<<<>", "_X<<<<<<<…"),
- (valid_html * bigger_len, "<p>Joel is a…</p>"), # 10 chars
- ]
- for value, expected in perf_test_values:
- with self.subTest(value=value):
- truncator = text.Truncator(value)
- self.assertEqual(expected, truncator.chars(10, html=True))
-
def test_truncate_chars_html_with_newline_inside_tag(self):
truncator = text.Truncator(
'<p>The quick <a href="xyz.html"\n id="mylink">brown fox</a> jumped over '
@@ -329,24 +311,6 @@ def test_truncate_html_words(self):
self.assertEqual(truncator.words(3, html=True), "hello ><…")
self.assertEqual(truncator.words(4, html=True), "hello >< world")
- @patch("django.utils.text.Truncator.MAX_LENGTH_HTML", 10_000)
- def test_truncate_words_html_size_limit(self):
- max_len = text.Truncator.MAX_LENGTH_HTML
- bigger_len = text.Truncator.MAX_LENGTH_HTML + 1
- valid_html = "<p>Joel is a slug</p>" # 4 words
- perf_test_values = [
- ("</a" + "\t" * (max_len - 6) + "//>", "</a>"),
- ("</p" + "\t" * bigger_len + "//>", "</p>"),
- ("&" * max_len, ""),
- ("&" * bigger_len, ""),
- ("_X<<<<<<<<<<<>", "_X<<<<<<<<<<<>"),
- (valid_html * bigger_len, valid_html * 12 + "<p>Joel is…</p>"), # 50 words
- ]
- for value, expected in perf_test_values:
- with self.subTest(value=value):
- truncator = text.Truncator(value)
- self.assertEqual(expected, truncator.words(50, html=True))
-
def test_wrap(self):
digits = "1234 67 9"
self.assertEqual(text.wrap(digits, 100), "1234 67 9")
| diff --git a/django/utils/text.py b/django/utils/text.py
index ef4baa935bf2..cfe6ceca9e4b 100644
--- a/django/utils/text.py
+++ b/django/utils/text.py
@@ -185,14 +185,8 @@ def process(self, data):
class Truncator(SimpleLazyObject):
"""
An object used to truncate text, either by characters or words.
-
- When truncating HTML text (either chars or words), input will be limited to
- at most `MAX_LENGTH_HTML` characters.
"""
- # 5 million characters are approximately 4000 text pages or 3 web pages.
- MAX_LENGTH_HTML = 5_000_000
-
def __init__(self, text):
super().__init__(lambda: str(text))
| 20,766 | https://github.com/django/django/pull/20766 | 2026-02-25 16:08:53 | 36,944 | https://github.com/django/django/pull/20766 | 48 | ["tests/utils_tests/test_text.py"] | [] | 5.2 |
django__django-20696 | django/django | 69d47f921979aba5ad5d876bff015b55121fc49c | # Fixed #36839 -- Warned when model renames encounter conflicts from stale ContentTypes.
#### Trac ticket number
ticket-36839
#### Branch description
Fixed #36839 -- Warn when ContentType rename conflicts with stale entries.
When renaming a model, Django automatically injects a `RenameContentType` operation to update the content type. If a stale content type with the target name already exists, the operation catches the `IntegrityError` and silently reverts without notifying the user. This results in the migration appearing successful while the content type rename actually failed, leading to broken GenericForeignKey references and stale data.
This change adds a `RuntimeWarning` when the rename conflict occurs, informing users to run the `remove_stale_contenttypes` management command to resolve the issue. The existing fallback behavior is preserved—no data is deleted or overwritten automatically.
#### AI Assistance Disclosure (REQUIRED)
- [ ] **No AI tools were used** in preparing this PR.
- [x] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
Claude Sonnet 4.5 was used for assistance with adding tests. All output was thoroughly reviewed and verified by me.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch.
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes. | diff --git a/tests/contenttypes_tests/test_operations.py b/tests/contenttypes_tests/test_operations.py
index d44648d9fe6e..9f6506640ad6 100644
--- a/tests/contenttypes_tests/test_operations.py
+++ b/tests/contenttypes_tests/test_operations.py
@@ -154,13 +154,19 @@ def test_missing_content_type_rename_ignore(self):
def test_content_type_rename_conflict(self):
ContentType.objects.create(app_label="contenttypes_tests", model="foo")
ContentType.objects.create(app_label="contenttypes_tests", model="renamedfoo")
- call_command(
- "migrate",
- "contenttypes_tests",
- database="default",
- interactive=False,
- verbosity=0,
- )
+ msg = (
+ "Could not rename content type 'contenttypes_tests.foo' to "
+ "'renamedfoo' due to an existing conflicting content type. "
+ "Run 'remove_stale_contenttypes' to clean up stale entries."
+ )
+ with self.assertWarnsMessage(RuntimeWarning, msg):
+ call_command(
+ "migrate",
+ "contenttypes_tests",
+ database="default",
+ interactive=False,
+ verbosity=0,
+ )
self.assertTrue(
ContentType.objects.filter(
app_label="contenttypes_tests", model="foo"
@@ -171,14 +177,20 @@ def test_content_type_rename_conflict(self):
app_label="contenttypes_tests", model="renamedfoo"
).exists()
)
- call_command(
- "migrate",
- "contenttypes_tests",
- "zero",
- database="default",
- interactive=False,
- verbosity=0,
- )
+ msg = (
+ "Could not rename content type 'contenttypes_tests.renamedfoo' to "
+ "'foo' due to an existing conflicting content type. "
+ "Run 'remove_stale_contenttypes' to clean up stale entries."
+ )
+ with self.assertWarnsMessage(RuntimeWarning, msg):
+ call_command(
+ "migrate",
+ "contenttypes_tests",
+ "zero",
+ database="default",
+ interactive=False,
+ verbosity=0,
+ )
self.assertTrue(
ContentType.objects.filter(
app_label="contenttypes_tests", model="foo"
| diff --git a/django/contrib/contenttypes/management/__init__.py b/django/contrib/contenttypes/management/__init__.py
index 929e44f390db..55b08870d83e 100644
--- a/django/contrib/contenttypes/management/__init__.py
+++ b/django/contrib/contenttypes/management/__init__.py
@@ -1,3 +1,5 @@
+import warnings
+
from django.apps import apps as global_apps
from django.db import DEFAULT_DB_ALIAS, IntegrityError, migrations, router, transaction
@@ -28,8 +30,14 @@ def _rename(self, apps, schema_editor, old_model, new_model):
content_type.save(using=db, update_fields={"model"})
except IntegrityError:
# Gracefully fallback if a stale content type causes a
- # conflict as remove_stale_contenttypes will take care of
- # asking the user what should be done next.
+ # conflict. Warn the user so they can run the
+ # remove_stale_contenttypes management command.
+ warnings.warn(
+ f"Could not rename content type '{self.app_label}.{old_model}' "
+ f"to '{new_model}' due to an existing conflicting content type. "
+ "Run 'remove_stale_contenttypes' to clean up stale entries.",
+ RuntimeWarning,
+ )
content_type.model = old_model
else:
# Clear the cache as the `get_by_natural_key()` call will cache
| 20,696 | https://github.com/django/django/pull/20696 | 2026-02-25 15:22:58 | 36,839 | https://github.com/django/django/pull/20696 | 54 | ["tests/contenttypes_tests/test_operations.py"] | [] | 5.2 |
django__django-20679 | django/django | 97228a86d2b7d8011b97bebdfe0f126a536a3841 | # Fixed #36921 -- Fixed KeyError when adding inline instances of models not registered with admin.
#### Trac ticket number
ticket-36921
#### Branch description
Added an if statement to avoid key error if model not registered in admin.
Note this bug was introduced in another pull request I worked on [here](https://github.com/django/django/pull/18934/).
I added the example Jacob shared to the same example project that had been used with that issue [here](https://github.com/reergymerej/ticket_13883).
#### AI Assistance Disclosure (REQUIRED)
- [ ] **No AI tools were used** in preparing this PR.
- [x] **If AI tools were used** - Claude Code plugin in VS Code
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [x] I have added or updated relevant docs, including release notes if applicable.
- [x] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index 7f35d7c2f455..fa9d9a2dc6f5 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -589,6 +589,31 @@ def test_popup_add_POST_with_invalid_source_model(self):
self.assertIn("admin_views.nonexistent", str(messages[0]))
self.assertIn("could not be found", str(messages[0]))
+ def test_popup_add_POST_with_unregistered_source_model(self):
+ """
+ Popup add where source_model is a valid Django model but is not
+ registered in the admin site (e.g. a model only used as an inline)
+ should succeed without raising a KeyError.
+ """
+ post_data = {
+ IS_POPUP_VAR: "1",
+ # Chapter exists as a model but is not registered in site (only
+ # in site6), simulating a model used only as an inline.
+ SOURCE_MODEL_VAR: "admin_views.chapter",
+ "title": "Test Article",
+ "content": "some content",
+ "date_0": "2010-09-10",
+ "date_1": "14:55:39",
+ }
+ response = self.client.post(reverse("admin:admin_views_article_add"), post_data)
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "data-popup-response")
+ # No error messages - unregistered model is silently skipped.
+ messages = list(response.wsgi_request._messages)
+ self.assertEqual(len(messages), 0)
+ # No optgroup in the response.
+ self.assertNotContains(response, ""optgroup"")
+
def test_basic_edit_POST(self):
"""
A smoke test to ensure POST on edit_view works.
| diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index 9c787d232912..b67b023bd313 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -1419,7 +1419,7 @@ def response_add(self, request, obj, post_url_continue=None):
# Find the optgroup for the new item, if available
source_model_name = request.POST.get(SOURCE_MODEL_VAR)
-
+ source_admin = None
if source_model_name:
app_label, model_name = source_model_name.split(".", 1)
try:
@@ -1428,21 +1428,23 @@ def response_add(self, request, obj, post_url_continue=None):
msg = _('The app "%s" could not be found.') % source_model_name
self.message_user(request, msg, messages.ERROR)
else:
- source_admin = self.admin_site._registry[source_model]
- form = source_admin.get_form(request)()
- if self.opts.verbose_name_plural in form.fields:
- field = form.fields[self.opts.verbose_name_plural]
- for option_value, option_label in field.choices:
- # Check if this is an optgroup (label is a sequence
- # of choices rather than a single string value).
- if isinstance(option_label, (list, tuple)):
- # It's an optgroup:
- # (group_name, [(value, label), ...])
- optgroup_label = option_value
- for choice_value, choice_display in option_label:
- if choice_display == str(obj):
- popup_response["optgroup"] = str(optgroup_label)
- break
+ source_admin = self.admin_site._registry.get(source_model)
+
+ if source_admin:
+ form = source_admin.get_form(request)()
+ if self.opts.verbose_name_plural in form.fields:
+ field = form.fields[self.opts.verbose_name_plural]
+ for option_value, option_label in field.choices:
+ # Check if this is an optgroup (label is a sequence
+ # of choices rather than a single string value).
+ if isinstance(option_label, (list, tuple)):
+ # It's an optgroup:
+ # (group_name, [(value, label), ...])
+ optgroup_label = option_value
+ for choice_value, choice_display in option_label:
+ if choice_display == str(obj):
+ popup_response["optgroup"] = str(optgroup_label)
+ break
popup_response_data = json.dumps(popup_response)
return TemplateResponse(
| 20,679 | https://github.com/django/django/pull/20679 | 2026-02-11 23:07:40 | 36,921 | https://github.com/django/django/pull/20679 | 59 | ["tests/admin_views/tests.py"] | [] | 5.2 |
django__django-20628 | django/django | 7cf1c22d4dfdd46f2082cfc55b714b68c4fd2de3 | # Fixed #36890 -- Supported StringAgg(distinct=True) on SQLite with the default delimiter.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36890
#### Branch description
Currently, the generic StringAgg function raises an error on SQLite when distinct=True
This change enables support for distinct aggregation on SQLite by omitting the delimiter argument in the generated SQL when it matches the default comma.
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [ ] **No AI tools were used** in preparing this PR.
- [X] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
I used GitHub Copilot to assist with writing tests.
#### Checklist
- [X] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [X] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [X] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [X] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/aggregation/tests.py b/tests/aggregation/tests.py
index bf6bf2703112..0a975dcb529e 100644
--- a/tests/aggregation/tests.py
+++ b/tests/aggregation/tests.py
@@ -3,6 +3,7 @@
import re
from decimal import Decimal
from itertools import chain
+from unittest import skipUnless
from django.core.exceptions import FieldError
from django.db import NotSupportedError, connection
@@ -579,6 +580,16 @@ def test_distinct_on_stringagg(self):
)
self.assertCountEqual(books["ratings"].split(","), ["3", "4", "4.5", "5"])
+ @skipUnless(connection.vendor == "sqlite", "Special default case for SQLite.")
+ def test_distinct_on_stringagg_sqlite_special_case(self):
+ """
+ Value(",") is the only delimiter usable on SQLite with distinct=True.
+ """
+ books = Book.objects.aggregate(
+ ratings=StringAgg(Cast(F("rating"), CharField()), Value(","), distinct=True)
+ )
+ self.assertCountEqual(books["ratings"].split(","), ["3.0", "4.0", "4.5", "5.0"])
+
@skipIfDBFeature("supports_aggregate_distinct_multiple_argument")
def test_raises_error_on_multiple_argument_distinct(self):
message = (
@@ -589,7 +600,7 @@ def test_raises_error_on_multiple_argument_distinct(self):
Book.objects.aggregate(
ratings=StringAgg(
Cast(F("rating"), CharField()),
- Value(","),
+ Value(";"),
distinct=True,
)
)
| diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py
index 1cf82416cb73..d1139e8bcc3c 100644
--- a/django/db/models/aggregates.py
+++ b/django/db/models/aggregates.py
@@ -369,6 +369,24 @@ def as_mysql(self, compiler, connection, **extra_context):
return sql, (*params, *delimiter_params)
def as_sqlite(self, compiler, connection, **extra_context):
+ if (
+ self.distinct
+ and isinstance(self.delimiter.value, Value)
+ and self.delimiter.value.value == ","
+ ):
+ clone = self.copy()
+ source_expressions = clone.get_source_expressions()
+ clone.set_source_expressions(
+ source_expressions[:1] + source_expressions[2:]
+ )
+
+ return clone.as_sql(
+ compiler,
+ connection,
+ function="GROUP_CONCAT",
+ **extra_context,
+ )
+
if connection.get_database_version() < (3, 44):
return self.as_sql(
compiler,
| 20,628 | https://github.com/django/django/pull/20628 | 2026-02-10 21:47:45 | 36,890 | https://github.com/django/django/pull/20628 | 43 | ["tests/aggregation/tests.py"] | [] | 5.2 |
django__django-20498 | django/django | 56ed37e17e5b1a509aa68a0c797dcff34fcc1366 | # Fixed #36841 -- Made multipart parser class pluggable on HttpRequest.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number, or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36841
#### Branch description
Provide a concise overview of the issue or rationale behind the proposed changes.
#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [x] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/requests_tests/tests.py b/tests/requests_tests/tests.py
index 36843df9b65b..e52989b0da78 100644
--- a/tests/requests_tests/tests.py
+++ b/tests/requests_tests/tests.py
@@ -13,7 +13,11 @@
RawPostDataException,
UnreadablePostError,
)
-from django.http.multipartparser import MAX_TOTAL_HEADER_SIZE, MultiPartParserError
+from django.http.multipartparser import (
+ MAX_TOTAL_HEADER_SIZE,
+ MultiPartParser,
+ MultiPartParserError,
+)
from django.http.request import split_domain_port
from django.test import RequestFactory, SimpleTestCase, override_settings
from django.test.client import BOUNDARY, MULTIPART_CONTENT, FakePayload
@@ -1112,6 +1116,72 @@ def test_deepcopy(self):
request.session["key"] = "value"
self.assertEqual(request_copy.session, {})
+ def test_custom_multipart_parser_class(self):
+
+ class CustomMultiPartParser(MultiPartParser):
+ def parse(self):
+ post, files = super().parse()
+ post._mutable = True
+ post["custom_parser_used"] = "yes"
+ post._mutable = False
+ return post, files
+
+ class CustomWSGIRequest(WSGIRequest):
+ multipart_parser_class = CustomMultiPartParser
+
+ payload = FakePayload(
+ "\r\n".join(
+ [
+ "--boundary",
+ 'Content-Disposition: form-data; name="name"',
+ "",
+ "value",
+ "--boundary--",
+ ]
+ )
+ )
+ request = CustomWSGIRequest(
+ {
+ "REQUEST_METHOD": "POST",
+ "CONTENT_TYPE": "multipart/form-data; boundary=boundary",
+ "CONTENT_LENGTH": len(payload),
+ "wsgi.input": payload,
+ }
+ )
+ self.assertEqual(request.POST.get("custom_parser_used"), "yes")
+ self.assertEqual(request.POST.get("name"), "value")
+
+ def test_multipart_parser_class_immutable_after_parse(self):
+ payload = FakePayload(
+ "\r\n".join(
+ [
+ "--boundary",
+ 'Content-Disposition: form-data; name="name"',
+ "",
+ "value",
+ "--boundary--",
+ ]
+ )
+ )
+ request = WSGIRequest(
+ {
+ "REQUEST_METHOD": "POST",
+ "CONTENT_TYPE": "multipart/form-data; boundary=boundary",
+ "CONTENT_LENGTH": len(payload),
+ "wsgi.input": payload,
+ }
+ )
+
+ # Access POST to trigger parsing.
+ request.POST
+
+ msg = (
+ "You cannot set the multipart parser class after the upload has been "
+ "processed."
+ )
+ with self.assertRaisesMessage(RuntimeError, msg):
+ request.multipart_parser_class = MultiPartParser
+
class HostValidationTests(SimpleTestCase):
poisoned_hosts = [
| diff --git a/django/http/request.py b/django/http/request.py
index c8adde768d23..573ae2b229d6 100644
--- a/django/http/request.py
+++ b/django/http/request.py
@@ -56,6 +56,7 @@ class HttpRequest:
# The encoding used in GET/POST dicts. None means use default setting.
_encoding = None
_upload_handlers = []
+ _multipart_parser_class = MultiPartParser
def __init__(self):
# WARNING: The `WSGIRequest` subclass doesn't call `super`.
@@ -364,6 +365,19 @@ def upload_handlers(self, upload_handlers):
)
self._upload_handlers = upload_handlers
+ @property
+ def multipart_parser_class(self):
+ return self._multipart_parser_class
+
+ @multipart_parser_class.setter
+ def multipart_parser_class(self, multipart_parser_class):
+ if hasattr(self, "_files"):
+ raise RuntimeError(
+ "You cannot set the multipart parser class after the upload has been "
+ "processed."
+ )
+ self._multipart_parser_class = multipart_parser_class
+
def parse_file_upload(self, META, post_data):
"""Return a tuple of (POST QueryDict, FILES MultiValueDict)."""
self.upload_handlers = ImmutableList(
@@ -373,7 +387,9 @@ def parse_file_upload(self, META, post_data):
"processed."
),
)
- parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)
+ parser = self.multipart_parser_class(
+ META, post_data, self.upload_handlers, self.encoding
+ )
return parser.parse()
@property
| 20,498 | https://github.com/django/django/pull/20498 | 2026-02-10 22:59:02 | 36,841 | https://github.com/django/django/pull/20498 | 117 | ["tests/requests_tests/tests.py"] | [] | 5.2 |
django__django-20338 | django/django | 7c54fee7760b1c61fd7f9cb7cc6a2965f4236137 | # Refs #36036 -- Added m dimension to GEOSCoordSeq.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number, or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36036
#### Branch description
As per the suggestion in https://github.com/django/django/pull/19013#issuecomment-2816751388 this adds M dimension support to `coordseq`.
#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [ ] I have checked the "Has patch" ticket flag in the Trac system.
- [ ] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/gis_tests/geos_tests/test_coordseq.py b/tests/gis_tests/geos_tests/test_coordseq.py
index b6f5136dd19c..37c421f5c3b8 100644
--- a/tests/gis_tests/geos_tests/test_coordseq.py
+++ b/tests/gis_tests/geos_tests/test_coordseq.py
@@ -1,4 +1,11 @@
-from django.contrib.gis.geos import LineString
+import math
+from unittest import skipIf
+from unittest.mock import patch
+
+from django.contrib.gis.geos import GEOSGeometry, LineString
+from django.contrib.gis.geos import prototypes as capi
+from django.contrib.gis.geos.coordseq import GEOSCoordSeq
+from django.contrib.gis.geos.libgeos import geos_version_tuple
from django.test import SimpleTestCase
@@ -13,3 +20,130 @@ def test_getitem(self):
with self.subTest(i):
with self.assertRaisesMessage(IndexError, msg):
coord_seq[i]
+
+ @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
+ def test_has_m(self):
+ geom = GEOSGeometry("POINT ZM (1 2 3 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ self.assertIs(coord_seq.hasm, True)
+
+ geom = GEOSGeometry("POINT Z (1 2 3)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ self.assertIs(coord_seq.hasm, False)
+
+ geom = GEOSGeometry("POINT M (1 2 3)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ self.assertIs(coord_seq.hasm, True)
+
+ @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
+ def test_get_set_m(self):
+ geom = GEOSGeometry("POINT ZM (1 2 3 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ self.assertEqual(coord_seq.tuple, (1, 2, 3, 4))
+ self.assertEqual(coord_seq.getM(0), 4)
+ coord_seq.setM(0, 10)
+ self.assertEqual(coord_seq.tuple, (1, 2, 3, 10))
+ self.assertEqual(coord_seq.getM(0), 10)
+
+ geom = GEOSGeometry("POINT M (1 2 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ self.assertEqual(coord_seq.tuple, (1, 2, 4))
+ self.assertEqual(coord_seq.getM(0), 4)
+ coord_seq.setM(0, 10)
+ self.assertEqual(coord_seq.tuple, (1, 2, 10))
+ self.assertEqual(coord_seq.getM(0), 10)
+ self.assertIs(math.isnan(coord_seq.getZ(0)), True)
+
+ @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
+ def test_setitem(self):
+ geom = GEOSGeometry("POINT ZM (1 2 3 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ coord_seq[0] = (10, 20, 30, 40)
+ self.assertEqual(coord_seq.tuple, (10, 20, 30, 40))
+
+ geom = GEOSGeometry("POINT M (1 2 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ coord_seq[0] = (10, 20, 40)
+ self.assertEqual(coord_seq.tuple, (10, 20, 40))
+ self.assertEqual(coord_seq.getM(0), 40)
+ self.assertIs(math.isnan(coord_seq.getZ(0)), True)
+
+ @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
+ def test_kml_m_dimension(self):
+ geom = GEOSGeometry("POINT ZM (1 2 3 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ self.assertEqual(coord_seq.kml, "<coordinates>1.0,2.0,3.0</coordinates>")
+ geom = GEOSGeometry("POINT M (1 2 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ self.assertEqual(coord_seq.kml, "<coordinates>1.0,2.0,0</coordinates>")
+
+ @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
+ def test_clone_m_dimension(self):
+ geom = GEOSGeometry("POINT ZM (1 2 3 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ clone = coord_seq.clone()
+ self.assertEqual(clone.tuple, (1, 2, 3, 4))
+ self.assertIs(clone.hasz, True)
+ self.assertIs(clone.hasm, True)
+
+ geom = GEOSGeometry("POINT M (1 2 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ clone = coord_seq.clone()
+ self.assertEqual(clone.tuple, (1, 2, 4))
+ self.assertIs(clone.hasz, False)
+ self.assertIs(clone.hasm, True)
+
+ @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
+ def test_dims(self):
+ geom = GEOSGeometry("POINT ZM (1 2 3 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ self.assertEqual(coord_seq.dims, 4)
+
+ geom = GEOSGeometry("POINT M (1 2 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ self.assertEqual(coord_seq.dims, 3)
+
+ geom = GEOSGeometry("POINT Z (1 2 3)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ self.assertEqual(coord_seq.dims, 3)
+
+ geom = GEOSGeometry("POINT (1 2)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ self.assertEqual(coord_seq.dims, 2)
+
+ def test_size(self):
+ geom = GEOSGeometry("POINT (1 2)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ self.assertEqual(coord_seq.size, 1)
+
+ geom = GEOSGeometry("POINT M (1 2 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)
+ self.assertEqual(coord_seq.size, 1)
+
+ @skipIf(geos_version_tuple() < (3, 14), "GEOS M support requires 3.14+")
+ def test_iscounterclockwise(self):
+ geom = GEOSGeometry("LINEARRING ZM (0 0 3 0, 1 0 0 2, 0 1 1 3, 0 0 3 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ self.assertEqual(
+ coord_seq.tuple,
+ (
+ (0.0, 0.0, 3.0, 0.0),
+ (1.0, 0.0, 0.0, 2.0),
+ (0.0, 1.0, 1.0, 3.0),
+ (0.0, 0.0, 3.0, 4.0),
+ ),
+ )
+ self.assertIs(coord_seq.is_counterclockwise, True)
+
+ def test_m_support_error(self):
+ geom = GEOSGeometry("POINT M (1 2 4)")
+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)
+ msg = "GEOSCoordSeq with an M dimension requires GEOS 3.14+."
+
+ # mock geos_version_tuple to be 3.13.13
+ with patch(
+ "django.contrib.gis.geos.coordseq.geos_version_tuple",
+ return_value=(3, 13, 13),
+ ):
+ with self.assertRaisesMessage(NotImplementedError, msg):
+ coord_seq.hasm
| diff --git a/django/contrib/gis/geos/coordseq.py b/django/contrib/gis/geos/coordseq.py
index dec3495d25c9..febeeebfa3bc 100644
--- a/django/contrib/gis/geos/coordseq.py
+++ b/django/contrib/gis/geos/coordseq.py
@@ -9,7 +9,7 @@
from django.contrib.gis.geos import prototypes as capi
from django.contrib.gis.geos.base import GEOSBase
from django.contrib.gis.geos.error import GEOSException
-from django.contrib.gis.geos.libgeos import CS_PTR
+from django.contrib.gis.geos.libgeos import CS_PTR, geos_version_tuple
from django.contrib.gis.shortcuts import numpy
@@ -20,6 +20,8 @@ class GEOSCoordSeq(GEOSBase):
def __init__(self, ptr, z=False):
"Initialize from a GEOS pointer."
+ # TODO when dropping support for GEOS 3.13 the z argument can be
+ # deprecated in favor of using the GEOS function GEOSCoordSeq_hasZ.
if not isinstance(ptr, CS_PTR):
raise TypeError("Coordinate sequence should initialize with a CS_PTR.")
self._ptr = ptr
@@ -58,6 +60,12 @@ def __setitem__(self, index, value):
if self.dims == 3 and self._z:
n_args = 3
point_setter = self._set_point_3d
+ elif self.dims == 3 and self.hasm:
+ n_args = 3
+ point_setter = self._set_point_3d_m
+ elif self.dims == 4 and self._z and self.hasm:
+ n_args = 4
+ point_setter = self._set_point_4d
else:
n_args = 2
point_setter = self._set_point_2d
@@ -74,7 +82,7 @@ def _checkindex(self, index):
def _checkdim(self, dim):
"Check the given dimension."
- if dim < 0 or dim > 2:
+ if dim < 0 or dim > 3:
raise GEOSException(f'Invalid ordinate dimension: "{dim:d}"')
def _get_x(self, index):
@@ -86,6 +94,9 @@ def _get_y(self, index):
def _get_z(self, index):
return capi.cs_getz(self.ptr, index, byref(c_double()))
+ def _get_m(self, index):
+ return capi.cs_getm(self.ptr, index, byref(c_double()))
+
def _set_x(self, index, value):
capi.cs_setx(self.ptr, index, value)
@@ -95,9 +106,18 @@ def _set_y(self, index, value):
def _set_z(self, index, value):
capi.cs_setz(self.ptr, index, value)
+ def _set_m(self, index, value):
+ capi.cs_setm(self.ptr, index, value)
+
@property
def _point_getter(self):
- return self._get_point_3d if self.dims == 3 and self._z else self._get_point_2d
+ if self.dims == 3 and self._z:
+ return self._get_point_3d
+ elif self.dims == 3 and self.hasm:
+ return self._get_point_3d_m
+ elif self.dims == 4 and self._z and self.hasm:
+ return self._get_point_4d
+ return self._get_point_2d
def _get_point_2d(self, index):
return (self._get_x(index), self._get_y(index))
@@ -105,6 +125,17 @@ def _get_point_2d(self, index):
def _get_point_3d(self, index):
return (self._get_x(index), self._get_y(index), self._get_z(index))
+ def _get_point_3d_m(self, index):
+ return (self._get_x(index), self._get_y(index), self._get_m(index))
+
+ def _get_point_4d(self, index):
+ return (
+ self._get_x(index),
+ self._get_y(index),
+ self._get_z(index),
+ self._get_m(index),
+ )
+
def _set_point_2d(self, index, value):
x, y = value
self._set_x(index, x)
@@ -116,6 +147,19 @@ def _set_point_3d(self, index, value):
self._set_y(index, y)
self._set_z(index, z)
+ def _set_point_3d_m(self, index, value):
+ x, y, m = value
+ self._set_x(index, x)
+ self._set_y(index, y)
+ self._set_m(index, m)
+
+ def _set_point_4d(self, index, value):
+ x, y, z, m = value
+ self._set_x(index, x)
+ self._set_y(index, y)
+ self._set_z(index, z)
+ self._set_m(index, m)
+
# #### Ordinate getting and setting routines ####
def getOrdinate(self, dimension, index):
"Return the value for the given dimension and index."
@@ -153,6 +197,14 @@ def setZ(self, index, value):
"Set Z with the value at the given index."
self.setOrdinate(2, index, value)
+ def getM(self, index):
+ "Get M with the value at the given index."
+ return self.getOrdinate(3, index)
+
+ def setM(self, index, value):
+ "Set M with the value at the given index."
+ self.setOrdinate(3, index, value)
+
# ### Dimensions ###
@property
def size(self):
@@ -172,6 +224,18 @@ def hasz(self):
"""
return self._z
+ @property
+ def hasm(self):
+ """
+ Return whether this coordinate sequence has M dimension.
+ """
+ if geos_version_tuple() >= (3, 14):
+ return capi.cs_hasm(self._ptr)
+ else:
+ raise NotImplementedError(
+ "GEOSCoordSeq with an M dimension requires GEOS 3.14+."
+ )
+
# ### Other Methods ###
def clone(self):
"Clone this coordinate sequence."
@@ -180,16 +244,13 @@ def clone(self):
@property
def kml(self):
"Return the KML representation for the coordinates."
- # Getting the substitution string depending on whether the coordinates
- # have a Z dimension.
if self.hasz:
- substr = "%s,%s,%s "
+ coords = [f"{coord[0]},{coord[1]},{coord[2]}" for coord in self]
else:
- substr = "%s,%s,0 "
- return (
- "<coordinates>%s</coordinates>"
- % "".join(substr % self[i] for i in range(len(self))).strip()
- )
+ coords = [f"{coord[0]},{coord[1]},0" for coord in self]
+
+ coordinate_string = " ".join(coords)
+ return f"<coordinates>{coordinate_string}</coordinates>"
@property
def tuple(self):
diff --git a/django/contrib/gis/geos/prototypes/__init__.py b/django/contrib/gis/geos/prototypes/__init__.py
index 6b0da37ee676..cac0b3fdf46b 100644
--- a/django/contrib/gis/geos/prototypes/__init__.py
+++ b/django/contrib/gis/geos/prototypes/__init__.py
@@ -8,12 +8,15 @@
create_cs,
cs_clone,
cs_getdims,
+ cs_getm,
cs_getordinate,
cs_getsize,
cs_getx,
cs_gety,
cs_getz,
+ cs_hasm,
cs_is_ccw,
+ cs_setm,
cs_setordinate,
cs_setx,
cs_sety,
diff --git a/django/contrib/gis/geos/prototypes/coordseq.py b/django/contrib/gis/geos/prototypes/coordseq.py
index cfc242c00dd1..eadaf8dfcf1e 100644
--- a/django/contrib/gis/geos/prototypes/coordseq.py
+++ b/django/contrib/gis/geos/prototypes/coordseq.py
@@ -1,7 +1,15 @@
from ctypes import POINTER, c_byte, c_double, c_int, c_uint
-from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, GEOSFuncFactory
-from django.contrib.gis.geos.prototypes.errcheck import GEOSException, last_arg_byref
+from django.contrib.gis.geos.libgeos import (
+ CS_PTR,
+ GEOM_PTR,
+ GEOSFuncFactory,
+)
+from django.contrib.gis.geos.prototypes.errcheck import (
+ GEOSException,
+ check_predicate,
+ last_arg_byref,
+)
# ## Error-checking routines specific to coordinate sequences. ##
@@ -67,6 +75,12 @@ def errcheck(result, func, cargs):
return result
+class CsUnaryPredicate(GEOSFuncFactory):
+ argtypes = [CS_PTR]
+ restype = c_byte
+ errcheck = staticmethod(check_predicate)
+
+
# ## Coordinate Sequence ctypes prototypes ##
# Coordinate Sequence constructors & cloning.
@@ -78,20 +92,25 @@ def errcheck(result, func, cargs):
cs_getordinate = CsOperation("GEOSCoordSeq_getOrdinate", ordinate=True, get=True)
cs_setordinate = CsOperation("GEOSCoordSeq_setOrdinate", ordinate=True)
-# For getting, x, y, z
+# For getting, x, y, z, m
cs_getx = CsOperation("GEOSCoordSeq_getX", get=True)
cs_gety = CsOperation("GEOSCoordSeq_getY", get=True)
cs_getz = CsOperation("GEOSCoordSeq_getZ", get=True)
+cs_getm = CsOperation("GEOSCoordSeq_getM", get=True)
-# For setting, x, y, z
+# For setting, x, y, z, m
cs_setx = CsOperation("GEOSCoordSeq_setX")
cs_sety = CsOperation("GEOSCoordSeq_setY")
cs_setz = CsOperation("GEOSCoordSeq_setZ")
+cs_setm = CsOperation("GEOSCoordSeq_setM")
# These routines return size & dimensions.
cs_getsize = CsInt("GEOSCoordSeq_getSize")
cs_getdims = CsInt("GEOSCoordSeq_getDimensions")
+# Unary Predicates
+cs_hasm = CsUnaryPredicate("GEOSCoordSeq_hasM")
+
cs_is_ccw = GEOSFuncFactory(
"GEOSCoordSeq_isCCW", restype=c_int, argtypes=[CS_PTR, POINTER(c_byte)]
)
| 20,338 | https://github.com/django/django/pull/20338 | 2026-02-09 13:44:08 | 36,036 | https://github.com/django/django/pull/20338 | 249 | ["tests/gis_tests/geos_tests/test_coordseq.py"] | [] | 5.2 |
django__django-19256 | django/django | 0d31ca98830542088299d2078402891d08cc3a65 | # Fixed #36246 -- Caught `GDALException` in `BaseGeometryWidget.deserialize`.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number, or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36246
#### Branch description
@sarahboyce Thank you for providing the test code for this ticket.
#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/gis_tests/test_geoforms.py b/tests/gis_tests/test_geoforms.py
index c351edaaad5a..b6068948f358 100644
--- a/tests/gis_tests/test_geoforms.py
+++ b/tests/gis_tests/test_geoforms.py
@@ -435,6 +435,19 @@ def test_get_context_attrs(self):
context = widget.get_context("geometry", None, None)
self.assertEqual(context["geom_type"], "Geometry")
+ def test_invalid_values(self):
+ bad_inputs = [
+ "POINT(5)",
+ "MULTI POLYGON(((0 0, 0 1, 1 1, 1 0, 0 0)))",
+ "BLAH(0 0, 1 1)",
+ '{"type": "FeatureCollection", "features": ['
+ '{"geometry": {"type": "Point", "coordinates": [508375, 148905]}, '
+ '"type": "Feature"}]}',
+ ]
+ for input in bad_inputs:
+ with self.subTest(input=input):
+ self.assertIsNone(BaseGeometryWidget().deserialize(input))
+
def test_subwidgets(self):
widget = forms.BaseGeometryWidget()
self.assertEqual(
| diff --git a/django/contrib/gis/forms/fields.py b/django/contrib/gis/forms/fields.py
index 1fd31530c135..bf6be709ed3a 100644
--- a/django/contrib/gis/forms/fields.py
+++ b/django/contrib/gis/forms/fields.py
@@ -1,5 +1,4 @@
from django import forms
-from django.contrib.gis.gdal import GDALException
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
@@ -41,10 +40,7 @@ def to_python(self, value):
if not isinstance(value, GEOSGeometry):
if hasattr(self.widget, "deserialize"):
- try:
- value = self.widget.deserialize(value)
- except GDALException:
- value = None
+ value = self.widget.deserialize(value)
else:
try:
value = GEOSGeometry(value)
diff --git a/django/contrib/gis/forms/widgets.py b/django/contrib/gis/forms/widgets.py
index 55895ae9f362..c091d3fcfc20 100644
--- a/django/contrib/gis/forms/widgets.py
+++ b/django/contrib/gis/forms/widgets.py
@@ -2,6 +2,7 @@
from django.conf import settings
from django.contrib.gis import gdal
+from django.contrib.gis.gdal import GDALException
from django.contrib.gis.geometry import json_regex
from django.contrib.gis.geos import GEOSException, GEOSGeometry
from django.forms.widgets import Widget
@@ -36,7 +37,7 @@ def serialize(self, value):
def deserialize(self, value):
try:
return GEOSGeometry(value)
- except (GEOSException, ValueError, TypeError) as err:
+ except (GEOSException, GDALException, ValueError, TypeError) as err:
logger.error("Error creating geometry from value '%s' (%s)", value, err)
return None
| 19,256 | https://github.com/django/django/pull/19256 | 2026-02-06 21:19:49 | 36,246 | https://github.com/django/django/pull/19256 | 22 | ["tests/gis_tests/test_geoforms.py"] | [] | 5.2 |
django__django-20458 | django/django | 6f8b2d1c6dfaab4b18a2b10bca4e54bdbabc10d8 | # Fixed #36644 -- Enabled empty order_by() to avoid pk ordering by first()/last().
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number, or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36644
#### Branch description
Enabled calling `order_by()` without arguments to disable implicit primary key ordering in `first()`/`last()`. When a queryset is explicitly marked as unordered via `order_by()`, `first()`/`last()` now respect this and avoid adding PK ordering. Also reset default_ordering in `_combinator_query()` so that `union().first()` can still add pk ordering.
Discussion: https://github.com/django/new-features/issues/71,
#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/get_earliest_or_latest/models.py b/tests/get_earliest_or_latest/models.py
index bbf2075d368a..91725865b194 100644
--- a/tests/get_earliest_or_latest/models.py
+++ b/tests/get_earliest_or_latest/models.py
@@ -21,6 +21,14 @@ class Comment(models.Model):
likes_count = models.PositiveIntegerField()
+class OrderedArticle(models.Model):
+ headline = models.CharField(max_length=100)
+ pub_date = models.DateField()
+
+ class Meta:
+ ordering = ["headline"]
+
+
# Ticket #23555 - model with an intentionally broken QuerySet.__iter__ method.
diff --git a/tests/get_earliest_or_latest/tests.py b/tests/get_earliest_or_latest/tests.py
index 49c803b73a0f..793fb12bb9c1 100644
--- a/tests/get_earliest_or_latest/tests.py
+++ b/tests/get_earliest_or_latest/tests.py
@@ -1,9 +1,10 @@
from datetime import datetime
+from unittest.mock import patch
from django.db.models import Avg
from django.test import TestCase
-from .models import Article, Comment, IndexErrorArticle, Person
+from .models import Article, Comment, IndexErrorArticle, OrderedArticle, Person
class EarliestOrLatestTests(TestCase):
@@ -265,3 +266,30 @@ def test_first_last_unordered_qs_aggregation_error(self):
qs.first()
with self.assertRaisesMessage(TypeError, msg % "last"):
qs.last()
+
+ def test_first_last_empty_order_by_has_no_pk_ordering(self):
+ Article.objects.create(
+ headline="Article 1",
+ pub_date=datetime(2006, 9, 10),
+ expire_date=datetime(2056, 9, 11),
+ )
+
+ qs = Article.objects.order_by()
+ with patch.object(type(qs), "order_by") as mock_order_by:
+ qs.first()
+ mock_order_by.assert_not_called()
+ qs.last()
+ mock_order_by.assert_not_called()
+
+ def test_first_last_empty_order_by_clears_default_ordering(self):
+ OrderedArticle.objects.create(
+ headline="Article 1",
+ pub_date=datetime(2006, 9, 10),
+ )
+
+ qs = OrderedArticle.objects.order_by()
+ with patch.object(type(qs), "order_by") as mock_order_by:
+ qs.first()
+ mock_order_by.assert_not_called()
+ qs.last()
+ mock_order_by.assert_not_called()
diff --git a/tests/queries/test_qs_combinators.py b/tests/queries/test_qs_combinators.py
index 2b4cd2bbbdd1..7e1e01bd4be4 100644
--- a/tests/queries/test_qs_combinators.py
+++ b/tests/queries/test_qs_combinators.py
@@ -418,6 +418,15 @@ def test_union_with_first(self):
qs2 = base_qs.filter(name="a2")
self.assertEqual(qs1.union(qs2).first(), a1)
+ @skipUnlessDBFeature("supports_slicing_ordering_in_compound")
+ def test_union_applies_default_ordering_afterward(self):
+ c = Tag.objects.create(name="C")
+ Tag.objects.create(name="B")
+ a = Tag.objects.create(name="A")
+ qs1 = Tag.objects.filter(name__in=["A", "B"])[:1]
+ qs2 = Tag.objects.filter(name__in=["C"])[:1]
+ self.assertSequenceEqual(qs1.union(qs2), [a, c])
+
def test_union_multiple_models_with_values_list_and_order(self):
reserved_name = ReservedName.objects.create(name="rn1", order=0)
qs1 = Celebrity.objects.all()
| diff --git a/django/db/models/query.py b/django/db/models/query.py
index 5649a83428f7..76d0f449a67e 100644
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -1158,7 +1158,7 @@ async def alatest(self, *fields):
def first(self):
"""Return the first object of a query or None if no match is found."""
- if self.ordered:
+ if self.ordered or not self.query.default_ordering:
queryset = self
else:
self._check_ordering_first_last_queryset_aggregation(method="first")
@@ -1171,7 +1171,7 @@ async def afirst(self):
def last(self):
"""Return the last object of a query or None if no match is found."""
- if self.ordered:
+ if self.ordered or not self.query.default_ordering:
queryset = self.reverse()
else:
self._check_ordering_first_last_queryset_aggregation(method="last")
@@ -1679,6 +1679,7 @@ def _combinator_query(self, combinator, *other_qs, all=False):
clone = self._chain()
# Clear limits and ordering so they can be reapplied
clone.query.clear_ordering(force=True)
+ clone.query.default_ordering = True
clone.query.clear_limits()
clone.query.combined_queries = (self.query, *(qs.query for qs in other_qs))
clone.query.combinator = combinator
| 20,458 | https://github.com/django/django/pull/20458 | 2026-02-06 20:45:45 | 36,644 | https://github.com/django/django/pull/20458 | 52 | ["tests/get_earliest_or_latest/models.py", "tests/get_earliest_or_latest/tests.py", "tests/queries/test_qs_combinators.py"] | [] | 5.2 |
django__django-20346 | django/django | 5d5f95da40afbaede9f483de891c14f5da0e8218 | # Fixed #36233 -- Avoided quantizing integers stored in DecimalField on SQLite.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number, or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36233
#### Branch description
Fixed a crash in DecimalField when using SQLite with integers exceeding 15 digits (e.g., 16-digit IDs).
The Issue: SQLite lacks a native decimal type. When retrieving large integers (e.g., 9999999999999999), the default converter treats them as floating-point numbers. Since IEEE 754 floats only support ~15 significant digits, precision is lost (e.g., becoming 10000000000000000). When Django attempts to quantize() this inaccurate value against the field's context, it raises decimal.InvalidOperation.
The Fix: Updated django.db.backends.sqlite3.operations.py to check if the underlying SQLite driver returned a native int. If so, the value is converted directly to Decimal, bypassing the lossy float conversion entirely.
Verification: Added a regression test test_sqlite_integer_precision_bypass in model_fields/test_decimalfield.py to ensure 16-digit integers are stored and retrieved correctly without crashing.
#### Checklist
- [ ] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [ ] I have checked the "Has patch" ticket flag in the Trac system.
- [ ] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/model_fields/models.py b/tests/model_fields/models.py
index cdf3c00080c9..1d8a447dee8b 100644
--- a/tests/model_fields/models.py
+++ b/tests/model_fields/models.py
@@ -102,6 +102,7 @@ def get_choices():
class BigD(models.Model):
d = models.DecimalField(max_digits=32, decimal_places=30)
+ large_int = models.DecimalField(max_digits=16, decimal_places=0, null=True)
class FloatModel(models.Model):
diff --git a/tests/model_fields/test_decimalfield.py b/tests/model_fields/test_decimalfield.py
index 17f59674e872..bab9a39c19d7 100644
--- a/tests/model_fields/test_decimalfield.py
+++ b/tests/model_fields/test_decimalfield.py
@@ -5,6 +5,7 @@
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import connection, models
+from django.db.models import Max
from django.test import TestCase
from .models import BigD, Foo
@@ -140,3 +141,20 @@ def test_roundtrip_with_trailing_zeros(self):
obj = Foo.objects.create(a="bar", d=Decimal("8.320"))
obj.refresh_from_db()
self.assertEqual(obj.d.compare_total(Decimal("8.320")), Decimal("0"))
+
+ def test_large_integer_precision(self):
+ large_int_val = Decimal("9999999999999999")
+ obj = BigD.objects.create(large_int=large_int_val, d=Decimal("0"))
+ obj.refresh_from_db()
+ self.assertEqual(obj.large_int, large_int_val)
+
+ def test_large_integer_precision_aggregation(self):
+ large_int_val = Decimal("9999999999999999")
+ BigD.objects.create(large_int=large_int_val, d=Decimal("0"))
+ result = BigD.objects.aggregate(max_val=Max("large_int"))
+ self.assertEqual(result["max_val"], large_int_val)
+
+ def test_roundtrip_integer_with_trailing_zeros(self):
+ obj = Foo.objects.create(a="bar", d=Decimal("8"))
+ obj.refresh_from_db()
+ self.assertEqual(obj.d.compare_total(Decimal("8.000")), Decimal("0"))
| diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py
index 23c17054d260..18ff204ae37b 100644
--- a/django/db/backends/sqlite3/operations.py
+++ b/django/db/backends/sqlite3/operations.py
@@ -300,10 +300,15 @@ def convert_timefield_value(self, value, expression, connection):
value = parse_time(value)
return value
+ @staticmethod
+ def _create_decimal(value):
+ if isinstance(value, (int, str)):
+ return decimal.Decimal(value)
+ return decimal.Context(prec=15).create_decimal_from_float(value)
+
def get_decimalfield_converter(self, expression):
# SQLite stores only 15 significant digits. Digits coming from
# float inaccuracy must be removed.
- create_decimal = decimal.Context(prec=15).create_decimal_from_float
if isinstance(expression, Col):
quantize_value = decimal.Decimal(1).scaleb(
-expression.output_field.decimal_places
@@ -311,7 +316,7 @@ def get_decimalfield_converter(self, expression):
def converter(value, expression, connection):
if value is not None:
- return create_decimal(value).quantize(
+ return self._create_decimal(value).quantize(
quantize_value, context=expression.output_field.context
)
@@ -319,7 +324,7 @@ def converter(value, expression, connection):
def converter(value, expression, connection):
if value is not None:
- return create_decimal(value)
+ return self._create_decimal(value)
return converter
| 20,346 | https://github.com/django/django/pull/20346 | 2026-01-28 22:04:39 | 36,233 | https://github.com/django/django/pull/20346 | 30 | ["tests/model_fields/models.py", "tests/model_fields/test_decimalfield.py"] | [] | 5.2 |
django__django-20580 | django/django | d725f6856d7488ba2a397dfe47dd851420188159 | # Fixed #36879 -- Identified Django client in Redis client metadata.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36879
#### Branch description
Redis documentation recommends that clients identify themselves via connection metadata to help operators monitor, debug, and reason about production systems (for example using CLIENT SETINFO / CLIENT INFO).
This patch allows Django to set its own driver info for redis-py connections, which will be a different `lib-name`:
`redis-py` -> `redis-py(django_v{django_version})`.
This is achieved by subclassing the redis-py `Connection` class to include Django's custom `lib_name` or `driver_info`.
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [x] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/cache/tests.py b/tests/cache/tests.py
index db5df2070124..b36e3a6a0602 100644
--- a/tests/cache/tests.py
+++ b/tests/cache/tests.py
@@ -15,6 +15,7 @@
from pathlib import Path
from unittest import mock, skipIf
+import django
from django.conf import settings
from django.core import management, signals
from django.core.cache import (
@@ -1986,6 +1987,24 @@ def test_redis_pool_options(self):
self.assertEqual(pool.connection_kwargs["socket_timeout"], 0.1)
self.assertIs(pool.connection_kwargs["retry_on_timeout"], True)
+ def test_client_driver_info(self):
+ client_info = cache._cache.get_client().client_info()
+ if {"lib-name", "lib-ver"}.issubset(client_info):
+ version = django.get_version()
+ if hasattr(self.lib, "DriverInfo"):
+ info = self._lib.DriverInfo().add_upstream_driver("django", version)
+ correct_lib_name = info.formatted_name
+ else:
+ correct_lib_name = f"redis-py(django_v{version})"
+ # Relax the assertion to allow date variance in editable installs.
+ truncated_lib_name = correct_lib_name.rsplit(".dev", maxsplit=1)[0]
+ self.assertIn(truncated_lib_name, client_info["lib-name"])
+ self.assertEqual(client_info["lib-ver"], self.lib.__version__)
+ else:
+ # Redis versions below 7.2 lack CLIENT SETINFO.
+ self.assertNotIn("lib-ver", client_info)
+ self.assertNotIn("lib-name", client_info)
+
class FileBasedCachePathLibTests(FileBasedCacheTests):
def mkdtemp(self):
| diff --git a/django/core/cache/backends/redis.py b/django/core/cache/backends/redis.py
index bbf070a37573..727ea51f84d6 100644
--- a/django/core/cache/backends/redis.py
+++ b/django/core/cache/backends/redis.py
@@ -4,6 +4,7 @@
import random
import re
+import django
from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache
from django.utils.functional import cached_property
from django.utils.module_loading import import_string
@@ -59,7 +60,19 @@ def __init__(
parser_class = import_string(parser_class)
parser_class = parser_class or self._lib.connection.DefaultParser
- self._pool_options = {"parser_class": parser_class, **options}
+ version = django.get_version()
+ if hasattr(self._lib, "DriverInfo"):
+ driver_info = self._lib.DriverInfo().add_upstream_driver("django", version)
+ driver_info_options = {"driver_info": driver_info}
+ else:
+ # DriverInfo is not available in this redis-py version.
+ driver_info_options = {"lib_name": f"redis-py(django_v{version})"}
+
+ self._pool_options = {
+ "parser_class": parser_class,
+ **driver_info_options,
+ **options,
+ }
def _get_connection_pool_index(self, write):
# Write to the first server. Read from other servers if there are more,
| 20,580 | https://github.com/django/django/pull/20580 | 2026-02-03 11:40:29 | 36,879 | https://github.com/django/django/pull/20580 | 35 | ["tests/cache/tests.py"] | [] | 5.2 |
django__django-20614 | django/django | 93dfb16e96797583a6f45eeb918e78c7f2817318 | # Fixed #36893 -- Serialized elidable kwarg for RunSQL and RunPython operations.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36893
#### Branch description
Fixed an issue where `elidable=True` was not being serialized for Run-SQL and Run-Python operations which caused these operations to lose their elidable status when written to a migration file (e.g., during squashing), reverting to the default `False`.
-Updated deconstruct() for both Run-SQL and Run-Python to correctly include 'elidable' keyword when set to 'True'
-Regression Tests are test_run_sql_elidable , test_run_python_elidable and test_operations.py
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [ ] **No AI tools were used** in preparing this PR.
- [x] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
Assistance provided by Google DeepMind's Antigravity agent. I used the agent to understand the issue, implement the fix, and add regression tests.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [ ] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py
index ec4b772c13ed..235804adab60 100644
--- a/tests/migrations/test_operations.py
+++ b/tests/migrations/test_operations.py
@@ -5536,6 +5536,10 @@ def test_run_sql(self):
elidable_operation = migrations.RunSQL("SELECT 1 FROM void;", elidable=True)
self.assertEqual(elidable_operation.reduce(operation, []), [operation])
+ # Test elidable deconstruction
+ definition = elidable_operation.deconstruct()
+ self.assertIs(definition[2]["elidable"], True)
+
def test_run_sql_params(self):
"""
#23426 - RunSQL should accept parameters.
@@ -5789,6 +5793,10 @@ def create_shetlandponies(models, schema_editor):
elidable_operation = migrations.RunPython(inner_method, elidable=True)
self.assertEqual(elidable_operation.reduce(operation, []), [operation])
+ # Test elidable deconstruction
+ definition = elidable_operation.deconstruct()
+ self.assertIs(definition[2]["elidable"], True)
+
def test_run_python_invalid_reverse_code(self):
msg = "RunPython must be supplied with callable arguments"
with self.assertRaisesMessage(ValueError, msg):
| diff --git a/django/db/migrations/operations/special.py b/django/db/migrations/operations/special.py
index 07000233253c..311271483ea9 100644
--- a/django/db/migrations/operations/special.py
+++ b/django/db/migrations/operations/special.py
@@ -93,6 +93,8 @@ def deconstruct(self):
kwargs["state_operations"] = self.state_operations
if self.hints:
kwargs["hints"] = self.hints
+ if self.elidable:
+ kwargs["elidable"] = self.elidable
return (self.__class__.__qualname__, [], kwargs)
@property
@@ -173,6 +175,8 @@ def deconstruct(self):
kwargs["atomic"] = self.atomic
if self.hints:
kwargs["hints"] = self.hints
+ if self.elidable:
+ kwargs["elidable"] = self.elidable
return (self.__class__.__qualname__, [], kwargs)
@property
| 20,614 | https://github.com/django/django/pull/20614 | 2026-02-03 02:05:44 | 36,893 | https://github.com/django/django/pull/20614 | 12 | ["tests/migrations/test_operations.py"] | [] | 5.2 |
django__django-20538 | django/django | f87c2055b45356378a7c2a020eb872352d20f85e | # Fixed #36865 -- Removed casting from exact lookups in admin searches.
Fixes https://code.djangoproject.com/ticket/36865
## Description
This PR fixes a performance regression introduced in PR #17885.
The `Cast` to `CharField` for non-string field exact lookups prevents database index usage on primary key fields, generating SQL like:
```sql
WHERE ("table"."id")::varchar = '123'
```
This cannot use the primary key index and causes full table scans, resulting in timeouts on large tables (reported in [ticket #26001 comment 24](https://code.djangoproject.com/ticket/26001#comment:24)), and discovered in a project I work on at https://github.com/freelawproject/courtlistener/issues/6790.
## Solution
Drop the casting approach introduced in #17885, and replace it with field validation that uses `to_python` on the results of `smart_split` to ensure that we only apply field-term pairs that make sense. For example:
- searching a PrimaryKey field for "foo" --> Nope!
- searching a TextField for "foo" --> Yes!
- searching a TextField for "123" --> Close enough. Yes!
And so forth.
This should ensure DB indexes are used and that we don't send nonsensical queries in the first place.
## Trac tickets
Introducing issue: https://code.djangoproject.com/ticket/26001
Solving it: https://code.djangoproject.com/ticket/36865 | diff --git a/tests/admin_changelist/models.py b/tests/admin_changelist/models.py
index a84c27a06662..0b594300d2a3 100644
--- a/tests/admin_changelist/models.py
+++ b/tests/admin_changelist/models.py
@@ -140,3 +140,10 @@ class CharPK(models.Model):
class ProxyUser(User):
class Meta:
proxy = True
+
+
+class MixedFieldsModel(models.Model):
+ """Model with multiple field types for testing search validation."""
+
+ int_field = models.IntegerField(null=True, blank=True)
+ json_field = models.JSONField(null=True, blank=True)
diff --git a/tests/admin_changelist/tests.py b/tests/admin_changelist/tests.py
index 319d6259f6a9..e0772a3e6d4a 100644
--- a/tests/admin_changelist/tests.py
+++ b/tests/admin_changelist/tests.py
@@ -66,6 +66,7 @@
Group,
Invitation,
Membership,
+ MixedFieldsModel,
Musician,
OrderedObject,
Parent,
@@ -856,6 +857,89 @@ def test_custom_lookup_with_pk_shortcut(self):
cl = m.get_changelist_instance(request)
self.assertCountEqual(cl.queryset, [abcd])
+ def test_exact_lookup_with_invalid_value(self):
+ Child.objects.create(name="Test", age=10)
+ m = admin.ModelAdmin(Child, custom_site)
+ m.search_fields = ["pk__exact"]
+
+ request = self.factory.get("/", data={SEARCH_VAR: "foo"})
+ request.user = self.superuser
+
+ # Invalid values are gracefully ignored.
+ cl = m.get_changelist_instance(request)
+ self.assertCountEqual(cl.queryset, [])
+
+ def test_exact_lookup_mixed_terms(self):
+ """
+ Multi-term search validates each term independently.
+
+ For 'foo 123' with search_fields=['name__icontains', 'age__exact']:
+ - 'foo': age lookup skipped (invalid), name lookup used
+ - '123': both lookups used (valid for age)
+ No Cast should be used; invalid lookups are simply skipped.
+ """
+ child = Child.objects.create(name="foo123", age=123)
+ Child.objects.create(name="other", age=456)
+ m = admin.ModelAdmin(Child, custom_site)
+ m.search_fields = ["name__icontains", "age__exact"]
+
+ request = self.factory.get("/", data={SEARCH_VAR: "foo 123"})
+ request.user = self.superuser
+
+ # One result matching on foo and 123.
+ cl = m.get_changelist_instance(request)
+ self.assertCountEqual(cl.queryset, [child])
+
+ # "xyz" - invalid for age (skipped), no match for name either.
+ request = self.factory.get("/", data={SEARCH_VAR: "xyz"})
+ request.user = self.superuser
+ cl = m.get_changelist_instance(request)
+ self.assertCountEqual(cl.queryset, [])
+
+ def test_exact_lookup_with_more_lenient_formfield(self):
+ """
+ Exact lookups on BooleanField use formfield().to_python() for lenient
+ parsing. Using model field's to_python() would reject 'false' whereas
+ the form field accepts it.
+ """
+ obj = UnorderedObject.objects.create(bool=False)
+ UnorderedObject.objects.create(bool=True)
+ m = admin.ModelAdmin(UnorderedObject, custom_site)
+ m.search_fields = ["bool__exact"]
+
+ # 'false' is accepted by form field but rejected by model field.
+ request = self.factory.get("/", data={SEARCH_VAR: "false"})
+ request.user = self.superuser
+
+ cl = m.get_changelist_instance(request)
+ self.assertCountEqual(cl.queryset, [obj])
+
+ def test_exact_lookup_validates_each_field_independently(self):
+ """
+ Each field validates the search term independently without leaking
+ converted values between fields.
+
+ "3." is valid for IntegerField (converts to 3) but invalid for
+ JSONField. The converted value must not leak to the JSONField check.
+ """
+ # obj_int has int_field=3, should match "3." via IntegerField.
+ obj_int = MixedFieldsModel.objects.create(
+ int_field=3, json_field={"key": "value"}
+ )
+ # obj_json has json_field=3, should NOT match "3." because "3." is
+ # invalid JSON.
+ MixedFieldsModel.objects.create(int_field=99, json_field=3)
+ m = admin.ModelAdmin(MixedFieldsModel, custom_site)
+ m.search_fields = ["int_field__exact", "json_field__exact"]
+
+ # "3." is valid for int (becomes 3) but invalid JSON.
+ # Only obj_int should match via int_field.
+ request = self.factory.get("/", data={SEARCH_VAR: "3."})
+ request.user = self.superuser
+
+ cl = m.get_changelist_instance(request)
+ self.assertCountEqual(cl.queryset, [obj_int])
+
def test_search_with_exact_lookup_for_non_string_field(self):
child = Child.objects.create(name="Asher", age=11)
model_admin = ChildAdmin(Child, custom_site)
| diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index 69b7031e8260..9c787d232912 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -41,7 +41,6 @@
from django.core.paginator import Paginator
from django.db import models, router, transaction
from django.db.models.constants import LOOKUP_SEP
-from django.db.models.functions import Cast
from django.forms.formsets import DELETION_FIELD_NAME, all_valid
from django.forms.models import (
BaseInlineFormSet,
@@ -1137,6 +1136,12 @@ def get_search_results(self, request, queryset, search_term):
# Apply keyword searches.
def construct_search(field_name):
+ """
+ Return a tuple of (lookup, field_to_validate).
+
+ field_to_validate is set for non-text exact lookups so that
+ invalid search terms can be skipped (preserving index usage).
+ """
if field_name.startswith("^"):
return "%s__istartswith" % field_name.removeprefix("^"), None
elif field_name.startswith("="):
@@ -1148,7 +1153,7 @@ def construct_search(field_name):
lookup_fields = field_name.split(LOOKUP_SEP)
# Go through the fields, following all relations.
prev_field = None
- for i, path_part in enumerate(lookup_fields):
+ for path_part in lookup_fields:
if path_part == "pk":
path_part = opts.pk.name
try:
@@ -1159,15 +1164,9 @@ def construct_search(field_name):
if path_part == "exact" and not isinstance(
prev_field, (models.CharField, models.TextField)
):
- field_name_without_exact = "__".join(lookup_fields[:i])
- alias = Cast(
- field_name_without_exact,
- output_field=models.CharField(),
- )
- alias_name = "_".join(lookup_fields[:i])
- return f"{alias_name}_str", alias
- else:
- return field_name, None
+ # Use prev_field to validate the search term.
+ return field_name, prev_field
+ return field_name, None
else:
prev_field = field
if hasattr(field, "path_infos"):
@@ -1179,30 +1178,42 @@ def construct_search(field_name):
may_have_duplicates = False
search_fields = self.get_search_fields(request)
if search_fields and search_term:
- str_aliases = {}
orm_lookups = []
for field in search_fields:
- lookup, str_alias = construct_search(str(field))
- orm_lookups.append(lookup)
- if str_alias:
- str_aliases[lookup] = str_alias
-
- if str_aliases:
- queryset = queryset.alias(**str_aliases)
+ orm_lookups.append(construct_search(str(field)))
term_queries = []
for bit in smart_split(search_term):
if bit.startswith(('"', "'")) and bit[0] == bit[-1]:
bit = unescape_string_literal(bit)
- or_queries = models.Q.create(
- [(orm_lookup, bit) for orm_lookup in orm_lookups],
- connector=models.Q.OR,
- )
- term_queries.append(or_queries)
- queryset = queryset.filter(models.Q.create(term_queries))
+ # Build term lookups, skipping values invalid for their field.
+ bit_lookups = []
+ for orm_lookup, validate_field in orm_lookups:
+ if validate_field is not None:
+ formfield = validate_field.formfield()
+ try:
+ if formfield is not None:
+ value = formfield.to_python(bit)
+ else:
+ # Fields like AutoField lack a form field.
+ value = validate_field.to_python(bit)
+ except ValidationError:
+ # Skip this lookup for invalid values.
+ continue
+ else:
+ value = bit
+ bit_lookups.append((orm_lookup, value))
+ if bit_lookups:
+ or_queries = models.Q.create(bit_lookups, connector=models.Q.OR)
+ term_queries.append(or_queries)
+ else:
+ # No valid lookups: add a filter that returns nothing.
+ term_queries.append(models.Q(pk__in=[]))
+ if term_queries:
+ queryset = queryset.filter(models.Q.create(term_queries))
may_have_duplicates |= any(
lookup_spawns_duplicates(self.opts, search_spec)
- for search_spec in orm_lookups
+ for search_spec, _ in orm_lookups
)
return queryset, may_have_duplicates
| 20,538 | https://github.com/django/django/pull/20538 | 2026-01-30 16:45:39 | 36,865 | https://github.com/django/django/pull/20538 | 154 | ["tests/admin_changelist/models.py", "tests/admin_changelist/tests.py"] | [] | 5.2 |
django__django-20586 | django/django | 2831eaed797627e6e6410b06f74dadeb63316e09 | # Fixed #36847 -- Ensured auto_now_add fields are set before FileField.upload_to is called.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36847
#### Branch description
In Django 5.2 and earlier, an `auto_now_add=True` `DateTimeField` could be accessed inside a `FileField`’s `upload_to` callable, because the field was populated with the current timestamp during insertion.
This is a regression introduced in 94680437a45a71c70ca8bd2e68b72aa1e2eff337 where the insert path called `field.pre_save()` with `add=False` instead of `add=True`.
This fix restores the correct behavior by changing the argument back to `add=True`.
(Used AI to help create the test coverage for the fix. I have verified that it's working correctly.)
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [ ] **No AI tools were used** in preparing this PR.
- [x] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [x] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/model_fields/models.py b/tests/model_fields/models.py
index 1d8a447dee8b..a594b89adb0d 100644
--- a/tests/model_fields/models.py
+++ b/tests/model_fields/models.py
@@ -262,10 +262,20 @@ class DataModel(models.Model):
# FileField
+def upload_to_with_date(instance, filename):
+ return f"{instance.created_at.year}/{filename}"
+
+
class Document(models.Model):
myfile = models.FileField(storage=temp_storage, upload_to="unused", unique=True)
+# See ticket #36847.
+class DocumentWithTimestamp(models.Model):
+ created_at = models.DateTimeField(auto_now_add=True)
+ myfile = models.FileField(storage=temp_storage, upload_to=upload_to_with_date)
+
+
###############################################################################
# ImageField
diff --git a/tests/model_fields/test_filefield.py b/tests/model_fields/test_filefield.py
index 57cc7365da15..fbf5c837ac57 100644
--- a/tests/model_fields/test_filefield.py
+++ b/tests/model_fields/test_filefield.py
@@ -13,7 +13,7 @@
from django.test import TestCase, override_settings
from django.test.utils import isolate_apps
-from .models import Document
+from .models import Document, DocumentWithTimestamp
class FileFieldTests(TestCase):
@@ -209,3 +209,9 @@ class MyDocument(AbstractMyDocument):
document = MyDocument(myfile="test_file.py")
self.assertEqual(document.myfile.field.model, MyDocument)
+
+ def test_upload_to_callable_sees_auto_now_add_field_value(self):
+ d = DocumentWithTimestamp(myfile=ContentFile(b"content", name="foo"))
+ d.save()
+ self.assertIsNotNone(d.created_at)
+ self.assertIs(d.myfile.name.startswith(f"{d.created_at.year}/foo"), True)
| diff --git a/django/db/models/base.py b/django/db/models/base.py
index ad3f0c5e23a1..d53da600d792 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -1175,7 +1175,9 @@ def _save_table(
].features.can_return_columns_from_insert
for field in insert_fields:
value = (
- getattr(self, field.attname) if raw else field.pre_save(self, False)
+ getattr(self, field.attname)
+ if raw
+ else field.pre_save(self, add=True)
)
if hasattr(value, "resolve_expression"):
if field not in returning_fields:
| 20,586 | https://github.com/django/django/pull/20586 | 2026-01-29 13:11:33 | 36,847 | https://github.com/django/django/pull/20586 | 25 | ["tests/model_fields/models.py", "tests/model_fields/test_filefield.py"] | [] | 5.2 |
django__django-20574 | django/django | 5d5f95da40afbaede9f483de891c14f5da0e8218 | # Fixed #36878 -- Unified data type for *_together options in ModelState.
Ever since the beginning of Django's migration framework, there's been a bit of an inconsistency on how index_together and unique_together values have been stored on the ModelState[^1].
It's only really obvious, when looking at the current code for `from_model()`[^2] and the `rename_field()` state alteration code[^3].
The problem in the autodetector's detection of the `*_together` options as raised in the ticket, reinforces the inconsistency[^4]: the old value is being normalized to a set of tuples, whereas the new value is taken as-is.
Why this hasn't been caught before, is likely to the fact, that we never really look at a `to_state` that comes from migration operations in the autodetector. Instead, in both usages in Django[^5], [^6] the `to_state` is a `ProjectState.from_apps()`. And that state is consistently using sets of tuples and not lists of lists.
[^1]: https://github.com/django/django/commit/67dcea711e92025d0e8676b869b7ef15dbc6db73#diff-5dd147e9e978e645313dd99eab3a7bab1f1cb0a53e256843adb68aeed71e61dcR85-R87
[^2]: https://github.com/django/django/blob/b1ffa9a9d78b0c2c5ad6ed5a1d84e380d5cfd010/django/db/migrations/state.py#L842
[^3]: https://github.com/django/django/blob/b1ffa9a9d78b0c2c5ad6ed5a1d84e380d5cfd010/django/db/migrations/state.py#L340-L345
[^4]: https://github.com/django/django/blob/b1ffa9a9d78b0c2c5ad6ed5a1d84e380d5cfd010/django/db/migrations/autodetector.py#L1757-L1771
[^5]: https://github.com/django/django/blob/2351c1b12cc9cf82d642f769c774bc3ea0cc4006/django/core/management/commands/makemigrations.py#L215-L219
[^6]: https://github.com/django/django/blob/2351c1b12cc9cf82d642f769c774bc3ea0cc4006/django/core/management/commands/migrate.py#L329-L332
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number. -->
<!-- Or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36878
#### Branch description
Provide a concise overview of the issue or rationale behind the proposed changes.
#### AI Assistance Disclosure (REQUIRED)
<!-- Please select exactly ONE of the following: -->
- [x] **No AI tools were used** in preparing this PR.
- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.
#### Checklist
- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).
- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/migrations/test_autodetector.py b/tests/migrations/test_autodetector.py
index e33362185555..7a66e500cb89 100644
--- a/tests/migrations/test_autodetector.py
+++ b/tests/migrations/test_autodetector.py
@@ -5590,6 +5590,51 @@ def test_remove_composite_pk(self):
preserve_default=True,
)
+ def test_does_not_crash_after_rename_on_unique_together(self):
+ fields = ("first", "second")
+ before = self.make_project_state(
+ [
+ ModelState(
+ "app",
+ "Foo",
+ [
+ ("id", models.AutoField(primary_key=True)),
+ ("first", models.IntegerField()),
+ ("second", models.IntegerField()),
+ ],
+ options={"unique_together": {fields}},
+ ),
+ ]
+ )
+ after = before.clone()
+ after.rename_field("app", "foo", "first", "first_renamed")
+
+ changes = MigrationAutodetector(
+ before, after, MigrationQuestioner({"ask_rename": True})
+ )._detect_changes()
+
+ self.assertNumberMigrations(changes, "app", 1)
+ self.assertOperationTypes(
+ changes, "app", 0, ["RenameField", "AlterUniqueTogether"]
+ )
+ self.assertOperationAttributes(
+ changes,
+ "app",
+ 0,
+ 0,
+ model_name="foo",
+ old_name="first",
+ new_name="first_renamed",
+ )
+ self.assertOperationAttributes(
+ changes,
+ "app",
+ 0,
+ 1,
+ name="foo",
+ unique_together={("first_renamed", "second")},
+ )
+
class MigrationSuggestNameTests(SimpleTestCase):
def test_no_operations(self):
diff --git a/tests/migrations/test_base.py b/tests/migrations/test_base.py
index 24ae59ca1b9a..31967f9ed49c 100644
--- a/tests/migrations/test_base.py
+++ b/tests/migrations/test_base.py
@@ -290,14 +290,13 @@ def set_up_test_model(
):
"""Creates a test model state and database table."""
# Make the "current" state.
- model_options = {
- "swappable": "TEST_SWAP_MODEL",
- "unique_together": [["pink", "weight"]] if unique_together else [],
- }
+ model_options = {"swappable": "TEST_SWAP_MODEL"}
if options:
model_options["permissions"] = [("can_groom", "Can groom")]
if db_table:
model_options["db_table"] = db_table
+ if unique_together:
+ model_options["unique_together"] = {("pink", "weight")}
operations = [
migrations.CreateModel(
"Pony",
diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py
index 00c76538e0fb..e859b62a101b 100644
--- a/tests/migrations/test_operations.py
+++ b/tests/migrations/test_operations.py
@@ -3336,11 +3336,11 @@ def test_rename_field_unique_together(self):
# unique_together has the renamed column.
self.assertIn(
"blue",
- new_state.models["test_rnflut", "pony"].options["unique_together"][0],
+ list(new_state.models["test_rnflut", "pony"].options["unique_together"])[0],
)
self.assertNotIn(
"pink",
- new_state.models["test_rnflut", "pony"].options["unique_together"][0],
+ list(new_state.models["test_rnflut", "pony"].options["unique_together"])[0],
)
# Rename field.
self.assertColumnExists("test_rnflut_pony", "pink")
@@ -3377,7 +3377,7 @@ def test_rename_field_index_together(self):
("weight", models.FloatField()),
],
options={
- "index_together": [("weight", "pink")],
+ "index_together": {("weight", "pink")},
},
),
]
@@ -3390,10 +3390,12 @@ def test_rename_field_index_together(self):
self.assertNotIn("pink", new_state.models["test_rnflit", "pony"].fields)
# index_together has the renamed column.
self.assertIn(
- "blue", new_state.models["test_rnflit", "pony"].options["index_together"][0]
+ "blue",
+ list(new_state.models["test_rnflit", "pony"].options["index_together"])[0],
)
self.assertNotIn(
- "pink", new_state.models["test_rnflit", "pony"].options["index_together"][0]
+ "pink",
+ list(new_state.models["test_rnflit", "pony"].options["index_together"])[0],
)
# Rename field.
@@ -3952,7 +3954,7 @@ def test_rename_index_unnamed_index(self):
("weight", models.FloatField()),
],
options={
- "index_together": [("weight", "pink")],
+ "index_together": {("weight", "pink")},
},
),
]
@@ -3972,6 +3974,11 @@ def test_rename_index_unnamed_index(self):
)
new_state = project_state.clone()
operation.state_forwards(app_label, new_state)
+ # Ensure the model state has the correct type for the index_together
+ # option.
+ self.assertIsInstance(
+ new_state.models[app_label, "pony"].options["index_together"], set
+ )
# Rename index.
with connection.schema_editor() as editor:
operation.database_forwards(app_label, editor, project_state, new_state)
@@ -4079,7 +4086,7 @@ def test_rename_index_state_forwards_unnamed_index(self):
("weight", models.FloatField()),
],
options={
- "index_together": [("weight", "pink")],
+ "index_together": {("weight", "pink")},
},
),
]
| diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py
index 802aeb0b5e66..9e9cc58fae13 100644
--- a/django/db/migrations/state.py
+++ b/django/db/migrations/state.py
@@ -192,9 +192,10 @@ def alter_model_options(self, app_label, model_name, options, option_keys=None):
def remove_model_options(self, app_label, model_name, option_name, value_to_remove):
model_state = self.models[app_label, model_name]
if objs := model_state.options.get(option_name):
- model_state.options[option_name] = [
- obj for obj in objs if tuple(obj) != tuple(value_to_remove)
- ]
+ new_value = [obj for obj in objs if tuple(obj) != tuple(value_to_remove)]
+ if option_name in {"index_together", "unique_together"}:
+ new_value = set(normalize_together(new_value))
+ model_state.options[option_name] = new_value
self.reload_model(app_label, model_name, delay=True)
def alter_model_managers(self, app_label, model_name, managers):
@@ -339,10 +340,10 @@ def rename_field(self, app_label, model_name, old_name, new_name):
options = model_state.options
for option in ("index_together", "unique_together"):
if option in options:
- options[option] = [
- [new_name if n == old_name else n for n in together]
+ options[option] = {
+ tuple(new_name if n == old_name else n for n in together)
for together in options[option]
- ]
+ }
# Fix to_fields to refer to the new field.
delay = True
references = get_references(self, model_key, (old_name, found))
| 20,574 | https://github.com/django/django/pull/20574 | 2026-01-28 21:13:05 | 36,878 | https://github.com/django/django/pull/20574 | 86 | ["tests/migrations/test_autodetector.py", "tests/migrations/test_base.py", "tests/migrations/test_operations.py"] | [] | 5.2 |
django__django-20505 | django/django | 68d110f1fe593b7a368486c41cd062563a74fe0a | # Fixed #36812 -- Dropped support for MariaDB < 10.11.
#### Trac ticket number
<!-- Replace XXXXX with the corresponding Trac ticket number, or delete the line and write "N/A" if this is a trivial PR. -->
ticket-36812
#### Branch description
Dropped the support for MariaDB 10.6-10.10.
#### Checklist
- [x] This PR targets the `main` branch. <!-- Backports will be evaluated and done by mergers, when necessary. -->
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" ticket flag in the Trac system.
- [x] I have added or updated relevant tests.
- [x] I have added or updated relevant docs, including release notes if applicable.
- [x] I have attached screenshots in both light and dark modes for any UI changes.
| diff --git a/tests/backends/mysql/tests.py b/tests/backends/mysql/tests.py
index 15228d254fc1..237e7f94472b 100644
--- a/tests/backends/mysql/tests.py
+++ b/tests/backends/mysql/tests.py
@@ -106,8 +106,8 @@ class Tests(TestCase):
@mock.patch.object(connection, "get_database_version")
def test_check_database_version_supported(self, mocked_get_database_version):
if connection.mysql_is_mariadb:
- mocked_get_database_version.return_value = (10, 5)
- msg = "MariaDB 10.6 or later is required (found 10.5)."
+ mocked_get_database_version.return_value = (10, 10)
+ msg = "MariaDB 10.11 or later is required (found 10.10)."
else:
mocked_get_database_version.return_value = (8, 0, 31)
msg = "MySQL 8.4 or later is required (found 8.0.31)."
| diff --git a/django/db/backends/mysql/features.py b/django/db/backends/mysql/features.py
index 4f61e2bdf9af..eb9601bcef44 100644
--- a/django/db/backends/mysql/features.py
+++ b/django/db/backends/mysql/features.py
@@ -64,7 +64,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):
@cached_property
def minimum_database_version(self):
if self.connection.mysql_is_mariadb:
- return (10, 6)
+ return (10, 11)
else:
return (8, 4)
@@ -207,8 +207,6 @@ def can_introspect_json_field(self):
def supports_index_column_ordering(self):
if self._mysql_storage_engine != "InnoDB":
return False
- if self.connection.mysql_is_mariadb:
- return self.connection.mysql_version >= (10, 8)
return True
@cached_property
@@ -220,8 +218,7 @@ def supports_expression_indexes(self):
@cached_property
def has_native_uuid_field(self):
- is_mariadb = self.connection.mysql_is_mariadb
- return is_mariadb and self.connection.mysql_version >= (10, 7)
+ return self.connection.mysql_is_mariadb
@cached_property
def allows_group_by_selected_pks(self):
| 20,505 | https://github.com/django/django/pull/20505 | 2026-01-25 10:51:03 | 36,812 | https://github.com/django/django/pull/20505 | 41 | ["tests/backends/mysql/tests.py"] | [] | 5.2 |
django__django-18934 | django/django | 3851601b2e080df34fb9227fe5d2fd43af604263 | # Refs #26709 -- Made Index raise ValueError on non-string fields.
| diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py
index 69570a806233..64e0e232290a 100644
--- a/tests/admin_views/admin.py
+++ b/tests/admin_views/admin.py
@@ -18,7 +18,12 @@
from django.utils.safestring import mark_safe
from django.views.decorators.common import no_append_slash
-from .forms import MediaActionForm
+from .forms import (
+ MediaActionForm,
+ SectionFormWithDynamicOptgroups,
+ SectionFormWithObjectOptgroups,
+ SectionFormWithOptgroups,
+)
from .models import (
Actor,
AdminOrderedAdminMethod,
@@ -1345,6 +1350,32 @@ class CourseAdmin(admin.ModelAdmin):
site7 = admin.AdminSite(name="admin7")
site7.register(Article, ArticleAdmin2)
site7.register(Section)
+
+
+# Admin for testing optgroup in popup response
+class SectionAdminWithOptgroups(admin.ModelAdmin):
+ form = SectionFormWithOptgroups
+
+
+class SectionAdminWithObjectOptgroups(admin.ModelAdmin):
+ form = SectionFormWithObjectOptgroups
+
+
+class SectionAdminWithDynamicOptgroups(admin.ModelAdmin):
+ form = SectionFormWithDynamicOptgroups
+
+
+site11 = admin.AdminSite(name="admin11")
+site11.register(Article, ArticleAdmin2)
+site11.register(Section, SectionAdminWithOptgroups)
+
+site12 = admin.AdminSite(name="admin12")
+site12.register(Article, ArticleAdmin2)
+site12.register(Section, SectionAdminWithObjectOptgroups)
+
+site13 = admin.AdminSite(name="admin13")
+site13.register(Article, ArticleAdmin2)
+site13.register(Section, SectionAdminWithDynamicOptgroups)
site7.register(PrePopulatedPost, PrePopulatedPostReadOnlyAdmin)
site7.register(
Pizza,
diff --git a/tests/admin_views/forms.py b/tests/admin_views/forms.py
index 3a3566c10f12..f15a5b3ac195 100644
--- a/tests/admin_views/forms.py
+++ b/tests/admin_views/forms.py
@@ -1,7 +1,10 @@
+from django import forms
from django.contrib.admin.forms import AdminAuthenticationForm, AdminPasswordChangeForm
from django.contrib.admin.helpers import ActionForm
from django.core.exceptions import ValidationError
+from .models import Section
+
class CustomAdminAuthenticationForm(AdminAuthenticationForm):
class Media:
@@ -23,3 +26,63 @@ def __init__(self, *args, **kwargs):
class MediaActionForm(ActionForm):
class Media:
js = ["path/to/media.js"]
+
+
+class SectionFormWithOptgroups(forms.ModelForm):
+ articles = forms.ChoiceField(
+ choices=[
+ ("Published", [("1", "Test Article")]),
+ ("Draft", [("2", "Other Article")]),
+ ],
+ required=False,
+ )
+
+ class Meta:
+ model = Section
+ fields = ["name", "articles"]
+
+
+class SectionFormWithObjectOptgroups(forms.ModelForm):
+ """Form with model instances as optgroup keys (tests str() conversion)."""
+
+ articles = forms.ChoiceField(required=False)
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # Use Section instances as optgroup keys
+ sections = Section.objects.all()[:2]
+ if sections:
+ self.fields["articles"].choices = [
+ (sections[0], [("1", "Article 1")]),
+ (
+ sections[1] if len(sections) > 1 else sections[0],
+ [("2", "Article 2")],
+ ),
+ ]
+
+ class Meta:
+ model = Section
+ fields = ["name", "articles"]
+
+
+class SectionFormWithDynamicOptgroups(forms.ModelForm):
+ """
+ Form where the field with optgroups is added dynamically in __init__.
+ This tests that the implementation doesn't rely on accessing the
+ uninstantiated form class's _meta or fields, which wouldn't work here.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # Dynamically add a field with optgroups after instantiation.
+ self.fields["articles"] = forms.ChoiceField(
+ choices=[
+ ("Category A", [("1", "Item 1"), ("2", "Item 2")]),
+ ("Category B", [("3", "Item 3"), ("4", "Item 4")]),
+ ],
+ required=False,
+ )
+
+ class Meta:
+ model = Section
+ fields = ["name"]
diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py
index f7eaad659e6c..3377a6d44177 100644
--- a/tests/admin_views/tests.py
+++ b/tests/admin_views/tests.py
@@ -11,7 +11,7 @@
from django.contrib.admin import AdminSite, ModelAdmin
from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME
from django.contrib.admin.models import ADDITION, DELETION, LogEntry
-from django.contrib.admin.options import TO_FIELD_VAR
+from django.contrib.admin.options import SOURCE_MODEL_VAR, TO_FIELD_VAR
from django.contrib.admin.templatetags.admin_urls import add_preserved_filters
from django.contrib.admin.tests import AdminSeleniumTestCase
from django.contrib.admin.utils import quote
@@ -468,6 +468,126 @@ def test_popup_add_POST(self):
response = self.client.post(reverse("admin:admin_views_article_add"), post_data)
self.assertContains(response, "title with a new\\nline")
+ def test_popup_add_POST_with_valid_source_model(self):
+ """
+ Popup add with a valid source_model returns a successful response.
+ """
+ post_data = {
+ IS_POPUP_VAR: "1",
+ SOURCE_MODEL_VAR: "admin_views.section",
+ "title": "Test Article",
+ "content": "some content",
+ "date_0": "2010-09-10",
+ "date_1": "14:55:39",
+ }
+ response = self.client.post(reverse("admin:admin_views_article_add"), post_data)
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "data-popup-response")
+ messages = list(response.wsgi_request._messages)
+ self.assertEqual(len(messages), 0)
+
+ def test_popup_add_POST_with_optgroups(self):
+ """
+ Popup add with source_model containing optgroup choices includes
+ the optgroup in the response.
+ """
+ post_data = {
+ IS_POPUP_VAR: "1",
+ SOURCE_MODEL_VAR: "admin_views.section",
+ "title": "Test Article",
+ "content": "some content",
+ "date_0": "2010-09-10",
+ "date_1": "14:55:39",
+ }
+ response = self.client.post(
+ reverse("admin11:admin_views_article_add"), post_data
+ )
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, ""optgroup": "Published"")
+
+ def test_popup_add_POST_without_optgroups(self):
+ """
+ Popup add where source_model form exists but doesn't have the field
+ should work without crashing.
+ """
+ post_data = {
+ IS_POPUP_VAR: "1",
+ SOURCE_MODEL_VAR: "admin_views.section",
+ "title": "Test Article 2",
+ "content": "some content",
+ "date_0": "2010-09-10",
+ "date_1": "14:55:39",
+ }
+ # Use regular admin (not admin11) where Section doesn't have optgroups.
+ response = self.client.post(reverse("admin:admin_views_article_add"), post_data)
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "data-popup-response")
+ self.assertNotContains(response, ""optgroup"")
+
+ def test_popup_add_POST_with_object_optgroups(self):
+ """
+ Popup add with source_model containing optgroups where the optgroup
+ keys are model instances (not strings) still serialize to strings.
+ """
+ post_data = {
+ IS_POPUP_VAR: "1",
+ SOURCE_MODEL_VAR: "admin_views.section",
+ "title": "Article 1",
+ "content": "some content",
+ "date_0": "2010-09-10",
+ "date_1": "14:55:39",
+ }
+ response = self.client.post(
+ reverse("admin12:admin_views_article_add"), post_data
+ )
+ self.assertEqual(response.status_code, 200)
+ # Check that optgroup is in the response with str() of Section instance
+ # The form uses Section.objects.all()[:2] which includes cls.s1
+ # ("Test section") as the first optgroup key (HTML encoded).
+ self.assertContains(response, ""optgroup": "Test section"")
+
+ def test_popup_add_POST_with_dynamic_optgroups(self):
+ """
+ Popup add with source_model where optgroup field is added dynamically
+ in __init__. This ensures the implementation doesn't rely on accessing
+ the uninstantiated form class's _meta or fields, but instead properly
+ instantiates the form with get_form(request)() to access field info.
+ """
+ post_data = {
+ IS_POPUP_VAR: "1",
+ SOURCE_MODEL_VAR: "admin_views.section",
+ "title": "Item 1",
+ "content": "some content",
+ "date_0": "2010-09-10",
+ "date_1": "14:55:39",
+ }
+ response = self.client.post(
+ reverse("admin13:admin_views_article_add"), post_data
+ )
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, ""optgroup": "Category A"")
+
+ def test_popup_add_POST_with_invalid_source_model(self):
+ """
+ Popup add with an invalid source_model (non-existent app/model)
+ shows an error message instead of crashing.
+ """
+ post_data = {
+ IS_POPUP_VAR: "1",
+ SOURCE_MODEL_VAR: "admin_views.nonexistent",
+ "title": "Test Article",
+ "content": "some content",
+ "date_0": "2010-09-10",
+ "date_1": "14:55:39",
+ }
+ response = self.client.post(reverse("admin:admin_views_article_add"), post_data)
+ self.assertEqual(response.status_code, 200)
+ self.assertContains(response, "data-popup-response")
+ messages = list(response.wsgi_request._messages)
+ self.assertEqual(len(messages), 1)
+ self.assertIn("admin_views.nonexistent", str(messages[0]))
+ self.assertIn("could not be found", str(messages[0]))
+
def test_basic_edit_POST(self):
"""
A smoke test to ensure POST on edit_view works.
diff --git a/tests/admin_views/urls.py b/tests/admin_views/urls.py
index c1e673d81105..3c43b8721dc4 100644
--- a/tests/admin_views/urls.py
+++ b/tests/admin_views/urls.py
@@ -32,6 +32,9 @@ def non_admin_view(request):
),
path("test_admin/admin9/", admin.site9.urls),
path("test_admin/admin10/", admin.site10.urls),
+ path("test_admin/admin11/", admin.site11.urls),
+ path("test_admin/admin12/", admin.site12.urls),
+ path("test_admin/admin13/", admin.site13.urls),
path("test_admin/has_permission_admin/", custom_has_permission_admin.site.urls),
path("test_admin/autocomplete_admin/", autocomplete_site.urls),
# Shares the admin URL prefix.
diff --git a/tests/admin_widgets/tests.py b/tests/admin_widgets/tests.py
index 7588c2cc32a1..e0ae5b77471c 100644
--- a/tests/admin_widgets/tests.py
+++ b/tests/admin_widgets/tests.py
@@ -971,7 +971,7 @@ def test_data_model_ref_when_model_name_is_camel_case(self):
</select>
<a class="related-widget-wrapper-link add-related" id="add_id_stream"
data-popup="yes" title="Add another release event"
- href="/admin_widgets/releaseevent/add/?_to_field=album&_popup=1">
+ href="/admin_widgets/releaseevent/add/?_to_field=album&_popup=1&_source_model=admin_widgets.videostream">
<img src="/static/admin/img/icon-addlink.svg" alt="" width="24" height="24">
</a>
</div>
| diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py
index 2de07fde7e33..69b7031e8260 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -8,6 +8,7 @@
from urllib.parse import urlsplit
from django import forms
+from django.apps import apps
from django.conf import settings
from django.contrib import messages
from django.contrib.admin import helpers, widgets
@@ -71,6 +72,7 @@
from django.views.generic import RedirectView
IS_POPUP_VAR = "_popup"
+SOURCE_MODEL_VAR = "_source_model"
TO_FIELD_VAR = "_to_field"
IS_FACETS_VAR = "_facets"
@@ -1342,6 +1344,7 @@ def render_change_form(
"save_on_top": self.save_on_top,
"to_field_var": TO_FIELD_VAR,
"is_popup_var": IS_POPUP_VAR,
+ "source_model_var": SOURCE_MODEL_VAR,
"app_label": app_label,
}
)
@@ -1398,12 +1401,39 @@ def response_add(self, request, obj, post_url_continue=None):
else:
attr = obj._meta.pk.attname
value = obj.serializable_value(attr)
- popup_response_data = json.dumps(
- {
- "value": str(value),
- "obj": str(obj),
- }
- )
+ popup_response = {
+ "value": str(value),
+ "obj": str(obj),
+ }
+
+ # Find the optgroup for the new item, if available
+ source_model_name = request.POST.get(SOURCE_MODEL_VAR)
+
+ if source_model_name:
+ app_label, model_name = source_model_name.split(".", 1)
+ try:
+ source_model = apps.get_model(app_label, model_name)
+ except LookupError:
+ msg = _('The app "%s" could not be found.') % source_model_name
+ self.message_user(request, msg, messages.ERROR)
+ else:
+ source_admin = self.admin_site._registry[source_model]
+ form = source_admin.get_form(request)()
+ if self.opts.verbose_name_plural in form.fields:
+ field = form.fields[self.opts.verbose_name_plural]
+ for option_value, option_label in field.choices:
+ # Check if this is an optgroup (label is a sequence
+ # of choices rather than a single string value).
+ if isinstance(option_label, (list, tuple)):
+ # It's an optgroup:
+ # (group_name, [(value, label), ...])
+ optgroup_label = option_value
+ for choice_value, choice_display in option_label:
+ if choice_display == str(obj):
+ popup_response["optgroup"] = str(optgroup_label)
+ break
+
+ popup_response_data = json.dumps(popup_response)
return TemplateResponse(
request,
self.popup_response_template
@@ -1913,6 +1943,7 @@ def _changeform_view(self, request, object_id, form_url, extra_context):
"object_id": object_id,
"original": obj,
"is_popup": IS_POPUP_VAR in request.POST or IS_POPUP_VAR in request.GET,
+ "source_model": request.GET.get(SOURCE_MODEL_VAR),
"to_field": to_field,
"media": media,
"inline_admin_formsets": inline_formsets,
diff --git a/django/contrib/admin/views/main.py b/django/contrib/admin/views/main.py
index 40a6b3bf3a86..cd40f14ce37a 100644
--- a/django/contrib/admin/views/main.py
+++ b/django/contrib/admin/views/main.py
@@ -11,6 +11,7 @@
from django.contrib.admin.options import (
IS_FACETS_VAR,
IS_POPUP_VAR,
+ SOURCE_MODEL_VAR,
TO_FIELD_VAR,
IncorrectLookupParameters,
ShowFacets,
@@ -49,6 +50,7 @@
SEARCH_VAR,
IS_FACETS_VAR,
IS_POPUP_VAR,
+ SOURCE_MODEL_VAR,
TO_FIELD_VAR,
)
diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py
index f5c393901254..67eac083e793 100644
--- a/django/contrib/admin/widgets.py
+++ b/django/contrib/admin/widgets.py
@@ -333,16 +333,24 @@ def get_related_url(self, info, action, *args):
)
def get_context(self, name, value, attrs):
- from django.contrib.admin.views.main import IS_POPUP_VAR, TO_FIELD_VAR
+ from django.contrib.admin.views.main import (
+ IS_POPUP_VAR,
+ SOURCE_MODEL_VAR,
+ TO_FIELD_VAR,
+ )
rel_opts = self.rel.model._meta
info = (rel_opts.app_label, rel_opts.model_name)
related_field_name = self.rel.get_related_field().name
+ app_label = self.rel.field.model._meta.app_label
+ model_name = self.rel.field.model._meta.model_name
+
url_params = "&".join(
"%s=%s" % param
for param in [
(TO_FIELD_VAR, related_field_name),
(IS_POPUP_VAR, 1),
+ (SOURCE_MODEL_VAR, f"{app_label}.{model_name}"),
]
)
context = {
| 18,934 | https://github.com/django/django/pull/18934 | 2026-01-23 02:12:23 | 13,883 | https://github.com/django/django/pull/13883 | 512 | ["tests/admin_views/admin.py", "tests/admin_views/forms.py", "tests/admin_views/tests.py", "tests/admin_views/urls.py", "tests/admin_widgets/tests.py"] | [] | 5.2 |
django__django-20309 | django/django | 25416413470d8e6630528626ee8b033d2d77ff46 | # Fixed #36030 -- Fixed precision loss in division of Decimal literals on SQLite.
#### Trac ticket number
ticket-36030
#### Branch description
On SQLite, ``SQLiteNumericMixin.as_sqlite()`` currently wraps all ``DecimalField`` expressions in ``CAST(... AS NUMERIC)``, including literal ``Value(Decimal(...))`` expressions.
For these literals, the cast is unnecessary and differs from how other backends pass Decimal parameters.
The solution decouples ``Value`` from ``SQLiteNumericMixin`` by implementing a dedicated ``as_sqlite`` method that explicitly casts ``Decimal`` literals to ``REAL``, ensuring correct floating-point arithmetic is used. To prevent regressions, the implementation retains the existing ``CAST(... AS NUMERIC)`` wrapper for ``non-Decimal`` types (such as integers) when they are output to a DecimalField.
**Tests**
A new regression test, ``test_decimal_division_literal_value``, has been added to ``BasicExpressionsTests`` to verify that division yields the correct fractional precision on all backends.
#### Checklist
- [x] This PR targets the `main` branch.
- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.
- [x] I have checked the "Has patch" flag on the Trac ticket.
- [x] I have added or updated relevant tests.
- [ ] I have added or updated relevant docs, including release notes if applicable.
- [ ] I have attached screenshots in light/dark modes for UI changes (N/A).
| diff --git a/tests/expressions/tests.py b/tests/expressions/tests.py
index 981d84e9e8ec..02126fa89612 100644
--- a/tests/expressions/tests.py
+++ b/tests/expressions/tests.py
@@ -137,6 +137,16 @@ def test_annotate_values_aggregate(self):
)
self.assertEqual(companies["result"], 2395)
+ def test_decimal_division_literal_value(self):
+ """
+ Division with a literal Decimal value preserves precision.
+ """
+ num = Number.objects.create(integer=2)
+ obj = Number.objects.annotate(
+ val=F("integer") / Value(Decimal("3.0"), output_field=DecimalField())
+ ).get(pk=num.pk)
+ self.assertAlmostEqual(obj.val, Decimal("0.6667"), places=4)
+
def test_annotate_values_filter(self):
companies = (
Company.objects.annotate(
| diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py
index 6b90a42cf1d2..baa91cc2c173 100644
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -1141,7 +1141,7 @@ def allowed_default(self):
@deconstructible(path="django.db.models.Value")
-class Value(SQLiteNumericMixin, Expression):
+class Value(Expression):
"""Represent a wrapped value as a node within an expression."""
# Provide a default value for `for_save` in order to allow unresolved
@@ -1182,6 +1182,18 @@ def as_sql(self, compiler, connection):
return "NULL", []
return "%s", [val]
+ def as_sqlite(self, compiler, connection, **extra_context):
+ sql, params = self.as_sql(compiler, connection, **extra_context)
+ try:
+ if self.output_field.get_internal_type() == "DecimalField":
+ if isinstance(self.value, Decimal):
+ sql = "(CAST(%s AS REAL))" % sql
+ else:
+ sql = "(CAST(%s AS NUMERIC))" % sql
+ except FieldError:
+ pass
+ return sql, params
+
def resolve_expression(
self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False
):
| 20,309 | https://github.com/django/django/pull/20309 | 2026-01-20 15:42:29 | 36,030 | https://github.com/django/django/pull/20309 | 24 | ["tests/expressions/tests.py"] | [] | 5.2 |
SWE-bench Complex
A contamination-free, complexity-focused evaluation set for AI coding agents.
SWE-bench Complex is a curated dataset of 119 real-world GitHub issues from major Python open-source projects, designed specifically for studying code complexity in AI-generated patches. All tasks were merged between January–March 2026, guaranteeing they postdate the training cutoff of current frontier models.
Why SWE-bench Complex?
Existing benchmarks like SWE-bench Verified suffer from two problems for complexity research:
1. Data Contamination
Over 94% of SWE-bench issues predate current LLM training cutoffs. Aleithan et al. found that 32.67% of successful patches involve "cheating" through solution leakage, and resolution rates dropped from 12.47% to 3.97% when leaked instances were filtered out (SWE-bench+, 2024).
All SWE-bench Complex instances postdate the training cutoffs of:
| Model | Provider | Training Cutoff | Gap |
|---|---|---|---|
| Claude Opus 4.6 | Anthropic | Oct 2025 | 3+ months |
| GPT-5.3-Codex | OpenAI | Sep 2025 | 4+ months |
| GPT-5.4 | OpenAI | Nov 2025 | 2+ months |
| Gemini 3.1 Pro | Oct 2025 | 3+ months |
2. Trivial Patches
SWE-bench Verified has a median patch size of just 7 changed lines — 44.6% of tasks require only 1–5 lines. These trivial patches yield near-zero complexity deltas, reducing statistical power for quality studies.
SWE-bench Complex targets substantive patches with a median of 48 changed lines — 6.9× larger than SWE-bench Verified.
Dataset Comparison
| Characteristic | SWE-bench Verified | SWE-bench Complex |
|---|---|---|
| Tasks | 500 | 119 |
| Repositories | 12 | 8 |
| Median changed lines | 7 | 48 |
| Mean changed lines | 14.3 | 74.9 |
| Mean Python files changed | 1.2 | 3.9 |
| Human ΔCC (mean) | +1.14 | +4.06 |
| Human ΔLLOC (mean) | +2.77 | +19.08 |
| Human ΔMI (mean) | −0.230 | −0.417 |
| Human ΔCogC (mean) | N/A | +3.63 |
| Post-training-cutoff | <6% | 100% |
Complexity metrics measured using Wily v2:
- ΔCC: Cyclomatic Complexity change (McCabe, 1976)
- ΔLLOC: Logical Lines of Code change
- ΔMI: Maintainability Index change (Oman & Hagemeister, 1992)
- ΔCogC: Cognitive Complexity change (Campbell, 2018)
Repository Distribution
| Repository | Instances |
|---|---|
| django/django | 38 |
| astropy/astropy | 22 |
| pydata/xarray | 17 |
| scikit-learn/scikit-learn | 14 |
| pylint-dev/pylint | 10 |
| matplotlib/matplotlib | 9 |
| sympy/sympy | 8 |
| pallets/flask | 1 |
Selection Criteria
Instances were collected from merged pull requests in the SWE-bench ecosystem repositories with the following filters:
- Date range: Merged January 1 – March 10, 2026 (post-training-cutoff)
- Issue linkage: PR explicitly references a GitHub issue via "fixes #N" or equivalent
- Test coverage: PR includes both implementation and test changes to Python files
- Minimum complexity: Implementation patch modifies ≥4 changed lines
- Python files: Only
.pyfile changes retained - Manual review: Each candidate reviewed for solvability — documentation-only changes, large-scale refactors (>300 lines or >10 files), and tasks requiring external domain knowledge were excluded
From 1,043 scraped PRs → 712 with issue references → 224 after automated filters → 119 after manual review.
Schema
Each instance contains:
| Field | Type | Description |
|---|---|---|
instance_id |
string | Unique identifier ({owner}__{repo}-{pr_number}) |
repo |
string | GitHub repository (owner/repo) |
base_commit |
string | Parent commit SHA |
problem_statement |
string | GitHub issue text (title + body) |
test_patch |
string | Unified diff of test-file changes |
human_patch |
string | Unified diff of implementation-file changes |
pr_number |
int | Pull request number |
pr_url |
string | Pull request URL |
pr_merged_at |
string | Merge timestamp (ISO 8601) |
issue_number |
int | Referenced issue number |
issue_url |
string | Issue URL |
human_changed_lines |
int | Total changed lines in the human patch |
FAIL_TO_PASS |
string | JSON array of test IDs that must go FAIL→PASS |
PASS_TO_PASS |
string | JSON array of test IDs that must remain PASS |
SWE-bench Compatibility
SWE-bench Complex uses the same schema as SWE-bench Verified and can be evaluated using the standard SWE-bench harness:
python -m swebench.harness.run_evaluation \
-d anthonypjshaw/SWE-bench_Complex \
-s test \
-p predictions.jsonl \
-id my_run \
--max_workers 4
Usage
from datasets import load_dataset
dataset = load_dataset("anthonypjshaw/SWE-bench_Complex", split="test")
print(f"Tasks: {len(dataset)}")
print(f"Repos: {len(set(dataset['repo']))}")
Citation
If you use SWE-bench Complex in your research, please cite:
@inproceedings{Shaw2026SWEbenchComplex,
author = {Shaw, Anthony},
title = {Beyond the Benchmark: A Contamination-Free Study of {AI} Code Complexity Across Four Frontier Models},
booktitle = {Proceedings of the IEEE International Conference on Software Engineering (SSE)},
year = {2026},
}
License
MIT License. The dataset contains references to publicly available open-source code under their respective licenses.
- Downloads last month
- 5