4.1.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. ============================================
  2. Django 4.1 release notes - UNDER DEVELOPMENT
  3. ============================================
  4. *Expected August 2022*
  5. Welcome to Django 4.1!
  6. These release notes cover the :ref:`new features <whats-new-4.1>`, as well as
  7. some :ref:`backwards incompatible changes <backwards-incompatible-4.1>` you'll
  8. want to be aware of when upgrading from Django 4.0 or earlier. We've
  9. :ref:`begun the deprecation process for some features
  10. <deprecated-features-4.1>`.
  11. See the :doc:`/howto/upgrade-version` guide if you're updating an existing
  12. project.
  13. Python compatibility
  14. ====================
  15. Django 4.1 supports Python 3.8, 3.9, and 3.10. We **highly recommend** and only
  16. officially support the latest release of each series.
  17. .. _whats-new-4.1:
  18. What's new in Django 4.1
  19. ========================
  20. .. _csrf-cookie-masked-usage:
  21. ``CSRF_COOKIE_MASKED`` setting
  22. ------------------------------
  23. The new :setting:`CSRF_COOKIE_MASKED` transitional setting allows specifying
  24. whether to mask the CSRF cookie.
  25. :class:`~django.middleware.csrf.CsrfViewMiddleware` no longer masks the CSRF
  26. cookie like it does the CSRF token in the DOM. If you are upgrading multiple
  27. instances of the same project to Django 4.1, you should set
  28. :setting:`CSRF_COOKIE_MASKED` to ``True`` during the transition, in
  29. order to allow compatibility with the older versions of Django. Once the
  30. transition to 4.1 is complete you can stop overriding
  31. :setting:`CSRF_COOKIE_MASKED`.
  32. This setting is deprecated as of this release and will be removed in Django
  33. 5.0.
  34. Minor features
  35. --------------
  36. :mod:`django.contrib.admin`
  37. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  38. * The admin :ref:`dark mode CSS variables <admin-theming>` are now applied in a
  39. separate stylesheet and template block.
  40. * :ref:`modeladmin-list-filters` providing custom ``FieldListFilter``
  41. subclasses can now control the query string value separator when filtering
  42. for multiple values using the ``__in`` lookup.
  43. * The admin :meth:`history view <django.contrib.admin.ModelAdmin.history_view>`
  44. is now paginated.
  45. * Related widget wrappers now have a link to object's change form.
  46. * The :meth:`.AdminSite.get_app_list` method now allows changing the order of
  47. apps and models on the admin index page.
  48. :mod:`django.contrib.admindocs`
  49. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  50. * ...
  51. :mod:`django.contrib.auth`
  52. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  53. * The default iteration count for the PBKDF2 password hasher is increased from
  54. 320,000 to 390,000.
  55. * The :meth:`.RemoteUserBackend.configure_user` method now allows synchronizing
  56. user attributes with attributes in a remote system such as an LDAP directory.
  57. :mod:`django.contrib.contenttypes`
  58. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  59. * ...
  60. :mod:`django.contrib.gis`
  61. ~~~~~~~~~~~~~~~~~~~~~~~~~
  62. * The new :meth:`.GEOSGeometry.make_valid()` method allows converting invalid
  63. geometries to valid ones.
  64. :mod:`django.contrib.messages`
  65. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  66. * ...
  67. :mod:`django.contrib.postgres`
  68. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  69. * The new :class:`BitXor() <django.contrib.postgres.aggregates.BitXor>`
  70. aggregate function returns an ``int`` of the bitwise ``XOR`` of all non-null
  71. input values.
  72. * :class:`~django.contrib.postgres.indexes.SpGistIndex` now supports covering
  73. indexes on PostgreSQL 14+.
  74. * :class:`~django.contrib.postgres.constraints.ExclusionConstraint` now
  75. supports covering exclusion constraints using SP-GiST indexes on PostgreSQL
  76. 14+.
  77. * The new ``default_bounds`` attribute of :attr:`DateTimeRangeField
  78. <django.contrib.postgres.fields.DateTimeRangeField.default_bounds>` and
  79. :attr:`DecimalRangeField
  80. <django.contrib.postgres.fields.DecimalRangeField.default_bounds>` allows
  81. specifying bounds for list and tuple inputs.
  82. * :class:`~django.contrib.postgres.constraints.ExclusionConstraint` now allows
  83. specifying operator classes with the
  84. :class:`OpClass() <django.contrib.postgres.indexes.OpClass>` expression.
  85. :mod:`django.contrib.redirects`
  86. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  87. * ...
  88. :mod:`django.contrib.sessions`
  89. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  90. * ...
  91. :mod:`django.contrib.sitemaps`
  92. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  93. * The default sitemap index template ``<sitemapindex>`` now includes the
  94. ``<lastmod>`` timestamp where available, through the new
  95. :meth:`~django.contrib.sitemaps.Sitemap.get_latest_lastmod` method. Custom
  96. sitemap index templates should be updated for the adjusted :ref:`context
  97. variables <sitemap-index-context-variables>`.
  98. :mod:`django.contrib.sites`
  99. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  100. * ...
  101. :mod:`django.contrib.staticfiles`
  102. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  103. * :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` now
  104. replaces paths to CSS source map references with their hashed counterparts.
  105. :mod:`django.contrib.syndication`
  106. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  107. * ...
  108. Cache
  109. ~~~~~
  110. * ...
  111. CSRF
  112. ~~~~
  113. * ...
  114. Database backends
  115. ~~~~~~~~~~~~~~~~~
  116. * Third-party database backends can now specify the minimum required version of
  117. the database using the ``DatabaseFeatures.minimum_database_version``
  118. attribute which is a tuple (e.g. ``(10, 0)`` means "10.0"). If a minimum
  119. version is specified, backends must also implement
  120. ``DatabaseWrapper.get_database_version()``, which returns a tuple of the
  121. current database version. The backend's
  122. ``DatabaseWrapper.init_connection_state()`` method must call ``super()`` in
  123. order for the check to run.
  124. Decorators
  125. ~~~~~~~~~~
  126. * ...
  127. Email
  128. ~~~~~
  129. * ...
  130. Error Reporting
  131. ~~~~~~~~~~~~~~~
  132. * ...
  133. File Storage
  134. ~~~~~~~~~~~~
  135. * ...
  136. File Uploads
  137. ~~~~~~~~~~~~
  138. * ...
  139. Forms
  140. ~~~~~
  141. * The new :meth:`~django.forms.BoundField.legend_tag` allows rendering field
  142. labels in ``<legend>`` tags via the new ``tag`` argument of
  143. :meth:`~django.forms.BoundField.label_tag`.
  144. * The new ``edit_only`` argument for :func:`.modelformset_factory` and
  145. :func:`.inlineformset_factory` allows preventing new objects creation.
  146. * The ``js`` and ``css`` class attributes of :doc:`Media </topics/forms/media>`
  147. now allow using hashable objects, not only path strings, as long as those
  148. objects implement the ``__html__()`` method (typically when decorated with
  149. the :func:`~django.utils.html.html_safe` decorator).
  150. * The new :attr:`.BoundField.use_fieldset` and :attr:`.Widget.use_fieldset`
  151. attributes help to identify widgets where its inputs should be grouped in a
  152. ``<fieldset>`` with a ``<legend>``.
  153. Generic Views
  154. ~~~~~~~~~~~~~
  155. * ...
  156. Internationalization
  157. ~~~~~~~~~~~~~~~~~~~~
  158. * The :func:`~django.conf.urls.i18n.i18n_patterns` function now supports
  159. languages with both scripts and regions.
  160. Logging
  161. ~~~~~~~
  162. * ...
  163. Management Commands
  164. ~~~~~~~~~~~~~~~~~~~
  165. * :option:`makemigrations --no-input` now logs default answers and reasons why
  166. migrations cannot be created.
  167. * The new :option:`makemigrations --scriptable` option diverts log output and
  168. input prompts to ``stderr``, writing only paths of generated migration files
  169. to ``stdout``.
  170. * The new :option:`migrate --prune` option allows deleting nonexistent
  171. migrations from the ``django_migrations`` table.
  172. * Python files created by :djadmin:`startproject`, :djadmin:`startapp`,
  173. :djadmin:`optimizemigration`, :djadmin:`makemigrations`, and
  174. :djadmin:`squashmigrations` are now formatted using the ``black`` command if
  175. it is present on your ``PATH``.
  176. * The new :djadmin:`optimizemigration` command allows optimizing operations for
  177. a migration.
  178. Migrations
  179. ~~~~~~~~~~
  180. * ...
  181. Models
  182. ~~~~~~
  183. * The ``order_by`` argument of the
  184. :class:`~django.db.models.expressions.Window` expression now accepts string
  185. references to fields and transforms.
  186. * The new :setting:`CONN_HEALTH_CHECKS` setting allows enabling health checks
  187. for :ref:`persistent database connections <persistent-database-connections>`
  188. in order to reduce the number of failed requests, e.g. after database server
  189. restart.
  190. * :meth:`.QuerySet.bulk_create` now supports updating fields when a row
  191. insertion fails uniqueness constraints. This is supported on MariaDB, MySQL,
  192. PostgreSQL, and SQLite 3.24+.
  193. * :meth:`.QuerySet.iterator` now supports prefetching related objects as long
  194. as the ``chunk_size`` argument is provided. In older versions, no prefetching
  195. was done.
  196. * :class:`~django.db.models.Q` objects and querysets can now be combined using
  197. ``^`` as the exclusive or (``XOR``) operator. ``XOR`` is natively supported
  198. on MariaDB and MySQL. For databases that do not support ``XOR``, the query
  199. will be converted to an equivalent using ``AND``, ``OR``, and ``NOT``.
  200. Requests and Responses
  201. ~~~~~~~~~~~~~~~~~~~~~~
  202. * :meth:`.HttpResponse.set_cookie` now supports :class:`~datetime.timedelta`
  203. objects for the ``max_age`` argument.
  204. Security
  205. ~~~~~~~~
  206. * The new :setting:`SECRET_KEY_FALLBACKS` setting allows providing a list of
  207. values for secret key rotation.
  208. * The :setting:`SECURE_PROXY_SSL_HEADER` setting now supports a comma-separated
  209. list of protocols in the header value.
  210. Serialization
  211. ~~~~~~~~~~~~~
  212. * ...
  213. Signals
  214. ~~~~~~~
  215. * The :data:`~django.db.models.signals.pre_delete` and
  216. :data:`~django.db.models.signals.post_delete` signals now dispatch the
  217. ``origin`` of the deletion.
  218. Templates
  219. ~~~~~~~~~
  220. * :tfilter:`json_script` template filter now allows wrapping in a ``<script>``
  221. tag without the HTML ``id`` attribute.
  222. Tests
  223. ~~~~~
  224. * A nested atomic block marked as durable in :class:`django.test.TestCase` now
  225. raises a ``RuntimeError``, the same as outside of tests.
  226. URLs
  227. ~~~~
  228. * The new :attr:`.ResolverMatch.captured_kwargs` attribute stores the captured
  229. keyword arguments, as parsed from the URL.
  230. * The new :attr:`.ResolverMatch.extra_kwargs` attribute stores the additional
  231. keyword arguments passed to the view function.
  232. Utilities
  233. ~~~~~~~~~
  234. * ``SimpleLazyObject`` now supports addition operations.
  235. * :func:`~django.utils.safestring.mark_safe` now preserves lazy objects.
  236. Validators
  237. ~~~~~~~~~~
  238. * ...
  239. .. _backwards-incompatible-4.1:
  240. Backwards incompatible changes in 4.1
  241. =====================================
  242. Database backend API
  243. --------------------
  244. This section describes changes that may be needed in third-party database
  245. backends.
  246. * ``BaseDatabaseFeatures.has_case_insensitive_like`` is changed from ``True``
  247. to ``False`` to reflect the behavior of most databases.
  248. * ``DatabaseIntrospection.get_key_columns()`` is removed. Use
  249. ``DatabaseIntrospection.get_relations()`` instead.
  250. * ``DatabaseOperations.ignore_conflicts_suffix_sql()`` method is replaced by
  251. ``DatabaseOperations.on_conflict_suffix_sql()`` that accepts the ``fields``,
  252. ``on_conflict``, ``update_fields``, and ``unique_fields`` arguments.
  253. * The ``ignore_conflicts`` argument of the
  254. ``DatabaseOperations.insert_statement()`` method is replaced by
  255. ``on_conflict`` that accepts ``django.db.models.constants.OnConflict``.
  256. :mod:`django.contrib.gis`
  257. -------------------------
  258. * Support for GDAL 2.1 is removed.
  259. Dropped support for MariaDB 10.2
  260. --------------------------------
  261. Upstream support for MariaDB 10.2 ends in May 2022. Django 4.1 supports MariaDB
  262. 10.3 and higher.
  263. Admin changelist searches spanning multi-valued relationships changes
  264. ---------------------------------------------------------------------
  265. Admin changelist searches using multiple search terms are now applied in a
  266. single call to ``filter()``, rather than in sequential ``filter()`` calls.
  267. For multi-valued relationships, this means that rows from the related model
  268. must match all terms rather than any term. For example, if ``search_fields``
  269. is set to ``['child__name', 'child__age']``, and a user searches for
  270. ``'Jamal 17'``, parent rows will be returned only if there is a relationship to
  271. some 17-year-old child named Jamal, rather than also returning parents who
  272. merely have a younger or older child named Jamal in addition to some other
  273. 17-year-old.
  274. See the :ref:`spanning-multi-valued-relationships` topic for more discussion of
  275. this difference. In Django 4.0 and earlier,
  276. :meth:`~django.contrib.admin.ModelAdmin.get_search_results` followed the
  277. second example query, but this undocumented behavior led to queries with
  278. excessive joins.
  279. Reverse foreign key changes for unsaved model instances
  280. -------------------------------------------------------
  281. In order to unify the behavior with many-to-many relations for unsaved model
  282. instances, a reverse foreign key now raises ``ValueError`` when calling
  283. :class:`related managers <django.db.models.fields.related.RelatedManager>` for
  284. unsaved objects.
  285. Miscellaneous
  286. -------------
  287. * Related managers for :class:`~django.db.models.ForeignKey`,
  288. :class:`~django.db.models.ManyToManyField`, and
  289. :class:`~django.contrib.contenttypes.fields.GenericRelation` are now cached
  290. on the :class:`~django.db.models.Model` instance to which they belong.
  291. * The Django test runner now returns a non-zero error code for unexpected
  292. successes from tests marked with :py:func:`unittest.expectedFailure`.
  293. * :class:`~django.middleware.csrf.CsrfViewMiddleware` no longer masks the CSRF
  294. cookie like it does the CSRF token in the DOM.
  295. * :class:`~django.middleware.csrf.CsrfViewMiddleware` now uses
  296. ``request.META['CSRF_COOKIE']`` for storing the unmasked CSRF secret rather
  297. than a masked version. This is an undocumented, private API.
  298. * The :attr:`.ModelAdmin.actions` and
  299. :attr:`~django.contrib.admin.ModelAdmin.inlines` attributes now default to an
  300. empty tuple rather than an empty list to discourage unintended mutation.
  301. * The ``type="text/css"`` attribute is no longer included in ``<link>`` tags
  302. for CSS :doc:`form media </topics/forms/media>`.
  303. * ``formset:added`` and ``formset:removed`` JavaScript events are now pure
  304. JavaScript events and don't depend on jQuery. See
  305. :ref:`admin-javascript-inline-form-events` for more details on the change.
  306. * The ``exc_info`` argument of the undocumented
  307. ``django.utils.log.log_response()`` function is replaced by ``exception``.
  308. * The ``size`` argument of the undocumented
  309. ``django.views.static.was_modified_since()`` function is removed.
  310. * The admin log out UI now uses ``POST`` requests.
  311. .. _deprecated-features-4.1:
  312. Features deprecated in 4.1
  313. ==========================
  314. Log out via GET
  315. ---------------
  316. Logging out via ``GET`` requests to the :py:class:`built-in logout view
  317. <django.contrib.auth.views.LogoutView>` is deprecated. Use ``POST`` requests
  318. instead.
  319. If you want to retain the user experience of an HTML link, you can use a form
  320. that is styled to appear as a link:
  321. .. code-block:: html
  322. <form id="logout-form" method="post" action="{% url 'admin:logout' %}">
  323. {% csrf_token %}
  324. <button type="submit">{% translate "Log out" %}</button>
  325. </form>
  326. .. code-block:: css
  327. #logout-form {
  328. display: inline;
  329. }
  330. #logout-form button {
  331. background: none;
  332. border: none;
  333. cursor: pointer;
  334. padding: 0;
  335. text-decoration: underline;
  336. }
  337. Miscellaneous
  338. -------------
  339. * The context for sitemap index templates of a flat list of URLs is deprecated.
  340. Custom sitemap index templates should be updated for the adjusted
  341. :ref:`context variables <sitemap-index-context-variables>`, expecting a list
  342. of objects with ``location`` and optional ``lastmod`` attributes.
  343. * ``CSRF_COOKIE_MASKED`` transitional setting is deprecated.
  344. * The ``name`` argument of :func:`django.utils.functional.cached_property` is
  345. deprecated as it's unnecessary as of Python 3.6.
  346. * The ``opclasses`` argument of
  347. ``django.contrib.postgres.constraints.ExclusionConstraint`` is deprecated in
  348. favor of using :class:`OpClass() <django.contrib.postgres.indexes.OpClass>`
  349. in :attr:`.ExclusionConstraint.expressions`. To use it, you need to add
  350. ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS`.
  351. After making this change, :djadmin:`makemigrations` will generate a new
  352. migration with two operations: ``RemoveConstraint`` and ``AddConstraint``.
  353. Since this change has no effect on the database schema,
  354. the :class:`~django.db.migrations.operations.SeparateDatabaseAndState`
  355. operation can be used to only update the migration state without running any
  356. SQL. Move the generated operations into the ``state_operations`` argument of
  357. :class:`~django.db.migrations.operations.SeparateDatabaseAndState`. For
  358. example::
  359. class Migration(migrations.Migration):
  360. ...
  361. operations = [
  362. migrations.SeparateDatabaseAndState(
  363. database_operations=[],
  364. state_operations=[
  365. migrations.RemoveConstraint(
  366. ...
  367. ),
  368. migrations.AddConstraint(
  369. ...
  370. ),
  371. ],
  372. ),
  373. ]
  374. * The undocumented ability to pass ``errors=None`` to
  375. :meth:`.SimpleTestCase.assertFormError` and
  376. :meth:`~.SimpleTestCase.assertFormsetError` is deprecated. Use ``errors=[]``
  377. instead.
  378. * ``django.contrib.sessions.serializers.PickleSerializer`` is deprecated due to
  379. the risk of remote code execution.
  380. * The usage of ``QuerySet.iterator()`` on a queryset that prefetches related
  381. objects without providing the ``chunk_size`` argument is deprecated. In older
  382. versions, no prefetching was done. Providing a value for ``chunk_size``
  383. signifies that the additional query per chunk needed to prefetch is desired.
  384. * Passing unsaved model instances to related filters is deprecated. In Django
  385. 5.0, the exception will be raised.
  386. * ``created=True`` is added to the signature of
  387. :meth:`.RemoteUserBackend.configure_user`. Support for ``RemoteUserBackend``
  388. subclasses that do not accept this argument is deprecated.
  389. * The :data:`django.utils.timezone.utc` alias to :attr:`datetime.timezone.utc`
  390. is deprecated. Use :attr:`datetime.timezone.utc` directly.
  391. Features removed in 4.1
  392. =======================
  393. These features have reached the end of their deprecation cycle and are removed
  394. in Django 4.1.
  395. See :ref:`deprecated-features-3.2` for details on these changes, including how
  396. to remove usage of these features.
  397. * Support for assigning objects which don't support creating deep copies with
  398. ``copy.deepcopy()`` to class attributes in ``TestCase.setUpTestData()`` is
  399. removed.
  400. * Support for using a boolean value in
  401. :attr:`.BaseCommand.requires_system_checks` is removed.
  402. * The ``whitelist`` argument and ``domain_whitelist`` attribute of
  403. ``django.core.validators.EmailValidator`` are removed.
  404. * The ``default_app_config`` application configuration variable is removed.
  405. * ``TransactionTestCase.assertQuerysetEqual()`` no longer calls ``repr()`` on a
  406. queryset when compared to string values.
  407. * The ``django.core.cache.backends.memcached.MemcachedCache`` backend is
  408. removed.
  409. * Support for the pre-Django 3.2 format of messages used by
  410. ``django.contrib.messages.storage.cookie.CookieStorage`` is removed.