Django 4.2 release notes¶
These release notes cover the new features , as well as some backwards incompatible changes you’ll want to be aware of when upgrading from Django 4.1 or earlier. We’ve begun the deprecation process for some features .
See the How to upgrade Django to a newer version guide if you’re updating an existing project.
Django 4.2 is designated as a long-term support release . It will receive security updates for at least three years after its release. Support for the previous LTS, Django 3.2, will end in April 2024.
Python compatibility¶
Django 4.2 supports Python 3.8, 3.9, 3.10, and 3.11. We highly recommend and only officially support the latest release of each series.
What’s new in Django 4.2¶
Psycopg 3 support¶
Django now supports psycopg version 3.1.8 or higher. To update your code, install the psycopg library, you don’t need to change the ENGINE as django.db.backends.postgresql supports both libraries.
Support for psycopg2 is likely to be deprecated and removed at some point in the future.
Be aware that psycopg 3 introduces some breaking changes over psycopg2 . As a consequence, you may need to make some changes to account for differences from psycopg2.
Comments on columns and tables¶
The new Field.db_comment and Meta.db_table_comment options allow creating comments on columns and tables, respectively. For example:
from django.db import models class Question(models.Model): text = models.TextField(db_comment="Poll question") pub_date = models.DateTimeField( db_comment="Date and time when the question was published", ) class Meta: db_table_comment = "Poll questions" class Answer(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, db_comment="Reference to a question", ) answer = models.TextField(db_comment="Question answer") class Meta: db_table_comment = "Question answers"
Also, the new AlterModelTableComment operation allows changing table comments defined in the Meta.db_table_comment .
Mitigation for the BREACH attack¶
GZipMiddleware now includes a mitigation for the BREACH attack. It will add up to 100 random bytes to gzip responses to make BREACH attacks harder. Read more about the mitigation technique in the Heal The Breach (HTB) paper.
In-memory file storage¶
The new django.core.files.storage.InMemoryStorage class provides a non-persistent storage useful for speeding up tests by avoiding disk access.
Custom file storages¶
The new STORAGES setting allows configuring multiple custom file storage backends. It also controls storage engines for managing files (the «default» key) and static files (the «staticfiles» key).
The old DEFAULT_FILE_STORAGE and STATICFILES_STORAGE settings are deprecated as of this release.
Minor features¶
django.contrib.admin ¶
- The light or dark color theme of the admin can now be toggled in the UI, as well as being set to follow the system setting.
- The admin’s font stack now prefers system UI fonts and no longer requires downloading fonts. Additionally, CSS variables are available to more easily override the default font families.
- The admin/delete_confirmation.html template now has some additional blocks and scripting hooks to ease customization.
- The chosen options of filter_horizontal and filter_vertical widgets are now filterable.
- The admin/base.html template now has a new block nav-breadcrumbs which contains the navigation landmark and the breadcrumbs block.
- ModelAdmin.list_editable now uses atomic transactions when making edits.
- jQuery is upgraded from version 3.6.0 to 3.6.4.
django.contrib.auth ¶
- The default iteration count for the PBKDF2 password hasher is increased from 390,000 to 600,000.
- UserCreationForm now saves many-to-many form fields for a custom user model.
- The new BaseUserCreationForm is now the recommended base class for customizing the user creation form.
django.contrib.gis ¶
- The GeoJSON serializer now outputs the id key for serialized features, which defaults to the primary key of objects.
- The GDALRaster class now supports pathlib.Path .
- The GeoIP2 class now supports .mmdb files downloaded from DB-IP.
- The OpenLayers template widget no longer includes inline CSS (which also removes the former map_css block) to better comply with a strict Content Security Policy.
- OpenLayersWidget is now based on OpenLayers 7.2.2 (previously 4.6.5).
- The new isempty lookup and IsEmpty() expression allow filtering empty geometries on PostGIS.
- The new FromWKB() and FromWKT() functions allow creating geometries from Well-known binary (WKB) and Well-known text (WKT) representations.
django.contrib.postgres ¶
- The new trigram_strict_word_similar lookup, and the TrigramStrictWordSimilarity() and TrigramStrictWordDistance() expressions allow using trigram strict word similarity.
- The arrayfield.overlap lookup now supports QuerySet.values() and values_list() as a right-hand side.
django.contrib.sitemaps ¶
- The new Sitemap.get_languages_for_item() method allows customizing the list of languages for which the item is displayed.
django.contrib.staticfiles ¶
- ManifestStaticFilesStorage now has experimental support for replacing paths to JavaScript modules in import and export statements with their hashed counterparts. If you want to try it, subclass ManifestStaticFilesStorage and set the support_js_module_import_aggregation attribute to True .
- The new ManifestStaticFilesStorage.manifest_hash attribute provides a hash over all files in the manifest and changes whenever one of the files changes.
Database backends¶
- The new «assume_role» option is now supported in OPTIONS on PostgreSQL to allow specifying the session role .
- The new «server_side_binding» option is now supported in OPTIONS on PostgreSQL with psycopg 3.1.8+ to allow using server-side binding cursors .
Error Reporting¶
- The debug page now shows exception notes and fine-grained error locations on Python 3.11+.
- Session cookies are now treated as credentials and therefore hidden and replaced with stars ( ********** ) in error reports.
Forms¶
- ModelForm now accepts the new Meta option formfield_callback to customize form fields.
- modelform_factory() now respects the formfield_callback attribute of the form ’s Meta .
Internationalization¶
- Added support and translations for the Central Kurdish (Sorani) language.
Logging¶
- The django.db.backends logger now logs transaction management queries ( BEGIN , COMMIT , and ROLLBACK ) at the DEBUG level.
Management Commands¶
- makemessages command now supports locales with private sub-tags such as nl_NL-x-informal .
- The new makemigrations —update option merges model changes into the latest migration and optimizes the resulting operations.
Migrations¶
- Migrations now support serialization of enum.Flag objects.
Models¶
- QuerySet now extensively supports filtering against Window functions with the exception of disjunctive filter lookups against window functions when performing aggregation.
- prefetch_related() now supports Prefetch objects with sliced querysets.
- Registering lookups on Field instances is now supported.
- The new robust argument for on_commit() allows performing actions that can fail after a database transaction is successfully committed.
- The new KT() expression represents the text value of a key, index, or path transform of JSONField .
- Now now supports microsecond precision on MySQL and millisecond precision on SQLite.
- F() expressions that output BooleanField can now be negated using ~F() (inversion operator).
- Model now provides asynchronous versions of some methods that use the database, using an a prefix: adelete() , arefresh_from_db() , and asave() .
- Related managers now provide asynchronous versions of methods that change a set of related objects, using an a prefix: aadd() , aclear() , aremove() , and aset() .
- CharField.max_length is no longer required to be set on PostgreSQL, which supports unlimited VARCHAR columns.
Requests and Responses¶
- StreamingHttpResponse now supports async iterators when Django is served via ASGI.
Tests¶
- The test —debug-sql option now formats SQL queries with sqlparse .
- The RequestFactory , AsyncRequestFactory , Client , and AsyncClient classes now support the headers parameter, which accepts a dictionary of header names and values. This allows a more natural syntax for declaring headers.
# Before: self.client.get("/home/", HTTP_ACCEPT_LANGUAGE="fr") await self.async_client.get("/home/", ACCEPT_LANGUAGE="fr") # After: self.client.get("/home/", headers="accept-language": "fr">) await self.async_client.get("/home/", headers="accept-language": "fr">)
Utilities¶
- The new encoder parameter for django.utils.html.json_script() function allows customizing a JSON encoder class.
- The private internal vendored copy of urllib.parse.urlsplit() now strips ‘\r’ , ‘\n’ , and ‘\t’ (see CVE-2022-0391 and bpo-43882). This is to protect projects that may be incorrectly using the internal url_has_allowed_host_and_scheme() function, instead of using one of the documented functions for handling URL redirects. The Django functions were not affected.
- The new django.utils.http.content_disposition_header() function returns a Content-Disposition HTTP header value as specified by RFC 6266.
Validators¶
- The list of common passwords used by CommonPasswordValidator is updated to the most recent version.
Backwards incompatible changes in 4.2¶
Database backend API¶
This section describes changes that may be needed in third-party database backends.
- DatabaseFeatures.allows_group_by_pk is removed as it only remained to accommodate a MySQL extension that has been supplanted by proper functional dependency detection in MySQL 5.7.15. Note that DatabaseFeatures.allows_group_by_selected_pks is still supported and should be enabled if your backend supports functional dependency detection in GROUP BY clauses as specified by the SQL:1999 standard.
- inspectdb now uses display_size from DatabaseIntrospection.get_table_description() rather than internal_size for CharField .
Dropped support for MariaDB 10.3¶
Upstream support for MariaDB 10.3 ends in May 2023. Django 4.2 supports MariaDB 10.4 and higher.
Dropped support for MySQL 5.7¶
Upstream support for MySQL 5.7 ends in October 2023. Django 4.2 supports MySQL 8 and higher.
Dropped support for PostgreSQL 11¶
Upstream support for PostgreSQL 11 ends in November 2023. Django 4.2 supports PostgreSQL 12 and higher.
Setting update_fields in Model.save() may now be required¶
In order to avoid updating unnecessary columns, QuerySet.update_or_create() now passes update_fields to the Model.save() calls. As a consequence, any fields modified in the custom save() methods should be added to the update_fields keyword argument before calling super() . See Overriding predefined model methods for more details.
Miscellaneous¶
- The undocumented django.http.multipartparser.parse_header() function is removed. Use django.utils.http.parse_header_parameters() instead.
- result is now marked as safe for (HTML) output purposes.
- The autofocus HTML attribute in the admin search box is removed as it can be confusing for screen readers.
- The makemigrations —check option no longer creates missing migration files.
- The alias argument for Expression.get_group_by_cols() is removed.
- The minimum supported version of sqlparse is increased from 0.2.2 to 0.3.1.
- The undocumented negated parameter of the Exists expression is removed.
- The is_summary argument of the undocumented Query.add_annotation() method is removed.
- The minimum supported version of SQLite is increased from 3.9.0 to 3.21.0.
- The minimum supported version of asgiref is increased from 3.5.2 to 3.6.0.
- UserCreationForm now rejects usernames that differ only in case. If you need the previous behavior, use BaseUserCreationForm instead.
- The minimum supported version of mysqlclient is increased from 1.4.0 to 1.4.3.
- The minimum supported version of argon2-cffi is increased from 19.1.0 to 19.2.0.
- The minimum supported version of Pillow is increased from 6.2.0 to 6.2.1.
- The minimum supported version of jinja2 is increased from 2.9.2 to 2.11.0.
- The minimum supported version of redis-py is increased from 3.0.0 to 3.4.0.
- Manually instantiated WSGIRequest objects must be provided a file-like object for wsgi.input . Previously, Django was more lax than the expected behavior as specified by the WSGI specification.
- Support for PROJ < 5 is removed.
- EmailBackend now verifies a hostname and certificates . If you need the previous behavior that is less restrictive and not recommended, subclass EmailBackend and override the ssl_context property.
Features deprecated in 4.2¶
index_together option is deprecated in favor of indexes ¶
The Meta.index_together option is deprecated in favor of the indexes option.
Migrating existing index_together should be handled as a migration. For example:
class Author(models.Model): rank = models.IntegerField() name = models.CharField(max_length=30) class Meta: index_together = [["rank", "name"]]
class Author(models.Model): rank = models.IntegerField() name = models.CharField(max_length=30) class Meta: indexes = [models.Index(fields=["rank", "name"])]
Running the makemigrations command will generate a migration containing a RenameIndex operation which will rename the existing index. Next, consider squashing migrations to remove index_together from historical migrations.
The AlterIndexTogether migration operation is now officially supported only for pre-Django 4.2 migration files. For backward compatibility reasons, it’s still part of the public API, and there’s no plan to deprecate or remove it, but it should not be used for new migrations. Use AddIndex and RemoveIndex operations instead.
Passing encoded JSON string literals to JSONField is deprecated¶
JSONField and its associated lookups and aggregates used to allow passing JSON encoded string literals which caused ambiguity on whether string literals were already encoded from database backend’s perspective.
During the deprecation period string literals will be attempted to be JSON decoded and a warning will be emitted on success that points at passing non-encoded forms instead.
Code that used to pass JSON encoded string literals:
Document.objects.bulk_create( Document(data=Value("null")), Document(data=Value("[]")), Document(data=Value('"foo-bar"')), ) Document.objects.annotate( JSONBAgg("field", default=Value("[]")), )
Document.objects.bulk_create( Document(data=Value(None, JSONField())), Document(data=[]), Document(data="foo-bar"), ) Document.objects.annotate( JSONBAgg("field", default=[]), )
From Django 5.1+ string literals will be implicitly interpreted as JSON string literals.
Miscellaneous¶
- The BaseUserManager.make_random_password() method is deprecated. See recipes and best practices for using Python’s secrets module to generate passwords.
- The length_is template filter is deprecated in favor of length and the == operator within an tag. For example
if value|length == 4 %>… endif %> if value|length == 4 %>True else %>False endif %>
instead of:
if value|length_is:4 %>… endif %> value|length_is:4 >>
Статья [Python] Django 4 на примерах, 4-е издание
Вы используете устаревший браузер. Этот и другие сайты могут отображаться в нём некорректно.
Вам необходимо обновить браузер или попробовать использовать другой.
tonny_gram
CryptoCoder
Меценат
tonny_gram
CryptoCoder
Меценат
Регистрация 10 Июл 2019 Сообщения 289 Реакции 303 Баллы 655 BTC 0,00000000
Книга проведет вас через весь процесс разработки профессиональных веб-приложений с помощью Django. Автор объясняет как работает веб-фреймворк Django, путем создания нескольких проектов с нуля.
Книга не только обучает Django, но и знакомит с другими популярными технологиями, такими как PostgreSQL, Redis, Celery, RabbitMQ и Memcached. На протяжении всей книги вы узнаете, как интегрировать эти технологии в свои проекты Django, чтобы использовать расширенные функции и создавать сложные веб-приложения.
Автор: Antonio Mele
Год: 2023
Django 4.0 release notes¶
These release notes cover the new features , as well as some backwards incompatible changes you’ll want to be aware of when upgrading from Django 3.2 or earlier. We’ve begun the deprecation process for some features .
See the How to upgrade Django to a newer version guide if you’re updating an existing project.
Python compatibility¶
Django 4.0 supports Python 3.8, 3.9, and 3.10. We highly recommend and only officially support the latest release of each series.
The Django 3.2.x series is the last to support Python 3.6 and 3.7.
What’s new in Django 4.0¶
zoneinfo default timezone implementation¶
The Python standard library’s zoneinfo is now the default timezone implementation in Django.
This is the next step in the migration from using pytz to using zoneinfo . Django 3.2 allowed the use of non- pytz time zones. Django 4.0 makes zoneinfo the default implementation. Support for pytz is now deprecated and will be removed in Django 5.0.
zoneinfo is part of the Python standard library from Python 3.9. The backports.zoneinfo package is automatically installed alongside Django if you are using Python 3.8.
The move to zoneinfo should be largely transparent. Selection of the current timezone, conversion of datetime instances to the current timezone in forms and templates, as well as operations on aware datetimes in UTC are unaffected.
However, if you are working with non-UTC time zones, and using the pytz normalize() and localize() APIs, possibly with the TIME_ZONE setting, you will need to audit your code, since pytz and zoneinfo are not entirely equivalent.
To give time for such an audit, the transitional USE_DEPRECATED_PYTZ setting allows continued use of pytz during the 4.x release cycle. This setting will be removed in Django 5.0.
In addition, a pytz_deprecation_shim package, created by the zoneinfo author, can be used to assist with the migration from pytz . This package provides shims to help you safely remove pytz , and has a detailed migration guide showing how to move to the new zoneinfo APIs.
Using pytz_deprecation_shim and the USE_DEPRECATED_PYTZ transitional setting is recommended if you need a gradual update path.
Functional unique constraints¶
The new *expressions positional argument of UniqueConstraint() enables creating functional unique constraints on expressions and database functions. For example:
from django.db import models from django.db.models import UniqueConstraint from django.db.models.functions import Lower class MyModel(models.Model): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) class Meta: constraints = [ UniqueConstraint( Lower("first_name"), Lower("last_name").desc(), name="first_last_name_unique", ), ]
Functional unique constraints are added to models using the Meta.constraints option.
scrypt password hasher¶
The new scrypt password hasher is more secure and recommended over PBKDF2. However, it’s not the default as it requires OpenSSL 1.1+ and more memory.
Redis cache backend¶
The new django.core.cache.backends.redis.RedisCache cache backend provides built-in support for caching with Redis. redis-py 3.0.0 or higher is required. For more details, see the documentation on caching with Redis in Django .
Template based form rendering¶
Forms , Formsets , and ErrorList are now rendered using the template engine to enhance customization. See the new render() , get_context() , and template_name for Form and formset rendering for Formset .
Minor features¶
django.contrib.admin ¶
- The admin/base.html template now has a new block header which contains the admin site header.
- The new ModelAdmin.get_formset_kwargs() method allows customizing the keyword arguments passed to the constructor of a formset.
- The navigation sidebar now has a quick filter toolbar.
- The new context variable model which contains the model class for each model is added to the AdminSite.each_context() method.
- The new ModelAdmin.search_help_text attribute allows specifying a descriptive text for the search box.
- The InlineModelAdmin.verbose_name_plural attribute now fallbacks to the InlineModelAdmin.verbose_name + ‘s’ .
- jQuery is upgraded from version 3.5.1 to 3.6.0.
django.contrib.admindocs ¶
- The admindocs now allows esoteric setups where ROOT_URLCONF is not a string.
- The model section of the admindocs now shows cached properties.
django.contrib.auth ¶
- The default iteration count for the PBKDF2 password hasher is increased from 260,000 to 320,000.
- The new LoginView.next_page attribute and get_default_redirect_url() method allow customizing the redirect after login.
django.contrib.gis ¶
- Added support for SpatiaLite 5.
- GDALRaster now allows creating rasters in any GDAL virtual filesystem.
- The new GISModelAdmin class allows customizing the widget used for GeometryField . This is encouraged instead of deprecated GeoModelAdmin and OSMGeoAdmin .
django.contrib.postgres ¶
- The PostgreSQL backend now supports connecting by a service name. See PostgreSQL connection settings for more details.
- The new AddConstraintNotValid operation allows creating check constraints on PostgreSQL without verifying that all existing rows satisfy the new constraint.
- The new ValidateConstraint operation allows validating check constraints which were created using AddConstraintNotValid on PostgreSQL.
- The new ArraySubquery() expression allows using subqueries to construct lists of values on PostgreSQL.
- The new trigram_word_similar lookup, and the TrigramWordDistance() and TrigramWordSimilarity() expressions allow using trigram word similarity.
django.contrib.staticfiles ¶
- ManifestStaticFilesStorage now replaces paths to JavaScript source map references with their hashed counterparts.
- The new manifest_storage argument of ManifestFilesMixin and ManifestStaticFilesStorage allows customizing the manifest file storage.
Cache¶
- The new async API for django.core.cache.backends.base.BaseCache begins the process of making cache backends async-compatible. The new async methods all have a prefixed names, e.g. aadd() , aget() , aset() , aget_or_set() , or adelete_many() . Going forward, the a prefix will be used for async variants of methods generally.
CSRF¶
- CSRF protection now consults the Origin header, if present. To facilitate this, some changes to the CSRF_TRUSTED_ORIGINS setting are required.
Forms¶
- ModelChoiceField now includes the provided value in the params argument of a raised ValidationError for the invalid_choice error message. This allows custom error messages to use the %(value)s placeholder.
- BaseFormSet now renders non-form errors with an additional class of nonform to help distinguish them from form-specific errors.
- BaseFormSet now allows customizing the widget used when deleting forms via can_delete by setting the deletion_widget attribute or overriding get_deletion_widget() method.
Internationalization¶
- Added support and translations for the Malay language.
Generic Views¶
- DeleteView now uses FormMixin , allowing you to provide a Form subclass, with a checkbox for example, to confirm deletion. In addition, this allows DeleteView to function with django.contrib.messages.views.SuccessMessageMixin . In accordance with FormMixin , object deletion for POST requests is handled in form_valid() . Custom delete logic in delete() handlers should be moved to form_valid() , or a shared helper method, as needed.
Logging¶
- The alias of the database used in an SQL call is now passed as extra context along with each message to the django.db.backends logger.
Management Commands¶
- The runserver management command now supports the —skip-checks option.
- On PostgreSQL, dbshell now supports specifying a password file.
- The shell command now respects sys.__interactivehook__ at startup. This allows loading shell history between interactive sessions. As a consequence, readline is no longer loaded if running in isolated mode.
- The new BaseCommand.suppressed_base_arguments attribute allows suppressing unsupported default command options in the help output.
- The new startapp —exclude and startproject —exclude options allow excluding directories from the template.
Models¶
- New QuerySet.contains(obj) method returns whether the queryset contains the given object. This tries to perform the query in the simplest and fastest way possible.
- The new precision argument of the Round() database function allows specifying the number of decimal places after rounding.
- QuerySet.bulk_create() now sets the primary key on objects when using SQLite 3.35+.
- DurationField now supports multiplying and dividing by scalar values on SQLite.
- QuerySet.bulk_update() now returns the number of objects updated.
- The new Expression.empty_result_set_value attribute allows specifying a value to return when the function is used over an empty result set.
- The skip_locked argument of QuerySet.select_for_update() is now allowed on MariaDB 10.6+.
- Lookup expressions may now be used in QuerySet annotations, aggregations, and directly in filters.
- The new default argument for built-in aggregates allows specifying a value to be returned when the queryset (or grouping) contains no entries, rather than None .
Requests and Responses¶
- The SecurityMiddleware now adds the Cross-Origin Opener Policy header with a value of ‘same-origin’ to prevent cross-origin popups from sharing the same browsing context. You can prevent this header from being added by setting the SECURE_CROSS_ORIGIN_OPENER_POLICY setting to None .
Signals¶
- The new stdout argument for pre_migrate() and post_migrate() signals allows redirecting output to a stream-like object. It should be preferred over sys.stdout and print() when emitting verbose output in order to allow proper capture when testing.
Templates¶
- floatformat template filter now allows using the u suffix to force disabling localization.
Tests¶
- The new serialized_aliases argument of django.test.utils.setup_databases() determines which DATABASES aliases test databases should have their state serialized to allow usage of the serialized_rollback feature.
- Django test runner now supports a —buffer option with parallel tests.
- The new logger argument to DiscoverRunner allows a Python logger to be used for logging.
- The new DiscoverRunner.log() method provides a way to log messages that uses the DiscoverRunner.logger , or prints to the console if not set.
- Django test runner now supports a —shuffle option to execute tests in a random order.
- The test —parallel option now supports the value auto to run one test process for each processor core.
- TestCase.captureOnCommitCallbacks() now captures new callbacks added while executing transaction.on_commit() callbacks.
Backwards incompatible changes in 4.0¶
Database backend API¶
This section describes changes that may be needed in third-party database backends.
- DatabaseOperations.year_lookup_bounds_for_date_field() and year_lookup_bounds_for_datetime_field() methods now take the optional iso_year argument in order to support bounds for ISO-8601 week-numbering years.
- The second argument of DatabaseSchemaEditor._unique_sql() and _create_unique_sql() methods is now fields instead of columns .
django.contrib.gis ¶
- Support for PostGIS 2.3 is removed.
- Support for GDAL 2.0 and GEOS 3.5 is removed.
Dropped support for PostgreSQL 9.6¶
Upstream support for PostgreSQL 9.6 ends in November 2021. Django 4.0 supports PostgreSQL 10 and higher.
Also, the minimum supported version of psycopg2 is increased from 2.5.4 to 2.8.4, as psycopg2 2.8.4 is the first release to support Python 3.8.
Dropped support for Oracle 12.2 and 18c¶
Upstream support for Oracle 12.2 ends in March 2022 and for Oracle 18c it ends in June 2021. Django 3.2 will be supported until April 2024. Django 4.0 officially supports Oracle 19c.
CSRF_TRUSTED_ORIGINS changes¶
Format change¶
Values in the CSRF_TRUSTED_ORIGINS setting must include the scheme (e.g. ‘http://’ or ‘https://’ ) instead of only the hostname.
Also, values that started with a dot, must now also include an asterisk before the dot. For example, change ‘.example.com’ to ‘https://*.example.com’ .
A system check detects any required changes.
Configuring it may now be required¶
As CSRF protection now consults the Origin header, you may need to set CSRF_TRUSTED_ORIGINS , particularly if you allow requests from subdomains by setting CSRF_COOKIE_DOMAIN (or SESSION_COOKIE_DOMAIN if CSRF_USE_SESSIONS is enabled) to a value starting with a dot.
SecurityMiddleware no longer sets the X-XSS-Protection header¶
The SecurityMiddleware no longer sets the X-XSS-Protection header if the SECURE_BROWSER_XSS_FILTER setting is True . The setting is removed.
Most modern browsers don’t honor the X-XSS-Protection HTTP header. You can use Content-Security-Policy without allowing ‘unsafe-inline’ scripts instead.
If you want to support legacy browsers and set the header, use this line in a custom middleware:
response.headers.setdefault("X-XSS-Protection", "1; mode=block")
Migrations autodetector changes¶
The migrations autodetector now uses model states instead of model classes. Also, migration operations for ForeignKey and ManyToManyField fields no longer specify attributes which were not passed to the fields during initialization.
As a side-effect, running makemigrations might generate no-op AlterField operations for ManyToManyField and ForeignKey fields in some cases.
DeleteView changes¶
DeleteView now uses FormMixin to handle POST requests. As a consequence, any custom deletion logic in delete() handlers should be moved to form_valid() , or a shared helper method, if required.
Table and column naming scheme changes on Oracle¶
Django 4.0 inadvertently changed the table and column naming scheme on Oracle. This causes errors for models and fields with names longer than 30 characters. Unfortunately, renaming some Oracle tables and columns is required. Use the upgrade script in 33789 to generate RENAME statements to change naming scheme.
Miscellaneous¶
- Support for cx_Oracle < 7.0 is removed.
- To allow serving a Django site on a subpath without changing the value of STATIC_URL , the leading slash is removed from that setting (now ‘static/’ ) in the default startproject template.
- The AdminSite method for the admin index view is no longer decorated with never_cache when accessed directly, rather than via the recommended AdminSite.urls property, or AdminSite.get_urls() method.
- Unsupported operations on a sliced queryset now raise TypeError instead of AssertionError .
- The undocumented django.test.runner.reorder_suite() function is renamed to reorder_tests() . It now accepts an iterable of tests rather than a test suite, and returns an iterator of tests.
- Calling FileSystemStorage.delete() with an empty name now raises ValueError instead of AssertionError .
- Calling EmailMultiAlternatives.attach_alternative() or EmailMessage.attach() with an invalid content or mimetype arguments now raise ValueError instead of AssertionError .
- assertHTMLEqual() no longer considers a non-boolean attribute without a value equal to an attribute with the same name and value.
- Tests that fail to load, for example due to syntax errors, now always match when using test —tag .
- The undocumented django.contrib.admin.utils.lookup_needs_distinct() function is renamed to lookup_spawns_duplicates() .
- The undocumented HttpRequest.get_raw_uri() method is removed. The HttpRequest.build_absolute_uri() method may be a suitable alternative.
- The object argument of undocumented ModelAdmin.log_addition() , log_change() , and log_deletion() methods is renamed to obj .
- RssFeed , Atom1Feed , and their subclasses now emit elements with no content as self-closing tags.
- NodeList.render() no longer casts the output of render() method for individual nodes to a string. Node.render() should always return a string as documented.
- The where_class property of django.db.models.sql.query.Query and the where_class argument to the private get_extra_restriction() method of ForeignObject and ForeignObjectRel are removed. If needed, initialize django.db.models.sql.where.WhereNode instead.
- The filter_clause argument of the undocumented Query.add_filter() method is replaced by two positional arguments filter_lhs and filter_rhs .
- CsrfViewMiddleware now uses request.META[‘CSRF_COOKIE_NEEDS_UPDATE’] in place of request.META[‘CSRF_COOKIE_USED’] , request.csrf_cookie_needs_reset , and response.csrf_cookie_set to track whether the CSRF cookie should be sent. This is an undocumented, private API.
- The undocumented TRANSLATOR_COMMENT_MARK constant is moved from django.template.base to django.utils.translation.template .
- The real_apps argument of the undocumented django.db.migrations.state.ProjectState.__init__() method must now be a set if provided.
- RadioSelect and CheckboxSelectMultiple widgets are now rendered in tags so they are announced more concisely by screen readers. If you need the previous behavior, override the widget template with the appropriate template from Django 3.2.
- The floatformat template filter no longer depends on the USE_L10N setting and always returns localized output. Use the u suffix to disable localization.
- The default value of the USE_L10N setting is changed to True . See the Localization section above for more details.
- As part of the move to zoneinfo , django.utils.timezone.utc is changed to alias datetime.timezone.utc .
- The minimum supported version of asgiref is increased from 3.3.2 to 3.4.1.
Features deprecated in 4.0¶
Use of pytz time zones¶
As part of the move to zoneinfo , use of pytz time zones is deprecated.
Accordingly, the is_dst arguments to the following are also deprecated:
- django.db.models.query.QuerySet.datetimes()
- django.db.models.functions.Trunc()
- django.db.models.functions.TruncSecond()
- django.db.models.functions.TruncMinute()
- django.db.models.functions.TruncHour()
- django.db.models.functions.TruncDay()
- django.db.models.functions.TruncWeek()
- django.db.models.functions.TruncMonth()
- django.db.models.functions.TruncQuarter()
- django.db.models.functions.TruncYear()
- django.utils.timezone.make_aware()
Support for use of pytz will be removed in Django 5.0.
Time zone support¶
In order to follow good practice, the default value of the USE_TZ setting will change from False to True , and time zone support will be enabled by default, in Django 5.0.
Note that the default settings.py file created by django-admin startproject includes USE_TZ = True since Django 1.4.
You can set USE_TZ to False in your project settings before then to opt-out.
Localization¶
In order to follow good practice, the default value of the USE_L10N setting is changed from False to True .
Moreover USE_L10N is deprecated as of this release. Starting with Django 5.0, by default, any date or number displayed by Django will be localized.
The tag and the localize / unlocalize filters will still be honored by Django.
Miscellaneous¶
- SERIALIZE test setting is deprecated as it can be inferred from the databases with the serialized_rollback option enabled.
- The undocumented django.utils.baseconv module is deprecated.
- The undocumented django.utils.datetime_safe module is deprecated.
- The default sitemap protocol for sitemaps built outside the context of a request will change from ‘http’ to ‘https’ in Django 5.0.
- The extra_tests argument for DiscoverRunner.build_suite() and DiscoverRunner.run_tests() is deprecated.
- The ArrayAgg , JSONBAgg , and StringAgg aggregates will return None when there are no rows instead of [] , [] , and » respectively in Django 5.0. If you need the previous behavior, explicitly set default to Value([]) , Value(‘[]’) , or Value(») .
- The django.contrib.gis.admin.GeoModelAdmin and OSMGeoAdmin classes are deprecated. Use ModelAdmin and GISModelAdmin instead.
- Since form rendering now uses the template engine, the undocumented BaseForm._html_output() helper method is deprecated.
- The ability to return a str from ErrorList and ErrorDict is deprecated. It is expected these methods return a SafeString .
Features removed in 4.0¶
These features have reached the end of their deprecation cycle and are removed in Django 4.0.
See Features deprecated in 3.0 for details on these changes, including how to remove usage of these features.
- django.utils.http.urlquote() , urlquote_plus() , urlunquote() , and urlunquote_plus() are removed.
- django.utils.encoding.force_text() and smart_text() are removed.
- django.utils.translation.ugettext() , ugettext_lazy() , ugettext_noop() , ungettext() , and ungettext_lazy() are removed.
- django.views.i18n.set_language() doesn’t set the user language in request.session (key _language ).
- alias=None is required in the signature of django.db.models.Expression.get_group_by_cols() subclasses.
- django.utils.text.unescape_entities() is removed.
- django.utils.http.is_safe_url() is removed.
See Features deprecated in 3.1 for details on these changes, including how to remove usage of these features.
- The PASSWORD_RESET_TIMEOUT_DAYS setting is removed.
- The isnull lookup no longer allows using non-boolean values as the right-hand side.
- The django.db.models.query_utils.InvalidQuery exception class is removed.
- The django-admin.py entry point is removed.
- The HttpRequest.is_ajax() method is removed.
- Support for the pre-Django 3.1 encoding format of cookies values used by django.contrib.messages.storage.cookie.CookieStorage is removed.
- Support for the pre-Django 3.1 password reset tokens in the admin site (that use the SHA-1 hashing algorithm) is removed.
- Support for the pre-Django 3.1 encoding format of sessions is removed.
- Support for the pre-Django 3.1 django.core.signing.Signer signatures (encoded with the SHA-1 algorithm) is removed.
- Support for the pre-Django 3.1 django.core.signing.dumps() signatures (encoded with the SHA-1 algorithm) in django.core.signing.loads() is removed.
- Support for the pre-Django 3.1 user sessions (that use the SHA-1 algorithm) is removed.
- The get_response argument for django.utils.deprecation.MiddlewareMixin.__init__() is required and doesn’t accept None .
- The providing_args argument for django.dispatch.Signal is removed.
- The length argument for django.utils.crypto.get_random_string() is required.
- The list message for ModelMultipleChoiceField is removed.
- Support for passing raw column aliases to QuerySet.order_by() is removed.
- The NullBooleanField model field is removed, except for support in historical migrations.
- django.conf.urls.url() is removed.
- The django.contrib.postgres.fields.JSONField model field is removed, except for support in historical migrations.
- django.contrib.postgres.fields.jsonb.KeyTransform and django.contrib.postgres.fields.jsonb.KeyTextTransform are removed.
- django.contrib.postgres.forms.JSONField is removed.
- The and template tags are removed.
- The DEFAULT_HASHING_ALGORITHM transitional setting is removed.
Additional Information
Support Django!
Contents
- Django 4.0 release notes
- Python compatibility
- What’s new in Django 4.0
- zoneinfo default timezone implementation
- Functional unique constraints
- scrypt password hasher
- Redis cache backend
- Template based form rendering
- Minor features
- django.contrib.admin
- django.contrib.admindocs
- django.contrib.auth
- django.contrib.gis
- django.contrib.postgres
- django.contrib.staticfiles
- Cache
- CSRF
- Forms
- Internationalization
- Generic Views
- Logging
- Management Commands
- Models
- Requests and Responses
- Signals
- Templates
- Tests
- Database backend API
- django.contrib.gis
- Dropped support for PostgreSQL 9.6
- Dropped support for Oracle 12.2 and 18c
- CSRF_TRUSTED_ORIGINS changes
- Format change
- Configuring it may now be required
- Use of pytz time zones
- Time zone support
- Localization
- Miscellaneous
Browse
- Prev: Django 4.0.1 release notes
- Next: Django 3.2.23 release notes
- Table of contents
- General Index
- Python Module Index
You are here:
- Django 4.2 documentation
- Release notes
- Django 4.0 release notes
Getting help
FAQ Try the FAQ — it’s got answers to many common questions. Index, Module Index, or Table of Contents Handy when looking for specific information. django-users mailing list Search for information in the archives of the django-users mailing list, or post a question. #django IRC channel Ask a question in the #django IRC channel, or search the IRC logs to see if it’s been asked before. Django Discord Server Join the Django Discord Community. Official Django Forum Join the community on the Django Forum. Ticket tracker Report bugs with Django or Django documentation in our ticket tracker.
Download:
Offline (Django 4.2): HTML | PDF | ePub
Provided by Read the Docs.Django 4 что нового

Новые функции и изменения в Django 4.2: примечания к выпуску
01 мая 2023
Оценки статьи
Еще никто не оценил статьюDjango 4.2 был выпущен с новыми функциями и изменениями, которые включают поддержку библиотеки Psycopg 3 и усиленную защиту от атаки BREACH. Однако, также есть обратно несовместимые изменения, которые нужно учитывать при обновлении с более ранних версий.
Совместимость Django 4.2 с Python
Django 4.2 поддерживает Python 3.8, 3.9, 3.10 и 3.11. Настоятельно рекомендуется использовать последнюю версию каждой серии выпуска.
Что нового в Django 4.2
В Django 4.2 теперь возможна работа с psycopg версии 3.1 и выше. Для обновления вашего кода необходимо установить библиотеку psycopg, но не требуется изменять ENGINE, поскольку django.db.backends.postgresql поддерживает обе библиотеки.
Возможно, поддержка psycopg2 будет устаревшей и в будущем ее удаление будет осуществлено.
Устранение последствий атаки BREACH
В Django 4.2 было добавлено смягчение последствий атаки BREACH в GZipMiddleware . Теперь при отправке gzip-ответов он добавляет до 100 случайных байтов, чтобы затруднить возможные атаки. Дополнительную информацию о технике смягчения атаки можно найти в статье «Heal The Breach (HTB)».
Незначительные особенности
django.contrib.admin
- Теперь пользователи могут переключать цветовую тему административной панели на светлую или темную в пользовательском интерфейсе и установить ее в соответствии с системными настройками.
- Шрифты администратора теперь предпочитают системные шрифты пользовательского интерфейса, что позволяет избежать загрузки шрифтов, а также доступны переменные CSS для простой замены семейств шрифтов.
- Шаблон admin/delete_confirmation.html улучшен и теперь содержит несколько дополнительных блоков и скриптовых крючков, которые облегчают настройку.
- Выбранные опции виджетов filter_horizontal и filter_vertical могут быть теперь отфильтрованы.
- В шаблоне admin/base.html добавлен новый блок nav-breadcrumbs с навигационным ориентиром и блоком breadcrumbs. При использовании
- ModelAdmin.list_editable теперь используются атомарные транзакции для внесения правок.
django.contrib.auth
- В PBKDF2, хешере паролей, число итераций по умолчанию было увеличено с 390 000 до 480 000.
- Теперь UserCreationForm сохраняет поля формы «многие-ко-многим» для пользовательской модели пользователя.
django.contrib.gis
- Теперь в GeoJSON-сериализаторе выводится ключ id для сериализованных функций, который по умолчанию соответствует первичному ключу объектов.
- Класс GDALRaster теперь поддерживает использование объектов pathlib.Path .
- Класс GeoIP2 теперь поддерживает загрузку файлов .mmdb, полученных из DB-IP.
- Виджет шаблона OpenLayers больше не включает встроенный CSS (что также удаляет прежний блок map_css), чтобы лучше соответствовать строгой политике безопасности содержимого.
django.contrib.postgres
- Модуль trigram_strict_word_similar , а также выражения TrigramStrictWordSimilarity() и TrigramStrictWordDistance() добавлены для поддержки триграммного строгого сравнения слов при поиске.
- Теперь метод arrayfield.overlap поддерживает QuerySet.values() и values_list() в качестве правой части.
django.contrib.sitemaps
- Новый метод Sitemap.get_languages_for_item() позволяет настроить список языков, для которых отображается элемент.
django.contrib.staticfiles
- ManifestStaticFilesStorage теперь заменяет импортированные и экспортированные пути к модулям JavaScript на их хэшированные аналоги.
Отчеты об ошибках
- Страница отладки теперь показывает exception notes и fine-grained error locations на Python 3.11+.
Формы
- Теперь в ModelForm доступна новая опция Meta formfield_callback для индивидуальной настройки полей формы. -Функция modelform_factory() теперь учитывает атрибут formfield_callback в форме Meta .
- Сеансовые куки теперь считаются учетными данными и скрыты в выводе, а в отчетах об ошибках заменены звездочками (**********).
Интернационализация
- Обновленный пакет интернационализации теперь включает поддержку и переводы на центральнокурдский язык (Sorani).
- Кроме того, в LocaleMiddleware были внесены изменения, теперь он учитывает язык из запроса, когда i18n_patterns() используется с аргументом prefix_default_language , установленным в False.
Ведение журнала
- Регистратор django.db.backends теперь регистрирует запросы управления транзакциями (BEGIN, COMMIT и ROLLBACK) на уровне DEBUG.
Команды управления
- Команда makemessages теперь поддерживает локали с частными подтегами, такими как nl_NL-x-informal .
- Новая опция makemigrations —update объединяет изменения модели в последнюю миграцию и оптимизирует результирующие операции.
Миграции
- Миграции теперь поддерживают сериализацию объектов enum.Flag .
Модели
- Теперь QuerySet поддерживает фильтрацию с использованием функций окна, за исключением дизъюнктивного поиска фильтра против оконных функций при выполнении агрегации.
- prefetch_related() теперь может использовать Prefetch-объекты с нарезанными кверисетами.
- Добавлена поддержка регистрации lookups на экземплярах Field.
- Добавлен новый аргумент «robust» для on_commit() , позволяющий выполнить действия, которые могут завершиться неудачей после успешной фиксации транзакции базы данных.
- Добавлено новое выражение KT() , которое представляет текстовое значение ключа, индекса или преобразования пути JSONField.
- Now теперь поддерживает микросекундную точность в MySQL и миллисекундную точность в SQLite.
- Выражения F() , выводящие BooleanField, теперь можно отрицать с помощью оператора инверсии ~F() .
- Модель теперь предоставляет асинхронные версии некоторых методов, использующих базу данных, с использованием префикса «a»: adelete() , arefresh_from_db() и asave() .
- Менеджеры Related теперь предоставляют асинхронные версии методов, которые изменяют набор связанных объектов, используя префикс «a»: aadd() , aclear() , aremove() и aset() .
Запросы и ответы
- StreamingHttpResponse теперь поддерживает асинхронные итераторы, когда Django обслуживается через ASGI.
Тесты
- Опция test —debug-sql теперь форматирует SQL-запросы с помощью sqlparse .
- Классы RequestFactory, AsyncRequestFactory, Client и AsyncClient теперь поддерживают параметр headers , который принимает словарь имен и значений заголовков. Это позволяет использовать более естественный синтаксис для объявления заголовков.
# Before: self.client.get("/home/", HTTP_ACCEPT_LANGUAGE="fr") await self.async_client.get("/home/", ACCEPT_LANGUAGE="fr") # After: self.client.get("/home/", headers="accept-language": "fr">) await self.async_client.get("/home/", headers="accept-language": "fr">)Утилиты
- Теперь для функции json_script() из модуля django.utils.html доступен новый параметр encoder, который позволяет настроить класс кодировщика JSON.
- Внутренняя вендорная копия функции urllib.parse.urlsplit() теперь отделяет символы ‘\r’ , ‘\n’ и ‘\t’ , чтобы защитить проекты от уязвимости CVE-2022-0391 и bpo-43882, связанных с неправильным использованием функции url_has_allowed_host_and_scheme() . Однако, функции Django не были затронуты.
- Добавлена новая функция content_disposition_header() в модуль django.utils.http . Она возвращает значение заголовка HTTP Content-Disposition, указанное в RFC 6266.
Валидаторы
Список распространенных паролей, используемых CommonPasswordValidator, обновляется до последней версии.
Изменения в Django 4.2, несовместимые с обратными изменениями
- Изменения, несовместимые с обратными изменениями, в Django 4.2 относятся к API бэкенда базы данных сторонних производителей.
- DatabaseFeatures.allows_group_by_pk удалено, потому что оно было приспособлено для расширения MySQL, которое было вытеснено более правильным функциональным обнаружением зависимостей в MySQL 5.7.15. — Однако DatabaseFeatures.allows_group_by_selected_pks по-прежнему поддерживается и должен быть включен, если ваш бэкенд поддерживает обнаружение функциональных зависимостей в предложениях GROUP BY , как указано в стандарте SQL:1999.
- Кроме того, поддержка MariaDB 10.3, MySQL 5.7 и PostgreSQL 11 прекращена в Django 4.2, и вместо этого поддерживаются MariaDB 10.4 и выше, MySQL 8 и выше, и PostgreSQL 12 и выше.
- Также установка update_fields в Model.save() теперь может потребоваться, чтобы избежать обновления ненужных столбцов, поскольку QuerySet.update_or_create() теперь передает update_fields в вызовы Model.save() . Это означает, что любые поля, измененные в пользовательских методах save() , должны быть добавлены в аргумент ключевого слова update_fields перед вызовом super() .
Разное
- Переименованы недокументированные атрибуты SimpleTemplateResponse.rendering_attrs и TemplateResponse.rendering_attrs в non_picklable_attrs .
- Функция django.http.multipartparser.parse_header() , которая ранее не была задокументирована, удалена. Вместо нее теперь следует использовать django.utils.http.parse_header_parameters() .
- Результат теперь помечен как безопасный для вывода в HTML.
- Атрибут autofocus в окне поиска администратора был удален, так как он может быть неудобен для пользователей, использующих читалки экрана. Опция —check в команде makemigrations теперь не создает отсутствующие файлы миграций.
- Аргумент alias для метода Expression.get_group_by_cols() был удален.
Функции, устаревшие в Django 4.2
- Опция index_together устарела в пользу indexes .
- Опция Meta.index_together устарела в пользу опции indexes .
Миграция существующих index_together должна обрабатываться как миграция. Например:
class Author(models.Model): rank = models.IntegerField() name = models.CharField(max_length=30) class Meta: index_together = [["rank", "name"]]Должно стать:
class Author(models.Model): rank = models.IntegerField() name = models.CharField(max_length=30) class Meta: indexes = [models.Index(fields=["rank", "name"])]- Выполнение команды makemigrations создаст миграцию, содержащую операцию RenameIndex , которая переименует существующий индекс.
- Операция миграции AlterIndexTogether теперь официально поддерживается только для файлов миграции, созданных до версии Django 4.2. По причинам обратной совместимости, она все еще является частью публичного API, и нет планов по ее обесцениванию или удалению, но она не должна использоваться для новых миграций. Вместо этого используйте операции AddIndex и RemoveIndex .
- Минимальная версия поддержки JSONField была повышена с 3.5.2 до 3.6.0. Ранее JSONField и связанные с ним функции поиска и агрегации могли использовать строковые литералы в формате JSON, что могло привести к неоднозначности при передаче уже закодированных строковых литералов в бэкенд базы данных.
Во время переходного периода, строковые литералы будут декодироваться в JSON и в случае успешного декодирования будет выдано предупреждение, указывающее на передачу некодированных форм вместо закодированных.
Пример кода, который использовался для передачи строковых литералов в формате JSON:
Document.objects.bulk_create( Document(data=Value("null")), Document(data=Value("[]")), Document(data=Value('"foo-bar"')), ) Document.objects.annotate( JSONBAgg("field", default=Value('[]')), )Должно стать:
Document.objects.bulk_create( Document(data=Value(None, JSONField())), Document(data=[]), Document(data="foo-bar"), ) Document.objects.annotate( JSONBAgg("field", default=[]), )Начиная с Django 5.1+ строковые литералы будут неявно интерпретироваться как строковые литералы JSON.
Разное
- Не рекомендуется использовать метод BaseUserManager.make_random_password() . Рекомендуется использовать модуль Python secrets для генерации паролей.
- Шаблонный фильтр length_is больше не поддерживается.
- Вместо этого используйте length и оператор == внутри тега . Например, . .
- Устарели хеш-функции django.contrib.auth.hashers.SHA1PasswordHasher , django.contrib.auth.hashers.UnsaltedSHA1PasswordHasher и django.contrib.auth.hashers.UnsaltedMD5PasswordHasher .
- Устарел класс django.contrib.postgres.fields.CICharField в пользу CharField с параметром db_collation=». » для создания недетерминированной коллизии, нечувствительной к регистру.
- Устарел класс django.contrib.postgres.fields.CIEmailField в пользу EmailField с параметром db_collation=». » для создания недетерминированной коллизии, нечувствительной к регистру.
- Устарел класс django.contrib.postgres.fields.CITextField в пользу TextField с параметром db_collation=». » для создания недетерминированной коллизии, нечувствительной к регистру.
- Устарел миксин django.contrib.postgres.fields.CIText .
- Атрибуты map_height и map_width в классе BaseGeometryWidget устарели. Используйте CSS для определения размера виджетов карты.
- Метод SimpleTestCase.assertFormsetError() устарел в пользу assertFormSetError() .
- Метод TransactionTestCase.assertQuerysetEqual() устарел в пользу assertQuerySetEqual() .
- Устарела передача позиционных аргументов в классы Signer и TimestampSigner . Рекомендуется использовать только аргументы, содержащие ключевые слова.
Взято с сайта: django.fun
Меню категорий
-
Загрузка категорий.
- Release notes