4.0.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. ============================================
  2. Django 4.0 release notes - UNDER DEVELOPMENT
  3. ============================================
  4. *Expected December 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. Functional unique constraints
  22. -----------------------------
  23. The new :attr:`*expressions <django.db.models.UniqueConstraint.expressions>`
  24. positional argument of
  25. :class:`UniqueConstraint() <django.db.models.UniqueConstraint>` enables
  26. creating functional unique constraints on expressions and database functions.
  27. For example::
  28. from django.db import models
  29. from django.db.models import UniqueConstraint
  30. from django.db.models.functions import Lower
  31. class MyModel(models.Model):
  32. first_name = models.CharField(max_length=255)
  33. last_name = models.CharField(max_length=255)
  34. class Meta:
  35. indexes = [
  36. UniqueConstraint(
  37. Lower('first_name'),
  38. Lower('last_name').desc(),
  39. name='first_last_name_unique',
  40. ),
  41. ]
  42. Functional unique constraints are added to models using the
  43. :attr:`Meta.constraints <django.db.models.Options.constraints>` option.
  44. Minor features
  45. --------------
  46. :mod:`django.contrib.admin`
  47. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  48. * The ``admin/base.html`` template now has a new block ``header`` which
  49. contains the admin site header.
  50. * The new :meth:`.ModelAdmin.get_formset_kwargs` method allows customizing the
  51. keyword arguments passed to the constructor of a formset.
  52. * The navigation sidebar now has a quick filter toolbar.
  53. * The new context variable ``model`` which contains the model class for each
  54. model is added to the :meth:`.AdminSite.each_context` method.
  55. * The new :attr:`.ModelAdmin.search_help_text` attribute allows specifying a
  56. descriptive text for the search box.
  57. :mod:`django.contrib.admindocs`
  58. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  59. * The admindocs now allows esoteric setups where :setting:`ROOT_URLCONF` is not
  60. a string.
  61. * The model section of the ``admindocs`` now shows cached properties.
  62. :mod:`django.contrib.auth`
  63. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  64. * The default iteration count for the PBKDF2 password hasher is increased from
  65. 260,000 to 320,000.
  66. * The new
  67. :attr:`LoginView.next_page <django.contrib.auth.views.LoginView.next_page>`
  68. attribute and
  69. :meth:`~django.contrib.auth.views.LoginView.get_default_redirect_url` method
  70. allow customizing the redirect after login.
  71. :mod:`django.contrib.contenttypes`
  72. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  73. * ...
  74. :mod:`django.contrib.gis`
  75. ~~~~~~~~~~~~~~~~~~~~~~~~~
  76. * Added support for SpatiaLite 5.
  77. * :class:`~django.contrib.gis.gdal.GDALRaster` now allows creating rasters in
  78. any GDAL virtual filesystem.
  79. :mod:`django.contrib.messages`
  80. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  81. * ...
  82. :mod:`django.contrib.postgres`
  83. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  84. * The PostgreSQL backend now supports connecting by a service name. See
  85. :ref:`postgresql-connection-settings` for more details.
  86. :mod:`django.contrib.redirects`
  87. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  88. * ...
  89. :mod:`django.contrib.sessions`
  90. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  91. * ...
  92. :mod:`django.contrib.sitemaps`
  93. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  94. * ...
  95. :mod:`django.contrib.sites`
  96. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. * ...
  98. :mod:`django.contrib.staticfiles`
  99. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  100. * :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` now
  101. replaces paths to JavaScript source map references with their hashed
  102. counterparts.
  103. * :class:`~django.contrib.staticfiles.storage.ManifestStaticFilesStorage` now
  104. replaces paths to JavaScript modules in ``import`` and ``export`` statements
  105. with their hashed counterparts.
  106. :mod:`django.contrib.syndication`
  107. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  108. * ...
  109. Cache
  110. ~~~~~
  111. * ...
  112. CSRF
  113. ~~~~
  114. * CSRF protection now consults the ``Origin`` header, if present. To facilitate
  115. this, :ref:`some changes <csrf-trusted-origins-changes-4.0>` to the
  116. :setting:`CSRF_TRUSTED_ORIGINS` setting are required.
  117. Decorators
  118. ~~~~~~~~~~
  119. * ...
  120. Email
  121. ~~~~~
  122. * ...
  123. Error Reporting
  124. ~~~~~~~~~~~~~~~
  125. * ...
  126. File Storage
  127. ~~~~~~~~~~~~
  128. * ...
  129. File Uploads
  130. ~~~~~~~~~~~~
  131. * ...
  132. Forms
  133. ~~~~~
  134. * :class:`~django.forms.ModelChoiceField` now includes the provided value in
  135. the ``params`` argument of a raised
  136. :exc:`~django.core.exceptions.ValidationError` for the ``invalid_choice``
  137. error message. This allows custom error messages to use the ``%(value)s``
  138. placeholder.
  139. Generic Views
  140. ~~~~~~~~~~~~~
  141. * ...
  142. Internationalization
  143. ~~~~~~~~~~~~~~~~~~~~
  144. * ...
  145. Logging
  146. ~~~~~~~
  147. * ...
  148. Management Commands
  149. ~~~~~~~~~~~~~~~~~~~
  150. * The :djadmin:`runserver` management command now supports the
  151. :option:`--skip-checks` option.
  152. * On PostgreSQL, :djadmin:`dbshell` now supports specifying a password file.
  153. Migrations
  154. ~~~~~~~~~~
  155. * ...
  156. Models
  157. ~~~~~~
  158. * New :meth:`QuerySet.contains(obj) <.QuerySet.contains>` method returns
  159. whether the queryset contains the given object. This tries to perform the
  160. query in the simplest and fastest way possible.
  161. * The new ``precision`` argument of the
  162. :class:`Round() <django.db.models.functions.Round>` database function allows
  163. specifying the number of decimal places after rounding.
  164. * :meth:`.QuerySet.bulk_create` now sets the primary key on objects when using
  165. SQLite 3.35+.
  166. * :class:`~django.db.models.DurationField` now supports multiplying and
  167. dividing by scalar values on SQLite.
  168. Requests and Responses
  169. ~~~~~~~~~~~~~~~~~~~~~~
  170. * The :class:`~django.middleware.security.SecurityMiddleware` now adds the
  171. :ref:`Cross-Origin Opener Policy <cross-origin-opener-policy>` header with a
  172. value of ``'same-origin'`` to prevent cross-origin popups from sharing the
  173. same browsing context. You can prevent this header from being added by
  174. setting the :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY` setting to ``None``.
  175. Security
  176. ~~~~~~~~
  177. * ...
  178. Serialization
  179. ~~~~~~~~~~~~~
  180. * ...
  181. Signals
  182. ~~~~~~~
  183. * The new ``stdout`` argument for :func:`~django.db.models.signals.pre_migrate`
  184. and :func:`~django.db.models.signals.post_migrate` signals allows redirecting
  185. output to a stream-like object. It should be preferred over
  186. :py:data:`sys.stdout` and :py:func:`print` when emitting verbose output in
  187. order to allow proper capture when testing.
  188. Templates
  189. ~~~~~~~~~
  190. * ...
  191. Tests
  192. ~~~~~
  193. * The new ``serialized_aliases`` argument of
  194. :func:`django.test.utils.setup_databases` determines which
  195. :setting:`DATABASES` aliases test databases should have their state
  196. serialized to allow usage of the
  197. :ref:`serialized_rollback <test-case-serialized-rollback>` feature.
  198. * Django test runner now supports a :option:`--buffer <test --buffer>` option
  199. with parallel tests.
  200. * The new :meth:`.DiscoverRunner.log` method allows customizing the way
  201. messages are logged.
  202. URLs
  203. ~~~~
  204. * ...
  205. Utilities
  206. ~~~~~~~~~
  207. * ...
  208. Validators
  209. ~~~~~~~~~~
  210. * ...
  211. .. _backwards-incompatible-4.0:
  212. Backwards incompatible changes in 4.0
  213. =====================================
  214. Database backend API
  215. --------------------
  216. This section describes changes that may be needed in third-party database
  217. backends.
  218. * ``DatabaseOperations.year_lookup_bounds_for_date_field()`` and
  219. ``year_lookup_bounds_for_datetime_field()`` methods now take the optional
  220. ``iso_year`` argument in order to support bounds for ISO-8601 week-numbering
  221. years.
  222. * The second argument of ``DatabaseSchemaEditor._unique_sql()`` and
  223. ``_create_unique_sql()`` methods is now fields instead of columns.
  224. :mod:`django.contrib.gis`
  225. -------------------------
  226. * Support for PostGIS 2.3 is removed.
  227. * Support for GDAL 2.0 and GEOS 3.5 is removed.
  228. Dropped support for PostgreSQL 9.6
  229. ----------------------------------
  230. Upstream support for PostgreSQL 9.6 ends in November 2021. Django 4.0 supports
  231. PostgreSQL 10 and higher.
  232. Dropped support for Oracle 12.2 and 18c
  233. ---------------------------------------
  234. Upstream support for Oracle 12.2 ends in March 2022 and for Oracle 18c it ends
  235. in June 2021. Django 3.2 will be supported until April 2024. Django 4.0
  236. officially supports Oracle 19c.
  237. .. _csrf-trusted-origins-changes-4.0:
  238. ``CSRF_TRUSTED_ORIGINS`` changes
  239. --------------------------------
  240. Format change
  241. ~~~~~~~~~~~~~
  242. Values in the :setting:`CSRF_TRUSTED_ORIGINS` setting must include the scheme
  243. (e.g. ``'http://'`` or ``'https://'``) instead of only the hostname.
  244. Also, values that started with a dot, must now also include an asterisk before
  245. the dot. For example, change ``'.example.com'`` to ``'https://*.example.com'``.
  246. A system check detects any required changes.
  247. Configuring it may now be required
  248. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  249. As CSRF protection now consults the ``Origin`` header, you may need to set
  250. :setting:`CSRF_TRUSTED_ORIGINS`, particularly if you allow requests from
  251. subdomains by setting :setting:`CSRF_COOKIE_DOMAIN` (or
  252. :setting:`SESSION_COOKIE_DOMAIN` if :setting:`CSRF_USE_SESSIONS` is enabled) to
  253. a value starting with a dot.
  254. ``SecurityMiddleware`` no longer sets the ``X-XSS-Protection`` header
  255. ---------------------------------------------------------------------
  256. The :class:`~django.middleware.security.SecurityMiddleware` no longer sets the
  257. ``X-XSS-Protection`` header if the ``SECURE_BROWSER_XSS_FILTER`` setting is
  258. ``True``. The setting is removed.
  259. Most modern browsers don't honor the ``X-XSS-Protection`` HTTP header. You can
  260. use Content-Security-Policy_ without allowing ``'unsafe-inline'`` scripts
  261. instead.
  262. If you want to support legacy browsers and set the header, use this line in a
  263. custom middleware::
  264. response.headers.setdefault('X-XSS-Protection', '1; mode=block')
  265. .. _Content-Security-Policy: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
  266. Migrations autodetector changes
  267. -------------------------------
  268. The migrations autodetector now uses model states instead of model classes.
  269. Also, migration operations for ``ForeignKey`` and ``ManyToManyField`` fields no
  270. longer specify attributes which were not passed to the fields during
  271. initialization.
  272. As a side-effect, running ``makemigrations`` might generate no-op
  273. ``AlterField`` operations for ``ManyToManyField`` and ``ForeignKey`` fields in
  274. some cases.
  275. Miscellaneous
  276. -------------
  277. * Support for ``cx_Oracle`` < 7.0 is removed.
  278. * To allow serving a Django site on a subpath without changing the value of
  279. :setting:`STATIC_URL`, the leading slash is removed from that setting (now
  280. ``'static/'``) in the default :djadmin:`startproject` template.
  281. * The :class:`~django.contrib.admin.AdminSite` method for the admin ``index``
  282. view is no longer decorated with ``never_cache`` when accessed directly,
  283. rather than via the recommended ``AdminSite.urls`` property, or
  284. ``AdminSite.get_urls()`` method.
  285. * Unsupported operations on a sliced queryset now raise ``TypeError`` instead
  286. of ``AssertionError``.
  287. * The undocumented ``django.test.runner.reorder_suite()`` function is renamed
  288. to ``reorder_tests()``. It now accepts an iterable of tests rather than a
  289. test suite, and returns an iterator of tests.
  290. * Calling ``FileSystemStorage.delete()`` with an empty ``name`` now raises
  291. ``ValueError`` instead of ``AssertionError``.
  292. * Calling ``EmailMultiAlternatives.attach_alternative()`` or
  293. ``EmailMessage.attach()`` with an invalid ``content`` or ``mimetype``
  294. arguments now raise ``ValueError`` instead of ``AssertionError``.
  295. * :meth:`~django.test.SimpleTestCase.assertHTMLEqual` no longer considers a
  296. non-boolean attribute without a value equal to an attribute with the same
  297. name and value.
  298. * Tests that fail to load, for example due to syntax errors, now always match
  299. when using :option:`test --tag`.
  300. * The undocumented ``django.contrib.admin.utils.lookup_needs_distinct()``
  301. function is renamed to ``lookup_spawns_duplicates()``.
  302. * The undocumented ``HttpRequest.get_raw_uri()`` method is removed. The
  303. :meth:`.HttpRequest.build_absolute_uri` method may be a suitable alternative.
  304. * The ``object`` argument of undocumented ``ModelAdmin.log_addition()``,
  305. ``log_change()``, and ``log_deletion()`` methods is renamed to ``obj``.
  306. * :class:`~django.utils.feedgenerator.RssFeed`,
  307. :class:`~django.utils.feedgenerator.Atom1Feed`, and their subclasses now
  308. emit elements with no content as self-closing tags.
  309. .. _deprecated-features-4.0:
  310. Features deprecated in 4.0
  311. ==========================
  312. Time zone support
  313. -----------------
  314. In order to follow good practice, the default value of the :setting:`USE_TZ`
  315. setting will change from ``False`` to ``True``, and time zone support will be
  316. enabled by default, in Django 5.0.
  317. Note that the default :file:`settings.py` file created by
  318. :djadmin:`django-admin startproject <startproject>` includes
  319. :setting:`USE_TZ = True <USE_TZ>` since Django 1.4.
  320. You can set ``USE_TZ`` to ``False`` in your project settings before then to
  321. opt-out.
  322. Miscellaneous
  323. -------------
  324. * ``SERIALIZE`` test setting is deprecated as it can be inferred from the
  325. :attr:`~django.test.TestCase.databases` with the
  326. :ref:`serialized_rollback <test-case-serialized-rollback>` option enabled.
  327. * The undocumented ``django.utils.baseconv`` module is deprecated.
  328. * The undocumented ``django.utils.datetime_safe`` module is deprecated.
  329. * The default sitemap protocol for sitemaps built outside the context of a
  330. request will change from ``'http'`` to ``'https'`` in Django 5.0.
  331. Features removed in 4.0
  332. =======================
  333. These features have reached the end of their deprecation cycle and are removed
  334. in Django 4.0.
  335. See :ref:`deprecated-features-3.0` for details on these changes, including how
  336. to remove usage of these features.
  337. * ``django.utils.http.urlquote()``, ``urlquote_plus()``, ``urlunquote()``, and
  338. ``urlunquote_plus()`` are removed.
  339. * ``django.utils.encoding.force_text()`` and ``smart_text()`` are removed.
  340. * ``django.utils.translation.ugettext()``, ``ugettext_lazy()``,
  341. ``ugettext_noop()``, ``ungettext()``, and ``ungettext_lazy()`` are removed.
  342. * ``django.views.i18n.set_language()`` doesn't set the user language in
  343. ``request.session`` (key ``_language``).
  344. * ``alias=None`` is required in the signature of
  345. ``django.db.models.Expression.get_group_by_cols()`` subclasses.
  346. * ``django.utils.text.unescape_entities()`` is removed.
  347. * ``django.utils.http.is_safe_url()`` is removed.
  348. See :ref:`deprecated-features-3.1` for details on these changes, including how
  349. to remove usage of these features.
  350. * The ``PASSWORD_RESET_TIMEOUT_DAYS`` setting is removed.
  351. * The :lookup:`isnull` lookup no longer allows using non-boolean values as the
  352. right-hand side.
  353. * The ``django.db.models.query_utils.InvalidQuery`` exception class is removed.
  354. * The ``django-admin.py`` entry point is removed.
  355. * The ``HttpRequest.is_ajax()`` method is removed.
  356. * Support for the pre-Django 3.1 encoding format of cookies values used by
  357. ``django.contrib.messages.storage.cookie.CookieStorage`` is removed.
  358. * Support for the pre-Django 3.1 password reset tokens in the admin site (that
  359. use the SHA-1 hashing algorithm) is removed.
  360. * Support for the pre-Django 3.1 encoding format of sessions is removed.
  361. * Support for the pre-Django 3.1 ``django.core.signing.Signer`` signatures
  362. (encoded with the SHA-1 algorithm) is removed.
  363. * Support for the pre-Django 3.1 ``django.core.signing.dumps()`` signatures
  364. (encoded with the SHA-1 algorithm) in ``django.core.signing.loads()`` is
  365. removed.
  366. * Support for the pre-Django 3.1 user sessions (that use the SHA-1 algorithm)
  367. is removed.
  368. * The ``get_response`` argument for
  369. ``django.utils.deprecation.MiddlewareMixin.__init__()`` is required and
  370. doesn't accept ``None``.
  371. * The ``providing_args`` argument for ``django.dispatch.Signal`` is removed.
  372. * The ``length`` argument for ``django.utils.crypto.get_random_string()`` is
  373. required.
  374. * The ``list`` message for ``ModelMultipleChoiceField`` is removed.
  375. * Support for passing raw column aliases to ``QuerySet.order_by()`` is removed.
  376. * The ``NullBooleanField`` model field is removed, except for support in
  377. historical migrations.
  378. * ``django.conf.urls.url()`` is removed.
  379. * The ``django.contrib.postgres.fields.JSONField`` model field is removed,
  380. except for support in historical migrations.
  381. * ``django.contrib.postgres.fields.jsonb.KeyTransform`` and
  382. ``django.contrib.postgres.fields.jsonb.KeyTextTransform`` are removed.
  383. * ``django.contrib.postgres.forms.JSONField`` is removed.
  384. * The ``{% ifequal %}`` and ``{% ifnotequal %}`` template tags are removed.
  385. * The ``DEFAULT_HASHING_ALGORITHM`` transitional setting is removed.