Debian Codegraph @

docs/releases/5.2.txt

raw
1 ========================
2 Django 5.2 release notes
3 ========================
4
5 *April 2, 2025*
6
7 Welcome to Django 5.2!
8
9 These release notes cover the :ref:`new features <whats-new-5.2>`, as well as
10 some :ref:`backwards incompatible changes <backwards-incompatible-5.2>` you
11 should be aware of when upgrading from Django 5.1 or earlier. We've
12 :ref:`begun the deprecation process for some features
13 <deprecated-features-5.2>`.
14
15 See the :doc:`/howto/upgrade-version` guide if you're updating an existing
16 project.
17
18 Django 5.2 is designated as a :term:`long-term support release
19 <Long-term support release>`. It will receive security updates for at least
20 three years after its release. Support for the previous LTS, Django 4.2, will
21 end in April 2026.
22
23 Python compatibility
24 ====================
25
26 Django 5.2 supports Python 3.10, 3.11, 3.12, 3.13, and 3.14 (as of 5.2.8). We
27 **highly recommend** and only officially support the latest release of each
28 series.
29
30 .. _whats-new-5.2:
31
32 What's new in Django 5.2
33 ========================
34
35 Automatic models import in the ``shell``
36 ----------------------------------------
37
38 The :djadmin:`shell` management command now automatically imports models from
39 all installed apps. You can view further details of the imported objects by
40 setting the ``--verbosity`` flag to 2 or more:
41
42 .. console::
43
44 $ python -Wall manage.py shell --verbosity=2
45 6 objects imported automatically, including:
46
47 from django.contrib.admin.models import LogEntry
48 from django.contrib.auth.models import Group, Permission, User
49 from django.contrib.contenttypes.models import ContentType
50 from django.contrib.sessions.models import Session
51
52 This :ref:`behavior can be customized <customizing-shell-auto-imports>` to add
53 or remove automatic imports.
54
55 Composite Primary Keys
56 ----------------------
57
58 The new :class:`django.db.models.CompositePrimaryKey` allows tables to be
59 created with a primary key consisting of multiple fields.
60
61 To use a composite primary key, when defining a model set the ``pk`` attribute
62 to be a ``CompositePrimaryKey``::
63
64 from django.db import models
65
66
67 class Release(models.Model):
68 pk = models.CompositePrimaryKey("version", "name")
69 version = models.IntegerField()
70 name = models.CharField(max_length=20)
71
72 See :doc:`/topics/composite-primary-key` for more details.
73
74 Simplified override of :class:`~django.forms.BoundField`
75 --------------------------------------------------------
76
77 Prior to version 5.2, overriding :meth:`.Field.get_bound_field()` was the only
78 option to use a custom :class:`~django.forms.BoundField`. Django now supports
79 specifying the following attributes to customize form rendering:
80
81 * :attr:`.BaseRenderer.bound_field_class` at the project level,
82 * :attr:`.Form.bound_field_class` at the form level, and
83 * :attr:`.Field.bound_field_class` at the field level.
84
85 For example, to customize the ``BoundField`` of a ``Form`` class::
86
87 from django import forms
88
89
90 class CustomBoundField(forms.BoundField):
91
92 custom_class = "custom"
93
94 def css_classes(self, extra_classes=None):
95 result = super().css_classes(extra_classes)
96 if self.custom_class not in result:
97 result += f" {self.custom_class}"
98 return result.strip()
99
100
101 class CustomForm(forms.Form):
102 bound_field_class = CustomBoundField
103
104 name = forms.CharField(
105 label="Your Name",
106 max_length=100,
107 required=False,
108 widget=forms.TextInput(attrs={"class": "name-input-class"}),
109 )
110 email = forms.EmailField(label="Your Email")
111
112
113 When rendering a ``CustomForm`` instance, the following HTML is included:
114
115 .. code:: html
116
117 <div class="custom">
118 <label for="id_name">Your Name:</label>
119 <input type="text" name="name" class="name-input-class" maxlength="100" id="id_name">
120 </div>
121
122 <div class="custom">
123 <label for="id_email">Your Email:</label>
124 <input type="email" name="email" maxlength="320" required="" id="id_email">
125 </div>
126
127
128 See :ref:`custom-boundfield` for more details about this feature.
129
130 Minor features
131 --------------
132
133 :mod:`django.contrib.admin`
134 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
135
136 * The ``admin/base.html`` template now has a new block
137 :ref:`extrabody <extrabody>` for adding custom code before the closing
138 ``</body>`` tag.
139
140 * The value of a :class:`~django.db.models.URLField` now renders as a link.
141
142 :mod:`django.contrib.admindocs`
143 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
144
145 * Links to components in docstrings now supports custom link text, using the
146 format ``:role:`link text <link>```. See :ref:`documentation helpers
147 <admindocs-helpers>` for more details.
148
149 * The :ref:`model pages <admindocs-model-reference>` are now restricted to
150 users with the corresponding view or change permissions.
151
152 :mod:`django.contrib.auth`
153 ~~~~~~~~~~~~~~~~~~~~~~~~~~
154
155 * The default iteration count for the PBKDF2 password hasher is increased from
156 870,000 to 1,000,000.
157
158 * The following new asynchronous methods are now provided, using an ``a``
159 prefix:
160
161 * :meth:`.UserManager.acreate_user`
162 * :meth:`.UserManager.acreate_superuser`
163 * :meth:`.BaseUserManager.aget_by_natural_key`
164 * :meth:`.User.aget_user_permissions`
165 * :meth:`.User.aget_all_permissions`
166 * :meth:`.User.aget_group_permissions`
167 * :meth:`.User.ahas_perm`
168 * :meth:`.User.ahas_perms`
169 * :meth:`.User.ahas_module_perms`
170 * :meth:`.ModelBackend.aauthenticate`
171 * :meth:`.ModelBackend.aget_user_permissions`
172 * :meth:`.ModelBackend.aget_group_permissions`
173 * :meth:`.ModelBackend.aget_all_permissions`
174 * :meth:`.ModelBackend.ahas_perm`
175 * :meth:`.ModelBackend.ahas_module_perms`
176 * :meth:`.RemoteUserBackend.aauthenticate`
177 * :meth:`.RemoteUserBackend.aconfigure_user`
178
179 * Auth backends can now provide async implementations which are used when
180 calling async auth functions (e.g.
181 :func:`~.django.contrib.auth.aauthenticate`) to reduce context-switching
182 which improves performance. See :ref:`adding an async interface
183 <writing-authentication-backends-async-interface>` for more details.
184
185 * The :ref:`password validator classes <included-password-validators>`
186 now have a new method ``get_error_message()``, which can be overridden in
187 subclasses to customize the error messages.
188
189 :mod:`django.contrib.gis`
190 ~~~~~~~~~~~~~~~~~~~~~~~~~
191
192 * GDAL now supports curved geometries ``CurvePolygon``, ``CompoundCurve``,
193 ``CircularString``, ``MultiSurface``, and ``MultiCurve`` via the new
194 :attr:`.OGRGeometry.has_curve` property, and the
195 :meth:`.OGRGeometry.get_linear_geometry` and
196 :meth:`.OGRGeometry.get_curve_geometry` methods.
197
198 * :lookup:`coveredby` and :lookup:`covers` lookup are now supported on MySQL.
199
200 :mod:`django.contrib.syndication`
201 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
202
203 * All :class:`~django.utils.feedgenerator.SyndicationFeed` classes now support
204 a ``stylesheets`` attribute. If specified, an ``<? xml-stylesheet ?>``
205 processing instruction will be added to the top of the document for each
206 stylesheet in the given list. See :ref:`feed-stylesheets` for more details.
207
208 Database backends
209 ~~~~~~~~~~~~~~~~~
210
211 * MySQL connections now default to using the ``utf8mb4`` character set,
212 instead of ``utf8``, which is an alias for the deprecated character set
213 ``utf8mb3``.
214
215 * Oracle backends now support :ref:`connection pools <oracle-pool>`, by setting
216 ``"pool"`` in the :setting:`OPTIONS` part of your database configuration.
217
218 Decorators
219 ~~~~~~~~~~
220
221 * :func:`~django.utils.decorators.method_decorator` now supports wrapping
222 asynchronous view methods.
223
224 Email
225 ~~~~~
226
227 * Tuple items of :class:`EmailMessage.attachments
228 <django.core.mail.EmailMessage>` and
229 :class:`EmailMultiAlternatives.attachments
230 <django.core.mail.EmailMultiAlternatives>` are now named tuples, as opposed
231 to regular tuples.
232
233 * :attr:`EmailMultiAlternatives.alternatives
234 <django.core.mail.EmailMultiAlternatives.alternatives>` is now a list of
235 named tuples, as opposed to regular tuples.
236
237 * The new :meth:`~django.core.mail.EmailMultiAlternatives.body_contains` method
238 returns a boolean indicating whether a provided text is contained in the
239 email ``body`` and in all attached MIME type ``text/*`` alternatives.
240
241 Error Reporting
242 ~~~~~~~~~~~~~~~
243
244 * The attribute :attr:`.SafeExceptionReporterFilter.hidden_settings` now
245 treats values as sensitive if their name includes ``AUTH``.
246
247 Forms
248 ~~~~~
249
250 * The new :class:`~django.forms.ColorInput` form widget is for entering a color
251 in ``rrggbb`` hexadecimal format and renders as ``<input type="color" ...>``.
252 Some browsers support a visual color picker interface for this input type.
253
254 * The new :class:`~django.forms.SearchInput` form widget is for entering search
255 queries and renders as ``<input type="search" ...>``.
256
257 * The new :class:`~django.forms.TelInput` form widget is for entering telephone
258 numbers and renders as ``<input type="tel" ...>``.
259
260 * The new ``field_id`` argument for :class:`~django.forms.ErrorList` allows an
261 HTML ``id`` attribute to be added in the error template. See
262 :attr:`.ErrorList.field_id` for details.
263
264 * An :attr:`~django.forms.BoundField.aria_describedby` property is added to
265 ``BoundField`` to ease use of this HTML attribute in templates.
266
267 * To improve accessibility for screen reader users ``aria-describedby`` is used
268 to associate form fields with their error messages. See
269 :ref:`how form errors are displayed <form-error-display>` for details.
270
271 * The new asset object :class:`~django.forms.Script` is available for adding
272 custom HTML-attributes to JavaScript in form media. See
273 :ref:`paths as objects <form-media-asset-objects>` for more details.
274
275 Management Commands
276 ~~~~~~~~~~~~~~~~~~~
277
278 * A new warning is displayed when running :djadmin:`runserver`, indicating that
279 it is unsuitable for production. This warning can be suppressed by setting
280 the :envvar:`DJANGO_RUNSERVER_HIDE_WARNING` environment variable to
281 ``"true"``.
282
283 * The :djadmin:`makemigrations` and :djadmin:`migrate` commands have a new
284 ``Command.autodetector`` attribute for subclasses to override in order to use
285 a custom autodetector class.
286
287 * The new :meth:`.BaseCommand.get_check_kwargs` method can be overridden in
288 custom commands to control the running of system checks, e.g. to opt into
289 database-dependent checks.
290
291 Migrations
292 ~~~~~~~~~~
293
294 * The new operation :class:`.AlterConstraint` is a no-op operation that alters
295 constraints without dropping and recreating constraints in the database.
296
297 Models
298 ~~~~~~
299
300 * The ``SELECT`` clause generated when using :meth:`.QuerySet.values` and
301 :meth:`.QuerySet.values_list` now matches the specified order of the
302 referenced expressions. Previously, the order was based on a set of
303 counterintuitive rules which made query combination through methods such as
304 :meth:`.QuerySet.union` unpredictable.
305
306 * Added support for validation of model constraints which use a
307 :class:`~django.db.models.GeneratedField`.
308
309 * The new :attr:`.Expression.set_returning` attribute specifies that the
310 expression contains a set-returning function, enforcing subquery evaluation.
311 This is necessary for many Postgres set-returning functions.
312
313 * :attr:`CharField.max_length <django.db.models.CharField.max_length>` is no
314 longer required to be set on SQLite, which supports unlimited ``VARCHAR``
315 columns.
316
317 * :meth:`.QuerySet.explain` now supports the ``memory`` and ``serialize``
318 options on PostgreSQL 17+.
319
320 * The new :class:`~django.db.models.functions.JSONArray` database function
321 accepts a list of field names or expressions and returns a JSON array
322 containing those values.
323
324 * The new :attr:`.Expression.allows_composite_expressions` attribute specifies
325 that the expression allows composite expressions, for example, to support
326 :ref:`composite primary keys <cpk-and-database-functions>`.
327
328 Requests and Responses
329 ~~~~~~~~~~~~~~~~~~~~~~
330
331 * The new :attr:`.HttpResponse.text` property provides the string
332 representation of :attr:`.HttpResponse.content`.
333
334 * The new :meth:`.HttpRequest.get_preferred_type` method can be used to query
335 the preferred media type the client accepts.
336
337 * The new ``preserve_request`` argument for
338 :class:`~django.http.HttpResponseRedirect` and
339 :class:`~django.http.HttpResponsePermanentRedirect`
340 determines whether the HTTP status codes 302/307 or 301/308 are used,
341 respectively.
342
343 * The new ``preserve_request`` argument for
344 :func:`~django.shortcuts.redirect` allows to instruct the user agent to reuse
345 the HTTP method and body during redirection using specific status codes.
346
347 Serialization
348 ~~~~~~~~~~~~~
349
350 * Each serialization format now defines a ``Deserializer`` class, rather than a
351 function, to improve extensibility when defining a
352 :ref:`custom serialization format <custom-serialization-formats>`.
353
354 Templates
355 ~~~~~~~~~
356
357 * The new :meth:`~django.template.Library.simple_block_tag` decorator enables
358 the creation of simple block tags, which can accept and use a section of the
359 template.
360
361 Tests
362 ~~~~~
363
364 * Stack frames from Django's custom assertions are now hidden. This makes test
365 failures easier to read and enables :option:`test --pdb` to directly enter
366 into the failing test method.
367
368 * Data loaded from :attr:`~django.test.TransactionTestCase.fixtures` and from
369 migrations enabled with :ref:`serialized_rollback=True
370 <test-case-serialized-rollback>` are now available during
371 ``TransactionTestCase.setUpClass()``.
372
373 URLs
374 ~~~~
375
376 * :func:`~django.urls.reverse` and :func:`~django.urls.reverse_lazy` now accept
377 ``query`` and ``fragment`` keyword arguments, allowing the addition of a
378 query string and/or fragment identifier in the generated URL, respectively.
379
380 Utilities
381 ~~~~~~~~~
382
383 * :class:`~django.utils.safestring.SafeString` now returns
384 :py:data:`NotImplemented` in ``__add__`` for non-string right-hand side
385 values. This aligns with the :py:class:`str` addition behavior and allows
386 ``__radd__`` to be used if available.
387
388 * :func:`~django.utils.html.format_html_join` now supports taking an iterable
389 of mappings, passing their contents as keyword arguments to
390 :func:`~django.utils.html.format_html`.
391
392 .. _backwards-incompatible-5.2:
393
394 Backwards incompatible changes in 5.2
395 =====================================
396
397 Database backend API
398 --------------------
399
400 This section describes changes that may be needed in third-party database
401 backends.
402
403 * The new :meth:`Model._is_pk_set() <django.db.models.Model._is_pk_set>` method
404 allows checking if a Model instance's primary key is defined.
405
406 * ``BaseDatabaseOperations.adapt_decimalfield_value()`` is now a no-op, simply
407 returning the given value.
408
409 :mod:`django.contrib.gis`
410 -------------------------
411
412 * Support for PostGIS 3.0 is removed.
413
414 * Support for GDAL 3.0 is removed.
415
416 Dropped support for PostgreSQL 13
417 ---------------------------------
418
419 Upstream support for PostgreSQL 13 ends in November 2025. Django 5.2 supports
420 PostgreSQL 14 and higher.
421
422 Changed MySQL connection character set default
423 ----------------------------------------------
424
425 MySQL connections now default to using the ``utf8mb4`` character set, instead
426 of ``utf8``, which is an alias for the deprecated character set ``utf8mb3``.
427 ``utf8mb3`` can be specified in the ``OPTIONS`` part of the ``DATABASES``
428 setting, if needed for legacy databases.
429
430 Miscellaneous
431 -------------
432
433 * Adding :attr:`.EmailMultiAlternatives.alternatives` is now only supported via
434 the :meth:`~.EmailMultiAlternatives.attach_alternative` method.
435
436 * The minimum supported version of ``gettext`` is increased from 0.15 to 0.19.
437
438 * ``HttpRequest.accepted_types`` is now sorted by the client's preference,
439 based on the request's ``Accept`` header.
440
441 * The attributes :attr:`.UniqueConstraint.violation_error_code` and
442 :attr:`.UniqueConstraint.violation_error_message` are now always used when
443 provided. Previously, they were ignored if :attr:`.UniqueConstraint.fields`
444 was set without a :attr:`.UniqueConstraint.condition`.
445
446 * The :func:`~django.template.context_processors.debug` context processor is no
447 longer included in the default project template.
448
449 * The following methods now have ``alters_data=True`` set to prevent side
450 effects when :ref:`rendering a template context <alters-data-description>`:
451
452 * :meth:`.UserManager.create_user`
453 * :meth:`.UserManager.acreate_user`
454 * :meth:`.UserManager.create_superuser`
455 * :meth:`.UserManager.acreate_superuser`
456 * :meth:`.QuerySet.create`
457 * :meth:`.QuerySet.acreate`
458 * :meth:`.QuerySet.bulk_create`
459 * :meth:`.QuerySet.abulk_create`
460 * :meth:`.QuerySet.get_or_create`
461 * :meth:`.QuerySet.aget_or_create`
462 * :meth:`.QuerySet.update_or_create`
463 * :meth:`.QuerySet.aupdate_or_create`
464
465 * The minimum supported version of ``oracledb`` is increased from 1.3.2 to
466 2.3.0.
467
468 * Built-in aggregate functions accepting only one argument (``Avg``, ``Count``,
469 ``Max``, ``Min``, ``StdDev``, ``Sum``, and ``Variance``) now raise
470 :exc:`TypeError` when called with an incorrect number of arguments.
471
472 .. _deprecated-features-5.2:
473
474 Features deprecated in 5.2
475 ==========================
476
477 Miscellaneous
478 -------------
479
480 * The ``all`` argument for the ``django.contrib.staticfiles.finders.find()``
481 function is deprecated in favor of the ``find_all`` argument.
482
483 * Fallbacks to ``request.user`` and ``request.auser()`` when ``user`` is
484 ``None`` in ``django.contrib.auth.login()`` and
485 ``django.contrib.auth.alogin()``, respectively, are deprecated.
486
487 * The ``ordering`` keyword argument of the PostgreSQL specific aggregation
488 functions ``django.contrib.postgres.aggregates.ArrayAgg``,
489 ``django.contrib.postgres.aggregates.JSONBAgg``, and
490 ``django.contrib.postgres.aggregates.StringAgg`` is deprecated in favor
491 of the ``order_by`` argument.
492
493 * Support for subclasses of ``RemoteUserMiddleware`` that override
494 ``process_request()`` without overriding ``aprocess_request()`` is
495 deprecated.