{"instance_id": "astropy__astropy-12907", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/modeling/separable.py b/astropy/modeling/separable.py\nindex a308e27297..45bea36085 100644\n--- a/astropy/modeling/separable.py\n+++ b/astropy/modeling/separable.py\n@@ -242,7 +242,7 @@ def _cstack(left, right):\n         cright = _coord_matrix(right, 'right', noutp)\n     else:\n         cright = np.zeros((noutp, right.shape[1]))\n-        cright[-right.shape[0]:, -right.shape[1]:] = 1\n+        cright[-right.shape[0]:, -right.shape[1]:] = right\n \n     return np.hstack([cleft, cright])\n \ndiff --git a/astropy/modeling/tests/test_separable.py b/astropy/modeling/tests/test_separable.py\nindex 8dfe5c8626..c4959eea29 100644\n--- a/astropy/modeling/tests/test_separable.py\n+++ b/astropy/modeling/tests/test_separable.py\n@@ -52,7 +52,22 @@ compound_models = {\n     'cm7': (map2 | p2 & sh1,\n             (np.array([False, True]),\n              np.array([[True, False], [False, True]]))\n-            )\n+            ),\n+    # Regression test for nested CompoundModels with &:\n+    # https://github.com/astropy/astropy/issues/XXXX\n+    'cm8': (models.Pix2Sky_TAN() & (models.Linear1D(10) & models.Linear1D(5)),\n+            (np.array([False, False, True, True]),\n+             np.array([[True, True, False, False],\n+                       [True, True, False, False],\n+                       [False, False, True, False],\n+                       [False, False, False, True]]))\n+            ),\n+    'cm9': (models.Linear1D(10) & models.Linear1D(5) & models.Linear1D(1),\n+            (np.array([True, True, True]),\n+             np.array([[True, False, False],\n+                       [False, True, False],\n+                       [False, False, True]]))\n+            ),\n }\n \n \ndiff --git a/astropy/utils/_compiler.py b/astropy/utils/_compiler.py\nnew file mode 100644\nindex 0000000000..d39919a40f\n--- /dev/null\n+++ b/astropy/utils/_compiler.py\n@@ -0,0 +1 @@\n+compiler_version = 'unknown'\n"}
{"instance_id": "astropy__astropy-14182", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/io/ascii/rst.py b/astropy/io/ascii/rst.py\nindex abdeba8efb..fad384d112 100644\n--- a/astropy/io/ascii/rst.py\n+++ b/astropy/io/ascii/rst.py\n@@ -50,6 +50,23 @@ class RST(FixedWidth):\n     or for ones which define column spans through the use of an additional\n     line of dashes in the header.\n \n+    Parameters\n+    ----------\n+    header_rows : list, optional\n+        A list of column attributes to include as header rows. The default is\n+        ``[\"name\"]``, which produces the standard RST simple table output. To\n+        include additional rows such as units, pass ``[\"name\", \"unit\"]``.\n+\n+        Example with units::\n+\n+            ===== ========\n+             wave response\n+               nm       ct\n+            ===== ========\n+            350.0      0.7\n+            950.0      1.2\n+            ===== ========\n+\n     \"\"\"\n \n     _format_name = \"rst\"\n@@ -57,10 +74,13 @@ class RST(FixedWidth):\n     data_class = SimpleRSTData\n     header_class = SimpleRSTHeader\n \n-    def __init__(self):\n-        super().__init__(delimiter_pad=None, bookend=False)\n+    def __init__(self, header_rows=None):\n+        super().__init__(delimiter_pad=None, bookend=False, header_rows=header_rows)\n \n     def write(self, lines):\n         lines = super().write(lines)\n-        lines = [lines[1]] + lines + [lines[1]]\n+        # The separator line is appended after all header rows by FixedWidthData.write().\n+        # Its index in the output equals the number of header rows.\n+        idx = len(self.header.header_rows)\n+        lines = [lines[idx]] + lines + [lines[idx]]\n         return lines\ndiff --git a/astropy/io/ascii/tests/test_rst.py b/astropy/io/ascii/tests/test_rst.py\nindex 84d6fed401..338e457dc6 100644\n--- a/astropy/io/ascii/tests/test_rst.py\n+++ b/astropy/io/ascii/tests/test_rst.py\n@@ -2,7 +2,11 @@\n \n from io import StringIO\n \n+import pytest\n+\n from astropy.io import ascii\n+from astropy.table import QTable\n+import astropy.units as u\n \n from .common import assert_almost_equal, assert_equal\n \n@@ -185,3 +189,40 @@ Col1      Col2 Col3 Col4\n ==== ========= ==== ====\n \"\"\",\n     )\n+\n+\n+def test_write_header_rows():\n+    \"\"\"Write a QTable as RST with header_rows=['name', 'unit']\"\"\"\n+    tbl = QTable({\"wave\": [350, 950] * u.nm, \"response\": [0.7, 1.2] * u.count})\n+    out = StringIO()\n+    tbl.write(out, format=\"ascii.rst\", header_rows=[\"name\", \"unit\"])\n+    assert_equal_splitlines(\n+        out.getvalue(),\n+        \"\"\"\\\n+===== ========\n+ wave response\n+   nm       ct\n+===== ========\n+350.0      0.7\n+950.0      1.2\n+===== ========\n+\"\"\",\n+    )\n+\n+\n+def test_write_header_rows_single():\n+    \"\"\"Write a QTable as RST with header_rows=['name'] (default behavior)\"\"\"\n+    tbl = QTable({\"wave\": [350, 950] * u.nm, \"response\": [0.7, 1.2] * u.count})\n+    out = StringIO()\n+    tbl.write(out, format=\"ascii.rst\", header_rows=[\"name\"])\n+    assert_equal_splitlines(\n+        out.getvalue(),\n+        \"\"\"\\\n+===== ========\n+ wave response\n+===== ========\n+350.0      0.7\n+950.0      1.2\n+===== ========\n+\"\"\",\n+    )\ndiff --git a/astropy/utils/_compiler.py b/astropy/utils/_compiler.py\nnew file mode 100644\nindex 0000000000..76a341caa1\n--- /dev/null\n+++ b/astropy/utils/_compiler.py\n@@ -0,0 +1,2 @@\n+# Stub compiler module for testing without building extensions\n+compiler_version = \"stub\"\n"}
{"instance_id": "astropy__astropy-14365", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/io/ascii/qdp.py b/astropy/io/ascii/qdp.py\nindex 83a4f004aa..2ad47bf561 100644\n--- a/astropy/io/ascii/qdp.py\n+++ b/astropy/io/ascii/qdp.py\n@@ -34,6 +34,8 @@ def _line_type(line, delimiter=None):\n     --------\n     >>> _line_type(\"READ SERR 3\")\n     'command'\n+    >>> _line_type(\"read serr 3\")\n+    'command'\n     >>> _line_type(\" \\\\n    !some gibberish\")\n     'comment'\n     >>> _line_type(\"   \")\n@@ -68,7 +70,7 @@ def _line_type(line, delimiter=None):\n     _new_re = rf\"NO({sep}NO)+\"\n     _data_re = rf\"({_decimal_re}|NO|[-+]?nan)({sep}({_decimal_re}|NO|[-+]?nan))*)\"\n     _type_re = rf\"^\\s*((?P<command>{_command_re})|(?P<new>{_new_re})|(?P<data>{_data_re})?\\s*(\\!(?P<comment>.*))?\\s*$\"\n-    _line_type_re = re.compile(_type_re)\n+    _line_type_re = re.compile(_type_re, re.IGNORECASE)\n     line = line.strip()\n     if not line:\n         return \"comment\"\n@@ -306,7 +308,7 @@ def _get_tables_from_qdp_file(qdp_file, input_colnames=None, delimiter=None):\n \n             values = []\n             for v in line.split(delimiter):\n-                if v == \"NO\":\n+                if v.upper() == \"NO\":\n                     values.append(np.ma.masked)\n                 else:\n                     # Understand if number is int or float\n"}
{"instance_id": "astropy__astropy-14995", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/nddata/mixins/ndarithmetic.py b/astropy/nddata/mixins/ndarithmetic.py\nindex 4153dfccb2..544795ddd2 100644\n--- a/astropy/nddata/mixins/ndarithmetic.py\n+++ b/astropy/nddata/mixins/ndarithmetic.py\n@@ -520,7 +520,8 @@ class NDArithmeticMixin:\n         elif self.mask is None and operand is not None:\n             # Make a copy so there is no reference in the result.\n             return deepcopy(operand.mask)\n-        elif operand is None:\n+        elif operand is None or operand.mask is None:\n+            # Make a copy so there is no reference in the result.\n             return deepcopy(self.mask)\n         else:\n             # Now lets calculate the resulting mask (operation enforces copy)\ndiff --git a/astropy/nddata/mixins/tests/test_ndarithmetic.py b/astropy/nddata/mixins/tests/test_ndarithmetic.py\nindex 8c461155ab..0e51367a5e 100644\n--- a/astropy/nddata/mixins/tests/test_ndarithmetic.py\n+++ b/astropy/nddata/mixins/tests/test_ndarithmetic.py\n@@ -1310,3 +1310,33 @@ def test_raise_method_not_supported():\n     # raise error for unsupported propagation operations:\n     with pytest.raises(ValueError):\n         ndd1.uncertainty.propagate(np.mod, ndd2, result, correlation)\n+\n+\n+def test_nddata_bitmask_propagation():\n+    \"\"\"\n+    Regression test for https://github.com/astropy/astropy/issues/15182\n+\n+    Verify that mask propagation works correctly when one operand has no mask,\n+    using a bitwise or handle_mask function (as opposed to the default\n+    np.logical_or).\n+    \"\"\"\n+    array = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]])\n+    mask = np.array([[0, 1, 64], [8, 0, 1], [2, 1, 0]])\n+\n+    nref_nomask = NDDataArithmetic(array)\n+    nref_mask = NDDataArithmetic(array, mask=mask)\n+\n+    # no mask * no mask: result should have no mask\n+    assert nref_nomask.multiply(1.0, handle_mask=np.bitwise_or).mask is None\n+    assert nref_nomask.multiply(nref_nomask, handle_mask=np.bitwise_or).mask is None\n+\n+    # mask * no mask: result should carry the existing mask unchanged\n+    result_mask_const = nref_mask.multiply(1.0, handle_mask=np.bitwise_or).mask\n+    assert_array_equal(result_mask_const, mask)\n+\n+    result_mask_nomask = nref_mask.multiply(nref_nomask, handle_mask=np.bitwise_or).mask\n+    assert_array_equal(result_mask_nomask, mask)\n+\n+    # mask * mask: result should be bitwise-or of both masks\n+    result_mask_mask = nref_mask.multiply(nref_mask, handle_mask=np.bitwise_or).mask\n+    assert_array_equal(result_mask_mask, mask | mask)\n"}
{"instance_id": "astropy__astropy-6938", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/io/fits/fitsrec.py b/astropy/io/fits/fitsrec.py\nindex 574b4073b1..621e0925b5 100644\n--- a/astropy/io/fits/fitsrec.py\n+++ b/astropy/io/fits/fitsrec.py\n@@ -1261,7 +1261,8 @@ class FITS_rec(np.recarray):\n \n         # Replace exponent separator in floating point numbers\n         if 'D' in format:\n-            output_field.replace(encode_ascii('E'), encode_ascii('D'))\n+            output_field[:] = np.char.replace(output_field, encode_ascii('E'),\n+                                              encode_ascii('D'))\n \n \n def _get_recarray_field(array, key):\ndiff --git a/astropy/io/fits/tests/test_table.py b/astropy/io/fits/tests/test_table.py\nindex 67fe21aa72..b998f7f780 100644\n--- a/astropy/io/fits/tests/test_table.py\n+++ b/astropy/io/fits/tests/test_table.py\n@@ -300,6 +300,35 @@ class TestTableFunctions(FitsTestCase):\n         hdul.close()\n         a.close()\n \n+    def test_ascii_table_double_exponent(self):\n+        \"\"\"\n+        Regression test for a bug where writing an ASCII table column with\n+        format 'D' (double precision with D exponent) failed to replace the\n+        'E' exponent character with 'D' in the output, because\n+        ``chararray.replace`` is not an in-place operation \u2014 it returns a new\n+        array whose result was being silently discarded.\n+        \"\"\"\n+        # Create a column of doubles using the ASCII 'D' (exponent) format\n+        c = fits.Column(name='col1', format='D25.17',\n+                        array=np.array([1.23456789e-99, 9.87654321e+99]))\n+        tbhdu = fits.TableHDU.from_columns([c])\n+        tbhdu.writeto(self.temp('ascii_d_exponent.fits'), overwrite=True)\n+\n+        # Read the raw bytes back and verify that 'D' exponents were written,\n+        # not 'E' exponents.\n+        with fits.open(self.temp('ascii_d_exponent.fits')) as hdul:\n+            raw = hdul[1].data.tobytes()\n+        assert b'D' in raw, (\n+            \"Expected 'D' exponent in ASCII table output, found: {!r}\".format(raw))\n+        assert b'E' not in raw, (\n+            \"Found unexpected 'E' exponent in ASCII table output: {!r}\".format(raw))\n+\n+        # Also verify the round-trip numeric values are preserved\n+        with fits.open(self.temp('ascii_d_exponent.fits')) as hdul:\n+            data = hdul[1].data\n+        np.testing.assert_allclose(data['col1'],\n+                                   [1.23456789e-99, 9.87654321e+99])\n+\n     def test_endianness(self):\n         x = np.ndarray((1,), dtype=object)\n         channelsIn = np.array([3], dtype='uint8')\n"}
{"instance_id": "astropy__astropy-7746", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/wcs/tests/test_wcs.py b/astropy/wcs/tests/test_wcs.py\nindex 85853e10e5..1dcbdc98fc 100644\n--- a/astropy/wcs/tests/test_wcs.py\n+++ b/astropy/wcs/tests/test_wcs.py\n@@ -1093,3 +1093,56 @@ def test_keyedsip():\n     assert isinstance( w.sip, wcs.Sip )\n     assert w.sip.crpix[0] == 2048\n     assert w.sip.crpix[1] == 1026\n+\n+\n+def test_empty_input_to_wcs_transforms():\n+    \"\"\"\n+    Test that passing empty lists/arrays to WCS transformation methods\n+    returns empty arrays rather than raising an error (issue #5997).\n+    \"\"\"\n+    w = wcs.WCS(naxis=2)\n+    w.wcs.crpix = [1, 1]\n+    w.wcs.cdelt = [1, 1]\n+    w.wcs.crval = [0, 0]\n+    w.wcs.ctype = ['RA---TAN', 'DEC--TAN']\n+    w.wcs.set()\n+\n+    # Test wcs_pix2world with list-of-arrays form (empty lists)\n+    result = w.wcs_pix2world([], [], 0)\n+    assert isinstance(result, list)\n+    assert len(result) == 2\n+    assert result[0].shape == (0,)\n+    assert result[1].shape == (0,)\n+\n+    # Test wcs_pix2world with single Nx2 array form (empty array)\n+    result = w.wcs_pix2world(np.empty((0, 2)), 0)\n+    assert result.shape == (0, 2)\n+\n+    # Test wcs_world2pix with list-of-arrays form (empty lists)\n+    result = w.wcs_world2pix([], [], 0)\n+    assert isinstance(result, list)\n+    assert len(result) == 2\n+    assert result[0].shape == (0,)\n+    assert result[1].shape == (0,)\n+\n+    # Test wcs_world2pix with single Nx2 array form (empty array)\n+    result = w.wcs_world2pix(np.empty((0, 2)), 0)\n+    assert result.shape == (0, 2)\n+\n+    # Test all_pix2world with list-of-arrays form (empty lists)\n+    result = w.all_pix2world([], [], 0)\n+    assert isinstance(result, list)\n+    assert len(result) == 2\n+    assert result[0].shape == (0,)\n+    assert result[1].shape == (0,)\n+\n+    # Test all_pix2world with single Nx2 array form (empty array)\n+    result = w.all_pix2world(np.empty((0, 2)), 0)\n+    assert result.shape == (0, 2)\n+\n+    # Test all_world2pix with empty arrays\n+    result = w.all_world2pix([], [], 0)\n+    assert isinstance(result, list)\n+    assert len(result) == 2\n+    assert result[0].shape == (0,)\n+    assert result[1].shape == (0,)\ndiff --git a/astropy/wcs/wcs.py b/astropy/wcs/wcs.py\nindex d3a06f2b31..89f6bfbe4c 100644\n--- a/astropy/wcs/wcs.py\n+++ b/astropy/wcs/wcs.py\n@@ -1220,6 +1220,13 @@ reduce these to 2 dimensions using the naxis kwarg.\n \n             xy = np.hstack([x.reshape((x.size, 1)) for x in axes])\n \n+            if xy.shape[0] == 0:\n+                if ra_dec_order and sky == 'output':\n+                    return (xy[:, 0].reshape(axes[0].shape),\n+                            xy[:, 1].reshape(axes[0].shape))\n+                return [xy[:, i].reshape(axes[0].shape)\n+                        for i in range(xy.shape[1])]\n+\n             if ra_dec_order and sky == 'input':\n                 xy = self._denormalize_sky(xy)\n             output = func(xy, origin)\n@@ -1235,6 +1242,10 @@ reduce these to 2 dimensions using the naxis kwarg.\n                 raise ValueError(\n                     \"When providing two arguments, the array must be \"\n                     \"of shape (N, {0})\".format(self.naxis))\n+            if 0 in xy.shape:\n+                if ra_dec_order and sky == 'output':\n+                    return self._normalize_sky(xy)\n+                return xy\n             if ra_dec_order and sky == 'input':\n                 xy = self._denormalize_sky(xy)\n             result = func(xy, origin)\n"}
{"instance_id": "django__django-10914", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/conf/global_settings.py b/django/conf/global_settings.py\nindex acee9887d2..bdeec80610 100644\n--- a/django/conf/global_settings.py\n+++ b/django/conf/global_settings.py\n@@ -304,7 +304,7 @@ FILE_UPLOAD_TEMP_DIR = None\n \n # The numeric mode to set newly-uploaded files to. The value should be a mode\n # you'd pass directly to os.chmod; see https://docs.python.org/library/os.html#files-and-directories.\n-FILE_UPLOAD_PERMISSIONS = None\n+FILE_UPLOAD_PERMISSIONS = 0o644\n \n # The numeric mode to assign to newly-created directories, when uploading files.\n # The value should be a mode as you'd pass to os.chmod;\ndiff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py\nindex 434869554c..ee878df332 100644\n--- a/tests/file_storage/tests.py\n+++ b/tests/file_storage/tests.py\n@@ -892,12 +892,11 @@ class FileStoragePermissions(unittest.TestCase):\n         actual_mode = os.stat(self.storage.path(name))[0] & 0o777\n         self.assertEqual(actual_mode, 0o654)\n \n-    @override_settings(FILE_UPLOAD_PERMISSIONS=None)\n     def test_file_upload_default_permissions(self):\n         self.storage = FileSystemStorage(self.storage_dir)\n         fname = self.storage.save(\"some_file\", ContentFile(\"data\"))\n         mode = os.stat(self.storage.path(fname))[0] & 0o777\n-        self.assertEqual(mode, 0o666 & ~self.umask)\n+        self.assertEqual(mode, 0o644)\n \n     @override_settings(FILE_UPLOAD_DIRECTORY_PERMISSIONS=0o765)\n     def test_file_upload_directory_permissions(self):\ndiff --git a/tests/test_utils/tests.py b/tests/test_utils/tests.py\nindex a1a113a26e..e953eb6609 100644\n--- a/tests/test_utils/tests.py\n+++ b/tests/test_utils/tests.py\n@@ -1099,7 +1099,7 @@ class OverrideSettingsTests(SimpleTestCase):\n         the file_permissions_mode attribute of\n         django.core.files.storage.default_storage.\n         \"\"\"\n-        self.assertIsNone(default_storage.file_permissions_mode)\n+        self.assertEqual(default_storage.file_permissions_mode, 0o644)\n         with self.settings(FILE_UPLOAD_PERMISSIONS=0o777):\n             self.assertEqual(default_storage.file_permissions_mode, 0o777)\n \n"}
{"instance_id": "django__django-10924", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 0c64748ccd..8abd317cd7 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -1663,7 +1663,8 @@ class FilePathField(Field):\n \n     def __init__(self, verbose_name=None, name=None, path='', match=None,\n                  recursive=False, allow_files=True, allow_folders=False, **kwargs):\n-        self.path, self.match, self.recursive = path, match, recursive\n+        self.path = path\n+        self.match, self.recursive = match, recursive\n         self.allow_files, self.allow_folders = allow_files, allow_folders\n         kwargs.setdefault('max_length', 100)\n         super().__init__(verbose_name, name, **kwargs)\n@@ -1709,7 +1710,7 @@ class FilePathField(Field):\n \n     def formfield(self, **kwargs):\n         return super().formfield(**{\n-            'path': self.path,\n+            'path': self.path() if callable(self.path) else self.path,\n             'match': self.match,\n             'recursive': self.recursive,\n             'form_class': forms.FilePathField,\ndiff --git a/django/forms/fields.py b/django/forms/fields.py\nindex a977256525..841c57d5a8 100644\n--- a/django/forms/fields.py\n+++ b/django/forms/fields.py\n@@ -1090,8 +1090,9 @@ class FilePathField(ChoiceField):\n         if self.match is not None:\n             self.match_re = re.compile(self.match)\n \n+        path = self.path() if callable(self.path) else self.path\n         if recursive:\n-            for root, dirs, files in sorted(os.walk(self.path)):\n+            for root, dirs, files in sorted(os.walk(path)):\n                 if self.allow_files:\n                     for f in sorted(files):\n                         if self.match is None or self.match_re.search(f):\n@@ -1106,7 +1107,7 @@ class FilePathField(ChoiceField):\n                             self.choices.append((f, f.replace(path, \"\", 1)))\n         else:\n             choices = []\n-            for f in os.scandir(self.path):\n+            for f in os.scandir(path):\n                 if f.name == '__pycache__':\n                     continue\n                 if (((self.allow_files and f.is_file()) or\ndiff --git a/tests/field_deconstruction/tests.py b/tests/field_deconstruction/tests.py\nindex 2cf1f93e22..d5876baef0 100644\n--- a/tests/field_deconstruction/tests.py\n+++ b/tests/field_deconstruction/tests.py\n@@ -186,6 +186,14 @@ class FieldDeconstructionTests(SimpleTestCase):\n         self.assertEqual(args, [])\n         self.assertEqual(kwargs, {\"recursive\": True, \"allow_folders\": True, \"max_length\": 123})\n \n+    def test_file_path_field_path_callable(self):\n+        path_callable = lambda: '/path/to/files/'\n+        field = models.FilePathField(path=path_callable)\n+        name, path, args, kwargs = field.deconstruct()\n+        self.assertEqual(path, \"django.db.models.FilePathField\")\n+        self.assertEqual(args, [])\n+        self.assertEqual(kwargs, {\"path\": path_callable})\n+\n     def test_float_field(self):\n         field = models.FloatField()\n         name, path, args, kwargs = field.deconstruct()\ndiff --git a/tests/forms_tests/field_tests/test_filepathfield.py b/tests/forms_tests/field_tests/test_filepathfield.py\nindex 44f6aff521..af93a46595 100644\n--- a/tests/forms_tests/field_tests/test_filepathfield.py\n+++ b/tests/forms_tests/field_tests/test_filepathfield.py\n@@ -97,3 +97,21 @@ class FilePathFieldTest(SimpleTestCase):\n             ('/filepathfield_test_dir/j', 'j'),\n             ('/filepathfield_test_dir/c/f', 'c/f'),\n         ])\n+\n+    def test_callable_path(self):\n+        f = FilePathField(path=lambda: self.path)\n+        expected = [\n+            ('/filepathfield_test_dir/README', 'README'),\n+        ] + self.expected_choices[:4]\n+        self.assertChoices(f, expected)\n+\n+    def test_callable_path_is_invoked_at_each_instantiation(self):\n+        path_values = [self.path, self.path]\n+        path_iter = iter(path_values)\n+        f1 = FilePathField(path=lambda: next(path_iter))\n+        f2 = FilePathField(path=lambda: self.path)\n+        expected = [\n+            ('/filepathfield_test_dir/README', 'README'),\n+        ] + self.expected_choices[:4]\n+        self.assertChoices(f1, expected)\n+        self.assertChoices(f2, expected)\n"}
{"instance_id": "django__django-11001", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py\nindex 7649c39262..57150f96dc 100644\n--- a/django/db/models/sql/compiler.py\n+++ b/django/db/models/sql/compiler.py\n@@ -32,7 +32,7 @@ class SQLCompiler:\n         self.select = None\n         self.annotation_col_map = None\n         self.klass_info = None\n-        self.ordering_parts = re.compile(r'(.*)\\s(ASC|DESC)(.*)')\n+        self.ordering_parts = re.compile(r'(.*)\\s(ASC|DESC)(.*)', re.DOTALL)\n         self._meta_ordering = None\n \n     def setup_query(self):\ndiff --git a/tests/ordering/tests.py b/tests/ordering/tests.py\nindex 16e5cc9b2d..86104d5c92 100644\n--- a/tests/ordering/tests.py\n+++ b/tests/ordering/tests.py\n@@ -2,6 +2,7 @@ from datetime import datetime\n from operator import attrgetter\n \n from django.db.models import Count, DateTimeField, F, Max, OuterRef, Subquery\n+from django.db.models.expressions import RawSQL\n from django.db.models.functions import Upper\n from django.test import TestCase\n from django.utils.deprecation import RemovedInDjango31Warning\n@@ -412,3 +413,36 @@ class OrderingTests(TestCase):\n         )\n         with self.assertRaisesMessage(RemovedInDjango31Warning, msg):\n             list(Article.objects.values('author').annotate(Count('headline')))\n+\n+    def test_order_by_multiline_rawsql_duplicates_not_removed(self):\n+        \"\"\"\n+        Multiline RawSQL expressions used in order_by() that share identical\n+        trailing lines must not be incorrectly identified as duplicates and\n+        dropped (#28712).\n+        \"\"\"\n+        # Two distinct multiline RawSQL expressions whose last lines are the\n+        # same (both end with \"else null end\"). Without the fix, the second\n+        # expression was mistakenly considered a duplicate of the first and\n+        # silently omitted from the ORDER BY clause.\n+        raw1 = RawSQL(\n+            '''\n+            case when headline = 'Article 1'\n+                 then 1 else 0 end''',\n+            [],\n+        )\n+        raw2 = RawSQL(\n+            '''\n+            case when headline = 'Article 2'\n+                 then 1 else 0 end''',\n+            [],\n+        )\n+        qs = Article.objects.order_by(raw1.desc(), raw2.asc())\n+        # Retrieve the compiled ORDER BY SQL.  It must contain both expressions.\n+        compiler = qs.query.get_compiler(using='default')\n+        order_by_clauses = compiler.get_order_by()\n+        # Both expressions must survive de-duplication.\n+        self.assertEqual(\n+            len(order_by_clauses), 2,\n+            \"Expected 2 ORDER BY clauses but got %d; the second multiline \"\n+            \"RawSQL was incorrectly removed as a duplicate.\" % len(order_by_clauses),\n+        )\n"}
{"instance_id": "django__django-11019", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/forms/widgets.py b/django/forms/widgets.py\nindex 02aa32b207..aa3eff678d 100644\n--- a/django/forms/widgets.py\n+++ b/django/forms/widgets.py\n@@ -59,22 +59,19 @@ class Media:\n \n     @property\n     def _css(self):\n-        css = self._css_lists[0]\n-        # filter(None, ...) avoids calling merge with empty dicts.\n-        for obj in filter(None, self._css_lists[1:]):\n-            css = {\n-                medium: self.merge(css.get(medium, []), obj.get(medium, []))\n-                for medium in css.keys() | obj.keys()\n-            }\n-        return css\n+        css = {}\n+        for obj in self._css_lists:\n+            for medium, sublist in obj.items():\n+                css.setdefault(medium, [])\n+                css[medium] = css[medium] + [sublist]\n+        return {\n+            medium: self.merge(*lists)\n+            for medium, lists in css.items()\n+        }\n \n     @property\n     def _js(self):\n-        js = self._js_lists[0]\n-        # filter(None, ...) avoids calling merge() with empty lists.\n-        for obj in filter(None, self._js_lists[1:]):\n-            js = self.merge(js, obj)\n-        return js\n+        return self.merge(*self._js_lists)\n \n     def render(self):\n         return mark_safe('\\n'.join(chain.from_iterable(getattr(self, 'render_' + name)() for name in MEDIA_TYPES)))\n@@ -115,39 +112,85 @@ class Media:\n         raise KeyError('Unknown media type \"%s\"' % name)\n \n     @staticmethod\n-    def merge(list_1, list_2):\n+    def merge(*lists):\n         \"\"\"\n-        Merge two lists while trying to keep the relative order of the elements.\n-        Warn if the lists have the same two elements in a different relative\n-        order.\n+        Merge multiple lists while trying to keep the relative order of the\n+        elements. Warn if the lists have the same two elements in a different\n+        relative order.\n \n         For static assets it can be important to have them included in the DOM\n         in a certain order. In JavaScript you may not be able to reference a\n         global or in CSS you might want to override a style.\n         \"\"\"\n-        # Start with a copy of list_1.\n-        combined_list = list(list_1)\n-        last_insert_index = len(list_1)\n-        # Walk list_2 in reverse, inserting each element into combined_list if\n-        # it doesn't already exist.\n-        for path in reversed(list_2):\n-            try:\n-                # Does path already exist in the list?\n-                index = combined_list.index(path)\n-            except ValueError:\n-                # Add path to combined_list since it doesn't exist.\n-                combined_list.insert(last_insert_index, path)\n-            else:\n-                if index > last_insert_index:\n-                    warnings.warn(\n-                        'Detected duplicate Media files in an opposite order:\\n'\n-                        '%s\\n%s' % (combined_list[last_insert_index], combined_list[index]),\n-                        MediaOrderConflictWarning,\n-                    )\n-                # path already exists in the list. Update last_insert_index so\n-                # that the following elements are inserted in front of this one.\n-                last_insert_index = index\n-        return combined_list\n+        # Collect all unique items in first-seen order across all lists.\n+        all_items = []\n+        item_set = set()\n+        for lst in lists:\n+            for item in lst:\n+                if item not in item_set:\n+                    all_items.append(item)\n+                    item_set.add(item)\n+\n+        if not all_items:\n+            return []\n+\n+        # Build a constraint graph: constraints[a] is the set of items that\n+        # must come after 'a'. Constraints are derived only from within each\n+        # individual list, so merging independent lists never creates false\n+        # ordering constraints.\n+        constraints = {item: set() for item in all_items}\n+        # Track pairs already warned about to avoid duplicate warnings.\n+        conflict_pairs = set()\n+\n+        for lst in lists:\n+            for i in range(len(lst)):\n+                for j in range(i + 1, len(lst)):\n+                    a, b = lst[i], lst[j]\n+                    # Skip duplicate items within the same list.\n+                    if a == b:\n+                        continue\n+                    # If 'b must come before a' is already a constraint, then\n+                    # 'a before b' (from this list) is a genuine conflict.\n+                    if a in constraints.get(b, set()):\n+                        key = (b, a)\n+                        if key not in conflict_pairs:\n+                            conflict_pairs.add(key)\n+                            warnings.warn(\n+                                'Detected duplicate Media files in an opposite order:\\n'\n+                                '%s\\n%s' % (b, a),\n+                                MediaOrderConflictWarning,\n+                            )\n+                    else:\n+                        constraints[a].add(b)\n+\n+        # Topological sort (Kahn's algorithm) with first-seen order as the\n+        # tie-breaker so that independent items preserve their relative order.\n+        in_degree = {item: 0 for item in all_items}\n+        for item in all_items:\n+            for dep in constraints[item]:\n+                in_degree[dep] += 1\n+\n+        # Map each item to its position in the first-seen order for stable sorting.\n+        position = {item: i for i, item in enumerate(all_items)}\n+        available = sorted(\n+            [item for item in all_items if in_degree[item] == 0],\n+            key=lambda x: position[x],\n+        )\n+        result = []\n+        while available:\n+            item = available.pop(0)\n+            result.append(item)\n+            newly_available = []\n+            for dep in constraints[item]:\n+                in_degree[dep] -= 1\n+                if in_degree[dep] == 0:\n+                    newly_available.append(dep)\n+            # Re-sort to maintain first-seen order among newly available items.\n+            available = sorted(\n+                available + newly_available,\n+                key=lambda x: position[x],\n+            )\n+        return result\n \n     def __add__(self, other):\n         combined = Media()\ndiff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py\nindex 8cb484a15e..c8dc41a963 100644\n--- a/tests/forms_tests/tests/test_media.py\n+++ b/tests/forms_tests/tests/test_media.py\n@@ -550,14 +550,31 @@ class FormsMediaTestCase(SimpleTestCase):\n         widget1 = Media(js=['custom_widget.js'])\n         widget2 = Media(js=['jquery.js', 'uses_jquery.js'])\n         form_media = widget1 + widget2\n-        # The relative ordering of custom_widget.js and jquery.js has been\n-        # established (but without a real need to).\n         self.assertEqual(form_media._js, ['custom_widget.js', 'jquery.js', 'uses_jquery.js'])\n         # The inline also uses custom_widget.js. This time, it's at the end.\n         inline_media = Media(js=['jquery.js', 'also_jquery.js']) + Media(js=['custom_widget.js'])\n         merged = form_media + inline_media\n         self.assertEqual(merged._js, ['custom_widget.js', 'jquery.js', 'uses_jquery.js', 'also_jquery.js'])\n \n+    def test_merge_js_three_way_no_false_conflict(self):\n+        \"\"\"\n+        Merging 3 or more media objects doesn't raise unnecessary\n+        MediaOrderConflictWarnings when the relative ordering of independent\n+        files hasn't been specified.\n+        \"\"\"\n+        # text-editor-extras.js depends on text-editor.js; color-picker.js is\n+        # independent of both. No ordering constraint exists between\n+        # color-picker.js and text-editor.js.\n+        widget1 = Media(js=['color-picker.js'])\n+        widget2 = Media(js=['text-editor.js'])\n+        widget3 = Media(js=['text-editor.js', 'text-editor-extras.js', 'color-picker.js'])\n+        import warnings\n+        with warnings.catch_warnings(record=True) as caught:\n+            warnings.simplefilter('always')\n+            merged = (widget1 + widget2 + widget3)._js\n+        self.assertEqual(merged, ['text-editor.js', 'text-editor-extras.js', 'color-picker.js'])\n+        self.assertEqual(caught, [])\n+\n     def test_merge_css_three_way(self):\n         widget1 = Media(css={'screen': ['a.css']})\n         widget2 = Media(css={'screen': ['b.css']})\n"}
{"instance_id": "django__django-11039", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/core/management/commands/sqlmigrate.py b/django/core/management/commands/sqlmigrate.py\nindex f0b663222a..35ac1840a7 100644\n--- a/django/core/management/commands/sqlmigrate.py\n+++ b/django/core/management/commands/sqlmigrate.py\n@@ -55,8 +55,9 @@ class Command(BaseCommand):\n                 migration_name, app_label))\n         targets = [(app_label, migration.name)]\n \n-        # Show begin/end around output only for atomic migrations\n-        self.output_transaction = migration.atomic\n+        # Show begin/end around output only if the migration is atomic and\n+        # the database supports transactional DDL.\n+        self.output_transaction = migration.atomic and connection.features.can_rollback_ddl\n \n         # Make a plan that represents just the requested migrations and show SQL\n         # for it\ndiff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py\nindex 0e8fa9fdd1..d41ed6915e 100644\n--- a/tests/migrations/test_commands.py\n+++ b/tests/migrations/test_commands.py\n@@ -616,6 +616,21 @@ class MigrateTests(MigrationTestBase):\n             self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)\n         self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)\n \n+    @override_settings(MIGRATION_MODULES={\"migrations\": \"migrations.test_migrations\"})\n+    def test_sqlmigrate_for_non_transactional_database(self):\n+        \"\"\"\n+        Transaction wrappers aren't shown for databases that do not support\n+        transactional DDL.\n+        \"\"\"\n+        out = io.StringIO()\n+        with mock.patch.object(connection.features, 'can_rollback_ddl', False):\n+            call_command(\"sqlmigrate\", \"migrations\", \"0001\", stdout=out)\n+        output = out.getvalue().lower()\n+        queries = [q.strip() for q in output.splitlines()]\n+        if connection.ops.start_transaction_sql():\n+            self.assertNotIn(connection.ops.start_transaction_sql().lower(), queries)\n+        self.assertNotIn(connection.ops.end_transaction_sql().lower(), queries)\n+\n     @override_settings(\n         INSTALLED_APPS=[\n             \"migrations.migrations_test_apps.migrated_app\",\n"}
{"instance_id": "django__django-11049", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/conf/locale/en/LC_MESSAGES/django.po b/django/conf/locale/en/LC_MESSAGES/django.po\nindex 2c52175822..e95f84be75 100644\n--- a/django/conf/locale/en/LC_MESSAGES/django.po\n+++ b/django/conf/locale/en/LC_MESSAGES/django.po\n@@ -645,7 +645,7 @@ msgstr \"\"\n #: db/models/fields/__init__.py:1587\n #, python-format\n msgid \"\"\n-\"'%(value)s' value has an invalid format. It must be in [DD] [HH:[MM:]]ss[.\"\n+\"'%(value)s' value has an invalid format. It must be in [DD] [[HH:]MM:]ss[.\"\n \"uuuuuu] format.\"\n msgstr \"\"\n \ndiff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex f32ce64629..71005490f3 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -1587,7 +1587,7 @@ class DurationField(Field):\n     empty_strings_allowed = False\n     default_error_messages = {\n         'invalid': _(\"'%(value)s' value has an invalid format. It must be in \"\n-                     \"[DD] [HH:[MM:]]ss[.uuuuuu] format.\")\n+                     \"[DD] [[HH:]MM:]ss[.uuuuuu] format.\")\n     }\n     description = _(\"Duration\")\n \ndiff --git a/tests/model_fields/test_durationfield.py b/tests/model_fields/test_durationfield.py\nindex b73994f86a..f1c82ab8bd 100644\n--- a/tests/model_fields/test_durationfield.py\n+++ b/tests/model_fields/test_durationfield.py\n@@ -75,7 +75,7 @@ class TestValidation(SimpleTestCase):\n         self.assertEqual(\n             cm.exception.message % cm.exception.params,\n             \"'not a datetime' value has an invalid format. \"\n-            \"It must be in [DD] [HH:[MM:]]ss[.uuuuuu] format.\"\n+            \"It must be in [DD] [[HH:]MM:]ss[.uuuuuu] format.\"\n         )\n \n \n"}
{"instance_id": "django__django-11099", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/contrib/auth/validators.py b/django/contrib/auth/validators.py\nindex b4878cfd45..1304f20a60 100644\n--- a/django/contrib/auth/validators.py\n+++ b/django/contrib/auth/validators.py\n@@ -7,7 +7,7 @@ from django.utils.translation import gettext_lazy as _\n \n @deconstructible\n class ASCIIUsernameValidator(validators.RegexValidator):\n-    regex = r'^[\\w.@+-]+$'\n+    regex = r'\\A[\\w.@+-]+\\Z'\n     message = _(\n         'Enter a valid username. This value may contain only English letters, '\n         'numbers, and @/./+/-/_ characters.'\n@@ -17,7 +17,7 @@ class ASCIIUsernameValidator(validators.RegexValidator):\n \n @deconstructible\n class UnicodeUsernameValidator(validators.RegexValidator):\n-    regex = r'^[\\w.@+-]+$'\n+    regex = r'\\A[\\w.@+-]+\\Z'\n     message = _(\n         'Enter a valid username. This value may contain only letters, '\n         'numbers, and @/./+/-/_ characters.'\ndiff --git a/tests/auth_tests/test_validators.py b/tests/auth_tests/test_validators.py\nindex 1c2c6b4aff..fcc18ed9e7 100644\n--- a/tests/auth_tests/test_validators.py\n+++ b/tests/auth_tests/test_validators.py\n@@ -237,7 +237,7 @@ class UsernameValidatorsTests(SimpleTestCase):\n         invalid_usernames = [\n             \"o'connell\", \"\u0639\u0628\u062f \u0627\u0644\",\n             \"zerowidth\\u200Bspace\", \"nonbreaking\\u00A0space\",\n-            \"en\\u2013dash\",\n+            \"en\\u2013dash\", \"joe\\n\",\n         ]\n         v = validators.UnicodeUsernameValidator()\n         for valid in valid_usernames:\n@@ -250,7 +250,7 @@ class UsernameValidatorsTests(SimpleTestCase):\n \n     def test_ascii_validator(self):\n         valid_usernames = ['glenn', 'GLEnN', 'jean-marc']\n-        invalid_usernames = [\"o'connell\", '\u00c9ric', 'jean marc', \"\u0623\u062d\u0645\u062f\"]\n+        invalid_usernames = [\"o'connell\", '\u00c9ric', 'jean marc', \"\u0623\u062d\u0645\u062f\", \"glenn\\n\"]\n         v = validators.ASCIIUsernameValidator()\n         for valid in valid_usernames:\n             with self.subTest(valid=valid):\n"}
{"instance_id": "django__django-11133", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex 6a84e193ba..27c1d89d84 100644\n--- a/django/http/response.py\n+++ b/django/http/response.py\n@@ -231,6 +231,8 @@ class HttpResponseBase:\n         # - when self._charset != 'utf-8' it re-encodes the content\n         if isinstance(value, bytes):\n             return bytes(value)\n+        if isinstance(value, memoryview):\n+            return bytes(value)\n         if isinstance(value, str):\n             return bytes(value.encode(self.charset))\n         # Handle non-string types.\n@@ -309,7 +311,7 @@ class HttpResponse(HttpResponseBase):\n     @content.setter\n     def content(self, value):\n         # Consume iterators upon assignment to allow repeated iteration.\n-        if hasattr(value, '__iter__') and not isinstance(value, (bytes, str)):\n+        if hasattr(value, '__iter__') and not isinstance(value, (bytes, memoryview, str)):\n             content = b''.join(self.make_bytes(chunk) for chunk in value)\n             if hasattr(value, 'close'):\n                 try:\ndiff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py\nindex e6c6297898..3bb52c9217 100644\n--- a/tests/httpwrappers/tests.py\n+++ b/tests/httpwrappers/tests.py\n@@ -366,6 +366,15 @@ class HttpResponseTests(unittest.TestCase):\n         r.content = 12345\n         self.assertEqual(r.content, b'12345')\n \n+    def test_memoryview_content(self):\n+        r = HttpResponse(memoryview(b'My Content'))\n+        self.assertEqual(r.content, b'My Content')\n+\n+        # Test via the content property setter.\n+        r = HttpResponse()\n+        r.content = memoryview(b'My Content')\n+        self.assertEqual(r.content, b'My Content')\n+\n     def test_iter_content(self):\n         r = HttpResponse(['abc', 'def', 'ghi'])\n         self.assertEqual(r.content, b'abcdefghi')\n"}
{"instance_id": "django__django-11179", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/db/models/deletion.py b/django/db/models/deletion.py\nindex 92fe4affb9..3a462f1c4c 100644\n--- a/django/db/models/deletion.py\n+++ b/django/db/models/deletion.py\n@@ -277,6 +277,7 @@ class Collector:\n             if self.can_fast_delete(instance):\n                 with transaction.mark_for_rollback_on_error():\n                     count = sql.DeleteQuery(model).delete_batch([instance.pk], self.using)\n+                setattr(instance, model._meta.pk.attname, None)\n                 return count, {model._meta.label: count}\n \n         with transaction.atomic(using=self.using, savepoint=False):\ndiff --git a/tests/delete/tests.py b/tests/delete/tests.py\nindex 55eeb226ea..03a998d473 100644\n--- a/tests/delete/tests.py\n+++ b/tests/delete/tests.py\n@@ -522,3 +522,14 @@ class FastDeleteTests(TestCase):\n                 User.objects.filter(avatar__desc='missing').delete(),\n                 (0, {'delete.User': 0})\n             )\n+\n+    def test_fast_delete_instance_set_pk_none(self):\n+        \"\"\"\n+        fast_delete path for a single object with no dependencies must set\n+        the instance's PK to None after deletion, consistent with the\n+        regular delete() path.\n+        \"\"\"\n+        u = User.objects.create()\n+        # Verify this goes through the fast-delete path (single query).\n+        self.assertNumQueries(1, u.delete)\n+        self.assertIsNone(u.pk)\n"}
{"instance_id": "django__django-11283", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/contrib/auth/migrations/0011_update_proxy_permissions.py b/django/contrib/auth/migrations/0011_update_proxy_permissions.py\nindex 0e66649695..9ff5811e12 100644\n--- a/django/contrib/auth/migrations/0011_update_proxy_permissions.py\n+++ b/django/contrib/auth/migrations/0011_update_proxy_permissions.py\n@@ -24,9 +24,22 @@ def update_proxy_model_permissions(apps, schema_editor, reverse=False):\n         proxy_content_type = ContentType.objects.get_for_model(Model, for_concrete_model=False)\n         old_content_type = proxy_content_type if reverse else concrete_content_type\n         new_content_type = concrete_content_type if reverse else proxy_content_type\n+        # Avoid updating permissions that already exist under the target\n+        # content type \u2014 this can happen when a model was originally concrete\n+        # and later re-created as a proxy. In that case the target content type\n+        # already has those permissions, so updating would violate the unique\n+        # constraint on (content_type_id, codename).\n+        existing_target_codenames = set(\n+            Permission.objects.filter(\n+                permissions_query,\n+                content_type=new_content_type,\n+            ).values_list('codename', flat=True)\n+        )\n         Permission.objects.filter(\n             permissions_query,\n             content_type=old_content_type,\n+        ).exclude(\n+            codename__in=existing_target_codenames,\n         ).update(content_type=new_content_type)\n \n \ndiff --git a/tests/auth_tests/test_migrations.py b/tests/auth_tests/test_migrations.py\nindex 5ff2f6b4b3..402bceb9fc 100644\n--- a/tests/auth_tests/test_migrations.py\n+++ b/tests/auth_tests/test_migrations.py\n@@ -10,6 +10,124 @@ from .models import Proxy, UserProxy\n update_proxy_permissions = import_module('django.contrib.auth.migrations.0011_update_proxy_permissions')\n \n \n+class ProxyModelWithSameAppLabelAndExistingPermissionsTests(TestCase):\n+    \"\"\"\n+    Test that the migration does not fail with an IntegrityError when a model\n+    was previously concrete and was re-created as a proxy. In that case the\n+    proxy ContentType already exists and already has permissions, so the\n+    migration must not attempt to duplicate them.\n+    \"\"\"\n+    available_apps = [\n+        'auth_tests',\n+        'django.contrib.auth',\n+        'django.contrib.contenttypes',\n+    ]\n+\n+    def setUp(self):\n+        \"\"\"\n+        Simulate a model that started as concrete (permissions stored under\n+        the concrete ContentType) and was later re-created as a proxy.  Both\n+        the concrete *and* the proxy ContentType therefore carry the same\n+        permissions \u2014 the state that triggers the IntegrityError.\n+        \"\"\"\n+        Permission.objects.all().delete()\n+        self.concrete_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=True)\n+        self.proxy_content_type = ContentType.objects.get_for_model(Proxy, for_concrete_model=False)\n+        # Permissions already exist under the proxy content type (the model\n+        # was once concrete and had its own ContentType).\n+        self.default_permission = Permission.objects.create(\n+            content_type=self.proxy_content_type,\n+            codename='add_proxy',\n+            name='Can add proxy',\n+        )\n+        self.custom_permission = Permission.objects.create(\n+            content_type=self.proxy_content_type,\n+            codename='display_proxys',\n+            name='May display proxys information',\n+        )\n+        # Duplicate entries under the concrete ContentType (old state left\n+        # over from before the model was turned into a proxy).\n+        Permission.objects.create(\n+            content_type=self.concrete_content_type,\n+            codename='add_proxy',\n+            name='Can add proxy',\n+        )\n+        Permission.objects.create(\n+            content_type=self.concrete_content_type,\n+            codename='display_proxys',\n+            name='May display proxys information',\n+        )\n+\n+    def test_does_not_raise_integrity_error(self):\n+        \"\"\"\n+        Running the migration should not raise an IntegrityError even when\n+        duplicate permissions already exist under the proxy ContentType.\n+        \"\"\"\n+        # This must not raise django.db.utils.IntegrityError.\n+        update_proxy_permissions.update_proxy_model_permissions(apps, None)\n+\n+    def test_existing_proxy_permissions_are_kept(self):\n+        \"\"\"\n+        After the migration the permissions originally under the proxy\n+        ContentType are still present.\n+        \"\"\"\n+        update_proxy_permissions.update_proxy_model_permissions(apps, None)\n+        self.default_permission.refresh_from_db()\n+        self.assertEqual(self.default_permission.content_type, self.proxy_content_type)\n+        self.custom_permission.refresh_from_db()\n+        self.assertEqual(self.custom_permission.content_type, self.proxy_content_type)\n+\n+\n+class ProxyModelWithDifferentAppLabelAndExistingPermissionsTests(TestCase):\n+    \"\"\"\n+    Same as ProxyModelWithSameAppLabelAndExistingPermissionsTests but for a\n+    proxy model whose app_label differs from that of the concrete parent\n+    (i.e. UserProxy / auth_tests vs User / auth).\n+    \"\"\"\n+    available_apps = [\n+        'auth_tests',\n+        'django.contrib.auth',\n+        'django.contrib.contenttypes',\n+    ]\n+\n+    def setUp(self):\n+        Permission.objects.all().delete()\n+        self.concrete_content_type = ContentType.objects.get_for_model(UserProxy, for_concrete_model=True)\n+        self.proxy_content_type = ContentType.objects.get_for_model(UserProxy, for_concrete_model=False)\n+        # Permissions already exist under the proxy ContentType.\n+        self.default_permission = Permission.objects.create(\n+            content_type=self.proxy_content_type,\n+            codename='add_userproxy',\n+            name='Can add userproxy',\n+        )\n+        self.custom_permission = Permission.objects.create(\n+            content_type=self.proxy_content_type,\n+            codename='use_different_app_label',\n+            name='May use a different app label',\n+        )\n+        # Duplicate entries under the concrete ContentType.\n+        Permission.objects.create(\n+            content_type=self.concrete_content_type,\n+            codename='add_userproxy',\n+            name='Can add userproxy',\n+        )\n+        Permission.objects.create(\n+            content_type=self.concrete_content_type,\n+            codename='use_different_app_label',\n+            name='May use a different app label',\n+        )\n+\n+    def test_does_not_raise_integrity_error(self):\n+        update_proxy_permissions.update_proxy_model_permissions(apps, None)\n+\n+    def test_existing_proxy_permissions_are_kept(self):\n+        update_proxy_permissions.update_proxy_model_permissions(apps, None)\n+        self.default_permission.refresh_from_db()\n+        self.assertEqual(self.default_permission.content_type, self.proxy_content_type)\n+        self.custom_permission.refresh_from_db()\n+        self.assertEqual(self.custom_permission.content_type, self.proxy_content_type)\n+\n+\n class ProxyModelWithDifferentAppLabelTests(TestCase):\n     available_apps = [\n         'auth_tests',\n"}
{"instance_id": "django__django-11422", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\nindex 7ca0d68fae..e2f9a2f136 100644\n--- a/django/utils/autoreload.py\n+++ b/django/utils/autoreload.py\n@@ -114,9 +114,16 @@ def iter_modules_and_files(modules, extra_files):\n         # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects\n         # are added to sys.modules, however they are types not modules and so\n         # cause issues here.\n-        if not isinstance(module, ModuleType) or getattr(module, '__spec__', None) is None:\n+        if not isinstance(module, ModuleType):\n+            continue\n+        spec = getattr(module, '__spec__', None)\n+        if spec is None:\n+            # __spec__ is None for the __main__ module when run as a script\n+            # (e.g. `python manage.py`). In this case, use __file__ instead\n+            # so that changes to the script itself trigger a reload.\n+            if getattr(module, '__file__', None):\n+                sys_file_paths.append(module.__file__)\n             continue\n-        spec = module.__spec__\n         # Modules could be loaded from places without a concrete location. If\n         # this is the case, skip them.\n         if spec.has_location:\ndiff --git a/tests/utils_tests/test_autoreload.py b/tests/utils_tests/test_autoreload.py\nindex 42bcd0a50b..16dce3dd9d 100644\n--- a/tests/utils_tests/test_autoreload.py\n+++ b/tests/utils_tests/test_autoreload.py\n@@ -132,6 +132,22 @@ class TestIterModulesAndFiles(SimpleTestCase):\n         del module.__spec__\n         self.assertEqual(autoreload.iter_modules_and_files((module,), frozenset()), frozenset())\n \n+    def test_main_module_is_resolved(self):\n+        \"\"\"\n+        If __main__ is loaded from a script (e.g. `python manage.py`), its\n+        __spec__ is None but its __file__ is set. It should be included in\n+        the watched files so that changes to it trigger a reload.\n+        \"\"\"\n+        main_module = types.ModuleType('__main__')\n+        main_module.__spec__ = None\n+        main_module.__file__ = self.temporary_file('manage.py')\n+        main_module.__file__.touch()\n+        self.clear_autoreload_caches()\n+        self.assertIn(\n+            main_module.__file__.resolve(),\n+            autoreload.iter_modules_and_files((main_module,), frozenset()),\n+        )\n+\n \n class TestCommonRoots(SimpleTestCase):\n     def test_common_roots(self):\n"}
{"instance_id": "django__django-11564", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/core/files/storage.py b/django/core/files/storage.py\nindex 4c27fce605..4c6c07b8b9 100644\n--- a/django/core/files/storage.py\n+++ b/django/core/files/storage.py\n@@ -332,7 +332,14 @@ class FileSystemStorage(Storage):\n         url = filepath_to_uri(name)\n         if url is not None:\n             url = url.lstrip('/')\n-        return urljoin(self.base_url, url)\n+        url = urljoin(self.base_url, url)\n+        if url.startswith('/') and not url.startswith(('http://', 'https://')):\n+            # Avoid circular import by deferring the import of get_script_prefix.\n+            from django.urls import get_script_prefix\n+            script_prefix = get_script_prefix()\n+            if script_prefix and not url.startswith(script_prefix):\n+                url = script_prefix.rstrip('/') + url\n+        return url\n \n     def _datetime_from_timestamp(self, ts):\n         \"\"\"\ndiff --git a/django/templatetags/static.py b/django/templatetags/static.py\nindex 39712aaba0..1fdc9dcb42 100644\n--- a/django/templatetags/static.py\n+++ b/django/templatetags/static.py\n@@ -40,10 +40,15 @@ class PrefixNode(template.Node):\n     def handle_simple(cls, name):\n         try:\n             from django.conf import settings\n+            from django.urls import get_script_prefix\n         except ImportError:\n             prefix = ''\n         else:\n             prefix = iri_to_uri(getattr(settings, name, ''))\n+            script_prefix = get_script_prefix()\n+            if script_prefix and prefix.startswith('/') and not prefix.startswith(('http://', 'https://')):\n+                if not prefix.startswith(script_prefix):\n+                    prefix = script_prefix.rstrip('/') + prefix\n         return prefix\n \n     def render(self, context):\ndiff --git a/tests/file_storage/tests.py b/tests/file_storage/tests.py\nindex 1c4176014c..ed9d71d6cd 100644\n--- a/tests/file_storage/tests.py\n+++ b/tests/file_storage/tests.py\n@@ -21,7 +21,7 @@ from django.test import (\n     LiveServerTestCase, SimpleTestCase, TestCase, override_settings,\n )\n from django.test.utils import requires_tz_support\n-from django.urls import NoReverseMatch, reverse_lazy\n+from django.urls import NoReverseMatch, clear_script_prefix, reverse_lazy, set_script_prefix\n from django.utils import timezone\n \n from .models import Storage, temp_storage, temp_storage_location\n@@ -359,6 +359,56 @@ class FileStorageTests(SimpleTestCase):\n             '%s%s' % (storage.base_url, 'test.file')\n         )\n \n+    def test_file_url_script_prefix(self):\n+        \"\"\"\n+        FileSystemStorage.url() prepends SCRIPT_NAME to the URL when the\n+        application is deployed on a sub-path.\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            self.assertEqual(\n+                self.storage.url('test.file'),\n+                '/subpath/test_media_url/test.file',\n+            )\n+        finally:\n+            clear_script_prefix()\n+\n+    def test_file_url_script_prefix_not_double_prefixed(self):\n+        \"\"\"\n+        FileSystemStorage.url() does not prepend SCRIPT_NAME when the\n+        base_url already starts with it.\n+        \"\"\"\n+        storage = self.storage_class(\n+            location=self.temp_dir,\n+            base_url='/subpath/test_media_url/',\n+        )\n+        set_script_prefix('/subpath/')\n+        try:\n+            self.assertEqual(\n+                storage.url('test.file'),\n+                '/subpath/test_media_url/test.file',\n+            )\n+        finally:\n+            clear_script_prefix()\n+\n+    def test_file_url_absolute_base_url(self):\n+        \"\"\"\n+        FileSystemStorage.url() does not prepend SCRIPT_NAME when base_url is\n+        an absolute URL (e.g. a CDN).\n+        \"\"\"\n+        storage = self.storage_class(\n+            location=self.temp_dir,\n+            base_url='https://cdn.example.com/media/',\n+        )\n+        set_script_prefix('/subpath/')\n+        try:\n+            self.assertEqual(\n+                storage.url('test.file'),\n+                'https://cdn.example.com/media/test.file',\n+            )\n+        finally:\n+            clear_script_prefix()\n+\n     def test_listdir(self):\n         \"\"\"\n         File storage returns a tuple containing directories and files.\ndiff --git a/tests/staticfiles_tests/test_templatetags.py b/tests/staticfiles_tests/test_templatetags.py\nindex cd3f7d4bfa..5b1b8ab15d 100644\n--- a/tests/staticfiles_tests/test_templatetags.py\n+++ b/tests/staticfiles_tests/test_templatetags.py\n@@ -1,4 +1,5 @@\n from django.test import override_settings\n+from django.urls import set_script_prefix, clear_script_prefix\n \n from .cases import StaticFilesTestCase\n \n@@ -19,3 +20,42 @@ class TestTemplateTag(StaticFilesTestCase):\n         \"\"\"\n         self.assertStaticRenders('a.html', 'a.html?a=b&amp;c=d')\n         self.assertStaticRenders('a.html', 'a.html?a=b&c=d', autoescape=False)\n+\n+    def test_template_tag_script_prefix(self):\n+        \"\"\"\n+        {% static %} prepends SCRIPT_NAME to the URL when the app is deployed\n+        on a sub-path.\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            self.assertStaticRenders(\"does/not/exist.png\", \"/subpath/static/does/not/exist.png\")\n+            self.assertStaticRenders(\"testfile.txt\", \"/subpath/static/testfile.txt\")\n+        finally:\n+            clear_script_prefix()\n+\n+    def test_template_tag_script_prefix_not_double_prefixed(self):\n+        \"\"\"\n+        {% static %} does not double-prepend SCRIPT_NAME when STATIC_URL\n+        already starts with it.\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            with self.settings(STATIC_URL='/subpath/static/'):\n+                self.assertStaticRenders(\"testfile.txt\", \"/subpath/static/testfile.txt\")\n+        finally:\n+            clear_script_prefix()\n+\n+    def test_template_tag_absolute_static_url(self):\n+        \"\"\"\n+        {% static %} does not prepend SCRIPT_NAME when STATIC_URL is an\n+        absolute URL (e.g. CDN).\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            with self.settings(STATIC_URL='https://cdn.example.com/static/'):\n+                self.assertStaticRenders(\n+                    \"testfile.txt\",\n+                    \"https://cdn.example.com/static/testfile.txt\",\n+                )\n+        finally:\n+            clear_script_prefix()\ndiff --git a/tests/template_tests/syntax_tests/test_static.py b/tests/template_tests/syntax_tests/test_static.py\nindex 00f8cdbc11..7bb8b4d3aa 100644\n--- a/tests/template_tests/syntax_tests/test_static.py\n+++ b/tests/template_tests/syntax_tests/test_static.py\n@@ -3,6 +3,7 @@ from urllib.parse import urljoin\n from django.conf import settings\n from django.template import TemplateSyntaxError\n from django.test import SimpleTestCase, override_settings\n+from django.urls import clear_script_prefix, set_script_prefix\n \n from ..utils import setup\n \n@@ -69,3 +70,56 @@ class StaticTagTests(SimpleTestCase):\n         msg = \"'static' takes at least one argument (path to file)\"\n         with self.assertRaisesMessage(TemplateSyntaxError, msg):\n             self.engine.render_to_string('t')\n+\n+    @setup({'t': '{% load static %}{% get_static_prefix %}'})\n+    def test_get_static_prefix_script_prefix(self):\n+        \"\"\"\n+        {% get_static_prefix %} prepends SCRIPT_NAME to STATIC_URL when the\n+        app is deployed on a sub-path.\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            output = self.engine.render_to_string('t')\n+            self.assertEqual(output, '/subpath/static/')\n+        finally:\n+            clear_script_prefix()\n+\n+    @setup({'t': '{% load static %}{% get_media_prefix %}'})\n+    def test_get_media_prefix_script_prefix(self):\n+        \"\"\"\n+        {% get_media_prefix %} prepends SCRIPT_NAME to MEDIA_URL when the\n+        app is deployed on a sub-path.\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            output = self.engine.render_to_string('t')\n+            self.assertEqual(output, '/subpath/media/')\n+        finally:\n+            clear_script_prefix()\n+\n+    @setup({'t': '{% load static %}{% get_static_prefix %}'})\n+    def test_get_static_prefix_not_double_prefixed(self):\n+        \"\"\"\n+        {% get_static_prefix %} does not double-prepend SCRIPT_NAME when\n+        STATIC_URL already starts with it.\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            with override_settings(STATIC_URL='/subpath/static/'):\n+                output = self.engine.render_to_string('t')\n+            self.assertEqual(output, '/subpath/static/')\n+        finally:\n+            clear_script_prefix()\n+\n+    @setup({'t': '{% load static %}{% static \"admin/base.css\" %}'})\n+    def test_static_tag_script_prefix(self):\n+        \"\"\"\n+        {% static %} (without staticfiles installed) prepends SCRIPT_NAME\n+        to the URL when the app is deployed on a sub-path.\n+        \"\"\"\n+        set_script_prefix('/subpath/')\n+        try:\n+            output = self.engine.render_to_string('t')\n+            self.assertEqual(output, '/subpath/static/admin/base.css')\n+        finally:\n+            clear_script_prefix()\n"}
{"instance_id": "django__django-11583", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\nindex 25c3b44250..8536e506a8 100644\n--- a/django/utils/autoreload.py\n+++ b/django/utils/autoreload.py\n@@ -143,6 +143,11 @@ def iter_modules_and_files(modules, extra_files):\n             # The module could have been removed, don't fail loudly if this\n             # is the case.\n             continue\n+        except ValueError:\n+            # ValueError is raised on Windows and some Unix-like systems\n+            # (e.g. when resolving paths on network mounts) if the path\n+            # contains a null byte. Skip such paths silently.\n+            continue\n         results.add(resolved_path)\n     return frozenset(results)\n \n@@ -189,6 +194,11 @@ def sys_path_directories():\n             resolved_path = path.resolve(strict=True).absolute()\n         except FileNotFoundError:\n             continue\n+        except ValueError:\n+            # ValueError is raised on Windows and some Unix-like systems\n+            # (e.g. when resolving paths on network mounts) if the path\n+            # contains a null byte. Skip such paths silently.\n+            continue\n         # If the path is a file (like a zip file), watch the parent directory.\n         if resolved_path.is_file():\n             yield resolved_path.parent\n"}
{"instance_id": "django__django-11620", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py\nindex 2154a46320..c719742c28 100644\n--- a/django/urls/resolvers.py\n+++ b/django/urls/resolvers.py\n@@ -17,6 +17,7 @@ from django.conf import settings\n from django.core.checks import Error, Warning\n from django.core.checks.urls import check_resolver\n from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist\n+from django.http import Http404\n from django.utils.datastructures import MultiValueDict\n from django.utils.functional import cached_property\n from django.utils.http import RFC3986_SUBDELIMS, escape_leading_slashes\n@@ -260,6 +261,8 @@ class RoutePattern(CheckURLMixin):\n                     kwargs[key] = converter.to_python(value)\n                 except ValueError:\n                     return None\n+                except Http404:\n+                    raise\n             return path[match.end():], (), kwargs\n         return None\n \ndiff --git a/django/views/debug.py b/django/views/debug.py\nindex cb3e8c7ec1..08bc43cf0e 100644\n--- a/django/views/debug.py\n+++ b/django/views/debug.py\n@@ -5,7 +5,7 @@ import types\n from pathlib import Path\n \n from django.conf import settings\n-from django.http import HttpResponse, HttpResponseNotFound\n+from django.http import Http404, HttpResponse, HttpResponseNotFound\n from django.template import Context, Engine, TemplateDoesNotExist\n from django.template.defaultfilters import pprint\n from django.urls import Resolver404, resolve\n@@ -483,7 +483,7 @@ def technical_404_response(request, exception):\n     caller = ''\n     try:\n         resolver_match = resolve(request.path)\n-    except Resolver404:\n+    except Http404:\n         pass\n     else:\n         obj = resolver_match.func\ndiff --git a/tests/urlpatterns/tests.py b/tests/urlpatterns/tests.py\nindex 214739f678..6d84fdbcb1 100644\n--- a/tests/urlpatterns/tests.py\n+++ b/tests/urlpatterns/tests.py\n@@ -1,6 +1,7 @@\n import uuid\n \n from django.core.exceptions import ImproperlyConfigured\n+from django.http import Http404\n from django.test import SimpleTestCase\n from django.test.utils import override_settings\n from django.urls import Resolver404, path, resolve, reverse\n@@ -219,6 +220,13 @@ class ConversionExceptionTests(SimpleTestCase):\n         with self.assertRaisesMessage(TypeError, 'This type error propagates.'):\n             resolve('/dynamic/abc/')\n \n+    def test_resolve_http404_propagates(self):\n+        @DynamicConverter.register_to_python\n+        def raises_http404(value):\n+            raise Http404('This Http404 propagates.')\n+        with self.assertRaisesMessage(Http404, 'This Http404 propagates.'):\n+            resolve('/dynamic/abc/')\n+\n     def test_reverse_value_error_propagates(self):\n         @DynamicConverter.register_to_url\n         def raises_value_error(value):\n"}
{"instance_id": "django__django-11630", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/core/checks/model_checks.py b/django/core/checks/model_checks.py\nindex 5c2266ca1d..affba1eb37 100644\n--- a/django/core/checks/model_checks.py\n+++ b/django/core/checks/model_checks.py\n@@ -19,7 +19,7 @@ def check_all_models(app_configs=None, **kwargs):\n         models = chain.from_iterable(app_config.get_models() for app_config in app_configs)\n     for model in models:\n         if model._meta.managed and not model._meta.proxy:\n-            db_table_models[model._meta.db_table].append(model._meta.label)\n+            db_table_models[model._meta.db_table].append(model)\n         if not inspect.ismethod(model.check):\n             errors.append(\n                 Error(\n@@ -35,16 +35,40 @@ def check_all_models(app_configs=None, **kwargs):\n             indexes[model_index.name].append(model._meta.label)\n         for model_constraint in model._meta.constraints:\n             constraints[model_constraint.name].append(model._meta.label)\n-    for db_table, model_labels in db_table_models.items():\n-        if len(model_labels) != 1:\n-            errors.append(\n-                Error(\n-                    \"db_table '%s' is used by multiple models: %s.\"\n-                    % (db_table, ', '.join(db_table_models[db_table])),\n-                    obj=db_table,\n-                    id='models.E028',\n+    for db_table, table_models in db_table_models.items():\n+        if len(table_models) != 1:\n+            from django.db import router\n+            from django.conf import settings\n+            # Only report an error if the models sharing a table name can be\n+            # routed to the same database. Models on different databases can\n+            # legitimately share a table name without conflict.\n+            # Build a set of (db alias, model) pairs allowed by the router.\n+            all_dbs = list(settings.DATABASES)\n+            # Collect the database aliases each model is allowed on.\n+            models_dbs = [\n+                {db for db in all_dbs if router.allow_migrate_model(db, m)}\n+                for m in table_models\n+            ]\n+            # If no two models share a common allowed database, there is no\n+            # real collision and we should not raise an error.\n+            collision = False\n+            for i, dbs_i in enumerate(models_dbs):\n+                for dbs_j in models_dbs[i + 1:]:\n+                    if dbs_i & dbs_j:\n+                        collision = True\n+                        break\n+                if collision:\n+                    break\n+            if collision:\n+                model_labels = [m._meta.label for m in table_models]\n+                errors.append(\n+                    Error(\n+                        \"db_table '%s' is used by multiple models: %s.\"\n+                        % (db_table, ', '.join(model_labels)),\n+                        obj=db_table,\n+                        id='models.E028',\n+                    )\n                 )\n-            )\n     for index_name, model_labels in indexes.items():\n         if len(model_labels) > 1:\n             model_labels = set(model_labels)\ndiff --git a/tests/check_framework/test_model_checks.py b/tests/check_framework/test_model_checks.py\nindex 79177e38f7..e2a36c877a 100644\n--- a/tests/check_framework/test_model_checks.py\n+++ b/tests/check_framework/test_model_checks.py\n@@ -3,7 +3,7 @@ from django.core.checks import Error\n from django.db import models\n from django.test import SimpleTestCase, TestCase, skipUnlessDBFeature\n from django.test.utils import (\n-    isolate_apps, modify_settings, override_system_checks,\n+    isolate_apps, modify_settings, override_settings, override_system_checks,\n )\n \n \n@@ -74,6 +74,70 @@ class DuplicateDBTableTests(SimpleTestCase):\n         self.assertEqual(Model._meta.db_table, ProxyModel._meta.db_table)\n         self.assertEqual(checks.run_checks(app_configs=self.apps.get_app_configs()), [])\n \n+    @modify_settings(INSTALLED_APPS={'append': 'basic'})\n+    @isolate_apps('basic', 'check_framework', kwarg_name='apps')\n+    def test_no_collision_across_apps_with_different_db_via_router(self, apps):\n+        \"\"\"\n+        Models in different apps that share a db_table but are routed to\n+        different databases via DATABASE_ROUTERS should not raise E028.\n+        \"\"\"\n+        class RouterAllowBasicOnly:\n+            \"\"\"Route 'basic' app to 'other' DB, everything else to 'default'.\"\"\"\n+            def allow_migrate(self, db, app_label, **hints):\n+                if app_label == 'basic':\n+                    return db == 'other'\n+                return db == 'default'\n+\n+        class Model1(models.Model):\n+            class Meta:\n+                app_label = 'basic'\n+                db_table = 'test_table'\n+\n+        class Model2(models.Model):\n+            class Meta:\n+                app_label = 'check_framework'\n+                db_table = 'test_table'\n+\n+        with self.settings(DATABASE_ROUTERS=['check_framework.test_model_checks.RouterAllowBasicOnly']):\n+            # Patch the router into the module scope so the dotted-path lookup works.\n+            import check_framework.test_model_checks as _mod\n+            _mod.RouterAllowBasicOnly = RouterAllowBasicOnly\n+            self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [])\n+\n+    @modify_settings(INSTALLED_APPS={'append': 'basic'})\n+    @isolate_apps('basic', 'check_framework', kwarg_name='apps')\n+    def test_collision_across_apps_with_same_db_via_router(self, apps):\n+        \"\"\"\n+        Models in different apps that share a db_table AND can be migrated to\n+        the same database via DATABASE_ROUTERS should still raise E028.\n+        \"\"\"\n+        class RouterAllowAll:\n+            \"\"\"Allow everything on every database.\"\"\"\n+            def allow_migrate(self, db, app_label, **hints):\n+                return True\n+\n+        class Model1(models.Model):\n+            class Meta:\n+                app_label = 'basic'\n+                db_table = 'test_table'\n+\n+        class Model2(models.Model):\n+            class Meta:\n+                app_label = 'check_framework'\n+                db_table = 'test_table'\n+\n+        import check_framework.test_model_checks as _mod\n+        _mod.RouterAllowAll = RouterAllowAll\n+        with self.settings(DATABASE_ROUTERS=['check_framework.test_model_checks.RouterAllowAll']):\n+            self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [\n+                Error(\n+                    \"db_table 'test_table' is used by multiple models: \"\n+                    \"basic.Model1, check_framework.Model2.\",\n+                    obj='test_table',\n+                    id='models.E028',\n+                )\n+            ])\n+\n \n @isolate_apps('check_framework', attr_name='apps')\n @override_system_checks([checks.model_checks.check_all_models])\n"}
{"instance_id": "django__django-11742", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 9ce46e3f73..f2ee177ad5 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -207,6 +207,7 @@ class Field(RegisterLookupMixin):\n             *self._check_backend_specific_checks(**kwargs),\n             *self._check_validators(),\n             *self._check_deprecation_details(),\n+            *self._check_max_length_fits_choices(),\n         ]\n \n     def _check_field_name(self):\n@@ -291,6 +292,42 @@ class Field(RegisterLookupMixin):\n             )\n         ]\n \n+    def _check_max_length_fits_choices(self):\n+        if not self.choices or not isinstance(self.max_length, int) or isinstance(self.max_length, bool):\n+            return []\n+\n+        def get_choice_values(choices):\n+            \"\"\"Recursively yield actual choice values from flat or grouped choices.\"\"\"\n+            for choice in choices:\n+                try:\n+                    group_name, group_choices = choice\n+                except (TypeError, ValueError):\n+                    # Not a pair \u2014 skip; _check_choices() will catch this.\n+                    continue\n+                if is_iterable(group_choices) and not isinstance(group_choices, str):\n+                    # Grouped choices: (group_name, [(value, display), ...])\n+                    for value, _ in group_choices:\n+                        yield value\n+                else:\n+                    # Flat choice: (value, display)\n+                    yield group_name\n+\n+        invalid_choices = [\n+            value for value in get_choice_values(self.choices)\n+            if isinstance(value, str) and len(value) > self.max_length\n+        ]\n+        if invalid_choices:\n+            return [\n+                checks.Error(\n+                    \"'max_length' is too small to fit the longest value \"\n+                    \"in 'choices' (%d < %d).\"\n+                    % (self.max_length, max(len(v) for v in invalid_choices)),\n+                    obj=self,\n+                    id='fields.E009',\n+                )\n+            ]\n+        return []\n+\n     def _check_db_index(self):\n         if self.db_index not in (None, True, False):\n             return [\ndiff --git a/docs/ref/checks.txt b/docs/ref/checks.txt\nindex 4da932720e..6c5f5ec809 100644\n--- a/docs/ref/checks.txt\n+++ b/docs/ref/checks.txt\n@@ -138,6 +138,8 @@ Model fields\n * **fields.E006**: ``db_index`` must be ``None``, ``True`` or ``False``.\n * **fields.E007**: Primary keys must not have ``null=True``.\n * **fields.E008**: All ``validators`` must be callable.\n+* **fields.E009**: ``max_length`` is too small to fit the longest value in\n+  ``choices``.\n * **fields.E100**: ``AutoField``\\s must set primary_key=True.\n * **fields.E110**: ``BooleanField``\\s do not accept null values. *This check\n   appeared before support for null values was added in Django 2.1.*\ndiff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py\nindex 5bb1847a70..fcd74352ff 100644\n--- a/tests/invalid_models_tests/test_ordinary_fields.py\n+++ b/tests/invalid_models_tests/test_ordinary_fields.py\n@@ -304,6 +304,73 @@ class CharFieldTests(SimpleTestCase):\n \n         self.assertEqual(Model._meta.get_field('field').check(), [])\n \n+    def test_max_length_is_too_small_for_choices(self):\n+        class Model(models.Model):\n+            field = models.CharField(\n+                max_length=2,\n+                choices=[('ABC', 'Value ABC'), ('XY', 'Value XY')],\n+            )\n+\n+        field = Model._meta.get_field('field')\n+        self.assertEqual(field.check(), [\n+            Error(\n+                \"'max_length' is too small to fit the longest value \"\n+                \"in 'choices' (2 < 3).\",\n+                obj=field,\n+                id='fields.E009',\n+            ),\n+        ])\n+\n+    def test_max_length_is_too_small_for_grouped_choices(self):\n+        class Model(models.Model):\n+            field = models.CharField(\n+                max_length=2,\n+                choices=[\n+                    ['Group', [('ABC', 'Value ABC'), ('XY', 'Value XY')]],\n+                ],\n+            )\n+\n+        field = Model._meta.get_field('field')\n+        self.assertEqual(field.check(), [\n+            Error(\n+                \"'max_length' is too small to fit the longest value \"\n+                \"in 'choices' (2 < 3).\",\n+                obj=field,\n+                id='fields.E009',\n+            ),\n+        ])\n+\n+    def test_max_length_fits_longest_choice(self):\n+        class Model(models.Model):\n+            field = models.CharField(\n+                max_length=3,\n+                choices=[('ABC', 'Value ABC'), ('XY', 'Value XY')],\n+            )\n+\n+        self.assertEqual(Model._meta.get_field('field').check(), [])\n+\n+    def test_max_length_fits_longest_choice_in_named_group(self):\n+        class Model(models.Model):\n+            field = models.CharField(\n+                max_length=3,\n+                choices=[\n+                    ['Group', [('ABC', 'Value ABC'), ('XY', 'Value XY')]],\n+                    ['R', 'Random character'],\n+                ],\n+            )\n+\n+        self.assertEqual(Model._meta.get_field('field').check(), [])\n+\n+    def test_non_string_choices_not_checked_for_max_length(self):\n+        \"\"\"Non-string choice values are not validated against max_length.\"\"\"\n+        class Model(models.Model):\n+            field = models.CharField(\n+                max_length=2,\n+                choices=[(1234, 'Long integer value')],\n+            )\n+\n+        self.assertEqual(Model._meta.get_field('field').check(), [])\n+\n     def test_bad_db_index_value(self):\n         class Model(models.Model):\n             field = models.CharField(max_length=10, db_index='bad')\n"}
{"instance_id": "django__django-11797", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": ""}
{"instance_id": "django__django-11815", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/db/migrations/serializer.py b/django/db/migrations/serializer.py\nindex 27b5cbd379..4275f91a7f 100644\n--- a/django/db/migrations/serializer.py\n+++ b/django/db/migrations/serializer.py\n@@ -120,9 +120,8 @@ class EnumSerializer(BaseSerializer):\n     def serialize(self):\n         enum_class = self.value.__class__\n         module = enum_class.__module__\n-        v_string, v_imports = serializer_factory(self.value.value).serialize()\n-        imports = {'import %s' % module, *v_imports}\n-        return \"%s.%s(%s)\" % (module, enum_class.__name__, v_string), imports\n+        imports = {'import %s' % module}\n+        return \"%s.%s[%r]\" % (module, enum_class.__name__, self.value.name), imports\n \n \n class FloatSerializer(BaseSimpleSerializer):\ndiff --git a/tests/migrations/test_writer.py b/tests/migrations/test_writer.py\nindex f97d76e9ad..39c9ab47b9 100644\n--- a/tests/migrations/test_writer.py\n+++ b/tests/migrations/test_writer.py\n@@ -267,15 +267,15 @@ class WriterTests(SimpleTestCase):\n \n         self.assertSerializedResultEqual(\n             TextEnum.A,\n-            (\"migrations.test_writer.TextEnum('a-value')\", {'import migrations.test_writer'})\n+            (\"migrations.test_writer.TextEnum['A']\", {'import migrations.test_writer'})\n         )\n         self.assertSerializedResultEqual(\n             BinaryEnum.A,\n-            (\"migrations.test_writer.BinaryEnum(b'a-value')\", {'import migrations.test_writer'})\n+            (\"migrations.test_writer.BinaryEnum['A']\", {'import migrations.test_writer'})\n         )\n         self.assertSerializedResultEqual(\n             IntEnum.B,\n-            (\"migrations.test_writer.IntEnum(2)\", {'import migrations.test_writer'})\n+            (\"migrations.test_writer.IntEnum['B']\", {'import migrations.test_writer'})\n         )\n \n         field = models.CharField(default=TextEnum.B, choices=[(m.value, m) for m in TextEnum])\n@@ -283,27 +283,27 @@ class WriterTests(SimpleTestCase):\n         self.assertEqual(\n             string,\n             \"models.CharField(choices=[\"\n-            \"('a-value', migrations.test_writer.TextEnum('a-value')), \"\n-            \"('value-b', migrations.test_writer.TextEnum('value-b'))], \"\n-            \"default=migrations.test_writer.TextEnum('value-b'))\"\n+            \"('a-value', migrations.test_writer.TextEnum['A']), \"\n+            \"('value-b', migrations.test_writer.TextEnum['B'])], \"\n+            \"default=migrations.test_writer.TextEnum['B'])\"\n         )\n         field = models.CharField(default=BinaryEnum.B, choices=[(m.value, m) for m in BinaryEnum])\n         string = MigrationWriter.serialize(field)[0]\n         self.assertEqual(\n             string,\n             \"models.CharField(choices=[\"\n-            \"(b'a-value', migrations.test_writer.BinaryEnum(b'a-value')), \"\n-            \"(b'value-b', migrations.test_writer.BinaryEnum(b'value-b'))], \"\n-            \"default=migrations.test_writer.BinaryEnum(b'value-b'))\"\n+            \"(b'a-value', migrations.test_writer.BinaryEnum['A']), \"\n+            \"(b'value-b', migrations.test_writer.BinaryEnum['B'])], \"\n+            \"default=migrations.test_writer.BinaryEnum['B'])\"\n         )\n         field = models.IntegerField(default=IntEnum.A, choices=[(m.value, m) for m in IntEnum])\n         string = MigrationWriter.serialize(field)[0]\n         self.assertEqual(\n             string,\n             \"models.IntegerField(choices=[\"\n-            \"(1, migrations.test_writer.IntEnum(1)), \"\n-            \"(2, migrations.test_writer.IntEnum(2))], \"\n-            \"default=migrations.test_writer.IntEnum(1))\"\n+            \"(1, migrations.test_writer.IntEnum['A']), \"\n+            \"(2, migrations.test_writer.IntEnum['B'])], \"\n+            \"default=migrations.test_writer.IntEnum['A'])\"\n         )\n \n     def test_serialize_choices(self):\n"}
{"instance_id": "django__django-11848", "model_name_or_path": "harness/claude-sonnet-4-6", "model_patch": "diff --git a/django/utils/http.py b/django/utils/http.py\nindex 572cfb4347..a35d686e03 100644\n--- a/django/utils/http.py\n+++ b/django/utils/http.py\n@@ -176,10 +176,11 @@ def parse_http_date(date):\n     try:\n         year = int(m.group('year'))\n         if year < 100:\n-            if year < 70:\n-                year += 2000\n-            else:\n-                year += 1900\n+            current_year = datetime.datetime.utcnow().year\n+            current_century = current_year - (current_year % 100)\n+            year += current_century\n+            if year > current_year + 50:\n+                year -= 100\n         month = MONTHS.index(m.group('mon').lower()) + 1\n         day = int(m.group('day'))\n         hour = int(m.group('hour'))\ndiff --git a/tests/utils_tests/test_http.py b/tests/utils_tests/test_http.py\nindex bc8bcfe977..2fd4e1e0e2 100644\n--- a/tests/utils_tests/test_http.py\n+++ b/tests/utils_tests/test_http.py\n@@ -1,5 +1,6 @@\n import unittest\n from datetime import datetime\n+from unittest import mock\n \n from django.test import SimpleTestCase, ignore_warnings\n from django.utils.datastructures import MultiValueDict\n@@ -328,6 +329,30 @@ class HttpDateProcessingTests(unittest.TestCase):\n         parsed = parse_http_date('Sun Nov  6 08:49:37 0037')\n         self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(2037, 11, 6, 8, 49, 37))\n \n+    def test_parsing_rfc850_two_digit_year(self):\n+        \"\"\"\n+        RFC 7231 \u00a77.1.1.1: two-digit years that appear to be more than 50\n+        years in the future must be interpreted as the most recent past year\n+        with the same last two digits.\n+        \"\"\"\n+        # Subclass datetime.datetime to freeze utcnow() to 2019 for\n+        # deterministic results (datetime.datetime is a C type, so utcnow\n+        # cannot be patched directly).\n+        import datetime as dt_module\n+\n+        class MockDatetime(datetime):\n+            @classmethod\n+            def utcnow(cls):\n+                return cls(2019, 1, 1)\n+\n+        with mock.patch('django.utils.http.datetime.datetime', MockDatetime):\n+            # 70 \u2192 2070: 2070 - 2019 = 51 years in the future (> 50) \u2192 1970\n+            parsed = parse_http_date('Sunday, 06-Nov-70 08:49:37 GMT')\n+            self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(1970, 11, 6, 8, 49, 37))\n+            # 69 \u2192 2069: 2069 - 2019 = 50 years in the future (not > 50) \u2192 2069\n+            parsed = parse_http_date('Sunday, 06-Nov-69 08:49:37 GMT')\n+            self.assertEqual(datetime.utcfromtimestamp(parsed), datetime(2069, 11, 6, 8, 49, 37))\n+\n \n class EscapeLeadingSlashesTests(unittest.TestCase):\n     def test(self):\n"}
