5.2.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. ============================================
  2. Django 5.2 release notes - UNDER DEVELOPMENT
  3. ============================================
  4. *Expected April 2025*
  5. Welcome to Django 5.2!
  6. These release notes cover the :ref:`new features <whats-new-5.2>`, as well as
  7. some :ref:`backwards incompatible changes <backwards-incompatible-5.2>` you
  8. should be aware of when upgrading from Django 5.1 or earlier. We've
  9. :ref:`begun the deprecation process for some features
  10. <deprecated-features-5.2>`.
  11. See the :doc:`/howto/upgrade-version` guide if you're updating an existing
  12. project.
  13. Django 5.2 is designated as a :term:`long-term support release
  14. <Long-term support release>`. It will receive security updates for at least
  15. three years after its release. Support for the previous LTS, Django 4.2, will
  16. end in April 2026.
  17. Python compatibility
  18. ====================
  19. Django 5.2 supports Python 3.10, 3.11, 3.12, and 3.13. We **highly recommend**
  20. and only officially support the latest release of each series.
  21. .. _whats-new-5.2:
  22. What's new in Django 5.2
  23. ========================
  24. Automatic models import in the ``shell``
  25. ----------------------------------------
  26. The :djadmin:`shell` management command now automatically imports models from
  27. all installed apps. You can view further details of the imported objects by
  28. setting the ``--verbosity`` flag to 2 or more:
  29. .. console::
  30. $ python -Wall manage.py shell --verbosity=2
  31. 6 objects imported automatically, including:
  32. from django.contrib.admin.models import LogEntry
  33. from django.contrib.auth.models import Group, Permission, User
  34. from django.contrib.contenttypes.models import ContentType
  35. from django.contrib.sessions.models import Session
  36. This :ref:`behavior can be customized <customizing-shell-auto-imports>` to add
  37. or remove automatic imports.
  38. Composite Primary Keys
  39. ----------------------
  40. The new :class:`django.db.models.CompositePrimaryKey` allows tables to be
  41. created with a primary key consisting of multiple fields.
  42. To use a composite primary key, when defining a model set the ``pk`` attribute
  43. to be a ``CompositePrimaryKey``::
  44. from django.db import models
  45. class Release(models.Model):
  46. pk = models.CompositePrimaryKey("version", "name")
  47. version = models.IntegerField()
  48. name = models.CharField(max_length=20)
  49. See :doc:`/topics/composite-primary-key` for more details.
  50. Simplified override of :class:`~django.forms.BoundField`
  51. --------------------------------------------------------
  52. Prior to version 5.2, overriding :meth:`.Field.get_bound_field()` was the only
  53. option to use a custom :class:`~django.forms.BoundField`. Django now supports
  54. specifying the following attributes to customize form rendering:
  55. * :attr:`.BaseRenderer.bound_field_class` at the project level,
  56. * :attr:`.Form.bound_field_class` at the form level, and
  57. * :attr:`.Field.bound_field_class` at the field level.
  58. For example, to customize the ``BoundField`` of a ``Form`` class::
  59. from django import forms
  60. class CustomBoundField(forms.BoundField):
  61. custom_class = "custom"
  62. def css_classes(self, extra_classes=None):
  63. result = super().css_classes(extra_classes)
  64. if self.custom_class not in result:
  65. result += f" {self.custom_class}"
  66. return result.strip()
  67. class CustomForm(forms.Form):
  68. bound_field_class = CustomBoundField
  69. name = forms.CharField(
  70. label="Your Name",
  71. max_length=100,
  72. required=False,
  73. widget=forms.TextInput(attrs={"class": "name-input-class"}),
  74. )
  75. email = forms.EmailField(label="Your Email")
  76. When rendering a ``CustomForm`` instance, the following HTML is included:
  77. .. code:: html
  78. <div class="custom">
  79. <label for="id_name">Your Name:</label>
  80. <input type="text" name="name" class="name-input-class" maxlength="100" id="id_name">
  81. </div>
  82. <div class="custom">
  83. <label for="id_email">Your Email:</label>
  84. <input type="email" name="email" maxlength="320" required="" id="id_email">
  85. </div>
  86. See :ref:`custom-boundfield` for more details about this feature.
  87. Minor features
  88. --------------
  89. :mod:`django.contrib.admin`
  90. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  91. * The ``admin/base.html`` template now has a new block
  92. :ref:`extrabody <extrabody>` for adding custom code before the closing
  93. ``</body>`` tag.
  94. * The value of a :class:`~django.db.models.URLField` now renders as a link.
  95. :mod:`django.contrib.admindocs`
  96. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. * Links to components in docstrings now supports custom link text, using the
  98. format ``:role:`link text <link>```. See :ref:`documentation helpers
  99. <admindocs-helpers>` for more details.
  100. * The :ref:`model pages <admindocs-model-reference>` are now restricted to
  101. users with the corresponding view or change permissions.
  102. :mod:`django.contrib.auth`
  103. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  104. * The default iteration count for the PBKDF2 password hasher is increased from
  105. 870,000 to 1,000,000.
  106. * The following new asynchronous methods are now provided, using an ``a``
  107. prefix:
  108. * :meth:`.UserManager.acreate_user`
  109. * :meth:`.UserManager.acreate_superuser`
  110. * :meth:`.BaseUserManager.aget_by_natural_key`
  111. * :meth:`.User.aget_user_permissions`
  112. * :meth:`.User.aget_all_permissions`
  113. * :meth:`.User.aget_group_permissions`
  114. * :meth:`.User.ahas_perm`
  115. * :meth:`.User.ahas_perms`
  116. * :meth:`.User.ahas_module_perms`
  117. * :meth:`.ModelBackend.aauthenticate`
  118. * :meth:`.ModelBackend.aget_user_permissions`
  119. * :meth:`.ModelBackend.aget_group_permissions`
  120. * :meth:`.ModelBackend.aget_all_permissions`
  121. * :meth:`.ModelBackend.ahas_perm`
  122. * :meth:`.ModelBackend.ahas_module_perms`
  123. * :meth:`.RemoteUserBackend.aauthenticate`
  124. * :meth:`.RemoteUserBackend.aconfigure_user`
  125. * Auth backends can now provide async implementations which are used when
  126. calling async auth functions (e.g.
  127. :func:`~.django.contrib.auth.aauthenticate`) to reduce context-switching
  128. which improves performance. See :ref:`adding an async interface
  129. <writing-authentication-backends-async-interface>` for more details.
  130. * The :ref:`password validator classes <included-password-validators>`
  131. now have a new method ``get_error_message()``, which can be overridden in
  132. subclasses to customize the error messages.
  133. :mod:`django.contrib.gis`
  134. ~~~~~~~~~~~~~~~~~~~~~~~~~
  135. * GDAL now supports curved geometries ``CurvePolygon``, ``CompoundCurve``,
  136. ``CircularString``, ``MultiSurface``, and ``MultiCurve`` via the new
  137. :attr:`.OGRGeometry.has_curve` property, and the
  138. :meth:`.OGRGeometry.get_linear_geometry` and
  139. :meth:`.OGRGeometry.get_curve_geometry` methods.
  140. * :lookup:`coveredby` and :lookup:`covers` lookup are now supported on MySQL.
  141. :mod:`django.contrib.syndication`
  142. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  143. * All :class:`~django.utils.feedgenerator.SyndicationFeed` classes now support
  144. a ``stylesheets`` attribute. If specified, an ``<? xml-stylesheet ?>``
  145. processing instruction will be added to the top of the document for each
  146. stylesheet in the given list. See :ref:`feed-stylesheets` for more details.
  147. Database backends
  148. ~~~~~~~~~~~~~~~~~
  149. * MySQL connections now default to using the ``utf8mb4`` character set,
  150. instead of ``utf8``, which is an alias for the deprecated character set
  151. ``utf8mb3``.
  152. * Oracle backends now support :ref:`connection pools <oracle-pool>`, by setting
  153. ``"pool"`` in the :setting:`OPTIONS` part of your database configuration.
  154. Decorators
  155. ~~~~~~~~~~
  156. * :func:`~django.utils.decorators.method_decorator` now supports wrapping
  157. asynchronous view methods.
  158. Email
  159. ~~~~~
  160. * Tuple items of :class:`EmailMessage.attachments
  161. <django.core.mail.EmailMessage>` and
  162. :class:`EmailMultiAlternatives.attachments
  163. <django.core.mail.EmailMultiAlternatives>` are now named tuples, as opposed
  164. to regular tuples.
  165. * :attr:`EmailMultiAlternatives.alternatives
  166. <django.core.mail.EmailMultiAlternatives.alternatives>` is now a list of
  167. named tuples, as opposed to regular tuples.
  168. * The new :meth:`~django.core.mail.EmailMultiAlternatives.body_contains` method
  169. returns a boolean indicating whether a provided text is contained in the
  170. email ``body`` and in all attached MIME type ``text/*`` alternatives.
  171. Error Reporting
  172. ~~~~~~~~~~~~~~~
  173. * The attribute :attr:`.SafeExceptionReporterFilter.hidden_settings` now
  174. treats values as sensitive if their name includes ``AUTH``.
  175. Forms
  176. ~~~~~
  177. * The new :class:`~django.forms.ColorInput` form widget is for entering a color
  178. in ``rrggbb`` hexadecimal format and renders as ``<input type="color" ...>``.
  179. Some browsers support a visual color picker interface for this input type.
  180. * The new :class:`~django.forms.SearchInput` form widget is for entering search
  181. queries and renders as ``<input type="search" ...>``.
  182. * The new :class:`~django.forms.TelInput` form widget is for entering telephone
  183. numbers and renders as ``<input type="tel" ...>``.
  184. * The new ``field_id`` argument for :class:`~django.forms.ErrorList` allows an
  185. HTML ``id`` attribute to be added in the error template. See
  186. :attr:`.ErrorList.field_id` for details.
  187. * An :attr:`~django.forms.BoundField.aria_describedby` property is added to
  188. ``BoundField`` to ease use of this HTML attribute in templates.
  189. * To improve accessibility for screen reader users ``aria-describedby`` is used
  190. to associate form fields with their error messages. See
  191. :ref:`how form errors are displayed <form-error-display>` for details.
  192. * The new asset object :class:`~django.forms.Script` is available for adding
  193. custom HTML-attributes to JavaScript in form media. See
  194. :ref:`paths as objects <form-media-asset-objects>` for more details.
  195. Management Commands
  196. ~~~~~~~~~~~~~~~~~~~
  197. * A new warning is displayed when running :djadmin:`runserver`, indicating that
  198. it is unsuitable for production. This warning can be suppressed by setting
  199. the :envvar:`HIDE_PRODUCTION_WARNING` environment variable to ``"true"``.
  200. * The :djadmin:`makemigrations` and :djadmin:`migrate` commands have a new
  201. ``Command.autodetector`` attribute for subclasses to override in order to use
  202. a custom autodetector class.
  203. * The new :meth:`.BaseCommand.get_check_kwargs` method can be overridden in
  204. custom commands to control the running of system checks, e.g. to opt into
  205. database-dependent checks.
  206. Migrations
  207. ~~~~~~~~~~
  208. * The new operation :class:`.AlterConstraint` is a no-op operation that alters
  209. constraints without dropping and recreating constraints in the database.
  210. Models
  211. ~~~~~~
  212. * The ``SELECT`` clause generated when using :meth:`.QuerySet.values` and
  213. :meth:`.QuerySet.values_list` now matches the specified order of the
  214. referenced expressions. Previously, the order was based on a set of
  215. counterintuitive rules which made query combination through methods such as
  216. :meth:`.QuerySet.union` unpredictable.
  217. * Added support for validation of model constraints which use a
  218. :class:`~django.db.models.GeneratedField`.
  219. * The new :attr:`.Expression.set_returning` attribute specifies that the
  220. expression contains a set-returning function, enforcing subquery evaluation.
  221. This is necessary for many Postgres set-returning functions.
  222. * :attr:`CharField.max_length <django.db.models.CharField.max_length>` is no
  223. longer required to be set on SQLite, which supports unlimited ``VARCHAR``
  224. columns.
  225. * :meth:`.QuerySet.explain` now supports the ``memory`` and ``serialize``
  226. options on PostgreSQL 17+.
  227. * The new :class:`~django.db.models.functions.JSONArray` database function
  228. accepts a list of field names or expressions and returns a JSON array
  229. containing those values.
  230. * The new :attr:`.Expression.allows_composite_expressions` attribute specifies
  231. that the expression allows composite expressions, for example, to support
  232. :ref:`composite primary keys <cpk-and-database-functions>`.
  233. Requests and Responses
  234. ~~~~~~~~~~~~~~~~~~~~~~
  235. * The new :attr:`.HttpResponse.text` property provides the string
  236. representation of :attr:`.HttpResponse.content`.
  237. * The new :meth:`.HttpRequest.get_preferred_type` method can be used to query
  238. the preferred media type the client accepts.
  239. * The new ``preserve_request`` argument for
  240. :class:`~django.http.HttpResponseRedirect` and
  241. :class:`~django.http.HttpResponsePermanentRedirect`
  242. determines whether the HTTP status codes 302/307 or 301/308 are used,
  243. respectively.
  244. * The new ``preserve_request`` argument for
  245. :func:`~django.shortcuts.redirect` allows to instruct the user agent to reuse
  246. the HTTP method and body during redirection using specific status codes.
  247. Serialization
  248. ~~~~~~~~~~~~~
  249. * Each serialization format now defines a ``Deserializer`` class, rather than a
  250. function, to improve extensibility when defining a
  251. :ref:`custom serialization format <custom-serialization-formats>`.
  252. Templates
  253. ~~~~~~~~~
  254. * The new :meth:`~django.template.Library.simple_block_tag` decorator enables
  255. the creation of simple block tags, which can accept and use a section of the
  256. template.
  257. Tests
  258. ~~~~~
  259. * Stack frames from Django's custom assertions are now hidden. This makes test
  260. failures easier to read and enables :option:`test --pdb` to directly enter
  261. into the failing test method.
  262. * Data loaded from :attr:`~django.test.TransactionTestCase.fixtures` and from
  263. migrations enabled with :ref:`serialized_rollback=True
  264. <test-case-serialized-rollback>` are now available during
  265. ``TransactionTestCase.setUpClass()``.
  266. URLs
  267. ~~~~
  268. * :func:`~django.urls.reverse` now accepts ``query`` and ``fragment`` keyword
  269. arguments, allowing the addition of a query string and/or fragment identifier
  270. in the generated URL, respectively.
  271. Utilities
  272. ~~~~~~~~~
  273. * :class:`~django.utils.safestring.SafeString` now returns
  274. :py:data:`NotImplemented` in ``__add__`` for non-string right-hand side
  275. values. This aligns with the :py:class:`str` addition behavior and allows
  276. ``__radd__`` to be used if available.
  277. * :func:`~django.utils.html.format_html_join` now supports taking an iterable
  278. of mappings, passing their contents as keyword arguments to
  279. :func:`~django.utils.html.format_html`.
  280. .. _backwards-incompatible-5.2:
  281. Backwards incompatible changes in 5.2
  282. =====================================
  283. Database backend API
  284. --------------------
  285. This section describes changes that may be needed in third-party database
  286. backends.
  287. * The new :meth:`Model._is_pk_set() <django.db.models.Model._is_pk_set>` method
  288. allows checking if a Model instance's primary key is defined.
  289. * ``BaseDatabaseOperations.adapt_decimalfield_value()`` is now a no-op, simply
  290. returning the given value.
  291. :mod:`django.contrib.gis`
  292. -------------------------
  293. * Support for PostGIS 3.0 is removed.
  294. * Support for GDAL 3.0 is removed.
  295. Dropped support for PostgreSQL 13
  296. ---------------------------------
  297. Upstream support for PostgreSQL 13 ends in November 2025. Django 5.2 supports
  298. PostgreSQL 14 and higher.
  299. Changed MySQL connection character set default
  300. ----------------------------------------------
  301. MySQL connections now default to using the ``utf8mb4`` character set, instead
  302. of ``utf8``, which is an alias for the deprecated character set ``utf8mb3``.
  303. ``utf8mb3`` can be specified in the ``OPTIONS`` part of the ``DATABASES``
  304. setting, if needed for legacy databases.
  305. Miscellaneous
  306. -------------
  307. * Adding :attr:`.EmailMultiAlternatives.alternatives` is now only supported via
  308. the :meth:`~.EmailMultiAlternatives.attach_alternative` method.
  309. * The minimum supported version of ``gettext`` is increased from 0.15 to 0.19.
  310. * ``HttpRequest.accepted_types`` is now sorted by the client's preference,
  311. based on the request's ``Accept`` header.
  312. * The attributes :attr:`.UniqueConstraint.violation_error_code` and
  313. :attr:`.UniqueConstraint.violation_error_message` are now always used when
  314. provided. Previously, they were ignored if :attr:`.UniqueConstraint.fields`
  315. was set without a :attr:`.UniqueConstraint.condition`.
  316. * The :func:`~django.template.context_processors.debug` context processor is no
  317. longer included in the default project template.
  318. * The following methods now have ``alters_data=True`` set to prevent side
  319. effects when :ref:`rendering a template context <alters-data-description>`:
  320. * :meth:`.UserManager.create_user`
  321. * :meth:`.UserManager.acreate_user`
  322. * :meth:`.UserManager.create_superuser`
  323. * :meth:`.UserManager.acreate_superuser`
  324. * :meth:`.QuerySet.create`
  325. * :meth:`.QuerySet.acreate`
  326. * :meth:`.QuerySet.bulk_create`
  327. * :meth:`.QuerySet.abulk_create`
  328. * :meth:`.QuerySet.get_or_create`
  329. * :meth:`.QuerySet.aget_or_create`
  330. * :meth:`.QuerySet.update_or_create`
  331. * :meth:`.QuerySet.aupdate_or_create`
  332. * The minimum supported version of ``oracledb`` is increased from 1.3.2 to
  333. 2.3.0.
  334. * Built-in aggregate functions accepting only one argument (``Avg``, ``Count``,
  335. ``Max``, ``Min``, ``StdDev``, ``Sum``, and ``Variance``) now raise
  336. :exc:`TypeError` when called with an incorrect number of arguments.
  337. .. _deprecated-features-5.2:
  338. Features deprecated in 5.2
  339. ==========================
  340. Miscellaneous
  341. -------------
  342. * The ``all`` argument for the ``django.contrib.staticfiles.finders.find()``
  343. function is deprecated in favor of the ``find_all`` argument.
  344. * The fallback to ``request.user`` when ``user`` is ``None`` in
  345. ``django.contrib.auth.login()`` and ``django.contrib.auth.alogin()`` will be
  346. removed.
  347. * The ``ordering`` keyword argument of the PostgreSQL specific aggregation
  348. functions ``django.contrib.postgres.aggregates.ArrayAgg``,
  349. ``django.contrib.postgres.aggregates.JSONBAgg``, and
  350. ``django.contrib.postgres.aggregates.StringAgg`` is deprecated in favor
  351. of the ``order_by`` argument.