4.0.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. ========================
  2. Django 4.0 release notes
  3. ========================
  4. *December 7, 2021*
  5. Welcome to Django 4.0!
  6. These release notes cover the :ref:`new features <whats-new-4.0>`, as well as
  7. some :ref:`backwards incompatible changes <backwards-incompatible-4.0>` you'll
  8. want to be aware of when upgrading from Django 3.2 or earlier. We've
  9. :ref:`begun the deprecation process for some features
  10. <deprecated-features-4.0>`.
  11. See the :doc:`/howto/upgrade-version` guide if you're updating an existing
  12. project.
  13. Python compatibility
  14. ====================
  15. Django 4.0 supports Python 3.8, 3.9, and 3.10. We **highly recommend** and only
  16. officially support the latest release of each series.
  17. The Django 3.2.x series is the last to support Python 3.6 and 3.7.
  18. .. _whats-new-4.0:
  19. What's new in Django 4.0
  20. ========================
  21. ``zoneinfo`` default timezone implementation
  22. --------------------------------------------
  23. The Python standard library's :mod:`zoneinfo` is now the default timezone
  24. implementation in Django.
  25. This is the next step in the migration from using ``pytz`` to using
  26. :mod:`zoneinfo`. Django 3.2 allowed the use of non-``pytz`` time zones. Django
  27. 4.0 makes ``zoneinfo`` the default implementation. Support for ``pytz`` is now
  28. deprecated and will be removed in Django 5.0.
  29. :mod:`zoneinfo` is part of the Python standard library from Python 3.9. The
  30. ``backports.zoneinfo`` package is automatically installed alongside Django if
  31. you are using Python 3.8.
  32. The move to ``zoneinfo`` should be largely transparent. Selection of the
  33. current timezone, conversion of datetime instances to the current timezone in
  34. forms and templates, as well as operations on aware datetimes in UTC are
  35. unaffected.
  36. However, if you are working with non-UTC time zones, and using the ``pytz``
  37. ``normalize()`` and ``localize()`` APIs, possibly with the :setting:`TIME_ZONE
  38. <DATABASE-TIME_ZONE>` setting, you will need to audit your code, since ``pytz``
  39. and ``zoneinfo`` are not entirely equivalent.
  40. To give time for such an audit, the transitional ``USE_DEPRECATED_PYTZ``
  41. setting allows continued use of ``pytz`` during the 4.x release cycle. This
  42. setting will be removed in Django 5.0.
  43. In addition, a `pytz_deprecation_shim`_ package, created by the ``zoneinfo``
  44. author, can be used to assist with the migration from ``pytz``. This package
  45. provides shims to help you safely remove ``pytz``, and has a detailed
  46. `migration guide`_ showing how to move to the new ``zoneinfo`` APIs.
  47. Using `pytz_deprecation_shim`_ and the ``USE_DEPRECATED_PYTZ``
  48. transitional setting is recommended if you need a gradual update path.
  49. .. _pytz_deprecation_shim: https://pytz-deprecation-shim.readthedocs.io/en/latest/index.html
  50. .. _migration guide: https://pytz-deprecation-shim.readthedocs.io/en/latest/migration.html
  51. Functional unique constraints
  52. -----------------------------
  53. The new :attr:`*expressions <django.db.models.UniqueConstraint.expressions>`
  54. positional argument of
  55. :class:`UniqueConstraint() <django.db.models.UniqueConstraint>` enables
  56. creating functional unique constraints on expressions and database functions.
  57. For example::
  58. from django.db import models
  59. from django.db.models import UniqueConstraint
  60. from django.db.models.functions import Lower
  61. class MyModel(models.Model):
  62. first_name = models.CharField(max_length=255)
  63. last_name = models.CharField(max_length=255)
  64. class Meta:
  65. constraints = [
  66. UniqueConstraint(
  67. Lower("first_name"),
  68. Lower("last_name").desc(),
  69. name="first_last_name_unique",
  70. ),
  71. ]
  72. Functional unique constraints are added to models using the
  73. :attr:`Meta.constraints <django.db.models.Options.constraints>` option.
  74. ``scrypt`` password hasher
  75. --------------------------
  76. The new :ref:`scrypt password hasher <scrypt-usage>` is more secure and
  77. recommended over PBKDF2. However, it's not the default as it requires OpenSSL
  78. 1.1+ and more memory.
  79. Redis cache backend
  80. -------------------
  81. The new ``django.core.cache.backends.redis.RedisCache`` cache backend provides
  82. built-in support for caching with Redis. :pypi:`redis-py <redis>` 3.0.0 or
  83. higher is required. For more details, see the :ref:`documentation on caching
  84. with Redis in Django <redis>`.
  85. Template based form rendering
  86. -----------------------------
  87. :class:`Forms <django.forms.Form>`, :doc:`Formsets </topics/forms/formsets>`,
  88. and :class:`~django.forms.ErrorList` are now rendered using the template engine
  89. to enhance customization. See the new :meth:`~django.forms.Form.render`,
  90. :meth:`~django.forms.Form.get_context`, and
  91. :attr:`~django.forms.Form.template_name` for ``Form`` and
  92. :ref:`formset rendering <formset-rendering>` for ``Formset``.
  93. Minor features
  94. --------------
  95. :mod:`django.contrib.admin`
  96. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. * The ``admin/base.html`` template now has a new block ``header`` which
  98. contains the admin site header.
  99. * The new :meth:`.ModelAdmin.get_formset_kwargs` method allows customizing the
  100. keyword arguments passed to the constructor of a formset.
  101. * The navigation sidebar now has a quick filter toolbar.
  102. * The new context variable ``model`` which contains the model class for each
  103. model is added to the :meth:`.AdminSite.each_context` method.
  104. * The new :attr:`.ModelAdmin.search_help_text` attribute allows specifying a
  105. descriptive text for the search box.
  106. * The :attr:`.InlineModelAdmin.verbose_name_plural` attribute now fallbacks to
  107. the :attr:`.InlineModelAdmin.verbose_name` + ``'s'``.
  108. * jQuery is upgraded from version 3.5.1 to 3.6.0.
  109. :mod:`django.contrib.admindocs`
  110. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  111. * The admindocs now allows esoteric setups where :setting:`ROOT_URLCONF` is not
  112. a string.
  113. * The model section of the ``admindocs`` now shows cached properties.
  114. :mod:`django.contrib.auth`
  115. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  116. * The default iteration count for the PBKDF2 password hasher is increased from
  117. 260,000 to 320,000.
  118. * The new
  119. :attr:`LoginView.next_page <django.contrib.auth.views.LoginView.next_page>`
  120. attribute and
  121. :meth:`~django.contrib.auth.views.LoginView.get_default_redirect_url` method
  122. allow customizing the redirect after login.
  123. :mod:`django.contrib.gis`
  124. ~~~~~~~~~~~~~~~~~~~~~~~~~
  125. * Added support for SpatiaLite 5.
  126. * :class:`~django.contrib.gis.gdal.GDALRaster` now allows creating rasters in
  127. any GDAL virtual filesystem.
  128. * The new :class:`~django.contrib.gis.admin.GISModelAdmin` class allows
  129. customizing the widget used for ``GeometryField``. This is encouraged instead
  130. of deprecated ``GeoModelAdmin`` and ``OSMGeoAdmin``.
  131. :mod:`django.contrib.postgres`
  132. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  133. * The PostgreSQL backend now supports connecting by a service name. See
  134. :ref:`postgresql-connection-settings` for more details.
  135. * The new :class:`~django.contrib.postgres.operations.AddConstraintNotValid`
  136. operation allows creating check constraints on PostgreSQL without verifying
  137. that all existing rows satisfy the new constraint.
  138. * The new :class:`~django.contrib.postgres.operations.ValidateConstraint`
  139. operation allows validating check constraints which were created using
  140. :class:`~django.contrib.postgres.operations.AddConstraintNotValid` on
  141. PostgreSQL.
  142. * The new
  143. :class:`ArraySubquery() <django.contrib.postgres.expressions.ArraySubquery>`
  144. expression allows using subqueries to construct lists of values on
  145. PostgreSQL.
  146. * The new :lookup:`trigram_word_similar` lookup, and the
  147. :class:`TrigramWordDistance()
  148. <django.contrib.postgres.search.TrigramWordDistance>` and
  149. :class:`TrigramWordSimilarity()
  150. <django.contrib.postgres.search.TrigramWordSimilarity>` expressions allow
  151. using trigram word similarity.
  152. :mod:`django.contrib.staticfiles`
  153. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  154. * :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` now
  155. replaces paths to JavaScript source map references with their hashed
  156. counterparts.
  157. * The new ``manifest_storage`` argument of
  158. :class:`~django.contrib.staticfiles.storage.ManifestFilesMixin` and
  159. :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage`
  160. allows customizing the manifest file storage.
  161. Cache
  162. ~~~~~
  163. * The new async API for ``django.core.cache.backends.base.BaseCache`` begins
  164. the process of making cache backends async-compatible. The new async methods
  165. all have ``a`` prefixed names, e.g. ``aadd()``, ``aget()``, ``aset()``,
  166. ``aget_or_set()``, or ``adelete_many()``.
  167. Going forward, the ``a`` prefix will be used for async variants of methods
  168. generally.
  169. CSRF
  170. ~~~~
  171. * CSRF protection now consults the ``Origin`` header, if present. To facilitate
  172. this, :ref:`some changes <csrf-trusted-origins-changes-4.0>` to the
  173. :setting:`CSRF_TRUSTED_ORIGINS` setting are required.
  174. Forms
  175. ~~~~~
  176. * :class:`~django.forms.ModelChoiceField` now includes the provided value in
  177. the ``params`` argument of a raised
  178. :exc:`~django.core.exceptions.ValidationError` for the ``invalid_choice``
  179. error message. This allows custom error messages to use the ``%(value)s``
  180. placeholder.
  181. * :class:`~django.forms.formsets.BaseFormSet` now renders non-form errors with
  182. an additional class of ``nonform`` to help distinguish them from
  183. form-specific errors.
  184. * :class:`~django.forms.formsets.BaseFormSet` now allows customizing the widget
  185. used when deleting forms via
  186. :attr:`~django.forms.formsets.BaseFormSet.can_delete` by setting the
  187. :attr:`~django.forms.formsets.BaseFormSet.deletion_widget` attribute or
  188. overriding :meth:`~django.forms.formsets.BaseFormSet.get_deletion_widget`
  189. method.
  190. Internationalization
  191. ~~~~~~~~~~~~~~~~~~~~
  192. * Added support and translations for the Malay language.
  193. Generic Views
  194. ~~~~~~~~~~~~~
  195. * :class:`~django.views.generic.edit.DeleteView` now uses
  196. :class:`~django.views.generic.edit.FormMixin`, allowing you to provide a
  197. :class:`~django.forms.Form` subclass, with a checkbox for example, to confirm
  198. deletion. In addition, this allows ``DeleteView`` to function with
  199. :class:`django.contrib.messages.views.SuccessMessageMixin`.
  200. In accordance with ``FormMixin``, object deletion for POST requests is
  201. handled in ``form_valid()``. Custom delete logic in ``delete()`` handlers
  202. should be moved to ``form_valid()``, or a shared helper method, as needed.
  203. Logging
  204. ~~~~~~~
  205. * The alias of the database used in an SQL call is now passed as extra context
  206. along with each message to the :ref:`django-db-logger` logger.
  207. Management Commands
  208. ~~~~~~~~~~~~~~~~~~~
  209. * The :djadmin:`runserver` management command now supports the
  210. :option:`--skip-checks` option.
  211. * On PostgreSQL, :djadmin:`dbshell` now supports specifying a password file.
  212. * The :djadmin:`shell` command now respects :py:data:`sys.__interactivehook__`
  213. at startup. This allows loading shell history between interactive sessions.
  214. As a consequence, ``readline`` is no longer loaded if running in *isolated*
  215. mode.
  216. * The new :attr:`BaseCommand.suppressed_base_arguments
  217. <django.core.management.BaseCommand.suppressed_base_arguments>` attribute
  218. allows suppressing unsupported default command options in the help output.
  219. * The new :option:`startapp --exclude` and :option:`startproject --exclude`
  220. options allow excluding directories from the template.
  221. Models
  222. ~~~~~~
  223. * New :meth:`QuerySet.contains(obj) <.QuerySet.contains>` method returns
  224. whether the queryset contains the given object. This tries to perform the
  225. query in the simplest and fastest way possible.
  226. * The new ``precision`` argument of the
  227. :class:`Round() <django.db.models.functions.Round>` database function allows
  228. specifying the number of decimal places after rounding.
  229. * :meth:`.QuerySet.bulk_create` now sets the primary key on objects when using
  230. SQLite 3.35+.
  231. * :class:`~django.db.models.DurationField` now supports multiplying and
  232. dividing by scalar values on SQLite.
  233. * :meth:`.QuerySet.bulk_update` now returns the number of objects updated.
  234. * The new :attr:`.Expression.empty_result_set_value` attribute allows
  235. specifying a value to return when the function is used over an empty result
  236. set.
  237. * The ``skip_locked`` argument of :meth:`.QuerySet.select_for_update()` is now
  238. allowed on MariaDB 10.6+.
  239. * :class:`~django.db.models.Lookup` expressions may now be used in ``QuerySet``
  240. annotations, aggregations, and directly in filters.
  241. * The new :ref:`default <aggregate-default>` argument for built-in aggregates
  242. allows specifying a value to be returned when the queryset (or grouping)
  243. contains no entries, rather than ``None``.
  244. Requests and Responses
  245. ~~~~~~~~~~~~~~~~~~~~~~
  246. * The :class:`~django.middleware.security.SecurityMiddleware` now adds the
  247. :ref:`Cross-Origin Opener Policy <cross-origin-opener-policy>` header with a
  248. value of ``'same-origin'`` to prevent cross-origin popups from sharing the
  249. same browsing context. You can prevent this header from being added by
  250. setting the :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY` setting to ``None``.
  251. Signals
  252. ~~~~~~~
  253. * The new ``stdout`` argument for :func:`~django.db.models.signals.pre_migrate`
  254. and :func:`~django.db.models.signals.post_migrate` signals allows redirecting
  255. output to a stream-like object. It should be preferred over
  256. :py:data:`sys.stdout` and :py:func:`print` when emitting verbose output in
  257. order to allow proper capture when testing.
  258. Templates
  259. ~~~~~~~~~
  260. * :tfilter:`floatformat` template filter now allows using the ``u`` suffix to
  261. force disabling localization.
  262. Tests
  263. ~~~~~
  264. * The new ``serialized_aliases`` argument of
  265. :func:`django.test.utils.setup_databases` determines which
  266. :setting:`DATABASES` aliases test databases should have their state
  267. serialized to allow usage of the
  268. :ref:`serialized_rollback <test-case-serialized-rollback>` feature.
  269. * Django test runner now supports a :option:`--buffer <test --buffer>` option
  270. with parallel tests.
  271. * The new ``logger`` argument to :class:`~django.test.runner.DiscoverRunner`
  272. allows a Python :py:ref:`logger <logger>` to be used for logging.
  273. * The new :meth:`.DiscoverRunner.log` method provides a way to log messages
  274. that uses the ``DiscoverRunner.logger``, or prints to the console if not set.
  275. * Django test runner now supports a :option:`--shuffle <test --shuffle>` option
  276. to execute tests in a random order.
  277. * The :option:`test --parallel` option now supports the value ``auto`` to run
  278. one test process for each processor core.
  279. * :meth:`.TestCase.captureOnCommitCallbacks` now captures new callbacks added
  280. while executing :func:`.transaction.on_commit` callbacks.
  281. .. _backwards-incompatible-4.0:
  282. Backwards incompatible changes in 4.0
  283. =====================================
  284. Database backend API
  285. --------------------
  286. This section describes changes that may be needed in third-party database
  287. backends.
  288. * ``DatabaseOperations.year_lookup_bounds_for_date_field()`` and
  289. ``year_lookup_bounds_for_datetime_field()`` methods now take the optional
  290. ``iso_year`` argument in order to support bounds for ISO-8601 week-numbering
  291. years.
  292. * The second argument of ``DatabaseSchemaEditor._unique_sql()`` and
  293. ``_create_unique_sql()`` methods is now ``fields`` instead of ``columns``.
  294. :mod:`django.contrib.gis`
  295. -------------------------
  296. * Support for PostGIS 2.3 is removed.
  297. * Support for GDAL 2.0 and GEOS 3.5 is removed.
  298. Dropped support for PostgreSQL 9.6
  299. ----------------------------------
  300. Upstream support for PostgreSQL 9.6 ends in November 2021. Django 4.0 supports
  301. PostgreSQL 10 and higher.
  302. Also, the minimum supported version of ``psycopg2`` is increased from 2.5.4 to
  303. 2.8.4, as ``psycopg2`` 2.8.4 is the first release to support Python 3.8.
  304. Dropped support for Oracle 12.2 and 18c
  305. ---------------------------------------
  306. Upstream support for Oracle 12.2 ends in March 2022 and for Oracle 18c it ends
  307. in June 2021. Django 3.2 will be supported until April 2024. Django 4.0
  308. officially supports Oracle 19c.
  309. .. _csrf-trusted-origins-changes-4.0:
  310. ``CSRF_TRUSTED_ORIGINS`` changes
  311. --------------------------------
  312. Format change
  313. ~~~~~~~~~~~~~
  314. Values in the :setting:`CSRF_TRUSTED_ORIGINS` setting must include the scheme
  315. (e.g. ``'http://'`` or ``'https://'``) instead of only the hostname.
  316. Also, values that started with a dot, must now also include an asterisk before
  317. the dot. For example, change ``'.example.com'`` to ``'https://*.example.com'``.
  318. A system check detects any required changes.
  319. Configuring it may now be required
  320. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  321. As CSRF protection now consults the ``Origin`` header, you may need to set
  322. :setting:`CSRF_TRUSTED_ORIGINS`, particularly if you allow requests from
  323. subdomains by setting :setting:`CSRF_COOKIE_DOMAIN` (or
  324. :setting:`SESSION_COOKIE_DOMAIN` if :setting:`CSRF_USE_SESSIONS` is enabled) to
  325. a value starting with a dot.
  326. ``SecurityMiddleware`` no longer sets the ``X-XSS-Protection`` header
  327. ---------------------------------------------------------------------
  328. The :class:`~django.middleware.security.SecurityMiddleware` no longer sets the
  329. ``X-XSS-Protection`` header if the ``SECURE_BROWSER_XSS_FILTER`` setting is
  330. ``True``. The setting is removed.
  331. Most modern browsers don't honor the ``X-XSS-Protection`` HTTP header. You can
  332. use Content-Security-Policy_ without allowing ``'unsafe-inline'`` scripts
  333. instead.
  334. If you want to support legacy browsers and set the header, use this line in a
  335. custom middleware::
  336. response.headers.setdefault("X-XSS-Protection", "1; mode=block")
  337. .. _Content-Security-Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
  338. Migrations autodetector changes
  339. -------------------------------
  340. The migrations autodetector now uses model states instead of model classes.
  341. Also, migration operations for ``ForeignKey`` and ``ManyToManyField`` fields no
  342. longer specify attributes which were not passed to the fields during
  343. initialization.
  344. As a side-effect, running ``makemigrations`` might generate no-op
  345. ``AlterField`` operations for ``ManyToManyField`` and ``ForeignKey`` fields in
  346. some cases.
  347. ``DeleteView`` changes
  348. ----------------------
  349. :class:`~django.views.generic.edit.DeleteView` now uses
  350. :class:`~django.views.generic.edit.FormMixin` to handle POST requests. As a
  351. consequence, any custom deletion logic in ``delete()`` handlers should be
  352. moved to ``form_valid()``, or a shared helper method, if required.
  353. Table and column naming scheme changes on Oracle
  354. ------------------------------------------------
  355. Django 4.0 inadvertently changed the table and column naming scheme on Oracle.
  356. This causes errors for models and fields with names longer than 30 characters.
  357. Unfortunately, renaming some Oracle tables and columns is required. Use the
  358. upgrade script in :ticket:`33789 <33789#comment:15>` to generate ``RENAME``
  359. statements to change naming scheme.
  360. Miscellaneous
  361. -------------
  362. * Support for ``cx_Oracle`` < 7.0 is removed.
  363. * To allow serving a Django site on a subpath without changing the value of
  364. :setting:`STATIC_URL`, the leading slash is removed from that setting (now
  365. ``'static/'``) in the default :djadmin:`startproject` template.
  366. * The :class:`~django.contrib.admin.AdminSite` method for the admin ``index``
  367. view is no longer decorated with ``never_cache`` when accessed directly,
  368. rather than via the recommended ``AdminSite.urls`` property, or
  369. ``AdminSite.get_urls()`` method.
  370. * Unsupported operations on a sliced queryset now raise ``TypeError`` instead
  371. of ``AssertionError``.
  372. * The undocumented ``django.test.runner.reorder_suite()`` function is renamed
  373. to ``reorder_tests()``. It now accepts an iterable of tests rather than a
  374. test suite, and returns an iterator of tests.
  375. * Calling ``FileSystemStorage.delete()`` with an empty ``name`` now raises
  376. ``ValueError`` instead of ``AssertionError``.
  377. * Calling ``EmailMultiAlternatives.attach_alternative()`` or
  378. ``EmailMessage.attach()`` with an invalid ``content`` or ``mimetype``
  379. arguments now raise ``ValueError`` instead of ``AssertionError``.
  380. * :meth:`~django.test.SimpleTestCase.assertHTMLEqual` no longer considers a
  381. non-boolean attribute without a value equal to an attribute with the same
  382. name and value.
  383. * Tests that fail to load, for example due to syntax errors, now always match
  384. when using :option:`test --tag`.
  385. * The undocumented ``django.contrib.admin.utils.lookup_needs_distinct()``
  386. function is renamed to ``lookup_spawns_duplicates()``.
  387. * The undocumented ``HttpRequest.get_raw_uri()`` method is removed. The
  388. :meth:`.HttpRequest.build_absolute_uri` method may be a suitable alternative.
  389. * The ``object`` argument of undocumented ``ModelAdmin.log_addition()``,
  390. ``log_change()``, and ``log_deletion()`` methods is renamed to ``obj``.
  391. * :class:`~django.utils.feedgenerator.RssFeed`,
  392. :class:`~django.utils.feedgenerator.Atom1Feed`, and their subclasses now emit
  393. elements with no content as self-closing tags.
  394. * ``NodeList.render()`` no longer casts the output of ``render()`` method for
  395. individual nodes to a string. ``Node.render()`` should always return a string
  396. as documented.
  397. * The ``where_class`` property of ``django.db.models.sql.query.Query`` and the
  398. ``where_class`` argument to the private ``get_extra_restriction()`` method of
  399. ``ForeignObject`` and ``ForeignObjectRel`` are removed. If needed, initialize
  400. ``django.db.models.sql.where.WhereNode`` instead.
  401. * The ``filter_clause`` argument of the undocumented ``Query.add_filter()``
  402. method is replaced by two positional arguments ``filter_lhs`` and
  403. ``filter_rhs``.
  404. * :class:`~django.middleware.csrf.CsrfViewMiddleware` now uses
  405. ``request.META['CSRF_COOKIE_NEEDS_UPDATE']`` in place of
  406. ``request.META['CSRF_COOKIE_USED']``, ``request.csrf_cookie_needs_reset``,
  407. and ``response.csrf_cookie_set`` to track whether the CSRF cookie should be
  408. sent. This is an undocumented, private API.
  409. * The undocumented ``TRANSLATOR_COMMENT_MARK`` constant is moved from
  410. ``django.template.base`` to ``django.utils.translation.template``.
  411. * The ``real_apps`` argument of the undocumented
  412. ``django.db.migrations.state.ProjectState.__init__()`` method must now be a
  413. set if provided.
  414. * :class:`~django.forms.RadioSelect` and
  415. :class:`~django.forms.CheckboxSelectMultiple` widgets are now rendered in
  416. ``<div>`` tags so they are announced more concisely by screen readers. If you
  417. need the previous behavior, :ref:`override the widget template
  418. <overriding-built-in-widget-templates>` with the appropriate template from
  419. Django 3.2.
  420. * The :tfilter:`floatformat` template filter no longer depends on the
  421. ``USE_L10N`` setting and always returns localized output. Use the ``u``
  422. suffix to disable localization.
  423. * The default value of the ``USE_L10N`` setting is changed to ``True``. See the
  424. :ref:`Localization section <use_l10n_deprecation>` above for more details.
  425. * As part of the :ref:`move to zoneinfo <whats-new-4.0>`,
  426. ``django.utils.timezone.utc`` is changed to alias
  427. :attr:`datetime.timezone.utc`.
  428. * The minimum supported version of ``asgiref`` is increased from 3.3.2 to
  429. 3.4.1.
  430. .. _deprecated-features-4.0:
  431. Features deprecated in 4.0
  432. ==========================
  433. Use of ``pytz`` time zones
  434. --------------------------
  435. As part of the :ref:`move to zoneinfo <whats-new-4.0>`, use of ``pytz`` time
  436. zones is deprecated.
  437. Accordingly, the ``is_dst`` arguments to the following are also deprecated:
  438. * :meth:`django.db.models.query.QuerySet.datetimes`
  439. * :func:`django.db.models.functions.Trunc`
  440. * :func:`django.db.models.functions.TruncSecond`
  441. * :func:`django.db.models.functions.TruncMinute`
  442. * :func:`django.db.models.functions.TruncHour`
  443. * :func:`django.db.models.functions.TruncDay`
  444. * :func:`django.db.models.functions.TruncWeek`
  445. * :func:`django.db.models.functions.TruncMonth`
  446. * :func:`django.db.models.functions.TruncQuarter`
  447. * :func:`django.db.models.functions.TruncYear`
  448. * :func:`django.utils.timezone.make_aware`
  449. Support for use of ``pytz`` will be removed in Django 5.0.
  450. Time zone support
  451. -----------------
  452. In order to follow good practice, the default value of the :setting:`USE_TZ`
  453. setting will change from ``False`` to ``True``, and time zone support will be
  454. enabled by default, in Django 5.0.
  455. Note that the default :file:`settings.py` file created by
  456. :djadmin:`django-admin startproject <startproject>` includes
  457. :setting:`USE_TZ = True <USE_TZ>` since Django 1.4.
  458. You can set ``USE_TZ`` to ``False`` in your project settings before then to
  459. opt-out.
  460. .. _use_l10n_deprecation:
  461. Localization
  462. ------------
  463. In order to follow good practice, the default value of the ``USE_L10N`` setting
  464. is changed from ``False`` to ``True``.
  465. Moreover ``USE_L10N`` is deprecated as of this release. Starting with Django
  466. 5.0, by default, any date or number displayed by Django will be localized.
  467. The :ttag:`{% localize %} <localize>` tag and the :tfilter:`localize`/
  468. :tfilter:`unlocalize` filters will still be honored by Django.
  469. Miscellaneous
  470. -------------
  471. * ``SERIALIZE`` test setting is deprecated as it can be inferred from the
  472. :attr:`~django.test.TestCase.databases` with the
  473. :ref:`serialized_rollback <test-case-serialized-rollback>` option enabled.
  474. * The undocumented ``django.utils.baseconv`` module is deprecated.
  475. * The undocumented ``django.utils.datetime_safe`` module is deprecated.
  476. * The default sitemap protocol for sitemaps built outside the context of a
  477. request will change from ``'http'`` to ``'https'`` in Django 5.0.
  478. * The ``extra_tests`` argument for :meth:`.DiscoverRunner.build_suite` and
  479. :meth:`.DiscoverRunner.run_tests` is deprecated.
  480. * The :class:`~django.contrib.postgres.aggregates.ArrayAgg`,
  481. :class:`~django.contrib.postgres.aggregates.JSONBAgg`, and
  482. :class:`~django.contrib.postgres.aggregates.StringAgg` aggregates will return
  483. ``None`` when there are no rows instead of ``[]``, ``[]``, and ``''``
  484. respectively in Django 5.0. If you need the previous behavior, explicitly set
  485. ``default`` to ``Value([])``, ``Value('[]')``, or ``Value('')``.
  486. * The ``django.contrib.gis.admin.GeoModelAdmin`` and ``OSMGeoAdmin`` classes
  487. are deprecated. Use :class:`~django.contrib.admin.ModelAdmin` and
  488. :class:`~django.contrib.gis.admin.GISModelAdmin` instead.
  489. * Since form rendering now uses the template engine, the undocumented
  490. ``BaseForm._html_output()`` helper method is deprecated.
  491. * The ability to return a ``str`` from ``ErrorList`` and ``ErrorDict`` is
  492. deprecated. It is expected these methods return a ``SafeString``.
  493. Features removed in 4.0
  494. =======================
  495. These features have reached the end of their deprecation cycle and are removed
  496. in Django 4.0.
  497. See :ref:`deprecated-features-3.0` for details on these changes, including how
  498. to remove usage of these features.
  499. * ``django.utils.http.urlquote()``, ``urlquote_plus()``, ``urlunquote()``, and
  500. ``urlunquote_plus()`` are removed.
  501. * ``django.utils.encoding.force_text()`` and ``smart_text()`` are removed.
  502. * ``django.utils.translation.ugettext()``, ``ugettext_lazy()``,
  503. ``ugettext_noop()``, ``ungettext()``, and ``ungettext_lazy()`` are removed.
  504. * ``django.views.i18n.set_language()`` doesn't set the user language in
  505. ``request.session`` (key ``_language``).
  506. * ``alias=None`` is required in the signature of
  507. ``django.db.models.Expression.get_group_by_cols()`` subclasses.
  508. * ``django.utils.text.unescape_entities()`` is removed.
  509. * ``django.utils.http.is_safe_url()`` is removed.
  510. See :ref:`deprecated-features-3.1` for details on these changes, including how
  511. to remove usage of these features.
  512. * The ``PASSWORD_RESET_TIMEOUT_DAYS`` setting is removed.
  513. * The :lookup:`isnull` lookup no longer allows using non-boolean values as the
  514. right-hand side.
  515. * The ``django.db.models.query_utils.InvalidQuery`` exception class is removed.
  516. * The ``django-admin.py`` entry point is removed.
  517. * The ``HttpRequest.is_ajax()`` method is removed.
  518. * Support for the pre-Django 3.1 encoding format of cookies values used by
  519. ``django.contrib.messages.storage.cookie.CookieStorage`` is removed.
  520. * Support for the pre-Django 3.1 password reset tokens in the admin site (that
  521. use the SHA-1 hashing algorithm) is removed.
  522. * Support for the pre-Django 3.1 encoding format of sessions is removed.
  523. * Support for the pre-Django 3.1 ``django.core.signing.Signer`` signatures
  524. (encoded with the SHA-1 algorithm) is removed.
  525. * Support for the pre-Django 3.1 ``django.core.signing.dumps()`` signatures
  526. (encoded with the SHA-1 algorithm) in ``django.core.signing.loads()`` is
  527. removed.
  528. * Support for the pre-Django 3.1 user sessions (that use the SHA-1 algorithm)
  529. is removed.
  530. * The ``get_response`` argument for
  531. ``django.utils.deprecation.MiddlewareMixin.__init__()`` is required and
  532. doesn't accept ``None``.
  533. * The ``providing_args`` argument for ``django.dispatch.Signal`` is removed.
  534. * The ``length`` argument for ``django.utils.crypto.get_random_string()`` is
  535. required.
  536. * The ``list`` message for ``ModelMultipleChoiceField`` is removed.
  537. * Support for passing raw column aliases to ``QuerySet.order_by()`` is removed.
  538. * The ``NullBooleanField`` model field is removed, except for support in
  539. historical migrations.
  540. * ``django.conf.urls.url()`` is removed.
  541. * The ``django.contrib.postgres.fields.JSONField`` model field is removed,
  542. except for support in historical migrations.
  543. * ``django.contrib.postgres.fields.jsonb.KeyTransform`` and
  544. ``django.contrib.postgres.fields.jsonb.KeyTextTransform`` are removed.
  545. * ``django.contrib.postgres.forms.JSONField`` is removed.
  546. * The ``{% ifequal %}`` and ``{% ifnotequal %}`` template tags are removed.
  547. * The ``DEFAULT_HASHING_ALGORITHM`` transitional setting is removed.