{"instance_id": "astropy__astropy-12907", "model_name_or_path": "claude-code/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..58a7ec17f6 100644\n--- a/astropy/modeling/tests/test_separable.py\n+++ b/astropy/modeling/tests/test_separable.py\n@@ -135,6 +135,26 @@ def test_separable(compound_model, result):\n     assert_allclose(separability_matrix(compound_model), result[1])\n \n \n+def test_cstack_nested_compound():\n+    \"\"\"Regression test for nested CompoundModel separability.\n+\n+    When a CompoundModel is used as the right-hand operand of `&`, its\n+    pre-computed separability matrix must be preserved, not replaced with\n+    an all-ones block.  See https://github.com/astropy/astropy/issues/NNNN\n+    \"\"\"\n+    cm = models.Linear1D(10) & models.Linear1D(5)\n+    result = separability_matrix(models.Pix2Sky_TAN() & cm)\n+    # Pix2Sky_TAN outputs are coupled; each Linear1D output depends on only\n+    # one input, so the bottom-right 2x2 block must be the identity.\n+    expected = np.array([\n+        [True,  True,  False, False],\n+        [True,  True,  False, False],\n+        [False, False, True,  False],\n+        [False, False, False, True],\n+    ])\n+    assert_allclose(result, expected)\n+\n+\n def test_custom_model_separable():\n     @custom_model\n     def model_a(x):\n"}
{"instance_id": "astropy__astropy-14182", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/io/ascii/rst.py b/astropy/io/ascii/rst.py\nindex abdeba8efb..f52f4c6bd8 100644\n--- a/astropy/io/ascii/rst.py\n+++ b/astropy/io/ascii/rst.py\n@@ -57,10 +57,12 @@ 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+        self.data.start_line = len(self.header.header_rows) + 2\n \n     def write(self, lines):\n         lines = super().write(lines)\n-        lines = [lines[1]] + lines + [lines[1]]\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..3116695854 100644\n--- a/astropy/io/ascii/tests/test_rst.py\n+++ b/astropy/io/ascii/tests/test_rst.py\n@@ -2,7 +2,9 @@\n \n from io import StringIO\n \n+import astropy.units as u\n from astropy.io import ascii\n+from astropy.table import QTable\n \n from .common import assert_almost_equal, assert_equal\n \n@@ -185,3 +187,22 @@ Col1      Col2 Col3 Col4\n ==== ========= ==== ====\n \"\"\",\n     )\n+\n+\n+def test_write_header_rows():\n+    \"\"\"Write a QTable with header_rows=['name', 'unit'] in RST format\"\"\"\n+    tbl = QTable({\"wave\": [350, 950] * u.nm, \"response\": [0.7, 1.2] * u.ct})\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+    )\ndiff --git a/astropy/utils/_compiler.py b/astropy/utils/_compiler.py\nnew file mode 100644\nindex 0000000000..91c8e7adb9\n--- /dev/null\n+++ b/astropy/utils/_compiler.py\n@@ -0,0 +1 @@\n+compiler_version = 'stub'\n"}
{"instance_id": "astropy__astropy-14365", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/io/ascii/qdp.py b/astropy/io/ascii/qdp.py\nindex 83a4f004aa..768beb0de9 100644\n--- a/astropy/io/ascii/qdp.py\n+++ b/astropy/io/ascii/qdp.py\n@@ -68,7 +68,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"}
{"instance_id": "astropy__astropy-14995", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/nddata/mixins/ndarithmetic.py b/astropy/nddata/mixins/ndarithmetic.py\nindex 4153dfccb2..69d77148e5 100644\n--- a/astropy/nddata/mixins/ndarithmetic.py\n+++ b/astropy/nddata/mixins/ndarithmetic.py\n@@ -522,6 +522,8 @@ class NDArithmeticMixin:\n             return deepcopy(operand.mask)\n         elif operand is None:\n             return deepcopy(self.mask)\n+        elif operand.mask is None:\n+            return deepcopy(self.mask)\n         else:\n             # Now lets calculate the resulting mask (operation enforces copy)\n             return handle_mask(self.mask, operand.mask, **kwds)\n"}
{"instance_id": "astropy__astropy-6938", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/io/fits/fitsrec.py b/astropy/io/fits/fitsrec.py\nindex 574b4073b1..11f8c608e5 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[:] = output_field.replace(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..531eb2e706 100644\n--- a/astropy/io/fits/tests/test_table.py\n+++ b/astropy/io/fits/tests/test_table.py\n@@ -2841,6 +2841,24 @@ class TestColumnFunctions(FitsTestCase):\n             raw = np.rec.recarray.field(hdul[1].data, 'TEST')\n             assert raw.tostring() == b'   1.   2.   3.'\n \n+    def test_d_exponent_column(self):\n+        \"\"\"Regression test for https://github.com/astropy/astropy/issues/6964\n+\n+        Ensure that ASCII table columns with D format have their exponent\n+        separator written as 'D' rather than 'E'.\n+        \"\"\"\n+\n+        c = fits.Column('TEST', 'D25.17', array=[1.23456789e100, 9.87654321e-200])\n+        t = fits.TableHDU.from_columns([c])\n+        t.writeto(self.temp('test.fits'))\n+\n+        with fits.open(self.temp('test.fits')) as hdul:\n+            assert hdul[1].header['TFORM1'] == 'D25.17'\n+            # Raw bytes in the file should use 'D' as the exponent separator\n+            raw = np.rec.recarray.field(hdul[1].data, 'TEST')\n+            assert b'E' not in raw.tostring()\n+            assert b'D' in raw.tostring()\n+\n     def test_column_array_type_mismatch(self):\n         \"\"\"Regression test for https://aeon.stsci.edu/ssb/trac/pyfits/ticket/218\"\"\"\n \n"}
{"instance_id": "astropy__astropy-7746", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/astropy/wcs/wcs.py b/astropy/wcs/wcs.py\nindex d3a06f2b31..ad076ff164 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 0 in xy.shape:\n+                if ra_dec_order and sky == 'output':\n+                    return (np.empty(axes[0].shape),\n+                            np.empty(axes[0].shape))\n+                return [np.empty(axes[0].shape)\n+                        for i in range(self.naxis)]\n+\n             if ra_dec_order and sky == 'input':\n                 xy = self._denormalize_sky(xy)\n             output = func(xy, origin)\n@@ -1235,6 +1242,8 @@ 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+                return np.empty(xy.shape)\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": "claude-code/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/docs/ref/settings.txt b/docs/ref/settings.txt\nindex 46e99af993..238a765765 100644\n--- a/docs/ref/settings.txt\n+++ b/docs/ref/settings.txt\n@@ -1484,16 +1484,15 @@ This value mirrors the functionality and caveats of the\n ``FILE_UPLOAD_PERMISSIONS``\n ---------------------------\n \n-Default: ``None``\n+Default: ``0o644``\n \n The numeric mode (i.e. ``0o644``) to set newly uploaded files to. For\n more information about what these modes mean, see the documentation for\n :func:`os.chmod`.\n \n-If this isn't given or is ``None``, you'll get operating-system\n-dependent behavior. On most platforms, temporary files will have a mode\n-of ``0o600``, and files saved from memory will be saved using the\n-system's standard umask.\n+If this is ``None``, you'll get operating-system dependent behavior.\n+On most platforms, temporary files will have a mode of ``0o600``, and\n+files saved from memory will be saved using the system's standard umask.\n \n For security reasons, these permissions aren't applied to the temporary files\n that are stored in :setting:`FILE_UPLOAD_TEMP_DIR`.\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):\n"}
{"instance_id": "django__django-10924", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 0c64748ccd..4d7eb11151 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -1709,7 +1709,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/tests/field_deconstruction/tests.py b/tests/field_deconstruction/tests.py\nindex 2cf1f93e22..d0cd49a60e 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_with_callable_path(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/model_fields/test_filepathfield.py b/tests/model_fields/test_filepathfield.py\nnew file mode 100644\nindex 0000000000..f4efa306a6\n--- /dev/null\n+++ b/tests/model_fields/test_filepathfield.py\n@@ -0,0 +1,29 @@\n+import os\n+\n+from django.db import models\n+from django.test import SimpleTestCase\n+\n+\n+PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),\n+                    'forms_tests', 'field_tests', 'filepathfield_test_dir')\n+\n+\n+class FilePathFieldTests(SimpleTestCase):\n+\n+    def test_callable_path(self):\n+        field = models.FilePathField(path=lambda: PATH)\n+        form_field = field.formfield()\n+        self.assertEqual(form_field.path, PATH)\n+\n+    def test_callable_path_is_resolved_in_formfield(self):\n+        \"\"\"\n+        A callable path should be called when generating the form field,\n+        allowing deferred path resolution (e.g. based on settings).\n+        \"\"\"\n+        path_callable = lambda: PATH\n+        field = models.FilePathField(path=path_callable)\n+        # path attribute stores the callable\n+        self.assertIs(field.path, path_callable)\n+        # formfield resolves the callable to a string\n+        form_field = field.formfield()\n+        self.assertEqual(form_field.path, PATH)\n"}
{"instance_id": "django__django-11001", "model_name_or_path": "claude-code/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/expressions/tests.py b/tests/expressions/tests.py\nindex c22ff34ee8..3aab2b90f6 100644\n--- a/tests/expressions/tests.py\n+++ b/tests/expressions/tests.py\n@@ -384,6 +384,23 @@ class BasicExpressionsTests(TestCase):\n         )\n         self.assertSequenceEqual(mustermanns_by_seniority, [self.max, mary])\n \n+    def test_order_by_multiline_rawsql(self):\n+        # Multiline RawSQL expressions with identical last lines must not be\n+        # incorrectly treated as duplicates and dropped from ORDER BY.\n+        # Regression test for #30052.\n+        employees = Employee.objects.order_by(\n+            RawSQL('''\n+                case when firstname = 'Joe'\n+                then 1 else 2 end''', []).asc(),\n+            RawSQL('''\n+                case when lastname = 'Smith'\n+                then 1 else 2 end''', []).asc(),\n+        )\n+        # Both ORDER BY expressions have the same last line ('then 1 else 2 end').\n+        # Verify both are present in the compiled SQL.\n+        sql = str(employees.query)\n+        self.assertEqual(sql.count('else 2 end'), 2)\n+\n     def test_outerref(self):\n         inner = Company.objects.filter(point_of_contact=OuterRef('pk'))\n         msg = (\n"}
{"instance_id": "django__django-11019", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/forms/widgets.py b/django/forms/widgets.py\nindex 02aa32b207..4b665db9bb 100644\n--- a/django/forms/widgets.py\n+++ b/django/forms/widgets.py\n@@ -70,11 +70,61 @@ class Media:\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+        js_lists = [js for js in self._js_lists if js]\n+        if not js_lists:\n+            return []\n+\n+        # Collect all unique elements in first-seen order.\n+        seen = {}\n+        for js_list in js_lists:\n+            for js in js_list:\n+                if js not in seen:\n+                    seen[js] = len(seen)\n+\n+        nodes = list(seen.keys())\n+        n = len(nodes)\n+\n+        # Build ordering constraints from consecutive pairs in each list.\n+        successors = {node: [] for node in nodes}\n+        predecessor_count = {node: 0 for node in nodes}\n+        edges = set()\n+        for js_list in js_lists:\n+            for i in range(len(js_list) - 1):\n+                a, b = js_list[i], js_list[i + 1]\n+                if (a, b) not in edges:\n+                    edges.add((a, b))\n+                    successors[a].append(b)\n+                    predecessor_count[b] += 1\n+\n+        # Perform topological sort (Kahn's algorithm).\n+        # Use first-seen order as a tiebreaker for deterministic output.\n+        result = []\n+        ready = [node for node in nodes if not predecessor_count[node]]\n+\n+        while ready:\n+            node = ready.pop(0)\n+            result.append(node)\n+            new_ready = []\n+            for successor in successors[node]:\n+                predecessor_count[successor] -= 1\n+                if not predecessor_count[successor]:\n+                    new_ready.append(successor)\n+            if new_ready:\n+                # Insert new_ready nodes in first-seen order relative to\n+                # existing ready nodes.\n+                ready = sorted(ready + new_ready, key=seen.get)\n+\n+        if len(result) < n:\n+            # Cycle detected: emit a warning for the conflicting files.\n+            remaining = [node for node in nodes if predecessor_count[node] > 0]\n+            warnings.warn(\n+                'Detected duplicate Media files in an opposite order:\\n'\n+                '%s\\n%s' % (remaining[0], remaining[1]),\n+                MediaOrderConflictWarning,\n+            )\n+            result.extend(remaining)\n+\n+        return result\n \n     def render(self):\n         return mark_safe('\\n'.join(chain.from_iterable(getattr(self, 'render_' + name)() for name in MEDIA_TYPES)))\ndiff --git a/tests/forms_tests/tests/test_media.py b/tests/forms_tests/tests/test_media.py\nindex 8cb484a15e..19dbcdc16e 100644\n--- a/tests/forms_tests/tests/test_media.py\n+++ b/tests/forms_tests/tests/test_media.py\n@@ -1,3 +1,6 @@\n+import warnings\n+\n+from django import forms\n from django.forms import CharField, Form, Media, MultiWidget, TextInput\n from django.template import Context, Template\n from django.test import SimpleTestCase, override_settings\n@@ -550,14 +553,43 @@ 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+        # custom_widget.js comes first because it was seen first.\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_conflict(self):\n+        \"\"\"\n+        Merging 3 or more media objects doesn't produce MediaOrderConflictWarning\n+        when the ordering is consistent across all media.\n+        \"\"\"\n+        # text-editor-extras.js depends on text-editor.js; color-picker.js\n+        # is independent.\n+        class ColorPicker(forms.Widget):\n+            class Media:\n+                js = ['color-picker.js']\n+\n+        class SimpleTextWidget(forms.Widget):\n+            class Media:\n+                js = ['text-editor.js']\n+\n+        class FancyTextWidget(forms.Widget):\n+            class Media:\n+                js = ['text-editor.js', 'text-editor-extras.js', 'color-picker.js']\n+\n+        class MyForm(forms.Form):\n+            background_color = forms.CharField(widget=ColorPicker())\n+            intro = forms.CharField(widget=SimpleTextWidget())\n+            body = forms.CharField(widget=FancyTextWidget())\n+\n+        with warnings.catch_warnings(record=True) as caught_warnings:\n+            warnings.simplefilter('always')\n+            js = MyForm().media._js\n+        self.assertEqual(js, ['text-editor.js', 'text-editor-extras.js', 'color-picker.js'])\n+        self.assertEqual(len(caught_warnings), 0)\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": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/core/management/commands/sqlmigrate.py b/django/core/management/commands/sqlmigrate.py\nindex f0b663222a..629dd19d1e 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 for atomic migrations and if the\n+        # 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..ac0bbe2d57 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 don't 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": "claude-code/claude-sonnet-4-6", "model_patch": "diff --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": "claude-code/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.'\n"}
{"instance_id": "django__django-11133", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/http/response.py b/django/http/response.py\nindex 6a84e193ba..e20136a95c 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"}
{"instance_id": "django__django-11179", "model_name_or_path": "claude-code/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):\n"}
{"instance_id": "django__django-11283", "model_name_or_path": "claude-code/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..584d10d163 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,6 +24,24 @@ 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+        if concrete_content_type.pk == proxy_content_type.pk:\n+            continue\n+        # Determine permissions that already exist in new_content_type so we\n+        # can avoid a UNIQUE constraint violation when updating old_content_type\n+        # rows (e.g. when a model was recreated as a proxy and\n+        # create_permissions already ran for the proxy content type).\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+        # Remove old-content-type permissions that would become duplicates.\n+        if existing_target_codenames:\n+            Permission.objects.filter(\n+                codename__in=existing_target_codenames,\n+                content_type=old_content_type,\n+            ).delete()\n         Permission.objects.filter(\n             permissions_query,\n             content_type=old_content_type,\ndiff --git a/tests/auth_tests/test_migrations.py b/tests/auth_tests/test_migrations.py\nindex 5ff2f6b4b3..1da1502e67 100644\n--- a/tests/auth_tests/test_migrations.py\n+++ b/tests/auth_tests/test_migrations.py\n@@ -84,6 +84,56 @@ class ProxyModelWithDifferentAppLabelTests(TestCase):\n             self.assertFalse(user.has_perm('auth_tests.' + permission.codename))\n \n \n+class ProxyModelWithDifferentAppLabelAndExistingPermissionsTests(TestCase):\n+    \"\"\"\n+    When a model is recreated as a proxy, create_permissions may have already\n+    created permissions for the proxy content type. The migration must not fail\n+    with an IntegrityError when those permissions already exist.\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)\n+        self.proxy_content_type = ContentType.objects.get_for_model(UserProxy, for_concrete_model=False)\n+        # Simulate old-style permission (concrete CT) \u2013 as pre-2.2 Django\n+        # would have stored it.\n+        self.concrete_permission = Permission.objects.create(\n+            content_type=self.concrete_content_type,\n+            codename='add_userproxy',\n+            name='Can add userproxy',\n+        )\n+        # Simulate permission already created with proxy CT (e.g. after the\n+        # model was recreated as a proxy and create_permissions ran again).\n+        self.proxy_permission = Permission.objects.create(\n+            content_type=self.proxy_content_type,\n+            codename='add_userproxy',\n+            name='Can add userproxy',\n+        )\n+\n+    def test_proxy_model_permissions_contenttype(self):\n+        \"\"\"\n+        Running the migration when duplicate permissions exist should not raise\n+        an IntegrityError and should leave exactly one permission using the\n+        proxy content type.\n+        \"\"\"\n+        update_proxy_permissions.update_proxy_model_permissions(apps, None)\n+        permissions = Permission.objects.filter(codename='add_userproxy')\n+        self.assertEqual(permissions.count(), 1)\n+        self.assertEqual(permissions.get().content_type, self.proxy_content_type)\n+\n+    def test_migrate_backwards(self):\n+        update_proxy_permissions.update_proxy_model_permissions(apps, None)\n+        update_proxy_permissions.revert_proxy_model_permissions(apps, None)\n+        permissions = Permission.objects.filter(codename='add_userproxy')\n+        self.assertEqual(permissions.count(), 1)\n+        self.assertEqual(permissions.get().content_type, self.concrete_content_type)\n+\n+\n class ProxyModelWithSameAppLabelTests(TestCase):\n     available_apps = [\n         'auth_tests',\n"}
{"instance_id": "django__django-11422", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\nindex 7ca0d68fae..0465c3f2bb 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+            # directly (e.g. \"python manage.py runserver\"). Use __file__ if\n+            # available to watch it for changes.\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..b4524c08ec 100644\n--- a/tests/utils_tests/test_autoreload.py\n+++ b/tests/utils_tests/test_autoreload.py\n@@ -132,6 +132,20 @@ 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+        __main__ executed as a script (e.g. \"python manage.py runserver\") has\n+        __spec__ == None. Its __file__ must still be watched.\n+        \"\"\"\n+        main_module = types.ModuleType('__main__')\n+        main_module.__spec__ = None\n+        main_module.__file__ = __file__\n+        self.clear_autoreload_caches()\n+        self.assertIn(\n+            Path(__file__).resolve().absolute(),\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": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/core/files/storage.py b/django/core/files/storage.py\nindex 4c27fce605..442c5280fb 100644\n--- a/django/core/files/storage.py\n+++ b/django/core/files/storage.py\n@@ -332,7 +332,12 @@ 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('//'):\n+            # Prepend SCRIPT_NAME to root-relative URLs.\n+            from django.urls import get_script_prefix\n+            url = get_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..8ef8af669c 100644\n--- a/django/templatetags/static.py\n+++ b/django/templatetags/static.py\n@@ -44,6 +44,9 @@ class PrefixNode(template.Node):\n             prefix = ''\n         else:\n             prefix = iri_to_uri(getattr(settings, name, ''))\n+        if prefix.startswith('/') and not prefix.startswith('//'):\n+            from django.urls import get_script_prefix\n+            prefix = get_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..a3242f63df 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,33 @@ class FileStorageTests(SimpleTestCase):\n             '%s%s' % (storage.base_url, 'test.file')\n         )\n \n+    def test_url_with_script_name(self):\n+        \"\"\"\n+        FileSystemStorage.url() prepends SCRIPT_NAME to root-relative URLs.\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_url_with_absolute_base_url_and_script_name(self):\n+        \"\"\"\n+        FileSystemStorage.url() does not prepend SCRIPT_NAME to absolute URLs.\n+        \"\"\"\n+        storage = self.storage_class(location=self.temp_dir, base_url='https://example.com/static/')\n+        set_script_prefix('/subpath/')\n+        try:\n+            self.assertEqual(\n+                storage.url('test.file'),\n+                'https://example.com/static/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/template_tests/syntax_tests/test_static.py b/tests/template_tests/syntax_tests/test_static.py\nindex 00f8cdbc11..cf207bcea1 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,30 @@ 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_with_script_name(self):\n+        set_script_prefix('/subpath/')\n+        try:\n+            output = self.engine.render_to_string('t')\n+            self.assertEqual(output, '/subpath' + settings.STATIC_URL)\n+        finally:\n+            clear_script_prefix()\n+\n+    @setup({'t': '{% load static %}{% get_media_prefix %}'})\n+    def test_get_media_prefix_with_script_name(self):\n+        set_script_prefix('/subpath/')\n+        try:\n+            output = self.engine.render_to_string('t')\n+            self.assertEqual(output, '/subpath' + settings.MEDIA_URL)\n+        finally:\n+            clear_script_prefix()\n+\n+    @setup({'t': '{% load static %}{% static \"admin/base.css\" %}'})\n+    def test_static_tag_with_script_name(self):\n+        set_script_prefix('/subpath/')\n+        try:\n+            output = self.engine.render_to_string('t')\n+            self.assertEqual(output, '/subpath' + urljoin(settings.STATIC_URL, 'admin/base.css'))\n+        finally:\n+            clear_script_prefix()\n"}
{"instance_id": "django__django-11583", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/utils/autoreload.py b/django/utils/autoreload.py\nindex 25c3b44250..eae1721f95 100644\n--- a/django/utils/autoreload.py\n+++ b/django/utils/autoreload.py\n@@ -139,7 +139,7 @@ def iter_modules_and_files(modules, extra_files):\n         path = Path(filename)\n         try:\n             resolved_path = path.resolve(strict=True).absolute()\n-        except FileNotFoundError:\n+        except (FileNotFoundError, ValueError):\n             # The module could have been removed, don't fail loudly if this\n             # is the case.\n             continue\n"}
{"instance_id": "django__django-11620", "model_name_or_path": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/views/debug.py b/django/views/debug.py\nindex cb3e8c7ec1..6643031340 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, Resolver404):\n         pass\n     else:\n         obj = resolver_match.func\ndiff --git a/tests/urlpatterns/tests.py b/tests/urlpatterns/tests.py\nindex 214739f678..9b427c9920 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,21 @@ 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()\n+        with self.assertRaises(Http404):\n+            resolve('/dynamic/abc/')\n+\n+    @override_settings(DEBUG=True)\n+    def test_resolve_http404_technical_response(self):\n+        @DynamicConverter.register_to_python\n+        def raises_http404(value):\n+            raise Http404()\n+        response = self.client.get('/dynamic/abc/')\n+        self.assertEqual(response.status_code, 404)\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": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/core/checks/model_checks.py b/django/core/checks/model_checks.py\nindex 5c2266ca1d..477f73a294 100644\n--- a/django/core/checks/model_checks.py\n+++ b/django/core/checks/model_checks.py\n@@ -5,6 +5,7 @@ from itertools import chain\n \n from django.apps import apps\n from django.core.checks import Error, Tags, register\n+from django.db import router\n \n \n @register(Tags.models)\n@@ -19,7 +20,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 +36,17 @@ 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, model_list in db_table_models.items():\n+        if len(model_list) != 1:\n+            if len({router.db_for_write(model) for model in model_list}) != len(model_list):\n+                errors.append(\n+                    Error(\n+                        \"db_table '%s' is used by multiple models: %s.\"\n+                        % (db_table, ', '.join(m._meta.label for m in model_list)),\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..2d034c8581 100644\n--- a/tests/check_framework/test_model_checks.py\n+++ b/tests/check_framework/test_model_checks.py\n@@ -74,6 +74,26 @@ 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_tables(self, apps):\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+        class Router:\n+            def db_for_write(self, model, **hints):\n+                return 'default' if model._meta.app_label == 'basic' else 'other'\n+\n+        with self.settings(DATABASE_ROUTERS=[Router()]):\n+            self.assertEqual(checks.run_checks(app_configs=apps.get_app_configs()), [])\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": "claude-code/claude-sonnet-4-6", "model_patch": "diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py\nindex 9ce46e3f73..5a82c80084 100644\n--- a/django/db/models/fields/__init__.py\n+++ b/django/db/models/fields/__init__.py\n@@ -975,8 +975,21 @@ class CharField(Field):\n                     id='fields.E121',\n                 )\n             ]\n-        else:\n-            return []\n+        elif self.choices:\n+            choice_max_length = max(\n+                (len(choice) for choice, _ in self.flatchoices if isinstance(choice, str)),\n+                default=0,\n+            )\n+            if self.max_length < choice_max_length:\n+                return [\n+                    checks.Error(\n+                        \"'max_length' is too small to fit the longest value \"\n+                        \"in 'choices' (%d < %d).\" % (self.max_length, choice_max_length),\n+                        obj=self,\n+                        id='fields.E122',\n+                    )\n+                ]\n+        return []\n \n     def cast_db_type(self, connection):\n         if self.max_length is None:\ndiff --git a/tests/invalid_models_tests/test_ordinary_fields.py b/tests/invalid_models_tests/test_ordinary_fields.py\nindex 5bb1847a70..c06283cdfe 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,44 @@ class CharFieldTests(SimpleTestCase):\n \n         self.assertEqual(Model._meta.get_field('field').check(), [])\n \n+    def test_max_length_with_choices_with_max_length(self):\n+        \"\"\"max_length is large enough to fit the longest choice value.\"\"\"\n+        class Model(models.Model):\n+            field = models.CharField(max_length=2, choices=[('ab', 'AB'), ('c', 'C')])\n+\n+        self.assertEqual(Model._meta.get_field('field').check(), [])\n+\n+    def test_max_length_smaller_than_longest_choice(self):\n+        class Model(models.Model):\n+            field = models.CharField(max_length=2, choices=[('abc', 'ABC'), ('c', 'C')])\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.E122',\n+            ),\n+        ])\n+\n+    def test_max_length_smaller_than_longest_named_group_choice(self):\n+        class Model(models.Model):\n+            field = models.CharField(\n+                max_length=2,\n+                choices=[['Group', [['abc', 'ABC'], ['c', 'C']]]],\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.E122',\n+            ),\n+        ])\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": "claude-code/claude-sonnet-4-6", "model_patch": ""}
{"instance_id": "django__django-11815", "model_name_or_path": "claude-code/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": "claude-code/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'))\n"}
