4.1.txt 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. * :meth:`.SimpleTestCase.assertFormError` and
  227. :meth:`~.SimpleTestCase.assertFormsetError` now support passing a
  228. form/formset object directly.
  229. URLs
  230. ~~~~
  231. * The new :attr:`.ResolverMatch.captured_kwargs` attribute stores the captured
  232. keyword arguments, as parsed from the URL.
  233. * The new :attr:`.ResolverMatch.extra_kwargs` attribute stores the additional
  234. keyword arguments passed to the view function.
  235. Utilities
  236. ~~~~~~~~~
  237. * ``SimpleLazyObject`` now supports addition operations.
  238. * :func:`~django.utils.safestring.mark_safe` now preserves lazy objects.
  239. Validators
  240. ~~~~~~~~~~
  241. * ...
  242. .. _backwards-incompatible-4.1:
  243. Backwards incompatible changes in 4.1
  244. =====================================
  245. Database backend API
  246. --------------------
  247. This section describes changes that may be needed in third-party database
  248. backends.
  249. * ``BaseDatabaseFeatures.has_case_insensitive_like`` is changed from ``True``
  250. to ``False`` to reflect the behavior of most databases.
  251. * ``DatabaseIntrospection.get_key_columns()`` is removed. Use
  252. ``DatabaseIntrospection.get_relations()`` instead.
  253. * ``DatabaseOperations.ignore_conflicts_suffix_sql()`` method is replaced by
  254. ``DatabaseOperations.on_conflict_suffix_sql()`` that accepts the ``fields``,
  255. ``on_conflict``, ``update_fields``, and ``unique_fields`` arguments.
  256. * The ``ignore_conflicts`` argument of the
  257. ``DatabaseOperations.insert_statement()`` method is replaced by
  258. ``on_conflict`` that accepts ``django.db.models.constants.OnConflict``.
  259. :mod:`django.contrib.gis`
  260. -------------------------
  261. * Support for GDAL 2.1 is removed.
  262. Dropped support for MariaDB 10.2
  263. --------------------------------
  264. Upstream support for MariaDB 10.2 ends in May 2022. Django 4.1 supports MariaDB
  265. 10.3 and higher.
  266. Admin changelist searches spanning multi-valued relationships changes
  267. ---------------------------------------------------------------------
  268. Admin changelist searches using multiple search terms are now applied in a
  269. single call to ``filter()``, rather than in sequential ``filter()`` calls.
  270. For multi-valued relationships, this means that rows from the related model
  271. must match all terms rather than any term. For example, if ``search_fields``
  272. is set to ``['child__name', 'child__age']``, and a user searches for
  273. ``'Jamal 17'``, parent rows will be returned only if there is a relationship to
  274. some 17-year-old child named Jamal, rather than also returning parents who
  275. merely have a younger or older child named Jamal in addition to some other
  276. 17-year-old.
  277. See the :ref:`spanning-multi-valued-relationships` topic for more discussion of
  278. this difference. In Django 4.0 and earlier,
  279. :meth:`~django.contrib.admin.ModelAdmin.get_search_results` followed the
  280. second example query, but this undocumented behavior led to queries with
  281. excessive joins.
  282. Reverse foreign key changes for unsaved model instances
  283. -------------------------------------------------------
  284. In order to unify the behavior with many-to-many relations for unsaved model
  285. instances, a reverse foreign key now raises ``ValueError`` when calling
  286. :class:`related managers <django.db.models.fields.related.RelatedManager>` for
  287. unsaved objects.
  288. Miscellaneous
  289. -------------
  290. * Related managers for :class:`~django.db.models.ForeignKey`,
  291. :class:`~django.db.models.ManyToManyField`, and
  292. :class:`~django.contrib.contenttypes.fields.GenericRelation` are now cached
  293. on the :class:`~django.db.models.Model` instance to which they belong.
  294. * The Django test runner now returns a non-zero error code for unexpected
  295. successes from tests marked with :py:func:`unittest.expectedFailure`.
  296. * :class:`~django.middleware.csrf.CsrfViewMiddleware` no longer masks the CSRF
  297. cookie like it does the CSRF token in the DOM.
  298. * :class:`~django.middleware.csrf.CsrfViewMiddleware` now uses
  299. ``request.META['CSRF_COOKIE']`` for storing the unmasked CSRF secret rather
  300. than a masked version. This is an undocumented, private API.
  301. * The :attr:`.ModelAdmin.actions` and
  302. :attr:`~django.contrib.admin.ModelAdmin.inlines` attributes now default to an
  303. empty tuple rather than an empty list to discourage unintended mutation.
  304. * The ``type="text/css"`` attribute is no longer included in ``<link>`` tags
  305. for CSS :doc:`form media </topics/forms/media>`.
  306. * ``formset:added`` and ``formset:removed`` JavaScript events are now pure
  307. JavaScript events and don't depend on jQuery. See
  308. :ref:`admin-javascript-inline-form-events` for more details on the change.
  309. * The ``exc_info`` argument of the undocumented
  310. ``django.utils.log.log_response()`` function is replaced by ``exception``.
  311. * The ``size`` argument of the undocumented
  312. ``django.views.static.was_modified_since()`` function is removed.
  313. * The admin log out UI now uses ``POST`` requests.
  314. * The undocumented ``InlineAdminFormSet.non_form_errors`` property is replaced
  315. by the ``non_form_errors()`` method. This is consistent with ``BaseFormSet``.
  316. .. _deprecated-features-4.1:
  317. Features deprecated in 4.1
  318. ==========================
  319. Log out via GET
  320. ---------------
  321. Logging out via ``GET`` requests to the :py:class:`built-in logout view
  322. <django.contrib.auth.views.LogoutView>` is deprecated. Use ``POST`` requests
  323. instead.
  324. If you want to retain the user experience of an HTML link, you can use a form
  325. that is styled to appear as a link:
  326. .. code-block:: html
  327. <form id="logout-form" method="post" action="{% url 'admin:logout' %}">
  328. {% csrf_token %}
  329. <button type="submit">{% translate "Log out" %}</button>
  330. </form>
  331. .. code-block:: css
  332. #logout-form {
  333. display: inline;
  334. }
  335. #logout-form button {
  336. background: none;
  337. border: none;
  338. cursor: pointer;
  339. padding: 0;
  340. text-decoration: underline;
  341. }
  342. Miscellaneous
  343. -------------
  344. * The context for sitemap index templates of a flat list of URLs is deprecated.
  345. Custom sitemap index templates should be updated for the adjusted
  346. :ref:`context variables <sitemap-index-context-variables>`, expecting a list
  347. of objects with ``location`` and optional ``lastmod`` attributes.
  348. * ``CSRF_COOKIE_MASKED`` transitional setting is deprecated.
  349. * The ``name`` argument of :func:`django.utils.functional.cached_property` is
  350. deprecated as it's unnecessary as of Python 3.6.
  351. * The ``opclasses`` argument of
  352. ``django.contrib.postgres.constraints.ExclusionConstraint`` is deprecated in
  353. favor of using :class:`OpClass() <django.contrib.postgres.indexes.OpClass>`
  354. in :attr:`.ExclusionConstraint.expressions`. To use it, you need to add
  355. ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS`.
  356. After making this change, :djadmin:`makemigrations` will generate a new
  357. migration with two operations: ``RemoveConstraint`` and ``AddConstraint``.
  358. Since this change has no effect on the database schema,
  359. the :class:`~django.db.migrations.operations.SeparateDatabaseAndState`
  360. operation can be used to only update the migration state without running any
  361. SQL. Move the generated operations into the ``state_operations`` argument of
  362. :class:`~django.db.migrations.operations.SeparateDatabaseAndState`. For
  363. example::
  364. class Migration(migrations.Migration):
  365. ...
  366. operations = [
  367. migrations.SeparateDatabaseAndState(
  368. database_operations=[],
  369. state_operations=[
  370. migrations.RemoveConstraint(
  371. ...
  372. ),
  373. migrations.AddConstraint(
  374. ...
  375. ),
  376. ],
  377. ),
  378. ]
  379. * The undocumented ability to pass ``errors=None`` to
  380. :meth:`.SimpleTestCase.assertFormError` and
  381. :meth:`~.SimpleTestCase.assertFormsetError` is deprecated. Use ``errors=[]``
  382. instead.
  383. * ``django.contrib.sessions.serializers.PickleSerializer`` is deprecated due to
  384. the risk of remote code execution.
  385. * The usage of ``QuerySet.iterator()`` on a queryset that prefetches related
  386. objects without providing the ``chunk_size`` argument is deprecated. In older
  387. versions, no prefetching was done. Providing a value for ``chunk_size``
  388. signifies that the additional query per chunk needed to prefetch is desired.
  389. * Passing unsaved model instances to related filters is deprecated. In Django
  390. 5.0, the exception will be raised.
  391. * ``created=True`` is added to the signature of
  392. :meth:`.RemoteUserBackend.configure_user`. Support for ``RemoteUserBackend``
  393. subclasses that do not accept this argument is deprecated.
  394. * The :data:`django.utils.timezone.utc` alias to :attr:`datetime.timezone.utc`
  395. is deprecated. Use :attr:`datetime.timezone.utc` directly.
  396. * Passing a response object and a form/formset name to
  397. ``SimpleTestCase.assertFormError()`` and ``assertFormsetError()`` is
  398. deprecated. Use::
  399. assertFormError(response.context['form_name'], …)
  400. assertFormsetError(response.context['formset_name'], …)
  401. or pass the form/formset object directly instead.
  402. Features removed in 4.1
  403. =======================
  404. These features have reached the end of their deprecation cycle and are removed
  405. in Django 4.1.
  406. See :ref:`deprecated-features-3.2` for details on these changes, including how
  407. to remove usage of these features.
  408. * Support for assigning objects which don't support creating deep copies with
  409. ``copy.deepcopy()`` to class attributes in ``TestCase.setUpTestData()`` is
  410. removed.
  411. * Support for using a boolean value in
  412. :attr:`.BaseCommand.requires_system_checks` is removed.
  413. * The ``whitelist`` argument and ``domain_whitelist`` attribute of
  414. ``django.core.validators.EmailValidator`` are removed.
  415. * The ``default_app_config`` application configuration variable is removed.
  416. * ``TransactionTestCase.assertQuerysetEqual()`` no longer calls ``repr()`` on a
  417. queryset when compared to string values.
  418. * The ``django.core.cache.backends.memcached.MemcachedCache`` backend is
  419. removed.
  420. * Support for the pre-Django 3.2 format of messages used by
  421. ``django.contrib.messages.storage.cookie.CookieStorage`` is removed.