4.2.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. ============================================
  2. Django 4.2 release notes - UNDER DEVELOPMENT
  3. ============================================
  4. *Expected April 2023*
  5. Welcome to Django 4.2!
  6. These release notes cover the :ref:`new features <whats-new-4.2>`, as well as
  7. some :ref:`backwards incompatible changes <backwards-incompatible-4.2>` you'll
  8. want to be aware of when upgrading from Django 4.1 or earlier. We've
  9. :ref:`begun the deprecation process for some features
  10. <deprecated-features-4.2>`.
  11. See the :doc:`/howto/upgrade-version` guide if you're updating an existing
  12. project.
  13. Python compatibility
  14. ====================
  15. Django 4.2 supports Python 3.8, 3.9, 3.10, and 3.11. We **highly recommend**
  16. and only officially support the latest release of each series.
  17. .. _whats-new-4.2:
  18. What's new in Django 4.2
  19. ========================
  20. Psycopg 3 support
  21. -----------------
  22. Django now supports `psycopg`_ version 3.1 or higher. To update your code,
  23. install the `psycopg library`_, you don't need to change the
  24. :setting:`ENGINE <DATABASE-ENGINE>` as ``django.db.backends.postgresql``
  25. supports both libraries.
  26. Support for ``psycopg2`` is likely to be deprecated and removed at some point
  27. in the future.
  28. .. _psycopg: https://www.psycopg.org/psycopg3/
  29. .. _psycopg library: https://pypi.org/project/psycopg/
  30. Comments on columns and tables
  31. ------------------------------
  32. The new :attr:`Field.db_comment <django.db.models.Field.db_comment>` and
  33. :attr:`Meta.db_table_comment <django.db.models.Options.db_table_comment>`
  34. options allow creating comments on columns and tables, respectively. For
  35. example::
  36. from django.db import models
  37. class Question(models.Model):
  38. text = models.TextField(db_comment="Poll question")
  39. pub_date = models.DateTimeField(
  40. db_comment="Date and time when the question was published",
  41. )
  42. class Meta:
  43. db_table_comment = "Poll questions"
  44. class Answer(models.Model):
  45. question = models.ForeignKey(
  46. Question,
  47. on_delete=models.CASCADE,
  48. db_comment="Reference to a question"
  49. )
  50. answer = models.TextField(db_comment="Question answer")
  51. class Meta:
  52. db_table_comment = "Question answers"
  53. Also, the new :class:`~django.db.migrations.operations.AlterModelTableComment`
  54. operation allows changing table comments defined in the
  55. :attr:`Meta.db_table_comment <django.db.models.Options.db_table_comment>`.
  56. Mitigation for the BREACH attack
  57. --------------------------------
  58. :class:`~django.middleware.gzip.GZipMiddleware` now includes a mitigation for
  59. the BREACH attack. It will add up to 100 random bytes to gzip responses to make
  60. BREACH attacks harder. Read more about the mitigation technique in the `Heal
  61. The Breach (HTB) paper`_.
  62. .. _Heal The Breach (HTB) paper: https://ieeexplore.ieee.org/document/9754554
  63. Minor features
  64. --------------
  65. :mod:`django.contrib.admin`
  66. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  67. * The light or dark color theme of the admin can now be toggled in the UI, as
  68. well as being set to follow the system setting.
  69. * The admin's font stack now prefers system UI fonts and no longer requires
  70. downloading fonts. Additionally, CSS variables are available to more easily
  71. override the default font families.
  72. * The :source:`admin/delete_confirmation.html
  73. <django/contrib/admin/templates/admin/delete_confirmation.html>` template now
  74. has some additional blocks and scripting hooks to ease customization.
  75. * The chosen options of
  76. :attr:`~django.contrib.admin.ModelAdmin.filter_horizontal` and
  77. :attr:`~django.contrib.admin.ModelAdmin.filter_vertical` widgets are now
  78. filterable.
  79. * The ``admin/base.html`` template now has a new block ``nav-breadcrumbs``
  80. which contains the navigation landmark and the ``breadcrumbs`` block.
  81. * :attr:`.ModelAdmin.list_editable` now uses atomic transactions when making
  82. edits.
  83. :mod:`django.contrib.admindocs`
  84. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  85. * ...
  86. :mod:`django.contrib.auth`
  87. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  88. * The default iteration count for the PBKDF2 password hasher is increased from
  89. 390,000 to 480,000.
  90. * :class:`~django.contrib.auth.forms.UserCreationForm` now saves many-to-many
  91. form fields for a custom user model.
  92. * The new :class:`~django.contrib.auth.forms.BaseUserCreationForm` is now the
  93. recommended base class for customizing the user creation form.
  94. :mod:`django.contrib.contenttypes`
  95. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  96. * ...
  97. :mod:`django.contrib.gis`
  98. ~~~~~~~~~~~~~~~~~~~~~~~~~
  99. * The :doc:`GeoJSON serializer </ref/contrib/gis/serializers>` now outputs the
  100. ``id`` key for serialized features, which defaults to the primary key of
  101. objects.
  102. * The :class:`~django.contrib.gis.gdal.GDALRaster` class now supports
  103. :class:`pathlib.Path`.
  104. * The :class:`~django.contrib.gis.geoip2.GeoIP2` class now supports ``.mmdb``
  105. files downloaded from DB-IP.
  106. * The OpenLayers template widget no longer includes inline CSS (which also
  107. removes the former ``map_css`` block) to better comply with a strict Content
  108. Security Policy.
  109. * :class:`~django.contrib.gis.forms.widgets.OpenLayersWidget` is now based on
  110. OpenLayers 7.2.2 (previously 4.6.5).
  111. :mod:`django.contrib.messages`
  112. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  113. * ...
  114. :mod:`django.contrib.postgres`
  115. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  116. * The new :lookup:`trigram_strict_word_similar` lookup, and the
  117. :class:`TrigramStrictWordSimilarity()
  118. <django.contrib.postgres.search.TrigramStrictWordSimilarity>` and
  119. :class:`TrigramStrictWordDistance()
  120. <django.contrib.postgres.search.TrigramStrictWordDistance>` expressions allow
  121. using trigram strict word similarity.
  122. * The :lookup:`arrayfield.overlap` lookup now supports ``QuerySet.values()``
  123. and ``values_list()`` as a right-hand side.
  124. :mod:`django.contrib.redirects`
  125. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  126. * ...
  127. :mod:`django.contrib.sessions`
  128. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  129. * ...
  130. :mod:`django.contrib.sitemaps`
  131. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  132. * The new :meth:`.Sitemap.get_languages_for_item` method allows customizing the
  133. list of languages for which the item is displayed.
  134. :mod:`django.contrib.sites`
  135. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  136. * ...
  137. :mod:`django.contrib.staticfiles`
  138. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  139. * :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` now
  140. replaces paths to JavaScript modules in ``import`` and ``export`` statements
  141. with their hashed counterparts.
  142. :mod:`django.contrib.syndication`
  143. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  144. * ...
  145. Cache
  146. ~~~~~
  147. * ...
  148. CSRF
  149. ~~~~
  150. * ...
  151. Decorators
  152. ~~~~~~~~~~
  153. * ...
  154. Email
  155. ~~~~~
  156. * ...
  157. Error Reporting
  158. ~~~~~~~~~~~~~~~
  159. * The debug page now shows :pep:`exception notes <678>` and
  160. :pep:`fine-grained error locations <657>` on Python 3.11+.
  161. File Storage
  162. ~~~~~~~~~~~~
  163. * ...
  164. File Uploads
  165. ~~~~~~~~~~~~
  166. * ...
  167. Forms
  168. ~~~~~
  169. * :class:`~django.forms.ModelForm` now accepts the new ``Meta`` option
  170. ``formfield_callback`` to customize form fields.
  171. * :func:`~django.forms.models.modelform_factory` now respects the
  172. ``formfield_callback`` attribute of the ``form``’s ``Meta``.
  173. * Session cookies are now treated as credentials and therefore hidden and
  174. replaced with stars (``**********``) in error reports.
  175. Generic Views
  176. ~~~~~~~~~~~~~
  177. * ...
  178. Internationalization
  179. ~~~~~~~~~~~~~~~~~~~~
  180. * Added support and translations for the Central Kurdish (Sorani) language.
  181. * The :class:`~django.middleware.locale.LocaleMiddleware` now respects a
  182. language from the request when :func:`~django.conf.urls.i18n.i18n_patterns`
  183. is used with the ``prefix_default_language`` argument set to ``False``.
  184. Logging
  185. ~~~~~~~
  186. * The :ref:`django-db-logger` logger now logs transaction management queries
  187. (``BEGIN``, ``COMMIT``, and ``ROLLBACK``) at the ``DEBUG`` level.
  188. Management Commands
  189. ~~~~~~~~~~~~~~~~~~~
  190. * :djadmin:`makemessages` command now supports locales with private sub-tags
  191. such as ``nl_NL-x-informal``.
  192. * The new :option:`makemigrations --update` option merges model changes into
  193. the latest migration and optimizes the resulting operations.
  194. Migrations
  195. ~~~~~~~~~~
  196. * Migrations now support serialization of ``enum.Flag`` objects.
  197. Models
  198. ~~~~~~
  199. * ``QuerySet`` now extensively supports filtering against
  200. :ref:`window-functions` with the exception of disjunctive filter lookups
  201. against window functions when performing aggregation.
  202. * :meth:`~.QuerySet.prefetch_related` now supports
  203. :class:`~django.db.models.Prefetch` objects with sliced querysets.
  204. * :ref:`Registering lookups <lookup-registration-api>` on
  205. :class:`~django.db.models.Field` instances is now supported.
  206. * The new ``robust`` argument for :func:`~django.db.transaction.on_commit`
  207. allows performing actions that can fail after a database transaction is
  208. successfully committed.
  209. * The new :class:`KT() <django.db.models.fields.json.KT>` expression represents
  210. the text value of a key, index, or path transform of
  211. :class:`~django.db.models.JSONField`.
  212. * :class:`~django.db.models.functions.Now` now supports microsecond precision
  213. on MySQL and millisecond precision on SQLite.
  214. * :class:`F() <django.db.models.F>` expressions that output ``BooleanField``
  215. can now be negated using ``~F()`` (inversion operator).
  216. * ``Model`` now provides asynchronous versions of some methods that use the
  217. database, using an ``a`` prefix: :meth:`~.Model.adelete`,
  218. :meth:`~.Model.arefresh_from_db`, and :meth:`~.Model.asave`.
  219. * Related managers now provide asynchronous versions of methods that change a
  220. set of related objects, using an ``a`` prefix: :meth:`~.RelatedManager.aadd`,
  221. :meth:`~.RelatedManager.aclear`, :meth:`~.RelatedManager.aremove`, and
  222. :meth:`~.RelatedManager.aset`.
  223. * :attr:`CharField.max_length <django.db.models.CharField.max_length>` is no
  224. longer required to be set on PostgreSQL, which supports unlimited ``VARCHAR``
  225. columns.
  226. Requests and Responses
  227. ~~~~~~~~~~~~~~~~~~~~~~
  228. * :class:`~django.http.StreamingHttpResponse` now supports async iterators
  229. when Django is served via ASGI.
  230. Security
  231. ~~~~~~~~
  232. * ...
  233. Serialization
  234. ~~~~~~~~~~~~~
  235. * ...
  236. Signals
  237. ~~~~~~~
  238. * ...
  239. Templates
  240. ~~~~~~~~~
  241. * ...
  242. Tests
  243. ~~~~~
  244. * The :option:`test --debug-sql` option now formats SQL queries with
  245. ``sqlparse``.
  246. * The :class:`~django.test.RequestFactory`,
  247. :class:`~django.test.AsyncRequestFactory`, :class:`~django.test.Client`, and
  248. :class:`~django.test.AsyncClient` classes now support the ``headers``
  249. parameter, which accepts a dictionary of header names and values. This allows
  250. a more natural syntax for declaring headers.
  251. .. code-block:: python
  252. # Before:
  253. self.client.get("/home/", HTTP_ACCEPT_LANGUAGE="fr")
  254. await self.async_client.get("/home/", ACCEPT_LANGUAGE="fr")
  255. # After:
  256. self.client.get("/home/", headers={"accept-language": "fr"})
  257. await self.async_client.get("/home/", headers={"accept-language": "fr"})
  258. URLs
  259. ~~~~
  260. * ...
  261. Utilities
  262. ~~~~~~~~~
  263. * The new ``encoder`` parameter for :meth:`django.utils.html.json_script`
  264. function allows customizing a JSON encoder class.
  265. * The private internal vendored copy of ``urllib.parse.urlsplit()`` now strips
  266. ``'\r'``, ``'\n'``, and ``'\t'`` (see :cve:`2022-0391` and :bpo:`43882`).
  267. This is to protect projects that may be incorrectly using the internal
  268. ``url_has_allowed_host_and_scheme()`` function, instead of using one of the
  269. documented functions for handling URL redirects. The Django functions were
  270. not affected.
  271. * The new :func:`django.utils.http.content_disposition_header` function returns
  272. a ``Content-Disposition`` HTTP header value as specified by :rfc:`6266`.
  273. Validators
  274. ~~~~~~~~~~
  275. * The list of common passwords used by ``CommonPasswordValidator`` is updated
  276. to the most recent version.
  277. .. _backwards-incompatible-4.2:
  278. Backwards incompatible changes in 4.2
  279. =====================================
  280. Database backend API
  281. --------------------
  282. This section describes changes that may be needed in third-party database
  283. backends.
  284. * ``DatabaseFeatures.allows_group_by_pk`` is removed as it only remained to
  285. accommodate a MySQL extension that has been supplanted by proper functional
  286. dependency detection in MySQL 5.7.15. Note that
  287. ``DatabaseFeatures.allows_group_by_selected_pks`` is still supported and
  288. should be enabled if your backend supports functional dependency detection in
  289. ``GROUP BY`` clauses as specified by the ``SQL:1999`` standard.
  290. Dropped support for MariaDB 10.3
  291. --------------------------------
  292. Upstream support for MariaDB 10.3 ends in May 2023. Django 4.2 supports MariaDB
  293. 10.4 and higher.
  294. Dropped support for MySQL 5.7
  295. -----------------------------
  296. Upstream support for MySQL 5.7 ends in October 2023. Django 4.2 supports MySQL
  297. 8 and higher.
  298. Dropped support for PostgreSQL 11
  299. ---------------------------------
  300. Upstream support for PostgreSQL 11 ends in November 2023. Django 4.2 supports
  301. PostgreSQL 12 and higher.
  302. Setting ``update_fields`` in ``Model.save()`` may now be required
  303. -----------------------------------------------------------------
  304. In order to avoid updating unnecessary columns,
  305. :meth:`.QuerySet.update_or_create` now passes ``update_fields`` to the
  306. :meth:`Model.save() <django.db.models.Model.save>` calls. As a consequence, any
  307. fields modified in the custom ``save()`` methods should be added to the
  308. ``update_fields`` keyword argument before calling ``super()``. See
  309. :ref:`overriding-model-methods` for more details.
  310. Miscellaneous
  311. -------------
  312. * The undocumented ``SimpleTemplateResponse.rendering_attrs`` and
  313. ``TemplateResponse.rendering_attrs`` are renamed to ``non_picklable_attrs``.
  314. * The undocumented ``django.http.multipartparser.parse_header()`` function is
  315. removed. Use ``django.utils.http.parse_header_parameters()`` instead.
  316. * :ttag:`{% blocktranslate asvar … %}<blocktranslate>` result is now marked as
  317. safe for (HTML) output purposes.
  318. * The ``autofocus`` HTML attribute in the admin search box is removed as it can
  319. be confusing for screen readers.
  320. * The :option:`makemigrations --check` option no longer creates missing
  321. migration files.
  322. * The ``alias`` argument for :meth:`.Expression.get_group_by_cols` is removed.
  323. * The minimum supported version of ``sqlparse`` is increased from 0.2.2 to
  324. 0.2.3.
  325. * The undocumented ``negated`` parameter of the
  326. :class:`~django.db.models.Exists` expression is removed.
  327. * The ``is_summary`` argument of the undocumented ``Query.add_annotation()``
  328. method is removed.
  329. * The minimum supported version of SQLite is increased from 3.9.0 to 3.21.0.
  330. * :djadmin:`inspectdb` now uses ``display_size`` from
  331. ``DatabaseIntrospection.get_table_description()`` rather than
  332. ``internal_size`` for ``CharField``.
  333. * The minimum supported version of ``asgiref`` is increased from 3.5.2 to
  334. 3.6.0.
  335. * :class:`~django.contrib.auth.forms.UserCreationForm` now rejects usernames
  336. that differ only in case. If you need the previous behavior, use
  337. :class:`~django.contrib.auth.forms.BaseUserCreationForm` instead.
  338. .. _deprecated-features-4.2:
  339. Features deprecated in 4.2
  340. ==========================
  341. ``index_together`` option is deprecated in favor of ``indexes``
  342. ---------------------------------------------------------------
  343. The :attr:`Meta.index_together <django.db.models.Options.index_together>`
  344. option is deprecated in favor of the :attr:`~django.db.models.Options.indexes`
  345. option.
  346. Migrating existing ``index_together`` should be handled as a migration. For
  347. example::
  348. class Author(models.Model):
  349. rank = models.IntegerField()
  350. name = models.CharField(max_length=30)
  351. class Meta:
  352. index_together = [["rank", "name"]]
  353. Should become::
  354. class Author(models.Model):
  355. rank = models.IntegerField()
  356. name = models.CharField(max_length=30)
  357. class Meta:
  358. indexes = [models.Index(fields=["rank", "name"])]
  359. Running the :djadmin:`makemigrations` command will generate a migration
  360. containing a :class:`~django.db.migrations.operations.RenameIndex` operation
  361. which will rename the existing index.
  362. The ``AlterIndexTogether`` migration operation is now officially supported only
  363. for pre-Django 4.2 migration files. For backward compatibility reasons, it's
  364. still part of the public API, and there's no plan to deprecate or remove it,
  365. but it should not be used for new migrations. Use
  366. :class:`~django.db.migrations.operations.AddIndex` and
  367. :class:`~django.db.migrations.operations.RemoveIndex` operations instead.
  368. Passing encoded JSON string literals to ``JSONField`` is deprecated
  369. -------------------------------------------------------------------
  370. ``JSONField`` and its associated lookups and aggregates use to allow passing
  371. JSON encoded string literals which caused ambiguity on whether string literals
  372. were already encoded from database backend's perspective.
  373. During the deprecation period string literals will be attempted to be JSON
  374. decoded and a warning will be emitted on success that points at passing
  375. non-encoded forms instead.
  376. Code that use to pass JSON encoded string literals::
  377. Document.objects.bulk_create(
  378. Document(data=Value("null")),
  379. Document(data=Value("[]")),
  380. Document(data=Value('"foo-bar"')),
  381. )
  382. Document.objects.annotate(
  383. JSONBAgg("field", default=Value('[]')),
  384. )
  385. Should become::
  386. Document.objects.bulk_create(
  387. Document(data=Value(None, JSONField())),
  388. Document(data=[]),
  389. Document(data="foo-bar"),
  390. )
  391. Document.objects.annotate(
  392. JSONBAgg("field", default=[]),
  393. )
  394. From Django 5.1+ string literals will be implicitly interpreted as JSON string
  395. literals.
  396. Miscellaneous
  397. -------------
  398. * The ``BaseUserManager.make_random_password()`` method is deprecated. See
  399. `recipes and best practices
  400. <https://docs.python.org/3/library/secrets.html#recipes-and-best-practices>`_
  401. for using Python's :py:mod:`secrets` module to generate passwords.
  402. * The ``length_is`` template filter is deprecated in favor of :tfilter:`length`
  403. and the ``==`` operator within an :ttag:`{% if %}<if>` tag. For example
  404. .. code-block:: html+django
  405. {% if value|length == 4 %}…{% endif %}
  406. {% if value|length == 4 %}True{% else %}False{% endif %}
  407. instead of:
  408. .. code-block:: html+django
  409. {% if value|length_is:4 %}…{% endif %}
  410. {{ value|length_is:4 }}
  411. * ``django.contrib.auth.hashers.SHA1PasswordHasher``,
  412. ``django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher``, and
  413. ``django.contrib.auth.hashers.UnsaltedMD5PasswordHasher`` are deprecated.
  414. * ``django.contrib.postgres.fields.CICharField`` is deprecated in favor of
  415. ``CharField(db_collation="…")`` with a case-insensitive non-deterministic
  416. collation.
  417. * ``django.contrib.postgres.fields.CIEmailField`` is deprecated in favor of
  418. ``EmailField(db_collation="…")`` with a case-insensitive non-deterministic
  419. collation.
  420. * ``django.contrib.postgres.fields.CITextField`` is deprecated in favor of
  421. ``TextField(db_collation="…")`` with a case-insensitive non-deterministic
  422. collation.
  423. * ``django.contrib.postgres.fields.CIText`` mixin is deprecated.
  424. * The ``map_height`` and ``map_width`` attributes of ``BaseGeometryWidget`` are
  425. deprecated, use CSS to size map widgets instead.
  426. * ``SimpleTestCase.assertFormsetError()`` is deprecated in favor of
  427. ``assertFormSetError()``.
  428. * ``TransactionTestCase.assertQuerysetEqual()`` is deprecated in favor of
  429. ``assertQuerySetEqual()``.
  430. * Passing positional arguments to ``Signer`` and ``TimestampSigner`` is
  431. deprecated in favor of keyword-only arguments.