Debian Codegraph @

docs/releases/5.1.txt

raw
1 ========================
2 Django 5.1 release notes
3 ========================
4
5 *August 7, 2024*
6
7 Welcome to Django 5.1!
8
9 These release notes cover the :ref:`new features <whats-new-5.1>`, as well as
10 some :ref:`backwards incompatible changes <backwards-incompatible-5.1>` you
11 should be aware of when upgrading from Django 5.0 or earlier. We've
12 :ref:`begun the deprecation process for some features
13 <deprecated-features-5.1>`.
14
15 See the :doc:`/howto/upgrade-version` guide if you're updating an existing
16 project.
17
18 Python compatibility
19 ====================
20
21 Django 5.1 supports Python 3.10, 3.11, 3.12, and 3.13 (as of 5.1.3). We
22 **highly recommend** and only officially support the latest release of each
23 series.
24
25 .. _whats-new-5.1:
26
27 What's new in Django 5.1
28 ========================
29
30 ``{% querystring %}`` template tag
31 -----------------------------------
32
33 Django 5.1 introduces the :ttag:`{% querystring %} <querystring>` template
34 tag, simplifying the modification of query parameters in URLs, making it easier
35 to generate links that maintain existing query parameters while adding or
36 changing specific ones.
37
38 For instance, navigating pagination and query strings in templates can be
39 cumbersome. Consider this template fragment that dynamically generates a URL
40 for navigating to the next page within a paginated view:
41
42 .. code-block:: html+django
43
44 {# Linebreaks added for readability, this should be one, long line. #}
45 <a href="?{% for key, values in request.GET.iterlists %}
46 {% if key != "page" %}
47 {% for value in values %}
48 {{ key }}={{ value }}&amp;
49 {% endfor %}
50 {% endif %}
51 {% endfor %}page={{ page.next_page_number }}">Next page</a>
52
53 When switching to using this new template tag, the above magically becomes:
54
55 .. code-block:: html+django
56
57 <a href="{% querystring page=page.next_page_number %}">Next page</a>
58
59 PostgreSQL Connection Pools
60 ---------------------------
61
62 Django 5.1 also introduces :ref:`connection pool <postgresql-pool>` support for
63 PostgreSQL. As the time to establish a new connection can be relatively long,
64 keeping connections open can reduce latency.
65
66 To use a connection pool with `psycopg`_, you can set the ``"pool"`` option
67 inside :setting:`OPTIONS` to be a dict to be passed to
68 :class:`~psycopg:psycopg_pool.ConnectionPool`, or to ``True`` to use the
69 ``ConnectionPool`` defaults::
70
71 DATABASES = {
72 "default": {
73 "ENGINE": "django.db.backends.postgresql",
74 # ...
75 "OPTIONS": {
76 "pool": {
77 "min_size": 2,
78 "max_size": 4,
79 "timeout": 10,
80 }
81 },
82 },
83 }
84
85 .. _psycopg: https://www.psycopg.org/
86
87 Middleware to require authentication by default
88 -----------------------------------------------
89
90 The new :class:`~django.contrib.auth.middleware.LoginRequiredMiddleware`
91 redirects all unauthenticated requests to a login page. Views can allow
92 unauthenticated requests by using the new
93 :func:`~django.contrib.auth.decorators.login_not_required` decorator.
94
95 ``LoginRequiredMiddleware`` respects the ``login_url`` and
96 ``redirect_field_name`` values set via the
97 :func:`~.django.contrib.auth.decorators.login_required` decorator, but does not
98 support setting ``login_url`` or ``redirect_field_name`` via the
99 :class:`~django.contrib.auth.mixins.LoginRequiredMixin`.
100
101 To enable this, add ``"django.contrib.auth.middleware.LoginRequiredMiddleware"``
102 to your :setting:`MIDDLEWARE` setting.
103
104 Minor features
105 --------------
106
107 :mod:`django.contrib.admin`
108 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
109
110 * :attr:`.ModelAdmin.list_display` now supports using ``__`` lookups to list
111 fields from related models.
112
113 :mod:`django.contrib.auth`
114 ~~~~~~~~~~~~~~~~~~~~~~~~~~
115
116 * The default iteration count for the PBKDF2 password hasher is increased from
117 720,000 to 870,000.
118
119 * The default ``parallelism`` of the ``ScryptPasswordHasher`` is increased from
120 1 to 5, to follow OWASP recommendations.
121
122 * The new :class:`~django.contrib.auth.forms.AdminUserCreationForm` and
123 the existing :class:`~django.contrib.auth.forms.AdminPasswordChangeForm` now
124 support disabling password-based authentication by setting an unusable
125 password on form save. This is now available in the admin when visiting the
126 user creation and password change pages.
127
128 * :func:`~.django.contrib.auth.decorators.login_required`,
129 :func:`~.django.contrib.auth.decorators.permission_required`, and
130 :func:`~.django.contrib.auth.decorators.user_passes_test` decorators now
131 support wrapping asynchronous view functions.
132
133 * ``ReadOnlyPasswordHashWidget`` now includes a button to reset the user's
134 password, which replaces the link previously embedded in the
135 ``ReadOnlyPasswordHashField``'s help text, improving the overall
136 accessibility of the
137 :class:`~django.contrib.auth.forms.UserChangeForm`.
138
139 :mod:`django.contrib.gis`
140 ~~~~~~~~~~~~~~~~~~~~~~~~~
141
142 * :class:`~django.contrib.gis.db.models.functions.BoundingCircle` is now
143 supported on SpatiaLite 5.1+.
144
145 * :class:`~django.contrib.gis.db.models.Collect` is now supported on MySQL
146 8.0.24+.
147
148 * :class:`~django.contrib.gis.geoip2.GeoIP2` now allows querying using
149 :class:`ipaddress.IPv4Address` or :class:`ipaddress.IPv6Address` objects.
150
151 * :meth:`.GeoIP2.country` now exposes the ``continent_code``,
152 ``continent_name``, and ``is_in_european_union`` values.
153
154 * :meth:`.GeoIP2.city` now exposes the ``accuracy_radius`` and ``region_name``
155 values. In addition, the ``dma_code`` and ``region`` values are now exposed
156 as ``metro_code`` and ``region_code``, but the previous keys are also
157 retained for backward compatibility.
158
159 * :class:`~django.contrib.gis.measure.Area` now supports the ``ha`` unit.
160
161 * The new :attr:`.OGRGeometry.is_3d` attribute allows checking if a geometry
162 has a ``Z`` coordinate dimension.
163
164 * The new :meth:`.OGRGeometry.set_3d` method allows addition and removal of the
165 ``Z`` coordinate dimension.
166
167 * :class:`~django.contrib.gis.gdal.OGRGeometry`,
168 :class:`~django.contrib.gis.gdal.Point`,
169 :class:`~django.contrib.gis.gdal.LineString`,
170 :class:`~django.contrib.gis.gdal.Polygon`, and
171 :class:`~django.contrib.gis.gdal.GeometryCollection` and its subclasses now
172 support measured geometries via the new :attr:`.OGRGeometry.is_measured` and
173 ``m`` properties, and the :meth:`.OGRGeometry.set_measured` method.
174
175 * :attr:`.OGRGeometry.centroid` is now available on all supported geometry
176 types.
177
178 * :class:`FromWKB() <django.contrib.gis.db.models.functions.FromWKB>` and
179 :class:`FromWKT() <django.contrib.gis.db.models.functions.FromWKT>` functions
180 now support the optional ``srid`` argument (except for Oracle where it is
181 ignored).
182
183 :mod:`django.contrib.postgres`
184 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
185
186 * :class:`~django.contrib.postgres.indexes.BTreeIndex` now supports the
187 ``deduplicate_items`` parameter.
188
189 :mod:`django.contrib.sessions`
190 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
191
192 * :class:`django.contrib.sessions.backends.cached_db.SessionStore` now handles
193 exceptions when storing session information in the cache, logging proper
194 error messages with their traceback via the newly added
195 :ref:`sessions logger <django-contrib-sessions-logger>`.
196
197 * :class:`django.contrib.sessions.backends.base.SessionBase` and all built-in
198 session engines now provide async API. The new asynchronous methods all have
199 ``a`` prefixed names, e.g. ``aget()``, ``akeys()``, or ``acycle_key()``.
200
201 Database backends
202 ~~~~~~~~~~~~~~~~~
203
204 * ``"init_command"`` option is now supported in :setting:`OPTIONS` on SQLite
205 to allow specifying :ref:`pragma options <sqlite-init-command>` to set upon
206 connection.
207
208 * ``"transaction_mode"`` option is now supported in :setting:`OPTIONS` on
209 SQLite to allow specifying the :ref:`sqlite-transaction-behavior`.
210
211 * ``"pool"`` option is now supported in :setting:`OPTIONS` on PostgreSQL to
212 allow using :ref:`connection pools <postgresql-pool>`.
213
214 Error Reporting
215 ~~~~~~~~~~~~~~~
216
217 * In order to improve accessibility, the technical 404 and 500 error pages now
218 use HTML landmark elements for the header, footer, and main content areas.
219
220 File Storage
221 ~~~~~~~~~~~~
222
223 * The :attr:`~django.core.files.storage.FileSystemStorage.allow_overwrite`
224 parameter of :class:`~django.core.files.storage.FileSystemStorage` now allows
225 saving new files over existing ones.
226
227 Forms
228 ~~~~~
229
230 * In order to improve accessibility and enable screen readers to associate
231 fieldsets with their help text, the form fieldset now includes the
232 ``aria-describedby`` HTML attribute.
233
234 Management Commands
235 ~~~~~~~~~~~~~~~~~~~
236
237 * The :djadmin:`makemigrations` command now displays meaningful symbols for
238 each operation to highlight :class:`operation categories
239 <django.db.migrations.operations.base.OperationCategory>`.
240
241 Migrations
242 ~~~~~~~~~~
243
244 * The new ``Operation.category`` attribute allows specifying an
245 :class:`operation category
246 <django.db.migrations.operations.base.OperationCategory>` used by the
247 :djadmin:`makemigrations` to display a meaningful symbol for the operation.
248
249 Models
250 ~~~~~~
251
252 * :meth:`.QuerySet.explain` now supports the ``generic_plan`` option on
253 PostgreSQL 16+.
254
255 * :class:`~django.db.models.expressions.RowRange` now accepts positive integers
256 for the ``start`` argument and negative integers for the ``end`` argument.
257
258 * The new ``exclusion`` argument of
259 :class:`~django.db.models.expressions.RowRange` and
260 :class:`~django.db.models.expressions.ValueRange` allows excluding rows,
261 groups, and ties from the window frames.
262
263 * :meth:`.QuerySet.order_by` now supports ordering by annotation transforms
264 such as ``JSONObject`` keys and ``ArrayAgg`` indices.
265
266 * :class:`F() <django.db.models.F>` and :class:`OuterRef()
267 <django.db.models.OuterRef>` expressions that output
268 :class:`~django.db.models.CharField`, :class:`~django.db.models.EmailField`,
269 :class:`~django.db.models.SlugField`, :class:`~django.db.models.URLField`,
270 :class:`~django.db.models.TextField`, or
271 :class:`~django.contrib.postgres.fields.ArrayField` can now be :ref:`sliced
272 <slicing-using-f>`.
273
274 * The new ``from_queryset`` argument of :meth:`.Model.refresh_from_db` and
275 :meth:`.Model.arefresh_from_db` allows customizing the queryset used to
276 reload a model's value. This can be used to lock the row before reloading or
277 to select related objects.
278
279 * The new :attr:`.Expression.constraint_validation_compatible` attribute allows
280 specifying that the expression should be ignored during a constraint
281 validation.
282
283 Templates
284 ~~~~~~~~~
285
286 * Custom tags may now set extra data on the ``Parser`` object that will later
287 be made available on the ``Template`` instance. Such data may be used, for
288 example, by the template loader, or other template clients.
289
290 * :ref:`Template engines <field-checking>` now implement a ``check()`` method
291 that is already registered with the check framework.
292
293 Tests
294 ~~~~~
295
296 * :meth:`~django.test.SimpleTestCase.assertContains`,
297 :meth:`~django.test.SimpleTestCase.assertNotContains`, and
298 :meth:`~django.test.SimpleTestCase.assertInHTML` assertions now add haystacks
299 to assertion error messages.
300
301 * The :class:`~django.test.RequestFactory`,
302 :class:`~django.test.AsyncRequestFactory`, :class:`~django.test.Client`, and
303 :class:`~django.test.AsyncClient` classes now support the ``query_params``
304 parameter, which accepts a dictionary of query string keys and values. This
305 allows setting query strings on any HTTP methods more easily.
306
307 .. code-block:: python
308
309 self.client.post("/items/1", query_params={"action": "delete"})
310 await self.async_client.post("/items/1", query_params={"action": "delete"})
311
312 * The new :meth:`.SimpleTestCase.assertNotInHTML` assertion allows testing that
313 an HTML fragment is not contained in the given HTML haystack.
314
315 * In order to enforce test isolation, database connections inside threads are
316 no longer allowed in :class:`~django.test.SimpleTestCase`.
317
318 Validators
319 ~~~~~~~~~~
320
321 * The new :class:`~django.core.validators.DomainNameValidator` validates domain
322 names, including internationalized domain names. The new
323 :func:`~django.core.validators.validate_domain_name` function returns an
324 instance of :class:`~django.core.validators.DomainNameValidator`.
325
326 .. _backwards-incompatible-5.1:
327
328 Backwards incompatible changes in 5.1
329 =====================================
330
331 :mod:`django.contrib.gis`
332 -------------------------
333
334 * Support for PostGIS 2.5 is removed.
335
336 * Support for PROJ < 6 is removed.
337
338 * Support for GDAL 2.4 is removed.
339
340 * :class:`~django.contrib.gis.geoip2.GeoIP2` no longer opens both city and
341 country databases when a directory path is provided, preferring the city
342 database, if it is available. The country database is a subset of the city
343 database and both are not typically needed. If you require use of the country
344 database when in the same directory as the city database, explicitly pass the
345 country database path to the constructor.
346
347 Dropped support for MariaDB 10.4
348 --------------------------------
349
350 Upstream support for MariaDB 10.4 ends in June 2024. Django 5.1 supports
351 MariaDB 10.5 and higher.
352
353 Dropped support for PostgreSQL 12
354 ---------------------------------
355
356 Upstream support for PostgreSQL 12 ends in November 2024. Django 5.1 supports
357 PostgreSQL 13 and higher.
358
359 Miscellaneous
360 -------------
361
362 * In order to improve accessibility, the admin's changelist filter is now
363 rendered in a ``<nav>`` tag instead of a ``<div>``.
364
365 * In order to improve accessibility, the admin's footer is now rendered in
366 a ``<footer>`` tag instead of a ``<div>``, and also moved below the
367 ``<div id="main">`` element.
368
369 * In order to improve accessibility, the expandable widget used for
370 :attr:`ModelAdmin.fieldsets <django.contrib.admin.ModelAdmin.fieldsets>` and
371 :attr:`InlineModelAdmin.fieldsets <django.contrib.admin.InlineModelAdmin>`,
372 when the fieldset has a name and use the ``collapse`` class, now includes
373 ``<details>`` and ``<summary>`` elements.
374
375 * The JavaScript file ``collapse.js`` is removed since it is no longer needed
376 in the Django admin site.
377
378 * :meth:`.SimpleTestCase.assertURLEqual` and
379 :meth:`~django.test.SimpleTestCase.assertInHTML` now add ``": "`` to the
380 ``msg_prefix``. This is consistent with the behavior of other assertions.
381
382 * ``django.utils.text.Truncator`` used by :tfilter:`truncatechars_html` and
383 :tfilter:`truncatewords_html` template filters now uses
384 :py:class:`html.parser.HTMLParser` subclasses. This results in a more robust
385 and faster operation, but there may be small differences in the output.
386
387 * The undocumented ``django.urls.converters.get_converter()`` function is
388 removed.
389
390 * The minimum supported version of SQLite is increased from 3.27.0 to 3.31.0.
391
392 * :class:`~django.db.models.FileField` now raises a
393 :class:`~django.core.exceptions.FieldError` when saving a file without a
394 ``name``.
395
396 * ``ImageField.update_dimension_fields(force=True)`` is no longer called after
397 saving the image to storage. If your storage backend resizes images, the
398 ``width_field`` and ``height_field`` will not match the width and height of
399 the image.
400
401 * The minimum supported version of ``asgiref`` is increased from 3.7.0 to
402 3.8.1.
403
404 * To improve performance, the ``delete_selected`` admin action now uses
405 ``QuerySet.bulk_create()`` when creating multiple ``LogEntry`` objects. As a
406 result, ``pre_save`` and ``post_save`` signals for ``LogEntry`` are not sent
407 when multiple objects are deleted via this admin action.
408
409 .. _deprecated-features-5.1:
410
411 Features deprecated in 5.1
412 ==========================
413
414 Miscellaneous
415 -------------
416
417 * The ``ModelAdmin.log_deletion()`` and ``LogEntryManager.log_action()``
418 methods are deprecated. Subclasses should implement
419 ``ModelAdmin.log_deletions()`` and ``LogEntryManager.log_actions()``
420 instead.
421
422 * The undocumented ``django.utils.itercompat.is_iterable()`` function and the
423 ``django.utils.itercompat`` module are deprecated. Use
424 ``isinstance(..., collections.abc.Iterable)`` instead.
425
426 * The ``django.contrib.gis.geoip2.GeoIP2.coords()`` method is deprecated. Use
427 ``django.contrib.gis.geoip2.GeoIP2.lon_lat()`` instead.
428
429 * The ``django.contrib.gis.geoip2.GeoIP2.open()`` method is deprecated. Use the
430 :class:`~django.contrib.gis.geoip2.GeoIP2` constructor instead.
431
432 * Passing positional arguments to :meth:`.Model.save` and :meth:`.Model.asave`
433 is deprecated in favor of keyword-only arguments.
434
435 * Setting ``django.contrib.gis.gdal.OGRGeometry.coord_dim`` is deprecated. Use
436 :meth:`~django.contrib.gis.gdal.OGRGeometry.set_3d` instead.
437
438 * Overriding existing converters with ``django.urls.register_converter()`` is
439 deprecated.
440
441 * The ``check`` keyword argument of ``CheckConstraint`` is deprecated in favor
442 of ``condition``.
443
444 * The undocumented ``OS_OPEN_FLAGS`` property of
445 :class:`~django.core.files.storage.FileSystemStorage` is deprecated. To allow
446 overwriting files in storage, set the new
447 :attr:`~django.core.files.storage.FileSystemStorage.allow_overwrite` option
448 to ``True`` instead.
449
450 * The ``get_cache_name()`` method of ``FieldCacheMixin`` is deprecated in favor
451 of the ``cache_name`` cached property.
452
453 Features removed in 5.1
454 =======================
455
456 These features have reached the end of their deprecation cycle and are removed
457 in Django 5.1.
458
459 See :ref:`deprecated-features-4.2` for details on these changes, including how
460 to remove usage of these features.
461
462 * The ``BaseUserManager.make_random_password()`` method is removed.
463
464 * The model's ``Meta.index_together`` option is removed.
465
466 * The ``length_is`` template filter is removed.
467
468 * The ``django.contrib.auth.hashers.SHA1PasswordHasher``,
469 ``django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher``, and
470 ``django.contrib.auth.hashers.UnsaltedMD5PasswordHasher`` are removed.
471
472 * The model ``django.contrib.postgres.fields.CICharField``,
473 ``django.contrib.postgres.fields.CIEmailField``, and
474 ``django.contrib.postgres.fields.CITextField`` are removed, except for
475 support in historical migrations.
476
477 * The ``django.contrib.postgres.fields.CIText`` mixin is removed.
478
479 * The ``map_width`` and ``map_height`` attributes of ``BaseGeometryWidget`` are
480 removed.
481
482 * The ``SimpleTestCase.assertFormsetError()`` method is removed.
483
484 * The ``TransactionTestCase.assertQuerysetEqual()`` method is removed.
485
486 * Support for passing encoded JSON string literals to ``JSONField`` and
487 associated lookups and expressions is removed.
488
489 * Support for passing positional arguments to ``Signer`` and
490 ``TimestampSigner`` is removed.
491
492 * The ``DEFAULT_FILE_STORAGE`` and ``STATICFILES_STORAGE`` settings is removed.
493
494 * The ``django.core.files.storage.get_storage_class()`` function is removed.