3.1.txt 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  1. ========================
  2. Django 3.1 release notes
  3. ========================
  4. *August 4, 2020*
  5. Welcome to Django 3.1!
  6. These release notes cover the :ref:`new features <whats-new-3.1>`, as well as
  7. some :ref:`backwards incompatible changes <backwards-incompatible-3.1>` you'll
  8. want to be aware of when upgrading from Django 3.0 or earlier. We've
  9. :ref:`dropped some features<removed-features-3.1>` that have reached the end of
  10. their deprecation cycle, and we've :ref:`begun the deprecation process for
  11. some features <deprecated-features-3.1>`.
  12. See the :doc:`/howto/upgrade-version` guide if you're updating an existing
  13. project.
  14. Python compatibility
  15. ====================
  16. Django 3.1 supports Python 3.6, 3.7, 3.8, and 3.9 (as of 3.1.3). We **highly
  17. recommend** and only officially support the latest release of each series.
  18. .. _whats-new-3.1:
  19. What's new in Django 3.1
  20. ========================
  21. Asynchronous views and middleware support
  22. -----------------------------------------
  23. Django now supports a fully asynchronous request path, including:
  24. * :ref:`Asynchronous views <async-views>`
  25. * :ref:`Asynchronous middleware <async-middleware>`
  26. * :ref:`Asynchronous tests and test client <async-tests>`
  27. To get started with async views, you need to declare a view using
  28. ``async def``::
  29. async def my_view(request):
  30. await asyncio.sleep(0.5)
  31. return HttpResponse("Hello, async world!")
  32. All asynchronous features are supported whether you are running under WSGI or
  33. ASGI mode. However, there will be performance penalties using async code in
  34. WSGI mode. You can read more about the specifics in :doc:`/topics/async`
  35. documentation.
  36. You are free to mix async and sync views, middleware, and tests as much as you
  37. want. Django will ensure that you always end up with the right execution
  38. context. We expect most projects will keep the majority of their views
  39. synchronous, and only have a select few running in async mode - but it is
  40. entirely your choice.
  41. Django's ORM, cache layer, and other pieces of code that do long-running
  42. network calls do not yet support async access. We expect to add support for
  43. them in upcoming releases. Async views are ideal, however, if you are doing a
  44. lot of API or HTTP calls inside your view, you can now natively do all those
  45. HTTP calls in parallel to considerably speed up your view's execution.
  46. Asynchronous support should be entirely backwards-compatible and we have tried
  47. to ensure that it has no speed regressions for your existing, synchronous code.
  48. It should have no noticeable effect on any existing Django projects.
  49. JSONField for all supported database backends
  50. ---------------------------------------------
  51. Django now includes :class:`.models.JSONField` and
  52. :class:`forms.JSONField <django.forms.JSONField>` that can be used on all
  53. supported database backends. Both fields support the use of custom JSON
  54. encoders and decoders. The model field supports the introspection,
  55. :ref:`lookups, and transforms <querying-jsonfield>` that were previously
  56. PostgreSQL-only::
  57. from django.db import models
  58. class ContactInfo(models.Model):
  59. data = models.JSONField()
  60. ContactInfo.objects.create(
  61. data={
  62. "name": "John",
  63. "cities": ["London", "Cambridge"],
  64. "pets": {"dogs": ["Rufus", "Meg"]},
  65. }
  66. )
  67. ContactInfo.objects.filter(
  68. data__name="John",
  69. data__pets__has_key="dogs",
  70. data__cities__contains="London",
  71. ).delete()
  72. If your project uses ``django.contrib.postgres.fields.JSONField``, plus the
  73. related form field and transforms, you should adjust to use the new fields,
  74. and generate and apply a database migration. For now, the old fields and
  75. transforms are left as a reference to the new ones and are :ref:`deprecated as
  76. of this release <deprecated-jsonfield>`.
  77. .. _default-hashing-algorithm-usage:
  78. ``DEFAULT_HASHING_ALGORITHM`` settings
  79. --------------------------------------
  80. The new ``DEFAULT_HASHING_ALGORITHM`` transitional setting allows specifying
  81. the default hashing algorithm to use for encoding cookies, password reset
  82. tokens in the admin site, user sessions, and signatures created by
  83. :class:`django.core.signing.Signer` and :meth:`django.core.signing.dumps`.
  84. Support for SHA-256 was added in Django 3.1. If you are upgrading multiple
  85. instances of the same project to Django 3.1, you should set
  86. ``DEFAULT_HASHING_ALGORITHM`` to ``'sha1'`` during the transition, in order to
  87. allow compatibility with the older versions of Django. Note that this requires
  88. Django 3.1.1+. Once the transition to 3.1 is complete you can stop overriding
  89. ``DEFAULT_HASHING_ALGORITHM``.
  90. This setting is deprecated as of this release, because support for tokens,
  91. cookies, sessions, and signatures that use SHA-1 algorithm will be removed in
  92. Django 4.0.
  93. Minor features
  94. --------------
  95. :mod:`django.contrib.admin`
  96. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  97. * The new ``django.contrib.admin.EmptyFieldListFilter`` for
  98. :attr:`.ModelAdmin.list_filter` allows filtering on empty values (empty
  99. strings and nulls) in the admin changelist view.
  100. * Filters in the right sidebar of the admin changelist view now contain a link
  101. to clear all filters.
  102. * The admin now has a sidebar on larger screens for easier navigation. It is
  103. enabled by default but can be disabled by using a custom ``AdminSite`` and
  104. setting :attr:`.AdminSite.enable_nav_sidebar` to ``False``.
  105. Rendering the sidebar requires access to the current request in order to set
  106. CSS and ARIA role affordances. This requires using
  107. ``'django.template.context_processors.request'`` in the
  108. ``'context_processors'`` option of :setting:`OPTIONS <TEMPLATES-OPTIONS>`.
  109. * Initially empty ``extra`` inlines can now be removed, in the same way as
  110. dynamically created ones.
  111. * ``XRegExp`` is upgraded from version 2.0.0 to 3.2.0.
  112. * jQuery is upgraded from version 3.4.1 to 3.5.1.
  113. * Select2 library is upgraded from version 4.0.7 to 4.0.13.
  114. :mod:`django.contrib.auth`
  115. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  116. * The default iteration count for the PBKDF2 password hasher is increased from
  117. 180,000 to 216,000.
  118. * The new :setting:`PASSWORD_RESET_TIMEOUT` setting allows defining the number
  119. of seconds a password reset link is valid for. This is encouraged instead of
  120. the deprecated ``PASSWORD_RESET_TIMEOUT_DAYS`` setting, which will be removed
  121. in Django 4.0.
  122. * The password reset mechanism now uses the SHA-256 hashing algorithm. Support
  123. for tokens that use the old hashing algorithm remains until Django 4.0.
  124. * :meth:`.AbstractBaseUser.get_session_auth_hash` now uses the SHA-256 hashing
  125. algorithm. Support for user sessions that use the old hashing algorithm
  126. remains until Django 4.0.
  127. :mod:`django.contrib.contenttypes`
  128. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  129. * The new :option:`remove_stale_contenttypes --include-stale-apps` option
  130. allows removing stale content types from previously installed apps that have
  131. been removed from :setting:`INSTALLED_APPS`.
  132. :mod:`django.contrib.gis`
  133. ~~~~~~~~~~~~~~~~~~~~~~~~~
  134. * :lookup:`relate` lookup is now supported on MariaDB.
  135. * Added the :attr:`.LinearRing.is_counterclockwise` property.
  136. * :class:`~django.contrib.gis.db.models.functions.AsGeoJSON` is now supported
  137. on Oracle.
  138. * Added the :class:`~django.contrib.gis.db.models.functions.AsWKB` and
  139. :class:`~django.contrib.gis.db.models.functions.AsWKT` functions.
  140. * Added support for PostGIS 3 and GDAL 3.
  141. :mod:`django.contrib.humanize`
  142. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  143. * :tfilter:`intword` template filter now supports negative integers.
  144. :mod:`django.contrib.postgres`
  145. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  146. * The new :class:`~django.contrib.postgres.indexes.BloomIndex` class allows
  147. creating ``bloom`` indexes in the database. The new
  148. :class:`~django.contrib.postgres.operations.BloomExtension` migration
  149. operation installs the ``bloom`` extension to add support for this index.
  150. * :meth:`~django.db.models.Model.get_FOO_display` now supports
  151. :class:`~django.contrib.postgres.fields.ArrayField` and
  152. :class:`~django.contrib.postgres.fields.RangeField`.
  153. * The new :lookup:`rangefield.lower_inc`, :lookup:`rangefield.lower_inf`,
  154. :lookup:`rangefield.upper_inc`, and :lookup:`rangefield.upper_inf` lookups
  155. allow querying :class:`~django.contrib.postgres.fields.RangeField` by a bound
  156. type.
  157. * :lookup:`rangefield.contained_by` now supports
  158. :class:`~django.db.models.SmallAutoField`,
  159. :class:`~django.db.models.AutoField`,
  160. :class:`~django.db.models.BigAutoField`,
  161. :class:`~django.db.models.SmallIntegerField`, and
  162. :class:`~django.db.models.DecimalField`.
  163. * :class:`~django.contrib.postgres.search.SearchQuery` now supports
  164. ``'websearch'`` search type on PostgreSQL 11+.
  165. * :class:`SearchQuery.value <django.contrib.postgres.search.SearchQuery>` now
  166. supports query expressions.
  167. * The new :class:`~django.contrib.postgres.search.SearchHeadline` class allows
  168. highlighting search results.
  169. * :lookup:`search` lookup now supports query expressions.
  170. * The new ``cover_density`` parameter of
  171. :class:`~django.contrib.postgres.search.SearchRank` allows ranking by cover
  172. density.
  173. * The new ``normalization`` parameter of
  174. :class:`~django.contrib.postgres.search.SearchRank` allows rank
  175. normalization.
  176. * The new :attr:`.ExclusionConstraint.deferrable` attribute allows creating
  177. deferrable exclusion constraints.
  178. :mod:`django.contrib.sessions`
  179. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  180. * The :setting:`SESSION_COOKIE_SAMESITE` setting now allows ``'None'`` (string)
  181. value to explicitly state that the cookie is sent with all same-site and
  182. cross-site requests.
  183. :mod:`django.contrib.staticfiles`
  184. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  185. * The :setting:`STATICFILES_DIRS` setting now supports :class:`pathlib.Path`.
  186. Cache
  187. ~~~~~
  188. * The :func:`~django.views.decorators.cache.cache_control` decorator and
  189. :func:`~django.utils.cache.patch_cache_control` method now support multiple
  190. field names in the ``no-cache`` directive for the ``Cache-Control`` header,
  191. according to :rfc:`7234#section-5.2.2.2`.
  192. * :meth:`~django.core.cache.cache.delete` now returns ``True`` if the key was
  193. successfully deleted, ``False`` otherwise.
  194. CSRF
  195. ~~~~
  196. * The :setting:`CSRF_COOKIE_SAMESITE` setting now allows ``'None'`` (string)
  197. value to explicitly state that the cookie is sent with all same-site and
  198. cross-site requests.
  199. Email
  200. ~~~~~
  201. * The :setting:`EMAIL_FILE_PATH` setting, used by the :ref:`file email backend
  202. <topic-email-file-backend>`, now supports :class:`pathlib.Path`.
  203. Error Reporting
  204. ~~~~~~~~~~~~~~~
  205. * :class:`django.views.debug.SafeExceptionReporterFilter` now filters sensitive
  206. values from ``request.META`` in exception reports.
  207. * The new :attr:`.SafeExceptionReporterFilter.cleansed_substitute` and
  208. :attr:`.SafeExceptionReporterFilter.hidden_settings` attributes allow
  209. customization of sensitive settings and ``request.META`` filtering in
  210. exception reports.
  211. * The technical 404 debug view now respects
  212. :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` when applying settings
  213. filtering.
  214. * The new :setting:`DEFAULT_EXCEPTION_REPORTER` allows providing a
  215. :class:`django.views.debug.ExceptionReporter` subclass to customize exception
  216. report generation. See :ref:`custom-error-reports` for details.
  217. File Storage
  218. ~~~~~~~~~~~~
  219. * ``FileSystemStorage.save()`` method now supports :class:`pathlib.Path`.
  220. * :class:`~django.db.models.FileField` and
  221. :class:`~django.db.models.ImageField` now accept a callable for ``storage``.
  222. This allows you to modify the used storage at runtime, selecting different
  223. storages for different environments, for example.
  224. Forms
  225. ~~~~~
  226. * :class:`~django.forms.ModelChoiceIterator`, used by
  227. :class:`~django.forms.ModelChoiceField` and
  228. :class:`~django.forms.ModelMultipleChoiceField`, now uses
  229. :class:`~django.forms.ModelChoiceIteratorValue` that can be used by widgets
  230. to access model instances. See :ref:`iterating-relationship-choices` for
  231. details.
  232. * :class:`django.forms.DateTimeField` now accepts dates in a subset of ISO 8601
  233. datetime formats, including optional timezone, e.g. ``2019-10-10T06:47``,
  234. ``2019-10-10T06:47:23+04:00``, or ``2019-10-10T06:47:23Z``. The timezone will
  235. always be retained if provided, with timezone-aware datetimes being returned
  236. even when :setting:`USE_TZ` is ``False``.
  237. Additionally, ``DateTimeField`` now uses ``DATE_INPUT_FORMATS`` in addition
  238. to ``DATETIME_INPUT_FORMATS`` when converting a field input to a ``datetime``
  239. value.
  240. * :attr:`.MultiWidget.widgets` now accepts a dictionary which allows
  241. customizing subwidget ``name`` attributes.
  242. * The new :attr:`.BoundField.widget_type` property can be used to dynamically
  243. adjust form rendering based upon the widget type.
  244. Internationalization
  245. ~~~~~~~~~~~~~~~~~~~~
  246. * The :setting:`LANGUAGE_COOKIE_SAMESITE` setting now allows ``'None'``
  247. (string) value to explicitly state that the cookie is sent with all same-site
  248. and cross-site requests.
  249. * Added support and translations for the Algerian Arabic, Igbo, Kyrgyz, Tajik,
  250. and Turkmen languages.
  251. Management Commands
  252. ~~~~~~~~~~~~~~~~~~~
  253. * The new :option:`check --database` option allows specifying database aliases
  254. for running the ``database`` system checks. Previously these checks were
  255. enabled for all configured :setting:`DATABASES` by passing the ``database``
  256. tag to the command.
  257. * The new :option:`migrate --check` option makes the command exit with a
  258. non-zero status when unapplied migrations are detected.
  259. * The new ``returncode`` argument for
  260. :attr:`~django.core.management.CommandError` allows customizing the exit
  261. status for management commands.
  262. * The new :option:`dbshell -- ARGUMENTS <dbshell -->` option allows passing
  263. extra arguments to the command-line client for the database.
  264. * The :djadmin:`flush` and :djadmin:`sqlflush` commands now include SQL to
  265. reset sequences on SQLite.
  266. Models
  267. ~~~~~~
  268. * The new :class:`~django.db.models.functions.ExtractIsoWeekDay` function
  269. extracts ISO-8601 week days from :class:`~django.db.models.DateField` and
  270. :class:`~django.db.models.DateTimeField`, and the new :lookup:`iso_week_day`
  271. lookup allows querying by an ISO-8601 day of week.
  272. * :meth:`.QuerySet.explain` now supports:
  273. * ``TREE`` format on MySQL 8.0.16+,
  274. * ``analyze`` option on MySQL 8.0.18+ and MariaDB.
  275. * Added :class:`~django.db.models.PositiveBigIntegerField` which acts much like
  276. a :class:`~django.db.models.PositiveIntegerField` except that it only allows
  277. values under a certain (database-dependent) limit. Values from ``0`` to
  278. ``9223372036854775807`` are safe in all databases supported by Django.
  279. * The new :class:`~django.db.models.RESTRICT` option for
  280. :attr:`~django.db.models.ForeignKey.on_delete` argument of ``ForeignKey`` and
  281. ``OneToOneField`` emulates the behavior of the SQL constraint ``ON DELETE
  282. RESTRICT``.
  283. * :attr:`.CheckConstraint.check` now supports boolean expressions.
  284. * The :meth:`.RelatedManager.add`, :meth:`~.RelatedManager.create`, and
  285. :meth:`~.RelatedManager.set` methods now accept callables as values in the
  286. ``through_defaults`` argument.
  287. * The new ``is_dst`` parameter of the :meth:`.QuerySet.datetimes` determines
  288. the treatment of nonexistent and ambiguous datetimes.
  289. * The new :class:`~django.db.models.F` expression ``bitxor()`` method allows
  290. :ref:`bitwise XOR operation <using-f-expressions-in-filters>`.
  291. * :meth:`.QuerySet.bulk_create` now sets the primary key on objects when using
  292. MariaDB 10.5+.
  293. * The ``DatabaseOperations.sql_flush()`` method now generates more efficient
  294. SQL on MySQL by using ``DELETE`` instead of ``TRUNCATE`` statements for
  295. tables which don't require resetting sequences.
  296. * SQLite functions are now marked as :py:meth:`deterministic
  297. <sqlite3.Connection.create_function>` on Python 3.8+. This allows using them
  298. in check constraints and partial indexes.
  299. * The new :attr:`.UniqueConstraint.deferrable` attribute allows creating
  300. deferrable unique constraints.
  301. Pagination
  302. ~~~~~~~~~~
  303. * :class:`~django.core.paginator.Paginator` can now be iterated over to yield
  304. its pages.
  305. Requests and Responses
  306. ~~~~~~~~~~~~~~~~~~~~~~
  307. * If :setting:`ALLOWED_HOSTS` is empty and ``DEBUG=True``, subdomains of
  308. localhost are now allowed in the ``Host`` header, e.g. ``static.localhost``.
  309. * :meth:`.HttpResponse.set_cookie` and :meth:`.HttpResponse.set_signed_cookie`
  310. now allow using ``samesite='None'`` (string) to explicitly state that the
  311. cookie is sent with all same-site and cross-site requests.
  312. * The new :meth:`.HttpRequest.accepts` method returns whether the request
  313. accepts the given MIME type according to the ``Accept`` HTTP header.
  314. .. _whats-new-security-3.1:
  315. Security
  316. ~~~~~~~~
  317. * The :setting:`SECURE_REFERRER_POLICY` setting now defaults to
  318. ``'same-origin'``. With this configured,
  319. :class:`~django.middleware.security.SecurityMiddleware` sets the
  320. :ref:`referrer-policy` header to ``same-origin`` on all responses that do not
  321. already have it. This prevents the ``Referer`` header being sent to other
  322. origins. If you need the previous behavior, explicitly set
  323. :setting:`SECURE_REFERRER_POLICY` to ``None``.
  324. * The default algorithm of :class:`django.core.signing.Signer`,
  325. :meth:`django.core.signing.loads`, and :meth:`django.core.signing.dumps` is
  326. changed to the SHA-256. Support for signatures made with the old SHA-1
  327. algorithm remains until Django 4.0.
  328. Also, the new ``algorithm`` parameter of the
  329. :class:`~django.core.signing.Signer` allows customizing the hashing
  330. algorithm.
  331. Templates
  332. ~~~~~~~~~
  333. * The renamed :ttag:`translate` and :ttag:`blocktranslate` template tags are
  334. introduced for internationalization in template code. The older :ttag:`trans`
  335. and :ttag:`blocktrans` template tags aliases continue to work, and will be
  336. retained for the foreseeable future.
  337. * The :ttag:`include` template tag now accepts iterables of template names.
  338. Tests
  339. ~~~~~
  340. * :class:`~django.test.SimpleTestCase` now implements the ``debug()`` method to
  341. allow running a test without collecting the result and catching exceptions.
  342. This can be used to support running tests under a debugger.
  343. * The new :setting:`MIGRATE <TEST_MIGRATE>` test database setting allows
  344. disabling of migrations during a test database creation.
  345. * Django test runner now supports a :option:`test --buffer` option to discard
  346. output for passing tests.
  347. * :class:`~django.test.runner.DiscoverRunner` now skips running the system
  348. checks on databases not :ref:`referenced by tests<testing-multi-db>`.
  349. * :class:`~django.test.TransactionTestCase` teardown is now faster on MySQL
  350. due to :djadmin:`flush` command improvements. As a side effect the latter
  351. doesn't automatically reset sequences on teardown anymore. Enable
  352. :attr:`.TransactionTestCase.reset_sequences` if your tests require this
  353. feature.
  354. URLs
  355. ~~~~
  356. * :ref:`Path converters <registering-custom-path-converters>` can now raise
  357. ``ValueError`` in ``to_url()`` to indicate no match when reversing URLs.
  358. Utilities
  359. ~~~~~~~~~
  360. * :func:`~django.utils.encoding.filepath_to_uri` now supports
  361. :class:`pathlib.Path`.
  362. * :func:`~django.utils.dateparse.parse_duration` now supports comma separators
  363. for decimal fractions in the ISO 8601 format.
  364. * :func:`~django.utils.dateparse.parse_datetime`,
  365. :func:`~django.utils.dateparse.parse_duration`, and
  366. :func:`~django.utils.dateparse.parse_time` now support comma separators for
  367. milliseconds.
  368. Miscellaneous
  369. ~~~~~~~~~~~~~
  370. * The SQLite backend now supports :class:`pathlib.Path` for the ``NAME``
  371. setting.
  372. * The ``settings.py`` generated by the :djadmin:`startproject` command now uses
  373. :class:`pathlib.Path` instead of :mod:`os.path` for building filesystem
  374. paths.
  375. * The :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` setting is now allowed on
  376. databases that support time zones.
  377. .. _backwards-incompatible-3.1:
  378. Backwards incompatible changes in 3.1
  379. =====================================
  380. Database backend API
  381. --------------------
  382. This section describes changes that may be needed in third-party database
  383. backends.
  384. * ``DatabaseOperations.fetch_returned_insert_columns()`` now requires an
  385. additional ``returning_params`` argument.
  386. * ``connection.timezone`` property is now ``'UTC'`` by default, or the
  387. :setting:`TIME_ZONE <DATABASE-TIME_ZONE>` when :setting:`USE_TZ` is ``True``
  388. on databases that support time zones. Previously, it was ``None`` on
  389. databases that support time zones.
  390. * ``connection._nodb_connection`` property is changed to the
  391. ``connection._nodb_cursor()`` method and now returns a context manager that
  392. yields a cursor and automatically closes the cursor and connection upon
  393. exiting the ``with`` statement.
  394. * ``DatabaseClient.runshell()`` now requires an additional ``parameters``
  395. argument as a list of extra arguments to pass on to the command-line client.
  396. * The ``sequences`` positional argument of ``DatabaseOperations.sql_flush()``
  397. is replaced by the boolean keyword-only argument ``reset_sequences``. If
  398. ``True``, the sequences of the truncated tables will be reset.
  399. * The ``allow_cascade`` argument of ``DatabaseOperations.sql_flush()`` is now a
  400. keyword-only argument.
  401. * The ``using`` positional argument of
  402. ``DatabaseOperations.execute_sql_flush()`` is removed. The method now uses
  403. the database of the called instance.
  404. * Third-party database backends must implement support for ``JSONField`` or set
  405. ``DatabaseFeatures.supports_json_field`` to ``False``. If storing primitives
  406. is not supported, set ``DatabaseFeatures.supports_primitives_in_json_field``
  407. to ``False``. If there is a true datatype for JSON, set
  408. ``DatabaseFeatures.has_native_json_field`` to ``True``. If
  409. :lookup:`jsonfield.contains` and :lookup:`jsonfield.contained_by` are not
  410. supported, set ``DatabaseFeatures.supports_json_field_contains`` to
  411. ``False``.
  412. * Third party database backends must implement introspection for ``JSONField``
  413. or set ``can_introspect_json_field`` to ``False``.
  414. Dropped support for MariaDB 10.1
  415. --------------------------------
  416. Upstream support for MariaDB 10.1 ends in October 2020. Django 3.1 supports
  417. MariaDB 10.2 and higher.
  418. ``contrib.admin`` browser support
  419. ---------------------------------
  420. The admin no longer supports the legacy Internet Explorer browser. See
  421. :ref:`the admin FAQ <admin-browser-support>` for details on supported browsers.
  422. :attr:`AbstractUser.first_name <django.contrib.auth.models.User.first_name>` ``max_length`` increased to 150
  423. ------------------------------------------------------------------------------------------------------------
  424. A migration for :attr:`django.contrib.auth.models.User.first_name` is included.
  425. If you have a custom user model inheriting from ``AbstractUser``, you'll need
  426. to generate and apply a database migration for your user model.
  427. If you want to preserve the 30 character limit for first names, use a custom
  428. form::
  429. from django import forms
  430. from django.contrib.auth.forms import UserChangeForm
  431. class MyUserChangeForm(UserChangeForm):
  432. first_name = forms.CharField(max_length=30, required=False)
  433. If you wish to keep this restriction in the admin when editing users, set
  434. ``UserAdmin.form`` to use this form::
  435. from django.contrib.auth.admin import UserAdmin
  436. from django.contrib.auth.models import User
  437. class MyUserAdmin(UserAdmin):
  438. form = MyUserChangeForm
  439. admin.site.unregister(User)
  440. admin.site.register(User, MyUserAdmin)
  441. Miscellaneous
  442. -------------
  443. * The cache keys used by :ttag:`cache` and generated by
  444. :func:`~django.core.cache.utils.make_template_fragment_key` are different
  445. from the keys generated by older versions of Django. After upgrading to
  446. Django 3.1, the first request to any previously cached template fragment will
  447. be a cache miss.
  448. * The logic behind the decision to return a redirection fallback or a 204 HTTP
  449. response from the :func:`~django.views.i18n.set_language` view is now based
  450. on the ``Accept`` HTTP header instead of the ``X-Requested-With`` HTTP header
  451. presence.
  452. * The compatibility imports of ``django.core.exceptions.EmptyResultSet`` in
  453. ``django.db.models.query``, ``django.db.models.sql``, and
  454. ``django.db.models.sql.datastructures`` are removed.
  455. * The compatibility import of ``django.core.exceptions.FieldDoesNotExist`` in
  456. ``django.db.models.fields`` is removed.
  457. * The compatibility imports of ``django.forms.utils.pretty_name()`` and
  458. ``django.forms.boundfield.BoundField`` in ``django.forms.forms`` are removed.
  459. * The compatibility imports of ``Context``, ``ContextPopException``, and
  460. ``RequestContext`` in ``django.template.base`` are removed.
  461. * The compatibility import of
  462. ``django.contrib.admin.helpers.ACTION_CHECKBOX_NAME`` in
  463. ``django.contrib.admin`` is removed.
  464. * The :setting:`STATIC_URL` and :setting:`MEDIA_URL` settings set to relative
  465. paths are now prefixed by the server-provided value of ``SCRIPT_NAME`` (or
  466. ``/`` if not set). This change should not affect settings set to valid URLs
  467. or absolute paths.
  468. * :class:`~django.middleware.http.ConditionalGetMiddleware` no longer adds the
  469. ``ETag`` header to responses with an empty
  470. :attr:`~django.http.HttpResponse.content`.
  471. * ``django.utils.decorators.classproperty()`` decorator is made public and
  472. moved to :class:`django.utils.functional.classproperty()`.
  473. * :tfilter:`floatformat` template filter now outputs (positive) ``0`` for
  474. negative numbers which round to zero.
  475. * :attr:`Meta.ordering <django.db.models.Options.ordering>` and
  476. :attr:`Meta.unique_together <django.db.models.Options.unique_together>`
  477. options on models in ``django.contrib`` modules that were formerly tuples are
  478. now lists.
  479. * The admin calendar widget now handles two-digit years according to the Open
  480. Group Specification, i.e. values between 69 and 99 are mapped to the previous
  481. century, and values between 0 and 68 are mapped to the current century.
  482. * Date-only formats are removed from the default list for
  483. :setting:`DATETIME_INPUT_FORMATS`.
  484. * The :class:`~django.forms.FileInput` widget no longer renders with the
  485. ``required`` HTML attribute when initial data exists.
  486. * The undocumented ``django.views.debug.ExceptionReporterFilter`` class is
  487. removed. As per the :ref:`custom-error-reports` documentation, classes to be
  488. used with :setting:`DEFAULT_EXCEPTION_REPORTER_FILTER` need to inherit from
  489. :class:`django.views.debug.SafeExceptionReporterFilter`.
  490. * The cache timeout set by :func:`~django.views.decorators.cache.cache_page`
  491. decorator now takes precedence over the ``max-age`` directive from the
  492. ``Cache-Control`` header.
  493. * Providing a non-local remote field in the :attr:`.ForeignKey.to_field`
  494. argument now raises :class:`~django.core.exceptions.FieldError`.
  495. * :setting:`SECURE_REFERRER_POLICY` now defaults to ``'same-origin'``. See the
  496. *What's New* :ref:`Security section <whats-new-security-3.1>` above for more
  497. details.
  498. * :djadmin:`check` management command now runs the ``database`` system checks
  499. only for database aliases specified using :option:`check --database` option.
  500. * :djadmin:`migrate` management command now runs the ``database`` system checks
  501. only for a database to migrate.
  502. * The admin CSS classes ``row1`` and ``row2`` are removed in favor of
  503. ``:nth-child(odd)`` and ``:nth-child(even)`` pseudo-classes.
  504. * The :func:`~django.contrib.auth.hashers.make_password` function now requires
  505. its argument to be a string or bytes. Other types should be explicitly cast
  506. to one of these.
  507. * The undocumented ``version`` parameter to the
  508. :class:`~django.contrib.gis.db.models.functions.AsKML` function is removed.
  509. * :ref:`JSON and YAML serializers <serialization-formats>`, used by
  510. :djadmin:`dumpdata`, now dump all data with Unicode by default. If you need
  511. the previous behavior, pass ``ensure_ascii=True`` to JSON serializer, or
  512. ``allow_unicode=False`` to YAML serializer.
  513. * The auto-reloader no longer monitors changes in built-in Django translation
  514. files.
  515. * The minimum supported version of ``mysqlclient`` is increased from 1.3.13 to
  516. 1.4.0.
  517. * The undocumented ``django.contrib.postgres.forms.InvalidJSONInput`` and
  518. ``django.contrib.postgres.forms.JSONString`` are moved to
  519. ``django.forms.fields``.
  520. * The undocumented ``django.contrib.postgres.fields.jsonb.JsonAdapter`` class
  521. is removed.
  522. * The :ttag:`{% localize off %} <localize>` tag and :tfilter:`unlocalize`
  523. filter no longer respect :setting:`DECIMAL_SEPARATOR` setting.
  524. * The minimum supported version of ``asgiref`` is increased from 3.2 to
  525. 3.2.10.
  526. * The :doc:`Media </topics/forms/media>` class now renders ``<script>`` tags
  527. without the ``type`` attribute to follow `WHATWG recommendations
  528. <https://html.spec.whatwg.org/multipage/scripting.html#the-script-element>`_.
  529. * :class:`~django.forms.ModelChoiceIterator`, used by
  530. :class:`~django.forms.ModelChoiceField` and
  531. :class:`~django.forms.ModelMultipleChoiceField`, now yields 2-tuple choices
  532. containing :class:`~django.forms.ModelChoiceIteratorValue` instances as the
  533. first ``value`` element in each choice. In most cases this proxies
  534. transparently, but if you need the ``field`` value itself, use the
  535. :attr:`.ModelChoiceIteratorValue.value` attribute instead.
  536. .. _deprecated-features-3.1:
  537. Features deprecated in 3.1
  538. ==========================
  539. .. _deprecated-jsonfield:
  540. PostgreSQL ``JSONField``
  541. ------------------------
  542. ``django.contrib.postgres.fields.JSONField`` and
  543. ``django.contrib.postgres.forms.JSONField`` are deprecated in favor of
  544. :class:`.models.JSONField` and
  545. :class:`forms.JSONField <django.forms.JSONField>`.
  546. The undocumented ``django.contrib.postgres.fields.jsonb.KeyTransform`` and
  547. ``django.contrib.postgres.fields.jsonb.KeyTextTransform`` are also deprecated
  548. in favor of the transforms in ``django.db.models.fields.json``.
  549. The new ``JSONField``\s, ``KeyTransform``, and ``KeyTextTransform`` can be used
  550. on all supported database backends.
  551. Miscellaneous
  552. -------------
  553. * ``PASSWORD_RESET_TIMEOUT_DAYS`` setting is deprecated in favor of
  554. :setting:`PASSWORD_RESET_TIMEOUT`.
  555. * The undocumented usage of the :lookup:`isnull` lookup with non-boolean values
  556. as the right-hand side is deprecated, use ``True`` or ``False`` instead.
  557. * The barely documented ``django.db.models.query_utils.InvalidQuery`` exception
  558. class is deprecated in favor of
  559. :class:`~django.core.exceptions.FieldDoesNotExist` and
  560. :class:`~django.core.exceptions.FieldError`.
  561. * The ``django-admin.py`` entry point is deprecated in favor of
  562. ``django-admin``.
  563. * The ``HttpRequest.is_ajax()`` method is deprecated as it relied on a
  564. jQuery-specific way of signifying AJAX calls, while current usage tends to
  565. use the JavaScript `Fetch API
  566. <https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API>`_. Depending on
  567. your use case, you can either write your own AJAX detection method, or use
  568. the new :meth:`.HttpRequest.accepts` method if your code depends on the
  569. client ``Accept`` HTTP header.
  570. If you are writing your own AJAX detection method, ``request.is_ajax()`` can
  571. be reproduced exactly as
  572. ``request.headers.get('x-requested-with') == 'XMLHttpRequest'``.
  573. * Passing ``None`` as the first argument to
  574. ``django.utils.deprecation.MiddlewareMixin.__init__()`` is deprecated.
  575. * The encoding format of cookies values used by
  576. :class:`~django.contrib.messages.storage.cookie.CookieStorage` is different
  577. from the format generated by older versions of Django. Support for the old
  578. format remains until Django 4.0.
  579. * The encoding format of sessions is different from the format generated by
  580. older versions of Django. Support for the old format remains until Django
  581. 4.0.
  582. * The purely documentational ``providing_args`` argument for
  583. :class:`~django.dispatch.Signal` is deprecated. If you rely on this
  584. argument as documentation, you can move the text to a code comment or
  585. docstring.
  586. * Calling ``django.utils.crypto.get_random_string()`` without a ``length``
  587. argument is deprecated.
  588. * The ``list`` message for :class:`~django.forms.ModelMultipleChoiceField` is
  589. deprecated in favor of ``invalid_list``.
  590. * Passing raw column aliases to :meth:`.QuerySet.order_by` is deprecated. The
  591. same result can be achieved by passing aliases in a
  592. :class:`~django.db.models.expressions.RawSQL` instead beforehand.
  593. * The ``NullBooleanField`` model field is deprecated in favor of
  594. ``BooleanField(null=True, blank=True)``.
  595. * ``django.conf.urls.url()`` alias of :func:`django.urls.re_path` is
  596. deprecated.
  597. * The ``{% ifequal %}`` and ``{% ifnotequal %}`` template tags are deprecated
  598. in favor of :ttag:`{% if %}<if>`. ``{% if %}`` covers all use cases, but if
  599. you need to continue using these tags, they can be extracted from Django to a
  600. module and included as a built-in tag in the :class:`'builtins'
  601. <django.template.backends.django.DjangoTemplates>` option in
  602. :setting:`OPTIONS <TEMPLATES-OPTIONS>`.
  603. * ``DEFAULT_HASHING_ALGORITHM`` transitional setting is deprecated.
  604. .. _removed-features-3.1:
  605. Features removed in 3.1
  606. =======================
  607. These features have reached the end of their deprecation cycle and are removed
  608. in Django 3.1.
  609. See :ref:`deprecated-features-2.2` for details on these changes, including how
  610. to remove usage of these features.
  611. * ``django.utils.timezone.FixedOffset`` is removed.
  612. * ``django.core.paginator.QuerySetPaginator`` is removed.
  613. * A model's ``Meta.ordering`` doesn't affect ``GROUP BY`` queries.
  614. * ``django.contrib.postgres.fields.FloatRangeField`` and
  615. ``django.contrib.postgres.forms.FloatRangeField`` are removed.
  616. * The ``FILE_CHARSET`` setting is removed.
  617. * ``django.contrib.staticfiles.storage.CachedStaticFilesStorage`` is removed.
  618. * The ``RemoteUserBackend.configure_user()`` method requires ``request`` as the
  619. first positional argument.
  620. * Support for ``SimpleTestCase.allow_database_queries`` and
  621. ``TransactionTestCase.multi_db`` is removed.