From 305757aec19c9d5111e4d76095ae0acd66163e4b Mon Sep 17 00:00:00 2001 From: Mariusz Felisiak Date: Fri, 26 Jan 2024 12:45:07 +0100 Subject: [PATCH] Applied Black's 2024 stable style. https://github.com/psf/black/releases/tag/24.1.0 --- .pre-commit-config.yaml | 4 +- django/__main__.py | 1 + django/contrib/admin/filters.py | 1 + django/contrib/admin/options.py | 14 ++-- .../contrib/admin/templatetags/admin_list.py | 14 ++-- django/contrib/admin/widgets.py | 1 + django/contrib/auth/base_user.py | 1 + django/contrib/auth/management/__init__.py | 1 + .../management/commands/createsuperuser.py | 23 ++++-- .../contrib/gis/db/backends/oracle/models.py | 1 + .../gis/db/backends/oracle/operations.py | 1 + .../gis/db/backends/postgis/adapter.py | 1 + .../contrib/gis/db/backends/postgis/const.py | 1 + .../contrib/gis/db/backends/postgis/models.py | 1 + .../gis/db/backends/spatialite/models.py | 1 + .../gis/db/backends/spatialite/operations.py | 1 + django/contrib/gis/db/models/functions.py | 14 ++-- django/contrib/gis/db/models/proxy.py | 1 + .../contrib/gis/db/models/sql/conversion.py | 1 + django/contrib/gis/gdal/__init__.py | 1 + django/contrib/gis/gdal/datasource.py | 1 + django/contrib/gis/gdal/envelope.py | 1 + django/contrib/gis/gdal/geometries.py | 1 + django/contrib/gis/gdal/prototypes/ds.py | 1 + .../contrib/gis/gdal/prototypes/errcheck.py | 1 + .../contrib/gis/gdal/prototypes/generation.py | 1 + django/contrib/gis/gdal/prototypes/raster.py | 1 + django/contrib/gis/gdal/raster/const.py | 1 + django/contrib/gis/gdal/srs.py | 1 + django/contrib/gis/geos/__init__.py | 1 + django/contrib/gis/geos/collections.py | 1 + django/contrib/gis/geos/coordseq.py | 1 + django/contrib/gis/geos/geometry.py | 1 + django/contrib/gis/geos/io.py | 1 + django/contrib/gis/geos/libgeos.py | 1 + .../contrib/gis/geos/prototypes/errcheck.py | 1 + django/contrib/gis/geos/prototypes/misc.py | 1 + .../contrib/gis/geos/prototypes/predicates.py | 1 + .../contrib/gis/geos/prototypes/topology.py | 1 + django/contrib/gis/utils/__init__.py | 1 + django/contrib/gis/utils/ogrinspect.py | 1 + django/contrib/postgres/search.py | 8 +- django/contrib/sessions/base_session.py | 1 + django/contrib/staticfiles/views.py | 1 + django/core/cache/__init__.py | 1 + django/core/exceptions.py | 1 + django/core/files/images.py | 1 + django/core/files/locks.py | 1 + django/core/files/uploadhandler.py | 1 + django/core/mail/__init__.py | 1 + django/core/mail/backends/console.py | 1 + django/core/mail/backends/locmem.py | 1 + django/core/mail/backends/smtp.py | 1 + django/core/management/base.py | 23 ++++-- django/core/serializers/base.py | 1 + django/core/serializers/xml_serializer.py | 1 + django/db/backends/base/schema.py | 16 ++-- django/db/backends/ddl_references.py | 1 + django/db/backends/mysql/base.py | 1 + django/db/backends/oracle/base.py | 1 + django/db/backends/oracle/creation.py | 18 ++-- django/db/backends/postgresql/base.py | 8 +- django/db/backends/postgresql/schema.py | 6 +- django/db/backends/sqlite3/_functions.py | 1 + django/db/backends/sqlite3/base.py | 1 + django/db/migrations/autodetector.py | 17 ++-- django/db/migrations/loader.py | 10 +-- django/db/migrations/operations/models.py | 10 +-- django/db/migrations/state.py | 10 +-- django/db/models/aggregates.py | 1 + django/db/models/base.py | 8 +- django/db/models/constants.py | 1 + django/db/models/expressions.py | 42 +++++----- .../db/models/fields/related_descriptors.py | 1 + django/db/models/fields/reverse_related.py | 1 + django/db/models/functions/comparison.py | 1 + django/db/models/functions/datetime.py | 16 ++-- django/db/models/functions/math.py | 8 +- django/db/models/functions/mixins.py | 8 +- django/db/models/functions/text.py | 8 +- django/db/models/indexes.py | 8 +- django/db/models/lookups.py | 8 +- django/db/models/query.py | 20 +++-- django/db/models/query_utils.py | 1 + django/db/models/sql/compiler.py | 6 +- django/db/models/sql/datastructures.py | 1 + django/db/models/sql/query.py | 1 + django/db/models/sql/where.py | 1 + django/forms/models.py | 10 ++- django/forms/widgets.py | 22 +++-- django/http/multipartparser.py | 1 + django/http/request.py | 8 +- django/middleware/csrf.py | 1 + django/shortcuts.py | 1 + django/template/defaultfilters.py | 1 + django/template/defaulttags.py | 1 + django/template/engine.py | 8 +- django/template/smartif.py | 1 + django/test/html.py | 1 + django/urls/conf.py | 1 + django/urls/resolvers.py | 9 +- django/utils/archive.py | 1 + django/utils/cache.py | 1 + django/utils/crypto.py | 1 + django/utils/dateformat.py | 1 + django/utils/deconstruct.py | 8 +- django/utils/feedgenerator.py | 1 + django/utils/jslex.py | 1 + django/utils/regex_helper.py | 1 + django/utils/translation/__init__.py | 1 + django/utils/translation/trans_real.py | 1 + django/views/decorators/http.py | 1 + django/views/static.py | 1 + docs/_ext/djangodocs.py | 1 + docs/howto/csrf.txt | 3 +- docs/howto/custom-file-storage.txt | 3 +- docs/howto/custom-lookups.txt | 3 +- docs/howto/custom-management-commands.txt | 3 +- docs/howto/custom-model-fields.txt | 12 +-- docs/howto/custom-template-tags.txt | 9 +- docs/howto/error-reporting.txt | 9 +- .../writing-code/coding-style.txt | 9 +- .../writing-code/submitting-patches.txt | 6 +- docs/intro/tutorial04.txt | 3 +- docs/intro/tutorial07.txt | 3 +- docs/ref/contrib/admin/index.txt | 9 +- docs/ref/contrib/gis/feeds.txt | 12 +-- docs/ref/settings.txt | 3 +- docs/ref/utils.txt | 12 +-- docs/releases/1.0-porting-guide.txt | 3 +- docs/releases/1.10.txt | 3 +- docs/releases/1.2.txt | 30 +++---- docs/releases/5.0.txt | 3 +- docs/topics/async.txt | 15 ++-- docs/topics/auth/default.txt | 27 ++---- docs/topics/cache.txt | 30 +++---- docs/topics/checks.txt | 6 +- docs/topics/conditional-view-processing.txt | 15 ++-- docs/topics/db/fixtures.txt | 3 +- docs/topics/db/transactions.txt | 3 +- docs/topics/forms/modelforms.txt | 3 +- docs/topics/http/file-uploads.txt | 6 +- docs/topics/signals.txt | 3 +- docs/topics/testing/tools.txt | 21 ++--- tests/admin_changelist/test_date_hierarchy.py | 5 +- tests/admin_inlines/models.py | 1 + tests/admin_scripts/tests.py | 5 +- .../custom_has_permission_admin.py | 1 + tests/admin_views/customadmin.py | 1 + tests/aggregation_regress/tests.py | 5 +- tests/auth_tests/models/custom_permissions.py | 1 + tests/auth_tests/test_forms.py | 11 +-- tests/auth_tests/test_hashers.py | 15 ++-- tests/auth_tests/test_views.py | 6 +- tests/backends/base/test_base.py | 11 ++- tests/backends/test_utils.py | 1 + tests/backends/tests.py | 1 + tests/bash_completion/tests.py | 1 + tests/basic/models.py | 1 + tests/check_framework/test_security.py | 12 ++- tests/contenttypes_tests/test_management.py | 14 ++-- tests/contenttypes_tests/test_models.py | 5 +- tests/contenttypes_tests/test_views.py | 12 +-- tests/context_processors/tests.py | 1 + tests/custom_lookups/tests.py | 9 +- tests/db_functions/comparison/test_nullif.py | 8 +- .../datetime/test_extract_trunc.py | 8 +- tests/db_functions/models.py | 1 + tests/db_functions/text/test_md5.py | 8 +- tests/db_functions/text/test_sha1.py | 8 +- tests/db_functions/text/test_sha224.py | 8 +- tests/db_functions/text/test_sha256.py | 8 +- tests/db_functions/text/test_sha384.py | 10 ++- tests/db_functions/text/test_sha512.py | 10 ++- tests/db_utils/tests.py | 1 + tests/dbshell/test_sqlite.py | 11 ++- tests/distinct_on_fields/tests.py | 8 +- tests/expressions/models.py | 1 + tests/file_uploads/tests.py | 14 ++-- tests/file_uploads/uploadhandler.py | 1 + tests/files/tests.py | 35 ++++---- tests/force_insert_update/models.py | 1 + .../field_tests/test_decimalfield.py | 5 +- .../forms_tests/field_tests/test_filefield.py | 3 +- tests/forms_tests/tests/test_formsets.py | 9 +- tests/gis_tests/gdal_tests/test_raster.py | 5 +- tests/gis_tests/geogapp/tests.py | 1 + tests/gis_tests/test_data.py | 1 + tests/handlers/tests.py | 5 +- tests/httpwrappers/tests.py | 6 +- tests/invalid_models_tests/test_models.py | 82 +++++++++++-------- tests/m2m_and_m2o/models.py | 1 + tests/m2m_intermediary/models.py | 1 + tests/mail/tests.py | 5 +- tests/many_to_many/models.py | 1 + tests/many_to_one/models.py | 1 + tests/middleware/test_security.py | 12 ++- tests/middleware/tests.py | 6 +- tests/migrations/test_commands.py | 16 ++-- tests/migrations/test_executor.py | 6 +- tests/migrations/test_operations.py | 38 +++++---- tests/model_inheritance/models.py | 1 + tests/model_inheritance/tests.py | 8 +- tests/model_inheritance_regress/tests.py | 1 + tests/null_fk_ordering/models.py | 1 + tests/one_to_one/models.py | 1 + tests/order_with_respect_to/base_tests.py | 10 ++- tests/postgres_tests/fields.py | 1 + tests/postgres_tests/test_constraints.py | 5 +- tests/postgres_tests/test_search.py | 1 + tests/prefetch_related/tests.py | 5 +- tests/proxy_models/models.py | 1 + tests/queries/models.py | 1 + tests/requests_tests/test_accept_header.py | 12 +-- tests/save_delete_hooks/models.py | 1 + tests/schema/fields.py | 8 +- tests/schema/tests.py | 22 +++-- tests/serializers/models/base.py | 1 + tests/serializers/models/data.py | 1 + tests/serializers/models/natural.py | 1 + tests/serializers/test_data.py | 1 + tests/servers/tests.py | 1 + tests/sessions_tests/models.py | 1 + tests/signals/models.py | 1 + tests/template_tests/test_parser.py | 1 + tests/test_client/tests.py | 1 + tests/test_client_regress/tests.py | 1 + tests/test_runner/test_discover_runner.py | 7 +- tests/test_runner/tests.py | 80 ++++++++++-------- tests/transactions/models.py | 1 + tests/urlpatterns_reverse/tests.py | 1 + tests/urls.py | 1 - tests/utils_tests/test_datastructures.py | 1 + tests/utils_tests/test_jslex.py | 1 + tests/view_tests/tests/test_debug.py | 21 +++-- 235 files changed, 809 insertions(+), 602 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1c3571406fda..d6ea11e8e06f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/psf/black-pre-commit-mirror - rev: 23.12.1 + rev: 24.1.0 hooks: - id: black exclude: \.py-tpl$ @@ -9,7 +9,7 @@ repos: hooks: - id: blacken-docs additional_dependencies: - - black==23.12.1 + - black==24.1.0 files: 'docs/.*\.txt$' - repo: https://github.com/PyCQA/isort rev: 5.13.2 diff --git a/django/__main__.py b/django/__main__.py index 8b96e91ea855..741514384822 100644 --- a/django/__main__.py +++ b/django/__main__.py @@ -3,6 +3,7 @@ Example: python -m django check """ + from django.core import management if __name__ == "__main__": diff --git a/django/contrib/admin/filters.py b/django/contrib/admin/filters.py index 06dedf872794..675c4a5d4993 100644 --- a/django/contrib/admin/filters.py +++ b/django/contrib/admin/filters.py @@ -5,6 +5,7 @@ Each filter subclass knows how to display a filter for a field that passes a certain test -- e.g. being a DateField or ForeignKey. """ + import datetime from django.contrib.admin.exceptions import NotRegistered diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index e3703f586683..d97597fe66dd 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -1759,9 +1759,9 @@ def get_inline_formsets(self, request, formsets, inline_instances, obj=None): has_delete_permission = inline.has_delete_permission(request, obj) else: # Disable all edit-permissions, and override formset settings. - has_add_permission = ( - has_change_permission - ) = has_delete_permission = False + has_add_permission = has_change_permission = has_delete_permission = ( + False + ) formset.extra = formset.max_num = 0 has_view_permission = inline.has_view_permission(request, obj) prepopulated = dict(inline.get_prepopulated_fields(request, obj)) @@ -1896,9 +1896,11 @@ def _changeform_view(self, request, object_id, form_url, extra_context): form, list(fieldsets), # Clear prepopulated fields on a view-only form to avoid a crash. - self.get_prepopulated_fields(request, obj) - if add or self.has_change_permission(request, obj) - else {}, + ( + self.get_prepopulated_fields(request, obj) + if add or self.has_change_permission(request, obj) + else {} + ), readonly_fields, model_admin=self, ) diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index 2dcdf62afb28..0c32290b6ca1 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -171,9 +171,9 @@ def make_qs_param(t, n): "url_primary": cl.get_query_string({ORDER_VAR: ".".join(o_list_primary)}), "url_remove": cl.get_query_string({ORDER_VAR: ".".join(o_list_remove)}), "url_toggle": cl.get_query_string({ORDER_VAR: ".".join(o_list_toggle)}), - "class_attrib": format_html(' class="{}"', " ".join(th_classes)) - if th_classes - else "", + "class_attrib": ( + format_html(' class="{}"', " ".join(th_classes)) if th_classes else "" + ), } @@ -270,9 +270,11 @@ def link_in_col(is_first, field_name, cl): link_or_text = format_html( '{}', url, - format_html(' data-popup-opener="{}"', value) - if cl.is_popup - else "", + ( + format_html(' data-popup-opener="{}"', value) + if cl.is_popup + else "" + ), result_repr, ) diff --git a/django/contrib/admin/widgets.py b/django/contrib/admin/widgets.py index 3352e75e79e9..216b87671b15 100644 --- a/django/contrib/admin/widgets.py +++ b/django/contrib/admin/widgets.py @@ -1,6 +1,7 @@ """ Form Widget classes specific to the Django admin site. """ + import copy import json diff --git a/django/contrib/auth/base_user.py b/django/contrib/auth/base_user.py index ccfe19fcc1ab..0c9538d69d1f 100644 --- a/django/contrib/auth/base_user.py +++ b/django/contrib/auth/base_user.py @@ -2,6 +2,7 @@ This module allows importing AbstractBaseUser even when django.contrib.auth is not in INSTALLED_APPS. """ + import unicodedata from django.conf import settings diff --git a/django/contrib/auth/management/__init__.py b/django/contrib/auth/management/__init__.py index ad31a6e68fa7..b29a980cb2d5 100644 --- a/django/contrib/auth/management/__init__.py +++ b/django/contrib/auth/management/__init__.py @@ -1,6 +1,7 @@ """ Creates permissions for all installed apps that need permissions. """ + import getpass import unicodedata diff --git a/django/contrib/auth/management/commands/createsuperuser.py b/django/contrib/auth/management/commands/createsuperuser.py index 6d650cca67ee..75ef68ff6812 100644 --- a/django/contrib/auth/management/commands/createsuperuser.py +++ b/django/contrib/auth/management/commands/createsuperuser.py @@ -1,6 +1,7 @@ """ Management utility to create superusers. """ + import getpass import os import sys @@ -271,15 +272,19 @@ def _get_input_message(self, field, default=None): return "%s%s%s: " % ( capfirst(field.verbose_name), " (leave blank to use '%s')" % default if default else "", - " (%s.%s)" - % ( - field.remote_field.model._meta.object_name, - field.m2m_target_field_name() - if field.many_to_many - else field.remote_field.field_name, - ) - if field.remote_field - else "", + ( + " (%s.%s)" + % ( + field.remote_field.model._meta.object_name, + ( + field.m2m_target_field_name() + if field.many_to_many + else field.remote_field.field_name + ), + ) + if field.remote_field + else "" + ), ) @cached_property diff --git a/django/contrib/gis/db/backends/oracle/models.py b/django/contrib/gis/db/backends/oracle/models.py index f06f73148e92..af749c3435c9 100644 --- a/django/contrib/gis/db/backends/oracle/models.py +++ b/django/contrib/gis/db/backends/oracle/models.py @@ -7,6 +7,7 @@ For example, the `USER_SDO_GEOM_METADATA` is used for the GeometryColumns model and the `SDO_COORD_REF_SYS` is used for the SpatialRefSys model. """ + from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin diff --git a/django/contrib/gis/db/backends/oracle/operations.py b/django/contrib/gis/db/backends/oracle/operations.py index ed86985cf8d3..eb86dc39dee3 100644 --- a/django/contrib/gis/db/backends/oracle/operations.py +++ b/django/contrib/gis/db/backends/oracle/operations.py @@ -7,6 +7,7 @@ support for an internal JVM, and Java libraries are required to use the WKT constructors. """ + import re from django.contrib.gis.db import models diff --git a/django/contrib/gis/db/backends/postgis/adapter.py b/django/contrib/gis/db/backends/postgis/adapter.py index c95f9032538a..c9715e175671 100644 --- a/django/contrib/gis/db/backends/postgis/adapter.py +++ b/django/contrib/gis/db/backends/postgis/adapter.py @@ -1,6 +1,7 @@ """ This object provides quoting for GEOS geometries into PostgreSQL/PostGIS. """ + from django.contrib.gis.db.backends.postgis.pgraster import to_pgraster from django.contrib.gis.geos import GEOSGeometry from django.db.backends.postgresql.psycopg_any import sql diff --git a/django/contrib/gis/db/backends/postgis/const.py b/django/contrib/gis/db/backends/postgis/const.py index 2f4393d25e53..8bc16a1abb68 100644 --- a/django/contrib/gis/db/backends/postgis/const.py +++ b/django/contrib/gis/db/backends/postgis/const.py @@ -1,6 +1,7 @@ """ PostGIS to GDAL conversion constant definitions """ + # Lookup to convert pixel type values from GDAL to PostGIS GDAL_TO_POSTGIS = [None, 4, 6, 5, 8, 7, 10, 11, None, None, None, None] diff --git a/django/contrib/gis/db/backends/postgis/models.py b/django/contrib/gis/db/backends/postgis/models.py index b7b568274aa3..e35ef75ce989 100644 --- a/django/contrib/gis/db/backends/postgis/models.py +++ b/django/contrib/gis/db/backends/postgis/models.py @@ -1,6 +1,7 @@ """ The GeometryColumns and SpatialRefSys models for the PostGIS backend. """ + from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin from django.db import models diff --git a/django/contrib/gis/db/backends/spatialite/models.py b/django/contrib/gis/db/backends/spatialite/models.py index 7cc98ae1268a..0f5f7b55ef02 100644 --- a/django/contrib/gis/db/backends/spatialite/models.py +++ b/django/contrib/gis/db/backends/spatialite/models.py @@ -1,6 +1,7 @@ """ The GeometryColumns and SpatialRefSys models for the SpatiaLite backend. """ + from django.contrib.gis.db.backends.base.models import SpatialRefSysMixin from django.db import models diff --git a/django/contrib/gis/db/backends/spatialite/operations.py b/django/contrib/gis/db/backends/spatialite/operations.py index 8a3d84b5de62..3d10a53641dc 100644 --- a/django/contrib/gis/db/backends/spatialite/operations.py +++ b/django/contrib/gis/db/backends/spatialite/operations.py @@ -2,6 +2,7 @@ SQL functions reference lists: https://www.gaia-gis.it/gaia-sins/spatialite-sql-4.3.0.html """ + from django.contrib.gis.db import models from django.contrib.gis.db.backends.base.operations import BaseSpatialOperations from django.contrib.gis.db.backends.spatialite.adapter import SpatiaLiteAdapter diff --git a/django/contrib/gis/db/models/functions.py b/django/contrib/gis/db/models/functions.py index 419b64c5e8e6..acbaa5ffc0dc 100644 --- a/django/contrib/gis/db/models/functions.py +++ b/django/contrib/gis/db/models/functions.py @@ -127,9 +127,11 @@ def as_sqlite(self, compiler, connection, **extra_context): copy = self.copy() copy.set_source_expressions( [ - Value(float(expr.value)) - if hasattr(expr, "value") and isinstance(expr.value, Decimal) - else expr + ( + Value(float(expr.value)) + if hasattr(expr, "value") and isinstance(expr.value, Decimal) + else expr + ) for expr in copy.get_source_expressions() ] ) @@ -349,9 +351,9 @@ def as_postgresql(self, compiler, connection, **extra_context): def as_sqlite(self, compiler, connection, **extra_context): if self.geo_field.geodetic(connection): # SpatiaLite returns NULL instead of zero on geodetic coordinates - extra_context[ - "template" - ] = "COALESCE(%(function)s(%(expressions)s, %(spheroid)s), 0)" + extra_context["template"] = ( + "COALESCE(%(function)s(%(expressions)s, %(spheroid)s), 0)" + ) extra_context["spheroid"] = int(bool(self.spheroid)) return super().as_sql(compiler, connection, **extra_context) diff --git a/django/contrib/gis/db/models/proxy.py b/django/contrib/gis/db/models/proxy.py index 4db365dc16c1..b415e147fc60 100644 --- a/django/contrib/gis/db/models/proxy.py +++ b/django/contrib/gis/db/models/proxy.py @@ -5,6 +5,7 @@ Thanks to Robert Coup for providing this functionality (see #4322). """ + from django.db.models.query_utils import DeferredAttribute diff --git a/django/contrib/gis/db/models/sql/conversion.py b/django/contrib/gis/db/models/sql/conversion.py index be712319fb24..7802b2dd1ec9 100644 --- a/django/contrib/gis/db/models/sql/conversion.py +++ b/django/contrib/gis/db/models/sql/conversion.py @@ -2,6 +2,7 @@ This module holds simple classes to convert geospatial values from the database. """ + from decimal import Decimal from django.contrib.gis.measure import Area, Distance diff --git a/django/contrib/gis/gdal/__init__.py b/django/contrib/gis/gdal/__init__.py index 9ed6e3115689..e63808d39d9d 100644 --- a/django/contrib/gis/gdal/__init__.py +++ b/django/contrib/gis/gdal/__init__.py @@ -25,6 +25,7 @@ by setting `GDAL_LIBRARY_PATH` in your settings with the path to the GDAL C library on your system. """ + from django.contrib.gis.gdal.datasource import DataSource from django.contrib.gis.gdal.driver import Driver from django.contrib.gis.gdal.envelope import Envelope diff --git a/django/contrib/gis/gdal/datasource.py b/django/contrib/gis/gdal/datasource.py index 890077711734..2ce859ad1326 100644 --- a/django/contrib/gis/gdal/datasource.py +++ b/django/contrib/gis/gdal/datasource.py @@ -33,6 +33,7 @@ # OFTReal returns floats, all else returns string. val = field.value """ + from pathlib import Path from django.contrib.gis.gdal.base import GDALBase diff --git a/django/contrib/gis/gdal/envelope.py b/django/contrib/gis/gdal/envelope.py index 4c2c1e4a1ad0..05832bd7cc4c 100644 --- a/django/contrib/gis/gdal/envelope.py +++ b/django/contrib/gis/gdal/envelope.py @@ -10,6 +10,7 @@ | | Lower left (min_x, min_y) o----------+ """ + from ctypes import Structure, c_double from django.contrib.gis.gdal.error import GDALException diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py index f4ba5816a242..4c1f74d4b0a2 100644 --- a/django/contrib/gis/gdal/geometries.py +++ b/django/contrib/gis/gdal/geometries.py @@ -38,6 +38,7 @@ >>> print(gt1 == 3, gt1 == 'Polygon') # Equivalence works w/non-OGRGeomType objects True True """ + import sys import warnings from binascii import b2a_hex diff --git a/django/contrib/gis/gdal/prototypes/ds.py b/django/contrib/gis/gdal/prototypes/ds.py index e3ef2699e9b3..71148f1b5574 100644 --- a/django/contrib/gis/gdal/prototypes/ds.py +++ b/django/contrib/gis/gdal/prototypes/ds.py @@ -3,6 +3,7 @@ related data structures. OGR_Dr_*, OGR_DS_*, OGR_L_*, OGR_F_*, OGR_Fld_* routines are relevant here. """ + from ctypes import POINTER, c_char_p, c_double, c_int, c_long, c_uint, c_void_p from django.contrib.gis.gdal.envelope import OGREnvelope diff --git a/django/contrib/gis/gdal/prototypes/errcheck.py b/django/contrib/gis/gdal/prototypes/errcheck.py index 52bb7cb08300..d37e81cdf666 100644 --- a/django/contrib/gis/gdal/prototypes/errcheck.py +++ b/django/contrib/gis/gdal/prototypes/errcheck.py @@ -2,6 +2,7 @@ This module houses the error-checking routines used by the GDAL ctypes prototypes. """ + from ctypes import c_void_p, string_at from django.contrib.gis.gdal.error import GDALException, SRSException, check_err diff --git a/django/contrib/gis/gdal/prototypes/generation.py b/django/contrib/gis/gdal/prototypes/generation.py index 230e56f66557..4d34a96e70d3 100644 --- a/django/contrib/gis/gdal/prototypes/generation.py +++ b/django/contrib/gis/gdal/prototypes/generation.py @@ -2,6 +2,7 @@ This module contains functions that generate ctypes prototypes for the GDAL routines. """ + from ctypes import POINTER, c_bool, c_char_p, c_double, c_int, c_int64, c_void_p from functools import partial diff --git a/django/contrib/gis/gdal/prototypes/raster.py b/django/contrib/gis/gdal/prototypes/raster.py index 17ee4a1926a6..d1dd9ec4e2b7 100644 --- a/django/contrib/gis/gdal/prototypes/raster.py +++ b/django/contrib/gis/gdal/prototypes/raster.py @@ -2,6 +2,7 @@ This module houses the ctypes function prototypes for GDAL DataSource (raster) related data structures. """ + from ctypes import POINTER, c_bool, c_char_p, c_double, c_int, c_void_p from functools import partial diff --git a/django/contrib/gis/gdal/raster/const.py b/django/contrib/gis/gdal/raster/const.py index dccc9cfab4ba..a1ab62f37aa2 100644 --- a/django/contrib/gis/gdal/raster/const.py +++ b/django/contrib/gis/gdal/raster/const.py @@ -1,6 +1,7 @@ """ GDAL - Constant definitions """ + from ctypes import ( c_double, c_float, diff --git a/django/contrib/gis/gdal/srs.py b/django/contrib/gis/gdal/srs.py index 9417c6684d13..0a8d95c1fcbd 100644 --- a/django/contrib/gis/gdal/srs.py +++ b/django/contrib/gis/gdal/srs.py @@ -26,6 +26,7 @@ >>> print(srs.name) NAD83 / Texas South Central """ + from ctypes import byref, c_char_p, c_int from enum import IntEnum from types import NoneType diff --git a/django/contrib/gis/geos/__init__.py b/django/contrib/gis/geos/__init__.py index 27de1ca8e694..f50cd198565e 100644 --- a/django/contrib/gis/geos/__init__.py +++ b/django/contrib/gis/geos/__init__.py @@ -2,6 +2,7 @@ The GeoDjango GEOS module. Please consult the GeoDjango documentation for more details: https://docs.djangoproject.com/en/dev/ref/contrib/gis/geos/ """ + from .collections import ( # NOQA GeometryCollection, MultiLineString, diff --git a/django/contrib/gis/geos/collections.py b/django/contrib/gis/geos/collections.py index abfec8af3d7f..35262a56221b 100644 --- a/django/contrib/gis/geos/collections.py +++ b/django/contrib/gis/geos/collections.py @@ -2,6 +2,7 @@ This module houses the Geometry Collection objects: GeometryCollection, MultiPoint, MultiLineString, and MultiPolygon """ + from django.contrib.gis.geos import prototypes as capi from django.contrib.gis.geos.geometry import GEOSGeometry, LinearGeometryMixin from django.contrib.gis.geos.libgeos import GEOM_PTR diff --git a/django/contrib/gis/geos/coordseq.py b/django/contrib/gis/geos/coordseq.py index 0ff4ecb2e54d..15400e08fe4a 100644 --- a/django/contrib/gis/geos/coordseq.py +++ b/django/contrib/gis/geos/coordseq.py @@ -3,6 +3,7 @@ by GEOSGeometry to house the actual coordinates of the Point, LineString, and LinearRing geometries. """ + from ctypes import byref, c_byte, c_double, c_uint from django.contrib.gis.geos import prototypes as capi diff --git a/django/contrib/gis/geos/geometry.py b/django/contrib/gis/geos/geometry.py index 00b36af0a696..8bbe2c264ada 100644 --- a/django/contrib/gis/geos/geometry.py +++ b/django/contrib/gis/geos/geometry.py @@ -2,6 +2,7 @@ This module contains the 'base' GEOSGeometry object -- all GEOS Geometries inherit from this object. """ + import re from ctypes import addressof, byref, c_double diff --git a/django/contrib/gis/geos/io.py b/django/contrib/gis/geos/io.py index d7898065f08a..8dd3f289e658 100644 --- a/django/contrib/gis/geos/io.py +++ b/django/contrib/gis/geos/io.py @@ -3,6 +3,7 @@ objects. Specifically, this has Python implementations of WKB/WKT reader and writer classes. """ + from django.contrib.gis.geos.geometry import GEOSGeometry from django.contrib.gis.geos.prototypes.io import ( WKBWriter, diff --git a/django/contrib/gis/geos/libgeos.py b/django/contrib/gis/geos/libgeos.py index 1121b4f71549..b883c6c09020 100644 --- a/django/contrib/gis/geos/libgeos.py +++ b/django/contrib/gis/geos/libgeos.py @@ -6,6 +6,7 @@ This module also houses GEOS Pointer utilities, including get_pointer_arr(), and GEOM_PTR. """ + import logging import os from ctypes import CDLL, CFUNCTYPE, POINTER, Structure, c_char_p diff --git a/django/contrib/gis/geos/prototypes/errcheck.py b/django/contrib/gis/geos/prototypes/errcheck.py index a527f513a7a9..42b24c289138 100644 --- a/django/contrib/gis/geos/prototypes/errcheck.py +++ b/django/contrib/gis/geos/prototypes/errcheck.py @@ -1,6 +1,7 @@ """ Error checking functions for GEOS ctypes prototype functions. """ + from ctypes import c_void_p, string_at from django.contrib.gis.geos.error import GEOSException diff --git a/django/contrib/gis/geos/prototypes/misc.py b/django/contrib/gis/geos/prototypes/misc.py index fccd0ecc9e42..bd5859e79bb6 100644 --- a/django/contrib/gis/geos/prototypes/misc.py +++ b/django/contrib/gis/geos/prototypes/misc.py @@ -2,6 +2,7 @@ This module is for the miscellaneous GEOS routines, particularly the ones that return the area, distance, and length. """ + from ctypes import POINTER, c_double, c_int from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory diff --git a/django/contrib/gis/geos/prototypes/predicates.py b/django/contrib/gis/geos/prototypes/predicates.py index 32b790173a67..dd07cbfb269e 100644 --- a/django/contrib/gis/geos/prototypes/predicates.py +++ b/django/contrib/gis/geos/prototypes/predicates.py @@ -2,6 +2,7 @@ This module houses the GEOS ctypes prototype functions for the unary and binary predicate operations on geometries. """ + from ctypes import c_byte, c_char_p, c_double from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory diff --git a/django/contrib/gis/geos/prototypes/topology.py b/django/contrib/gis/geos/prototypes/topology.py index e61eae964a93..9323bb2d1606 100644 --- a/django/contrib/gis/geos/prototypes/topology.py +++ b/django/contrib/gis/geos/prototypes/topology.py @@ -2,6 +2,7 @@ This module houses the GEOS ctypes prototype functions for the topological operations on geometries. """ + from ctypes import c_double, c_int from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory diff --git a/django/contrib/gis/utils/__init__.py b/django/contrib/gis/utils/__init__.py index 12f032c66580..f42fa90226e4 100644 --- a/django/contrib/gis/utils/__init__.py +++ b/django/contrib/gis/utils/__init__.py @@ -1,6 +1,7 @@ """ This module contains useful utilities for GeoDjango. """ + from django.contrib.gis.utils.ogrinfo import ogrinfo from django.contrib.gis.utils.ogrinspect import mapping, ogrinspect from django.contrib.gis.utils.srs import add_srs_entry diff --git a/django/contrib/gis/utils/ogrinspect.py b/django/contrib/gis/utils/ogrinspect.py index 40ca0cb46151..76c8bfbcfab9 100644 --- a/django/contrib/gis/utils/ogrinspect.py +++ b/django/contrib/gis/utils/ogrinspect.py @@ -3,6 +3,7 @@ models for GeoDjango and/or mapping dictionaries for use with the `LayerMapping` utility. """ + from django.contrib.gis.gdal import DataSource from django.contrib.gis.gdal.field import ( OFTDate, diff --git a/django/contrib/postgres/search.py b/django/contrib/postgres/search.py index 936709c2f840..4d279857c662 100644 --- a/django/contrib/postgres/search.py +++ b/django/contrib/postgres/search.py @@ -116,9 +116,11 @@ def as_sql(self, compiler, connection, function=None, template=None): clone.set_source_expressions( [ Coalesce( - expression - if isinstance(expression.output_field, (CharField, TextField)) - else Cast(expression, TextField()), + ( + expression + if isinstance(expression.output_field, (CharField, TextField)) + else Cast(expression, TextField()) + ), Value(""), ) for expression in clone.get_source_expressions() diff --git a/django/contrib/sessions/base_session.py b/django/contrib/sessions/base_session.py index 603d2fe12cd4..8809dd36f778 100644 --- a/django/contrib/sessions/base_session.py +++ b/django/contrib/sessions/base_session.py @@ -2,6 +2,7 @@ This module allows importing AbstractBaseSession even when django.contrib.sessions is not in INSTALLED_APPS. """ + from django.db import models from django.utils.translation import gettext_lazy as _ diff --git a/django/contrib/staticfiles/views.py b/django/contrib/staticfiles/views.py index 83d04d4cec11..3fb2677322d0 100644 --- a/django/contrib/staticfiles/views.py +++ b/django/contrib/staticfiles/views.py @@ -3,6 +3,7 @@ development, and SHOULD NOT be used in a production setting. """ + import os import posixpath diff --git a/django/core/cache/__init__.py b/django/core/cache/__init__.py index eb7fa5b2e999..444d958e6882 100644 --- a/django/core/cache/__init__.py +++ b/django/core/cache/__init__.py @@ -12,6 +12,7 @@ See docs/topics/cache.txt for information on the public API. """ + from django.core import signals from django.core.cache.backends.base import ( BaseCache, diff --git a/django/core/exceptions.py b/django/core/exceptions.py index 2a2288ff4dc9..31c18ee7e161 100644 --- a/django/core/exceptions.py +++ b/django/core/exceptions.py @@ -1,6 +1,7 @@ """ Global Django exception and warning classes. """ + import operator from django.utils.hashable import make_hashable diff --git a/django/core/files/images.py b/django/core/files/images.py index 6a603f24fca4..7c1532ac8fdc 100644 --- a/django/core/files/images.py +++ b/django/core/files/images.py @@ -3,6 +3,7 @@ Requires Pillow as you might imagine. """ + import struct import zlib diff --git a/django/core/files/locks.py b/django/core/files/locks.py index c0f471f87da5..a7a7a22dce42 100644 --- a/django/core/files/locks.py +++ b/django/core/files/locks.py @@ -16,6 +16,7 @@ ... locks.lock(f, locks.LOCK_EX) ... f.write('Django') """ + import os __all__ = ("LOCK_EX", "LOCK_SH", "LOCK_NB", "lock", "unlock") diff --git a/django/core/files/uploadhandler.py b/django/core/files/uploadhandler.py index b6c185e8fc72..ab86f7fede58 100644 --- a/django/core/files/uploadhandler.py +++ b/django/core/files/uploadhandler.py @@ -1,6 +1,7 @@ """ Base file upload handler classes, and the built-in concrete subclasses """ + import os from io import BytesIO diff --git a/django/core/mail/__init__.py b/django/core/mail/__init__.py index dc63e8702c68..676326697b2e 100644 --- a/django/core/mail/__init__.py +++ b/django/core/mail/__init__.py @@ -1,6 +1,7 @@ """ Tools for sending email. """ + from django.conf import settings # Imported for backwards compatibility and for the sake diff --git a/django/core/mail/backends/console.py b/django/core/mail/backends/console.py index ee5dd2850433..2d7c778cc15e 100644 --- a/django/core/mail/backends/console.py +++ b/django/core/mail/backends/console.py @@ -1,6 +1,7 @@ """ Email backend that writes messages to console instead of sending them. """ + import sys import threading diff --git a/django/core/mail/backends/locmem.py b/django/core/mail/backends/locmem.py index 344350e89157..f5473da952c6 100644 --- a/django/core/mail/backends/locmem.py +++ b/django/core/mail/backends/locmem.py @@ -1,6 +1,7 @@ """ Backend for test environment. """ + import copy from django.core import mail diff --git a/django/core/mail/backends/smtp.py b/django/core/mail/backends/smtp.py index 1ee48269aee5..6820148ac122 100644 --- a/django/core/mail/backends/smtp.py +++ b/django/core/mail/backends/smtp.py @@ -1,4 +1,5 @@ """SMTP email backend class.""" + import smtplib import ssl import threading diff --git a/django/core/management/base.py b/django/core/management/base.py index 631c761c004a..4c47e1c6e513 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -2,6 +2,7 @@ Base classes for writing management commands (named commands which can be executed through ``django-admin`` or ``manage.py``). """ + import argparse import os import sys @@ -528,9 +529,11 @@ def check( if issues: visible_issue_count += len(issues) formatted = ( - self.style.ERROR(str(e)) - if e.is_serious() - else self.style.WARNING(str(e)) + ( + self.style.ERROR(str(e)) + if e.is_serious() + else self.style.WARNING(str(e)) + ) for e in issues ) formatted = "\n".join(sorted(formatted)) @@ -543,11 +546,15 @@ def check( if visible_issue_count: footer += "\n" footer += "System check identified %s (%s silenced)." % ( - "no issues" - if visible_issue_count == 0 - else "1 issue" - if visible_issue_count == 1 - else "%s issues" % visible_issue_count, + ( + "no issues" + if visible_issue_count == 0 + else ( + "1 issue" + if visible_issue_count == 1 + else "%s issues" % visible_issue_count + ) + ), len(all_issues) - visible_issue_count, ) diff --git a/django/core/serializers/base.py b/django/core/serializers/base.py index 20dffac05f7b..1fbca9244b08 100644 --- a/django/core/serializers/base.py +++ b/django/core/serializers/base.py @@ -1,6 +1,7 @@ """ Module for abstract serializer/unserializer base classes. """ + from io import StringIO from django.core.exceptions import ObjectDoesNotExist diff --git a/django/core/serializers/xml_serializer.py b/django/core/serializers/xml_serializer.py index 3f9955aa23c5..16b69770f6c3 100644 --- a/django/core/serializers/xml_serializer.py +++ b/django/core/serializers/xml_serializer.py @@ -1,6 +1,7 @@ """ XML serializer. """ + import json from xml.dom import pulldom from xml.sax import handler diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py index f01abf46b084..242083b85073 100644 --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -724,9 +724,9 @@ def add_field(self, model, field): namespace, _ = split_identifier(model._meta.db_table) definition += " " + self.sql_create_column_inline_fk % { "name": self._fk_constraint_name(model, field, constraint_suffix), - "namespace": "%s." % self.quote_name(namespace) - if namespace - else "", + "namespace": ( + "%s." % self.quote_name(namespace) if namespace else "" + ), "column": self.quote_name(field.column), "to_table": self.quote_name(to_table), "to_column": self.quote_name(to_column), @@ -1919,11 +1919,13 @@ def _constraint_names( """Return all constraint names matching the columns and conditions.""" if column_names is not None: column_names = [ - self.connection.introspection.identifier_converter( - truncate_name(name, self.connection.ops.max_name_length()) + ( + self.connection.introspection.identifier_converter( + truncate_name(name, self.connection.ops.max_name_length()) + ) + if self.connection.features.truncates_names + else self.connection.introspection.identifier_converter(name) ) - if self.connection.features.truncates_names - else self.connection.introspection.identifier_converter(name) for name in column_names ] with self.connection.cursor() as cursor: diff --git a/django/db/backends/ddl_references.py b/django/db/backends/ddl_references.py index 412d07a993db..75787ef8ab5c 100644 --- a/django/db/backends/ddl_references.py +++ b/django/db/backends/ddl_references.py @@ -2,6 +2,7 @@ Helpers to manipulate deferred DDL statements that might need to be adjusted or discarded within when executing a migration. """ + from copy import deepcopy diff --git a/django/db/backends/mysql/base.py b/django/db/backends/mysql/base.py index f36139881d00..b8d2d09c9478 100644 --- a/django/db/backends/mysql/base.py +++ b/django/db/backends/mysql/base.py @@ -3,6 +3,7 @@ Requires mysqlclient: https://pypi.org/project/mysqlclient/ """ + from django.core.exceptions import ImproperlyConfigured from django.db import IntegrityError from django.db.backends import utils as backend_utils diff --git a/django/db/backends/oracle/base.py b/django/db/backends/oracle/base.py index 2d91468d25b2..f626c4d2d41e 100644 --- a/django/db/backends/oracle/base.py +++ b/django/db/backends/oracle/base.py @@ -3,6 +3,7 @@ Requires oracledb: https://oracle.github.io/python-oracledb/ """ + import datetime import decimal import os diff --git a/django/db/backends/oracle/creation.py b/django/db/backends/oracle/creation.py index df773bff8c20..b0a51777286b 100644 --- a/django/db/backends/oracle/creation.py +++ b/django/db/backends/oracle/creation.py @@ -133,20 +133,20 @@ def _switch_to_test_user(self, parameters): credentials in the SAVED_USER/SAVED_PASSWORD key in the settings dict. """ real_settings = settings.DATABASES[self.connection.alias] - real_settings["SAVED_USER"] = self.connection.settings_dict[ - "SAVED_USER" - ] = self.connection.settings_dict["USER"] + real_settings["SAVED_USER"] = self.connection.settings_dict["SAVED_USER"] = ( + self.connection.settings_dict["USER"] + ) real_settings["SAVED_PASSWORD"] = self.connection.settings_dict[ "SAVED_PASSWORD" ] = self.connection.settings_dict["PASSWORD"] real_test_settings = real_settings["TEST"] test_settings = self.connection.settings_dict["TEST"] - real_test_settings["USER"] = real_settings["USER"] = test_settings[ - "USER" - ] = self.connection.settings_dict["USER"] = parameters["user"] - real_settings["PASSWORD"] = self.connection.settings_dict[ - "PASSWORD" - ] = parameters["password"] + real_test_settings["USER"] = real_settings["USER"] = test_settings["USER"] = ( + self.connection.settings_dict["USER"] + ) = parameters["user"] + real_settings["PASSWORD"] = self.connection.settings_dict["PASSWORD"] = ( + parameters["password"] + ) def set_as_test_mirror(self, primary_settings_dict): """ diff --git a/django/db/backends/postgresql/base.py b/django/db/backends/postgresql/base.py index cba89e0cc798..8349d8f31081 100644 --- a/django/db/backends/postgresql/base.py +++ b/django/db/backends/postgresql/base.py @@ -226,9 +226,11 @@ def get_connection_params(self): server_side_binding = conn_params.pop("server_side_binding", None) conn_params.setdefault( "cursor_factory", - ServerBindingCursor - if is_psycopg3 and server_side_binding is True - else Cursor, + ( + ServerBindingCursor + if is_psycopg3 and server_side_binding is True + else Cursor + ), ) if settings_dict["USER"]: conn_params["user"] = settings_dict["USER"] diff --git a/django/db/backends/postgresql/schema.py b/django/db/backends/postgresql/schema.py index 5dc93a27d05e..842830be3040 100644 --- a/django/db/backends/postgresql/schema.py +++ b/django/db/backends/postgresql/schema.py @@ -267,9 +267,9 @@ def _alter_column_collation_sql( % { "column": self.quote_name(new_field.column), "type": new_type, - "collation": " " + self._collate_sql(new_collation) - if new_collation - else "", + "collation": ( + " " + self._collate_sql(new_collation) if new_collation else "" + ), }, [], ) diff --git a/django/db/backends/sqlite3/_functions.py b/django/db/backends/sqlite3/_functions.py index 7e86950f7df1..0171b60f3872 100644 --- a/django/db/backends/sqlite3/_functions.py +++ b/django/db/backends/sqlite3/_functions.py @@ -1,6 +1,7 @@ """ Implementations of SQL functions for SQLite. """ + import functools import random import statistics diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index 08de0bad5aa1..10a296c992ce 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -1,6 +1,7 @@ """ SQLite backend for the sqlite3 module in the standard library. """ + import datetime import decimal import warnings diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py index 6b01403d18af..f000d9fcaa34 100644 --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -620,11 +620,12 @@ def generate_renamed_models(self): rem_model_state.app_label, rem_model_state.name_lower, ) - self.renamed_models_rel[ - renamed_models_rel_key - ] = "%s.%s" % ( - model_state.app_label, - model_state.name_lower, + self.renamed_models_rel[renamed_models_rel_key] = ( + "%s.%s" + % ( + model_state.app_label, + model_state.name_lower, + ) ) self.old_model_keys.remove((rem_app_label, rem_model_name)) self.old_model_keys.add((app_label, model_name)) @@ -1058,9 +1059,9 @@ def create_renamed_fields(self): (rem_app_label, rem_model_name, rem_field_name) ) old_field_keys.add((app_label, model_name, field_name)) - self.renamed_fields[ - app_label, model_name, field_name - ] = rem_field_name + self.renamed_fields[app_label, model_name, field_name] = ( + rem_field_name + ) break def generate_renamed_fields(self): diff --git a/django/db/migrations/loader.py b/django/db/migrations/loader.py index 81dcd06e04de..50445f31014e 100644 --- a/django/db/migrations/loader.py +++ b/django/db/migrations/loader.py @@ -131,11 +131,11 @@ def load_disk(self): "Migration %s in app %s has no Migration class" % (migration_name, app_config.label) ) - self.disk_migrations[ - app_config.label, migration_name - ] = migration_module.Migration( - migration_name, - app_config.label, + self.disk_migrations[app_config.label, migration_name] = ( + migration_module.Migration( + migration_name, + app_config.label, + ) ) def get_migration(self, app_label, name_prefix): diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index b24a8f6557b9..38c68f3ff359 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -56,11 +56,11 @@ def __init__(self, name, fields, options=None, bases=None, managers=None): _check_for_duplicates( "bases", ( - base._meta.label_lower - if hasattr(base, "_meta") - else base.lower() - if isinstance(base, str) - else base + ( + base._meta.label_lower + if hasattr(base, "_meta") + else base.lower() if isinstance(base, str) else base + ) for base in self.bases ), ) diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index 5ffd7fc07a74..42a2c80a5e21 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -524,11 +524,11 @@ def _get_concrete_models_mapping_and_proxy_models(self): if model_state.options.get("proxy"): proxy_models[model_key] = model_state # Find a concrete model for the proxy. - concrete_models_mapping[ - model_key - ] = self._find_concrete_model_from_proxy( - proxy_models, - model_state, + concrete_models_mapping[model_key] = ( + self._find_concrete_model_from_proxy( + proxy_models, + model_state, + ) ) else: concrete_models_mapping[model_key] = model_key diff --git a/django/db/models/aggregates.py b/django/db/models/aggregates.py index a778cd413b3e..0cbffacd1b97 100644 --- a/django/db/models/aggregates.py +++ b/django/db/models/aggregates.py @@ -1,6 +1,7 @@ """ Classes to represent the definitions of aggregate functions. """ + from django.core.exceptions import FieldError, FullResultSet from django.db.models.expressions import Case, Func, Star, Value, When from django.db.models.fields import IntegerField diff --git a/django/db/models/base.py b/django/db/models/base.py index 61925f63ea30..c1f78d0632b5 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -2265,9 +2265,11 @@ def _check_ordering(cls): opts = cls._meta valid_fields = set( chain.from_iterable( - (f.name, f.attname) - if not (f.auto_created and not f.concrete) - else (f.field.related_query_name(),) + ( + (f.name, f.attname) + if not (f.auto_created and not f.concrete) + else (f.field.related_query_name(),) + ) for f in chain(opts.fields, opts.related_objects) ) ) diff --git a/django/db/models/constants.py b/django/db/models/constants.py index a0c99c95fc7d..cec1b9b90f7a 100644 --- a/django/db/models/constants.py +++ b/django/db/models/constants.py @@ -1,6 +1,7 @@ """ Constants used across the ORM in general. """ + from enum import Enum # Separator used to split filter strings apart. diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index f25ad1af12cc..6d329ae85d38 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -204,9 +204,11 @@ def set_source_expressions(self, exprs): def _parse_expressions(self, *expressions): return [ - arg - if hasattr(arg, "resolve_expression") - else (F(arg) if isinstance(arg, str) else Value(arg)) + ( + arg + if hasattr(arg, "resolve_expression") + else (F(arg) if isinstance(arg, str) else Value(arg)) + ) for arg in expressions ] @@ -285,9 +287,11 @@ def resolve_expression( c.is_summary = summarize c.set_source_expressions( [ - expr.resolve_expression(query, allow_joins, reuse, summarize) - if expr - else None + ( + expr.resolve_expression(query, allow_joins, reuse, summarize) + if expr + else None + ) for expr in c.get_source_expressions() ] ) @@ -366,22 +370,16 @@ def convert_value(self): field = self.output_field internal_type = field.get_internal_type() if internal_type == "FloatField": - return ( - lambda value, expression, connection: None - if value is None - else float(value) + return lambda value, expression, connection: ( + None if value is None else float(value) ) elif internal_type.endswith("IntegerField"): - return ( - lambda value, expression, connection: None - if value is None - else int(value) + return lambda value, expression, connection: ( + None if value is None else int(value) ) elif internal_type == "DecimalField": - return ( - lambda value, expression, connection: None - if value is None - else Decimal(value) + return lambda value, expression, connection: ( + None if value is None else Decimal(value) ) return self._convert_value_noop @@ -432,9 +430,11 @@ def prefix_references(self, prefix): clone = self.copy() clone.set_source_expressions( [ - F(f"{prefix}{expr.name}") - if isinstance(expr, F) - else expr.prefix_references(prefix) + ( + F(f"{prefix}{expr.name}") + if isinstance(expr, F) + else expr.prefix_references(prefix) + ) for expr in self.get_source_expressions() ] ) diff --git a/django/db/models/fields/related_descriptors.py b/django/db/models/fields/related_descriptors.py index f5a81ab49c0e..62ddfc60b3d3 100644 --- a/django/db/models/fields/related_descriptors.py +++ b/django/db/models/fields/related_descriptors.py @@ -62,6 +62,7 @@ class Child(Model): If you're looking for ``ForwardManyToManyDescriptor`` or ``ReverseManyToManyDescriptor``, use ``ManyToManyDescriptor`` instead. """ + import warnings from asgiref.sync import sync_to_async diff --git a/django/db/models/fields/reverse_related.py b/django/db/models/fields/reverse_related.py index c74e92ba89f1..144cce6142c7 100644 --- a/django/db/models/fields/reverse_related.py +++ b/django/db/models/fields/reverse_related.py @@ -8,6 +8,7 @@ They also act as reverse fields for the purposes of the Meta API because they're the closest concept currently available. """ + import warnings from django.core import exceptions diff --git a/django/db/models/functions/comparison.py b/django/db/models/functions/comparison.py index ae41f1da95ea..6db81d6f4663 100644 --- a/django/db/models/functions/comparison.py +++ b/django/db/models/functions/comparison.py @@ -1,4 +1,5 @@ """Database functions that do comparisons or type conversions.""" + from django.db import NotSupportedError from django.db.models.expressions import Func, Value from django.db.models.fields import TextField diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py index fca211e065dc..9937e79f6ffe 100644 --- a/django/db/models/functions/datetime.py +++ b/django/db/models/functions/datetime.py @@ -318,9 +318,11 @@ def resolve_expression( "Cannot truncate DateField '%s' to %s." % ( field.name, - output_field.__class__.__name__ - if has_explicit_output_field - else "DateTimeField", + ( + output_field.__class__.__name__ + if has_explicit_output_field + else "DateTimeField" + ), ) ) elif isinstance(field, TimeField) and ( @@ -331,9 +333,11 @@ def resolve_expression( "Cannot truncate TimeField '%s' to %s." % ( field.name, - output_field.__class__.__name__ - if has_explicit_output_field - else "DateTimeField", + ( + output_field.__class__.__name__ + if has_explicit_output_field + else "DateTimeField" + ), ) ) return copy diff --git a/django/db/models/functions/math.py b/django/db/models/functions/math.py index 460143ba5af0..5fa4654a843d 100644 --- a/django/db/models/functions/math.py +++ b/django/db/models/functions/math.py @@ -47,9 +47,11 @@ def as_sqlite(self, compiler, connection, **extra_context): clone = self.copy() clone.set_source_expressions( [ - Cast(expression, FloatField()) - if isinstance(expression.output_field, IntegerField) - else expression + ( + Cast(expression, FloatField()) + if isinstance(expression.output_field, IntegerField) + else expression + ) for expression in self.get_source_expressions()[::-1] ] ) diff --git a/django/db/models/functions/mixins.py b/django/db/models/functions/mixins.py index 661eee1c134c..0f6f0a2aa8f5 100644 --- a/django/db/models/functions/mixins.py +++ b/django/db/models/functions/mixins.py @@ -14,9 +14,11 @@ def as_postgresql(self, compiler, connection, **extra_context): clone = self.copy() clone.set_source_expressions( [ - Cast(expression, output_field) - if isinstance(expression.output_field, FloatField) - else expression + ( + Cast(expression, output_field) + if isinstance(expression.output_field, FloatField) + else expression + ) for expression in self.get_source_expressions() ] ) diff --git a/django/db/models/functions/text.py b/django/db/models/functions/text.py index 392061880c72..df826ffdb5a1 100644 --- a/django/db/models/functions/text.py +++ b/django/db/models/functions/text.py @@ -89,9 +89,11 @@ def as_postgresql(self, compiler, connection, **extra_context): c = self.copy() c.set_source_expressions( [ - expression - if isinstance(expression.output_field, (CharField, TextField)) - else Cast(expression, TextField()) + ( + expression + if isinstance(expression.output_field, (CharField, TextField)) + else Cast(expression, TextField()) + ) for expression in c.get_source_expressions() ] ) diff --git a/django/db/models/indexes.py b/django/db/models/indexes.py index b5451f9e2410..0ddfefec3878 100644 --- a/django/db/models/indexes.py +++ b/django/db/models/indexes.py @@ -196,9 +196,11 @@ def __repr__(self): "" if not self.fields else " fields=%s" % repr(self.fields), "" if not self.expressions else " expressions=%s" % repr(self.expressions), "" if not self.name else " name=%s" % repr(self.name), - "" - if self.db_tablespace is None - else " db_tablespace=%s" % repr(self.db_tablespace), + ( + "" + if self.db_tablespace is None + else " db_tablespace=%s" % repr(self.db_tablespace) + ), "" if self.condition is None else " condition=%s" % self.condition, "" if not self.include else " include=%s" % repr(self.include), "" if not self.opclasses else " opclasses=%s" % repr(self.opclasses), diff --git a/django/db/models/lookups.py b/django/db/models/lookups.py index 4a6e2b324147..139875eed50b 100644 --- a/django/db/models/lookups.py +++ b/django/db/models/lookups.py @@ -273,9 +273,11 @@ def get_db_prep_lookup(self, value, connection): return ( "%s", [ - v - if hasattr(v, "as_sql") - else get_db_prep_value(v, connection, prepared=True) + ( + v + if hasattr(v, "as_sql") + else get_db_prep_value(v, connection, prepared=True) + ) for v in value ], ) diff --git a/django/db/models/query.py b/django/db/models/query.py index 61d400200056..b9e2d1f7e510 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -109,9 +109,11 @@ def __iter__(self): related_objs, operator.attrgetter( *[ - field.attname - if from_field == "self" - else queryset.model._meta.get_field(from_field).attname + ( + field.attname + if from_field == "self" + else queryset.model._meta.get_field(from_field).attname + ) for from_field in field.from_fields ] ), @@ -1391,9 +1393,7 @@ def values_list(self, *fields, flat=False, named=False): clone._iterable_class = ( NamedValuesListIterable if named - else FlatValuesListIterable - if flat - else ValuesListIterable + else FlatValuesListIterable if flat else ValuesListIterable ) return clone @@ -1659,9 +1659,11 @@ def _annotate(self, args, kwargs, select=True): if names is None: names = set( chain.from_iterable( - (field.name, field.attname) - if hasattr(field, "attname") - else (field.name,) + ( + (field.name, field.attname) + if hasattr(field, "attname") + else (field.name,) + ) for field in self.model._meta.get_fields() ) ) diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py index 4f3358eb8daa..e1041b965370 100644 --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -5,6 +5,7 @@ large and/or so that they can be used by other modules without getting into circular import difficulties. """ + import functools import inspect import logging diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index 10338259d589..9a0d2eb4e720 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -1224,9 +1224,9 @@ def get_related_klass_infos(klass_info, related_klass_infos): "field": f, "reverse": False, "local_setter": f.set_cached_value, - "remote_setter": f.remote_field.set_cached_value - if f.unique - else lambda x, y: None, + "remote_setter": ( + f.remote_field.set_cached_value if f.unique else lambda x, y: None + ), "from_parent": False, } related_klass_infos.append(klass_info) diff --git a/django/db/models/sql/datastructures.py b/django/db/models/sql/datastructures.py index 5eaa8c25f6bd..7c0c14a46e87 100644 --- a/django/db/models/sql/datastructures.py +++ b/django/db/models/sql/datastructures.py @@ -2,6 +2,7 @@ Useful auxiliary data structures for query construction. Not useful outside the SQL domain. """ + import warnings from django.core.exceptions import FullResultSet diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index ce4fafb1e2bc..6e8813b5e747 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -6,6 +6,7 @@ databases). The abstraction barrier only works one way: this module has to know all about the internals of models in order to get the information it needs. """ + import copy import difflib import functools diff --git a/django/db/models/sql/where.py b/django/db/models/sql/where.py index 8423fcb52892..0fded5cce32a 100644 --- a/django/db/models/sql/where.py +++ b/django/db/models/sql/where.py @@ -1,6 +1,7 @@ """ Code to manage the creation and SQL rendering of 'where' constraints. """ + import operator from functools import reduce diff --git a/django/forms/models.py b/django/forms/models.py index 6a2608c0b3c3..cd6986d72a79 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -2,6 +2,7 @@ Helper functions for creating Form classes from Django models and database field objects. """ + from itertools import chain from django.core.exceptions import ( @@ -830,9 +831,12 @@ def validate_unique(self): ) # Reduce Model instances to their primary key values row_data = tuple( - d._get_pk_val() if hasattr(d, "_get_pk_val") - # Prevent "unhashable type: list" errors later on. - else tuple(d) if isinstance(d, list) else d + ( + d._get_pk_val() + if hasattr(d, "_get_pk_val") + # Prevent "unhashable type: list" errors later on. + else tuple(d) if isinstance(d, list) else d + ) for d in row_data ) if row_data and None not in row_data: diff --git a/django/forms/widgets.py b/django/forms/widgets.py index 2c734052d5bd..4fae110d5ed8 100644 --- a/django/forms/widgets.py +++ b/django/forms/widgets.py @@ -101,9 +101,11 @@ def render(self): def render_js(self): return [ - path.__html__() - if hasattr(path, "__html__") - else format_html('', self.absolute_path(path)) + ( + path.__html__() + if hasattr(path, "__html__") + else format_html('', self.absolute_path(path)) + ) for path in self._js ] @@ -113,12 +115,14 @@ def render_css(self): media = sorted(self._css) return chain.from_iterable( [ - path.__html__() - if hasattr(path, "__html__") - else format_html( - '', - self.absolute_path(path), - medium, + ( + path.__html__() + if hasattr(path, "__html__") + else format_html( + '', + self.absolute_path(path), + medium, + ) ) for path in self._css[medium] ] diff --git a/django/http/multipartparser.py b/django/http/multipartparser.py index dfd406c35eac..58b8546be720 100644 --- a/django/http/multipartparser.py +++ b/django/http/multipartparser.py @@ -4,6 +4,7 @@ Exposes one class, ``MultiPartParser``, which feeds chunks of uploaded data to file upload handlers for processing. """ + import base64 import binascii import collections diff --git a/django/http/request.py b/django/http/request.py index fe15a173be58..4c27d576ba4b 100644 --- a/django/http/request.py +++ b/django/http/request.py @@ -170,9 +170,11 @@ def _get_full_path(self, path, force_append_slash): return "%s%s%s" % ( escape_uri_path(path), "/" if force_append_slash and not path.endswith("/") else "", - ("?" + iri_to_uri(self.META.get("QUERY_STRING", ""))) - if self.META.get("QUERY_STRING", "") - else "", + ( + ("?" + iri_to_uri(self.META.get("QUERY_STRING", ""))) + if self.META.get("QUERY_STRING", "") + else "" + ), ) def get_signed_cookie(self, key, default=RAISE_ERROR, salt="", max_age=None): diff --git a/django/middleware/csrf.py b/django/middleware/csrf.py index 2c0d2cc12061..f7943494ba22 100644 --- a/django/middleware/csrf.py +++ b/django/middleware/csrf.py @@ -4,6 +4,7 @@ This module provides a middleware that implements protection against request forgeries from other sites. """ + import logging import string from collections import defaultdict diff --git a/django/shortcuts.py b/django/shortcuts.py index 822e6107aca1..b8b5be1f5f54 100644 --- a/django/shortcuts.py +++ b/django/shortcuts.py @@ -3,6 +3,7 @@ of MVC. In other words, these functions/classes introduce controlled coupling for convenience's sake. """ + from django.http import ( Http404, HttpResponse, diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index 1e1bdbc5c90a..a08ce2710dca 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -1,4 +1,5 @@ """Default variable filters.""" + import random as random_module import re import types diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index 40c2917f561e..dd0a6b3579e2 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -1,4 +1,5 @@ """Default tags used by the template system, available to all templates.""" + import re import sys import warnings diff --git a/django/template/engine.py b/django/template/engine.py index f2215c0e4e9c..9882d3a16d17 100644 --- a/django/template/engine.py +++ b/django/template/engine.py @@ -70,9 +70,11 @@ def __repr__(self): self.__class__.__qualname__, "" if not self.dirs else " dirs=%s" % repr(self.dirs), self.app_dirs, - "" - if not self.context_processors - else " context_processors=%s" % repr(self.context_processors), + ( + "" + if not self.context_processors + else " context_processors=%s" % repr(self.context_processors) + ), self.debug, repr(self.loaders), repr(self.string_if_invalid), diff --git a/django/template/smartif.py b/django/template/smartif.py index 5b15a5a4765e..0a917c2aaa4b 100644 --- a/django/template/smartif.py +++ b/django/template/smartif.py @@ -1,6 +1,7 @@ """ Parser and utilities for the smart 'if' tag """ + # Using a simple top down parser, as described here: # http://effbot.org/zone/simple-top-down-parsing.htm. # 'led' = left denotation diff --git a/django/test/html.py b/django/test/html.py index 6da79d6fb242..33d1d4dafb43 100644 --- a/django/test/html.py +++ b/django/test/html.py @@ -1,4 +1,5 @@ """Compare two HTML documents.""" + import html from html.parser import HTMLParser diff --git a/django/urls/conf.py b/django/urls/conf.py index 40708028a388..bb61063d7708 100644 --- a/django/urls/conf.py +++ b/django/urls/conf.py @@ -1,4 +1,5 @@ """Functions for use in URLsconfs.""" + from functools import partial from importlib import import_module diff --git a/django/urls/resolvers.py b/django/urls/resolvers.py index 89ae18694cdf..3607c84228a6 100644 --- a/django/urls/resolvers.py +++ b/django/urls/resolvers.py @@ -5,6 +5,7 @@ a string) and returns a ResolverMatch object which provides access to all attributes of the resolved URL match. """ + import functools import inspect import re @@ -91,9 +92,11 @@ def __repr__(self): self.app_names, self.namespaces, self.route, - f", captured_kwargs={self.captured_kwargs!r}" - if self.captured_kwargs - else "", + ( + f", captured_kwargs={self.captured_kwargs!r}" + if self.captured_kwargs + else "" + ), f", extra_kwargs={self.extra_kwargs!r}" if self.extra_kwargs else "", ) ) diff --git a/django/utils/archive.py b/django/utils/archive.py index 71ec2d00155d..56f34c00386d 100644 --- a/django/utils/archive.py +++ b/django/utils/archive.py @@ -21,6 +21,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ + import os import shutil import stat diff --git a/django/utils/cache.py b/django/utils/cache.py index cf797d0279a4..3b014fbe5141 100644 --- a/django/utils/cache.py +++ b/django/utils/cache.py @@ -14,6 +14,7 @@ An example: i18n middleware would need to distinguish caches by the "Accept-language" header. """ + import time from collections import defaultdict from hashlib import md5 diff --git a/django/utils/crypto.py b/django/utils/crypto.py index 1c0e7001c649..5134b854d635 100644 --- a/django/utils/crypto.py +++ b/django/utils/crypto.py @@ -1,6 +1,7 @@ """ Django's standard crypto functions and utilities. """ + import hashlib import hmac import secrets diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py index a6c315e4cf24..a3274b901c33 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -10,6 +10,7 @@ 7th October 2003 11:39 >>> """ + import calendar from datetime import date, datetime, time from email.utils import format_datetime as format_datetime_rfc5322 diff --git a/django/utils/deconstruct.py b/django/utils/deconstruct.py index f8754c197418..2e5463a651d9 100644 --- a/django/utils/deconstruct.py +++ b/django/utils/deconstruct.py @@ -42,9 +42,11 @@ def deconstruct(obj): "#serializing-values" % (name, module_name, get_docs_version()) ) return ( - path - if path and type(obj) is klass - else f"{obj.__class__.__module__}.{name}", + ( + path + if path and type(obj) is klass + else f"{obj.__class__.__module__}.{name}" + ), obj._constructor_args[0], obj._constructor_args[1], ) diff --git a/django/utils/feedgenerator.py b/django/utils/feedgenerator.py index 31ca9a2db9af..3bd456ca687a 100644 --- a/django/utils/feedgenerator.py +++ b/django/utils/feedgenerator.py @@ -21,6 +21,7 @@ For definitions of the different versions of RSS, see: https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss """ + import datetime import email from io import StringIO diff --git a/django/utils/jslex.py b/django/utils/jslex.py index 93a1a2e972fc..fc46a686c7dc 100644 --- a/django/utils/jslex.py +++ b/django/utils/jslex.py @@ -1,4 +1,5 @@ """JsLex: a lexer for JavaScript""" + # Originally from https://bitbucket.org/ned/jslex import re diff --git a/django/utils/regex_helper.py b/django/utils/regex_helper.py index 9ee82e1a9b77..b71298e3990f 100644 --- a/django/utils/regex_helper.py +++ b/django/utils/regex_helper.py @@ -5,6 +5,7 @@ This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ + import re from django.utils.functional import SimpleLazyObject diff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py index 0b3f78e48666..0618f0215947 100644 --- a/django/utils/translation/__init__.py +++ b/django/utils/translation/__init__.py @@ -1,6 +1,7 @@ """ Internationalization support. """ + from contextlib import ContextDecorator from decimal import ROUND_UP, Decimal diff --git a/django/utils/translation/trans_real.py b/django/utils/translation/trans_real.py index 872c80b00f73..a629528717f1 100644 --- a/django/utils/translation/trans_real.py +++ b/django/utils/translation/trans_real.py @@ -1,4 +1,5 @@ """Translation helper functions.""" + import functools import gettext as gettext_module import os diff --git a/django/views/decorators/http.py b/django/views/decorators/http.py index 5d5dcbc7906f..a4c1ebc31ebb 100644 --- a/django/views/decorators/http.py +++ b/django/views/decorators/http.py @@ -1,6 +1,7 @@ """ Decorators for views based on HTTP headers. """ + import datetime from functools import wraps diff --git a/django/views/static.py b/django/views/static.py index df46c53093e0..b24f0e30f9ee 100644 --- a/django/views/static.py +++ b/django/views/static.py @@ -2,6 +2,7 @@ Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ + import mimetypes import posixpath from pathlib import Path diff --git a/docs/_ext/djangodocs.py b/docs/_ext/djangodocs.py index 7d55cb033360..77e24ff0eb68 100644 --- a/docs/_ext/djangodocs.py +++ b/docs/_ext/djangodocs.py @@ -1,6 +1,7 @@ """ Sphinx plugins for Django documentation. """ + import json import os import re diff --git a/docs/howto/csrf.txt b/docs/howto/csrf.txt index 07f2e20a1c22..d40f4b4cb40e 100644 --- a/docs/howto/csrf.txt +++ b/docs/howto/csrf.txt @@ -208,8 +208,7 @@ will require a CSRF token to be inserted you should use the @cache_page(60 * 15) @csrf_protect - def my_view(request): - ... + def my_view(request): ... If you are using class-based views, you can refer to :ref:`Decorating class-based views`. diff --git a/docs/howto/custom-file-storage.txt b/docs/howto/custom-file-storage.txt index b7bd22d9c101..3cc96cce84c9 100644 --- a/docs/howto/custom-file-storage.txt +++ b/docs/howto/custom-file-storage.txt @@ -14,8 +14,7 @@ You'll need to follow these steps: from django.core.files.storage import Storage - class MyStorage(Storage): - ... + class MyStorage(Storage): ... #. Django must be able to instantiate your storage system without any arguments. This means that any settings should be taken from ``django.conf.settings``:: diff --git a/docs/howto/custom-lookups.txt b/docs/howto/custom-lookups.txt index 61ec9295ebee..fc8e92889063 100644 --- a/docs/howto/custom-lookups.txt +++ b/docs/howto/custom-lookups.txt @@ -53,8 +53,7 @@ Lookup registration can also be done using a decorator pattern:: @Field.register_lookup - class NotEqualLookup(Lookup): - ... + class NotEqualLookup(Lookup): ... We can now use ``foo__ne`` for any field ``foo``. You will need to ensure that this registration happens before you try to create any querysets using it. You diff --git a/docs/howto/custom-management-commands.txt b/docs/howto/custom-management-commands.txt index 8bdfb1e38b9d..b472f092e930 100644 --- a/docs/howto/custom-management-commands.txt +++ b/docs/howto/custom-management-commands.txt @@ -146,8 +146,7 @@ decorator on your :meth:`~BaseCommand.handle` method:: ... @no_translations - def handle(self, *args, **options): - ... + def handle(self, *args, **options): ... Since translation deactivation requires access to configured settings, the decorator can't be used for commands that work without configured settings. diff --git a/docs/howto/custom-model-fields.txt b/docs/howto/custom-model-fields.txt index 1e7ac4f0bad4..b4a153789688 100644 --- a/docs/howto/custom-model-fields.txt +++ b/docs/howto/custom-model-fields.txt @@ -338,24 +338,20 @@ Changing a custom field's base class You can't change the base class of a custom field because Django won't detect the change and make a migration for it. For example, if you start with:: - class CustomCharField(models.CharField): - ... + class CustomCharField(models.CharField): ... and then decide that you want to use ``TextField`` instead, you can't change the subclass like this:: - class CustomCharField(models.TextField): - ... + class CustomCharField(models.TextField): ... Instead, you must create a new custom field class and update your models to reference it:: - class CustomCharField(models.CharField): - ... + class CustomCharField(models.CharField): ... - class CustomTextField(models.TextField): - ... + class CustomTextField(models.TextField): ... As discussed in :ref:`removing fields `, you must retain the original ``CustomCharField`` class as long as you have diff --git a/docs/howto/custom-template-tags.txt b/docs/howto/custom-template-tags.txt index c7909c8a4bbf..15bef9b5fbbc 100644 --- a/docs/howto/custom-template-tags.txt +++ b/docs/howto/custom-template-tags.txt @@ -561,8 +561,7 @@ template loader, we'd register the tag like this:: # Here, register is a django.template.Library instance, as before @register.inclusion_tag("results.html") - def show_results(poll): - ... + def show_results(poll): ... Alternatively it is possible to register the inclusion tag using a :class:`django.template.Template` instance:: @@ -917,13 +916,11 @@ The ``tag()`` method takes two arguments: As with filter registration, it is also possible to use this as a decorator:: @register.tag(name="current_time") - def do_current_time(parser, token): - ... + def do_current_time(parser, token): ... @register.tag - def shout(parser, token): - ... + def shout(parser, token): ... If you leave off the ``name`` argument, as in the second example above, Django will use the function's name as the tag name. diff --git a/docs/howto/error-reporting.txt b/docs/howto/error-reporting.txt index 84fe3cb768d6..b36f88409690 100644 --- a/docs/howto/error-reporting.txt +++ b/docs/howto/error-reporting.txt @@ -177,8 +177,7 @@ filtered out of error reports in a production environment (that is, where do not provide any argument to the ``sensitive_variables`` decorator:: @sensitive_variables() - def my_function(): - ... + def my_function(): ... .. admonition:: When using multiple decorators @@ -191,8 +190,7 @@ filtered out of error reports in a production environment (that is, where @sensitive_variables("user", "pw", "cc") @some_decorator @another_decorator - def process_info(user): - ... + def process_info(user): ... .. versionchanged:: 5.0 @@ -229,8 +227,7 @@ filtered out of error reports in a production environment (that is, where do not provide any argument to the ``sensitive_post_parameters`` decorator:: @sensitive_post_parameters() - def my_view(request): - ... + def my_view(request): ... All POST parameters are systematically filtered out of error reports for certain :mod:`django.contrib.auth.views` views (``login``, diff --git a/docs/internals/contributing/writing-code/coding-style.txt b/docs/internals/contributing/writing-code/coding-style.txt index 6871d43d7be5..49b69bf066f1 100644 --- a/docs/internals/contributing/writing-code/coding-style.txt +++ b/docs/internals/contributing/writing-code/coding-style.txt @@ -201,8 +201,7 @@ Imports CONSTANT = "foo" - class Example: - ... + class Example: ... * Use convenience imports whenever available. For example, do this :: @@ -239,13 +238,11 @@ View style Do this:: - def my_view(request, foo): - ... + def my_view(request, foo): ... Don't do this:: - def my_view(req, foo): - ... + def my_view(req, foo): ... Model style =========== diff --git a/docs/internals/contributing/writing-code/submitting-patches.txt b/docs/internals/contributing/writing-code/submitting-patches.txt index be031f1f68c6..72c986cfc729 100644 --- a/docs/internals/contributing/writing-code/submitting-patches.txt +++ b/docs/internals/contributing/writing-code/submitting-patches.txt @@ -190,8 +190,7 @@ level: @ignore_warnings(category=RemovedInDjangoXXWarning) - def test_foo(self): - ... + def test_foo(self): ... #) For an entire test case:: @@ -200,8 +199,7 @@ level: @ignore_warnings(category=RemovedInDjangoXXWarning) - class MyDeprecatedTests(unittest.TestCase): - ... + class MyDeprecatedTests(unittest.TestCase): ... You should also add a test for the deprecation warning:: diff --git a/docs/intro/tutorial04.txt b/docs/intro/tutorial04.txt index 13a76188bb94..65dc132a947a 100644 --- a/docs/intro/tutorial04.txt +++ b/docs/intro/tutorial04.txt @@ -309,7 +309,8 @@ views and use Django's generic views instead. To do so, open the def vote(request, question_id): - ... # same as above, no changes needed. + # same as above, no changes needed. + ... Each generic view needs to know what model it will be acting upon. This is provided using either the ``model`` attribute (in this example, ``model = diff --git a/docs/intro/tutorial07.txt b/docs/intro/tutorial07.txt index 9cdadbe28692..8cb5dd5d5a2b 100644 --- a/docs/intro/tutorial07.txt +++ b/docs/intro/tutorial07.txt @@ -174,8 +174,7 @@ tabular way of displaying inline related objects. To use it, change the .. code-block:: python :caption: ``polls/admin.py`` - class ChoiceInline(admin.TabularInline): - ... + class ChoiceInline(admin.TabularInline): ... With that ``TabularInline`` (instead of ``StackedInline``), the related objects are displayed in a more compact, table-based format: diff --git a/docs/ref/contrib/admin/index.txt b/docs/ref/contrib/admin/index.txt index 23cfa833e06a..e85ba9c36af1 100644 --- a/docs/ref/contrib/admin/index.txt +++ b/docs/ref/contrib/admin/index.txt @@ -751,8 +751,7 @@ subclass:: like:: @admin.display(ordering="-first_name") - def colored_first_name(self): - ... + def colored_first_name(self): ... The ``ordering`` argument supports query lookups to sort by values on related models. This example includes an "author first name" column in @@ -3128,8 +3127,7 @@ returns a site instance. from django.contrib import admin - class MyAdminSite(admin.AdminSite): - ... + class MyAdminSite(admin.AdminSite): ... .. code-block:: python :caption: ``myproject/apps.py`` @@ -3467,5 +3465,4 @@ The ``staff_member_required`` decorator @staff_member_required - def my_view(request): - ... + def my_view(request): ... diff --git a/docs/ref/contrib/gis/feeds.txt b/docs/ref/contrib/gis/feeds.txt index 9ae9d4f03a4b..3f17a6857416 100644 --- a/docs/ref/contrib/gis/feeds.txt +++ b/docs/ref/contrib/gis/feeds.txt @@ -40,18 +40,14 @@ API Reference item_geometry = ... # Also a function with no arguments - def geometry(self): - ... + def geometry(self): ... - def item_geometry(self): - ... + def item_geometry(self): ... # And as a function with a single argument - def geometry(self, obj): - ... + def geometry(self, obj): ... - def item_geometry(self, item): - ... + def item_geometry(self, item): ... .. method:: geometry(obj) diff --git a/docs/ref/settings.txt b/docs/ref/settings.txt index eee1c66d5695..9db029cc60c6 100644 --- a/docs/ref/settings.txt +++ b/docs/ref/settings.txt @@ -422,8 +422,7 @@ A dotted path to the view function to be used when an incoming request is rejected by the :doc:`CSRF protection `. The function should have this signature:: - def csrf_failure(request, reason=""): - ... + def csrf_failure(request, reason=""): ... where ``reason`` is a short message (intended for developers or logging, not for end users) indicating the reason the request was rejected. It should return diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt index 8ebb4f511669..3e357cba1717 100644 --- a/docs/ref/utils.txt +++ b/docs/ref/utils.txt @@ -469,8 +469,7 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004 class Person(models.Model): @cached_property - def friends(self): - ... + def friends(self): ... Note that as the method is now a property, in Python code it will need to be accessed appropriately:: @@ -552,8 +551,7 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004 # Or more succinctly: @keep_lazy(str) - def fancy_utility_function(s, *args, **kwargs): - ... + def fancy_utility_function(s, *args, **kwargs): ... The ``keep_lazy()`` decorator takes a number of extra arguments (``*args``) specifying the type(s) that the original function can return. A common @@ -578,14 +576,12 @@ https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004 # Our previous example was: @keep_lazy(str) - def fancy_utility_function(s, *args, **kwargs): - ... + def fancy_utility_function(s, *args, **kwargs): ... # Which can be rewritten as: @keep_lazy_text - def fancy_utility_function(s, *args, **kwargs): - ... + def fancy_utility_function(s, *args, **kwargs): ... ``django.utils.html`` ===================== diff --git a/docs/releases/1.0-porting-guide.txt b/docs/releases/1.0-porting-guide.txt index f0ed8f41690b..145334c2383f 100644 --- a/docs/releases/1.0-porting-guide.txt +++ b/docs/releases/1.0-porting-guide.txt @@ -144,8 +144,7 @@ example: Old (0.96):: - class Parent(models.Model): - ... + class Parent(models.Model): ... class Child(models.Model): diff --git a/docs/releases/1.10.txt b/docs/releases/1.10.txt index b5213ee20723..d98fad2c6623 100644 --- a/docs/releases/1.10.txt +++ b/docs/releases/1.10.txt @@ -732,8 +732,7 @@ custom lookup for it. For example:: from django.db.models.lookups import Exact - class MyField(Field): - ... + class MyField(Field): ... class MyFieldExact(Exact): diff --git a/docs/releases/1.2.txt b/docs/releases/1.2.txt index de3ed69a70ac..526bb1d66e22 100644 --- a/docs/releases/1.2.txt +++ b/docs/releases/1.2.txt @@ -455,17 +455,13 @@ database-compatible values. A custom field might look something like:: class CustomModelField(models.Field): ... - def db_type(self): - ... + def db_type(self): ... - def get_db_prep_save(self, value): - ... + def get_db_prep_save(self, value): ... - def get_db_prep_value(self, value): - ... + def get_db_prep_value(self, value): ... - def get_db_prep_lookup(self, lookup_type, value): - ... + def get_db_prep_lookup(self, lookup_type, value): ... In 1.2, these three methods have undergone a change in prototype, and two extra methods have been introduced:: @@ -473,23 +469,17 @@ two extra methods have been introduced:: class CustomModelField(models.Field): ... - def db_type(self, connection): - ... + def db_type(self, connection): ... - def get_prep_value(self, value): - ... + def get_prep_value(self, value): ... - def get_prep_lookup(self, lookup_type, value): - ... + def get_prep_lookup(self, lookup_type, value): ... - def get_db_prep_save(self, value, connection): - ... + def get_db_prep_save(self, value, connection): ... - def get_db_prep_value(self, value, connection, prepared=False): - ... + def get_db_prep_value(self, value, connection, prepared=False): ... - def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): - ... + def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False): ... These changes are required to support multiple databases -- ``db_type`` and ``get_db_prep_*`` can no longer make any assumptions diff --git a/docs/releases/5.0.txt b/docs/releases/5.0.txt index 746eaae83673..6b18bace4f45 100644 --- a/docs/releases/5.0.txt +++ b/docs/releases/5.0.txt @@ -521,8 +521,7 @@ For example:: Should become:: - class Char32UUIDField(models.UUIDField): - ... + class Char32UUIDField(models.UUIDField): ... class MyModel(models.Model): diff --git a/docs/topics/async.txt b/docs/topics/async.txt index 6c9d35b53326..87550ff46dea 100644 --- a/docs/topics/async.txt +++ b/docs/topics/async.txt @@ -111,13 +111,11 @@ For example:: @never_cache - def my_sync_view(request): - ... + def my_sync_view(request): ... @never_cache - async def my_async_view(request): - ... + async def my_async_view(request): ... Queries & the ORM ----------------- @@ -294,16 +292,14 @@ as either a direct wrapper or a decorator:: from asgiref.sync import async_to_sync - async def get_data(): - ... + async def get_data(): ... sync_get_data = async_to_sync(get_data) @async_to_sync - async def get_other_data(): - ... + async def get_other_data(): ... The async function is run in the event loop for the current thread, if one is present. If there is no current event loop, a new event loop is spun up @@ -334,8 +330,7 @@ as either a direct wrapper or a decorator:: @sync_to_async - def sync_function(): - ... + def sync_function(): ... Threadlocals and contextvars values are preserved across the boundary in both directions. diff --git a/docs/topics/auth/default.txt b/docs/topics/auth/default.txt index 75d33b5e7ee0..de2bc51cda55 100644 --- a/docs/topics/auth/default.txt +++ b/docs/topics/auth/default.txt @@ -553,8 +553,7 @@ The ``login_required`` decorator @login_required - def my_view(request): - ... + def my_view(request): ... :func:`~django.contrib.auth.decorators.login_required` does the following: @@ -575,8 +574,7 @@ The ``login_required`` decorator @login_required(redirect_field_name="my_redirect_field") - def my_view(request): - ... + def my_view(request): ... Note that if you provide a value to ``redirect_field_name``, you will most likely need to customize your login template as well, since the template @@ -590,8 +588,7 @@ The ``login_required`` decorator @login_required(login_url="/accounts/login/") - def my_view(request): - ... + def my_view(request): ... Note that if you don't specify the ``login_url`` parameter, you'll need to ensure that the :setting:`settings.LOGIN_URL ` and your login @@ -688,8 +685,7 @@ email in the desired domain and if not, redirects to the login page:: @user_passes_test(email_check) - def my_view(request): - ... + def my_view(request): ... :func:`~django.contrib.auth.decorators.user_passes_test` takes a required argument: a callable that takes a @@ -716,8 +712,7 @@ email in the desired domain and if not, redirects to the login page:: For example:: @user_passes_test(email_check, login_url="/login/") - def my_view(request): - ... + def my_view(request): ... .. currentmodule:: django.contrib.auth.mixins @@ -761,8 +756,7 @@ email in the desired domain and if not, redirects to the login page:: return self.request.user.username.startswith("django") - class MyView(TestMixin1, TestMixin2, View): - ... + class MyView(TestMixin1, TestMixin2, View): ... If ``TestMixin1`` would call ``super()`` and take that result into account, ``TestMixin1`` wouldn't work standalone anymore. @@ -782,8 +776,7 @@ The ``permission_required`` decorator @permission_required("polls.add_choice") - def my_view(request): - ... + def my_view(request): ... Just like the :meth:`~django.contrib.auth.models.User.has_perm` method, permission names take the form ``"."`` @@ -800,8 +793,7 @@ The ``permission_required`` decorator @permission_required("polls.add_choice", login_url="/loginpage/") - def my_view(request): - ... + def my_view(request): ... As in the :func:`~django.contrib.auth.decorators.login_required` decorator, ``login_url`` defaults to :setting:`settings.LOGIN_URL `. @@ -820,8 +812,7 @@ The ``permission_required`` decorator @login_required @permission_required("polls.add_choice", raise_exception=True) - def my_view(request): - ... + def my_view(request): ... This also avoids a redirect loop when :class:`.LoginView`'s ``redirect_authenticated_user=True`` and the logged-in user doesn't have diff --git a/docs/topics/cache.txt b/docs/topics/cache.txt index 880f606aaef1..6625b6946cfe 100644 --- a/docs/topics/cache.txt +++ b/docs/topics/cache.txt @@ -668,8 +668,7 @@ decorator that will automatically cache the view's response for you:: @cache_page(60 * 15) - def my_view(request): - ... + def my_view(request): ... ``cache_page`` takes a single argument: the cache timeout, in seconds. In the above example, the result of the ``my_view()`` view will be cached for 15 @@ -699,8 +698,7 @@ which directs the decorator to use a specific cache (from your want:: @cache_page(60 * 15, cache="special_cache") - def my_view(request): - ... + def my_view(request): ... You can also override the cache prefix on a per-view basis. ``cache_page`` takes an optional keyword argument, ``key_prefix``, @@ -708,8 +706,7 @@ which works in the same way as the :setting:`CACHE_MIDDLEWARE_KEY_PREFIX` setting for the middleware. It can be used like this:: @cache_page(60 * 15, key_prefix="site1") - def my_view(request): - ... + def my_view(request): ... The ``key_prefix`` and ``cache`` arguments may be specified together. The ``key_prefix`` argument and the :setting:`KEY_PREFIX ` @@ -1342,8 +1339,7 @@ To do this in Django, use the convenient @vary_on_headers("User-Agent") - def my_view(request): - ... + def my_view(request): ... In this case, a caching mechanism (such as Django's own cache middleware) will cache a separate version of the page for each unique user-agent. @@ -1357,8 +1353,7 @@ anything that was already in there. You can pass multiple headers to ``vary_on_headers()``:: @vary_on_headers("User-Agent", "Cookie") - def my_view(request): - ... + def my_view(request): ... This tells downstream caches to vary on *both*, which means each combination of user-agent and cookie will get its own cache value. For example, a request with @@ -1371,13 +1366,11 @@ Because varying on cookie is so common, there's a are equivalent:: @vary_on_cookie - def my_view(request): - ... + def my_view(request): ... @vary_on_headers("Cookie") - def my_view(request): - ... + def my_view(request): ... The headers you pass to ``vary_on_headers`` are not case sensitive; ``"User-Agent"`` is the same thing as ``"user-agent"``. @@ -1423,8 +1416,7 @@ decorator. Example:: @cache_control(private=True) - def my_view(request): - ... + def my_view(request): ... This decorator takes care of sending out the appropriate HTTP header behind the scenes. @@ -1463,8 +1455,7 @@ directive:: @cache_control(max_age=3600) - def my_view(request): - ... + def my_view(request): ... (If you *do* use the caching middleware, it already sets the ``max-age`` with the value of the :setting:`CACHE_MIDDLEWARE_SECONDS` setting. In that case, @@ -1494,8 +1485,7 @@ caches. Example:: @never_cache - def myview(request): - ... + def myview(request): ... Order of ``MIDDLEWARE`` ======================= diff --git a/docs/topics/checks.txt b/docs/topics/checks.txt index 9a91ceb46903..3e3bbe19d658 100644 --- a/docs/topics/checks.txt +++ b/docs/topics/checks.txt @@ -113,8 +113,7 @@ You can register "deployment checks" that are only relevant to a production settings file like this:: @register(Tags.security, deploy=True) - def my_check(app_configs, **kwargs): - ... + def my_check(app_configs, **kwargs): ... These checks will only be run if the :option:`check --deploy` option is used. @@ -124,8 +123,7 @@ to ``register``. The code below is equivalent to the code above:: - def my_check(app_configs, **kwargs): - ... + def my_check(app_configs, **kwargs): ... register(my_check, Tags.security, deploy=True) diff --git a/docs/topics/conditional-view-processing.txt b/docs/topics/conditional-view-processing.txt index 2447697de46d..dfd36a64ae0b 100644 --- a/docs/topics/conditional-view-processing.txt +++ b/docs/topics/conditional-view-processing.txt @@ -72,8 +72,7 @@ Suppose you have this pair of models, representing a small blog system:: from django.db import models - class Blog(models.Model): - ... + class Blog(models.Model): ... class Entry(models.Model): @@ -96,8 +95,7 @@ for your front page view:: @condition(last_modified_func=latest_entry) - def front_page(request, blog_id): - ... + def front_page(request, blog_id): ... .. admonition:: Be careful with the order of decorators @@ -131,13 +129,11 @@ We could write the earlier example, which only uses a last-modified function, using one of these decorators:: @last_modified(latest_entry) - def front_page(request, blog_id): - ... + def front_page(request, blog_id): ... ...or:: - def front_page(request, blog_id): - ... + def front_page(request, blog_id): ... front_page = last_modified(latest_entry)(front_page) @@ -154,8 +150,7 @@ this would lead to incorrect behavior. # Bad code. Don't do this! @etag(etag_func) @last_modified(last_modified_func) - def my_view(request): - ... + def my_view(request): ... # End of bad code. diff --git a/docs/topics/db/fixtures.txt b/docs/topics/db/fixtures.txt index 48c5605ff484..ac5b34dae0d7 100644 --- a/docs/topics/db/fixtures.txt +++ b/docs/topics/db/fixtures.txt @@ -161,8 +161,7 @@ You could also write a decorator to encapsulate this logic:: @disable_for_loaddata - def my_handler(**kwargs): - ... + def my_handler(**kwargs): ... Just be aware that this logic will disable the signals whenever fixtures are deserialized, not just during :djadmin:`loaddata`. diff --git a/docs/topics/db/transactions.txt b/docs/topics/db/transactions.txt index 9146ecc2f738..63a6bc2d666e 100644 --- a/docs/topics/db/transactions.txt +++ b/docs/topics/db/transactions.txt @@ -311,8 +311,7 @@ Pass a function, or any callable, to :func:`on_commit`:: from django.db import transaction - def send_welcome_email(): - ... + def send_welcome_email(): ... transaction.on_commit(send_welcome_email) diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index 53ce716a4d9b..e2a37296b730 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -704,8 +704,7 @@ using the previous ``ArticleForm`` class: .. code-block:: pycon >>> class EnhancedArticleForm(ArticleForm): - ... def clean_pub_date(self): - ... ... + ... def clean_pub_date(self): ... ... This creates a form that behaves identically to ``ArticleForm``, except there's diff --git a/docs/topics/http/file-uploads.txt b/docs/topics/http/file-uploads.txt index 0e696badc00b..911c28215761 100644 --- a/docs/topics/http/file-uploads.txt +++ b/docs/topics/http/file-uploads.txt @@ -338,7 +338,8 @@ list:: @csrf_protect def _upload_file_view(request): - ... # Process request + # Process request + ... If you are using a class-based view, you will need to use :func:`~django.views.decorators.csrf.csrf_exempt` on its @@ -359,4 +360,5 @@ list:: @method_decorator(csrf_protect) def post(self, request, *args, **kwargs): - ... # Process request + # Process request + ... diff --git a/docs/topics/signals.txt b/docs/topics/signals.txt index a4d973ebb428..6a577dd8ad17 100644 --- a/docs/topics/signals.txt +++ b/docs/topics/signals.txt @@ -200,8 +200,7 @@ signals sent by some model:: @receiver(pre_save, sender=MyModel) - def my_handler(sender, **kwargs): - ... + def my_handler(sender, **kwargs): ... The ``my_handler`` function will only be called when an instance of ``MyModel`` is saved. diff --git a/docs/topics/testing/tools.txt b/docs/topics/testing/tools.txt index cd05db2cf84f..14a58c4c0030 100644 --- a/docs/topics/testing/tools.txt +++ b/docs/topics/testing/tools.txt @@ -1361,8 +1361,7 @@ For example:: class OtherDBTests(TestCase): databases = {"other"} - def test_other_db_query(self): - ... + def test_other_db_query(self): ... This test will only allow queries against the ``other`` database. Just like for :attr:`SimpleTestCase.databases` and :attr:`TransactionTestCase.databases`, the @@ -1981,22 +1980,18 @@ you might label fast or slow tests:: class SampleTestCase(TestCase): @tag("fast") - def test_fast(self): - ... + def test_fast(self): ... @tag("slow") - def test_slow(self): - ... + def test_slow(self): ... @tag("slow", "core") - def test_slow_but_core(self): - ... + def test_slow_but_core(self): ... You can also tag a test case class:: @tag("slow", "core") - class SampleTestCase(TestCase): - ... + class SampleTestCase(TestCase): ... Subclasses inherit tags from superclasses, and methods inherit tags from their class. Given:: @@ -2004,8 +1999,7 @@ class. Given:: @tag("foo") class SampleTestCaseChild(SampleTestCase): @tag("bar") - def test(self): - ... + def test(self): ... ``SampleTestCaseChild.test`` will be labeled with ``'slow'``, ``'core'``, ``'bar'``, and ``'foo'``. @@ -2105,8 +2099,7 @@ creates. class MyTests(TestCase): @mock.patch(...) @async_to_sync - async def test_my_thing(self): - ... + async def test_my_thing(self): ... .. _topics-testing-email: diff --git a/tests/admin_changelist/test_date_hierarchy.py b/tests/admin_changelist/test_date_hierarchy.py index 03afaa33d917..94a6a8eb6c60 100644 --- a/tests/admin_changelist/test_date_hierarchy.py +++ b/tests/admin_changelist/test_date_hierarchy.py @@ -90,7 +90,8 @@ def test_invalid_params(self): {"year": 2017, "month": 12, "day": 0}, ) for invalid_query in tests: - with self.subTest(query=invalid_query), self.assertRaises( - IncorrectLookupParameters + with ( + self.subTest(query=invalid_query), + self.assertRaises(IncorrectLookupParameters), ): self.assertDateParams(invalid_query, None, None) diff --git a/tests/admin_inlines/models.py b/tests/admin_inlines/models.py index a8d2ee02e137..eca5bae422c1 100644 --- a/tests/admin_inlines/models.py +++ b/tests/admin_inlines/models.py @@ -1,6 +1,7 @@ """ Testing of admin inline formsets. """ + import random from django.contrib.contenttypes.fields import GenericForeignKey diff --git a/tests/admin_scripts/tests.py b/tests/admin_scripts/tests.py index 7f39d7fcfc88..50e8d4a3b1ed 100644 --- a/tests/admin_scripts/tests.py +++ b/tests/admin_scripts/tests.py @@ -3,6 +3,7 @@ advertised - especially with regards to the handling of the DJANGO_SETTINGS_MODULE and default settings.py files. """ + import os import re import shutil @@ -757,7 +758,9 @@ def test_startapp_unicode_name(self): with open(os.path.join(app_path, "apps.py"), encoding="utf8") as f: content = f.read() self.assertIn("class こんにちはConfig(AppConfig)", content) - self.assertIn('name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content) + self.assertIn( + 'name = "こんにちは"' if HAS_BLACK else "name = 'こんにちは'", content + ) def test_builtin_command(self): """ diff --git a/tests/admin_views/custom_has_permission_admin.py b/tests/admin_views/custom_has_permission_admin.py index 6dc2011b24d9..17b6498aab86 100644 --- a/tests/admin_views/custom_has_permission_admin.py +++ b/tests/admin_views/custom_has_permission_admin.py @@ -1,6 +1,7 @@ """ A custom AdminSite for AdminViewPermissionsTest.test_login_has_permission(). """ + from django.contrib import admin from django.contrib.auth import get_permission_codename from django.contrib.auth.forms import AuthenticationForm diff --git a/tests/admin_views/customadmin.py b/tests/admin_views/customadmin.py index e3429ec4bc40..4b30c5c30fd3 100644 --- a/tests/admin_views/customadmin.py +++ b/tests/admin_views/customadmin.py @@ -1,6 +1,7 @@ """ A second, custom AdminSite -- see tests.CustomAdminSiteTests. """ + from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User diff --git a/tests/aggregation_regress/tests.py b/tests/aggregation_regress/tests.py index bfb3919b2370..9199bf3eba2e 100644 --- a/tests/aggregation_regress/tests.py +++ b/tests/aggregation_regress/tests.py @@ -1564,8 +1564,9 @@ def test_aggregate_unmanaged_model_as_tables(self): "django.db.connection.features.allows_group_by_selected_pks_on_model", return_value=True, ): - with mock.patch.object(Book._meta, "managed", False), mock.patch.object( - Author._meta, "managed", False + with ( + mock.patch.object(Book._meta, "managed", False), + mock.patch.object(Author._meta, "managed", False), ): _, _, grouping = qs.query.get_compiler(using="default").pre_sql_setup() self.assertEqual(len(grouping), 2) diff --git a/tests/auth_tests/models/custom_permissions.py b/tests/auth_tests/models/custom_permissions.py index 52d28bd2762c..385de4e8461a 100644 --- a/tests/auth_tests/models/custom_permissions.py +++ b/tests/auth_tests/models/custom_permissions.py @@ -3,6 +3,7 @@ Django permissions model. This allows us to check that the PermissionsMixin includes everything that is needed to interact with the ModelBackend. """ + from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.db import models diff --git a/tests/auth_tests/test_forms.py b/tests/auth_tests/test_forms.py index 14d71572daaa..14604cd2e6ca 100644 --- a/tests/auth_tests/test_forms.py +++ b/tests/auth_tests/test_forms.py @@ -486,8 +486,9 @@ def signal_handler(**kwargs): user_login_failed.disconnect(signal_handler) def test_inactive_user_i18n(self): - with self.settings(USE_I18N=True), translation.override( - "pt-br", deactivate=True + with ( + self.settings(USE_I18N=True), + translation.override("pt-br", deactivate=True), ): # The user is inactive. data = { @@ -906,9 +907,9 @@ def test_bug_14242(self): class MyUserForm(UserChangeForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) - self.fields[ - "groups" - ].help_text = "These groups give users different permissions" + self.fields["groups"].help_text = ( + "These groups give users different permissions" + ) class Meta(UserChangeForm.Meta): fields = ("groups",) diff --git a/tests/auth_tests/test_hashers.py b/tests/auth_tests/test_hashers.py index e0b640a998d7..1b0d2c65be4b 100644 --- a/tests/auth_tests/test_hashers.py +++ b/tests/auth_tests/test_hashers.py @@ -213,8 +213,9 @@ def test_bcrypt_harden_runtime(self): with mock.patch.object(hasher, "rounds", 4): encoded = make_password("letmein", hasher="bcrypt") - with mock.patch.object(hasher, "rounds", 6), mock.patch.object( - hasher, "encode", side_effect=hasher.encode + with ( + mock.patch.object(hasher, "rounds", 6), + mock.patch.object(hasher, "encode", side_effect=hasher.encode), ): hasher.harden_runtime("wrong_password", encoded) @@ -388,8 +389,9 @@ def test_pbkdf2_harden_runtime(self): with mock.patch.object(hasher, "iterations", 1): encoded = make_password("letmein") - with mock.patch.object(hasher, "iterations", 6), mock.patch.object( - hasher, "encode", side_effect=hasher.encode + with ( + mock.patch.object(hasher, "iterations", 6), + mock.patch.object(hasher, "encode", side_effect=hasher.encode), ): hasher.harden_runtime("wrong_password", encoded) @@ -437,8 +439,9 @@ def test_check_password_calls_harden_runtime(self): hasher = get_hasher("default") encoded = make_password("letmein") - with mock.patch.object(hasher, "harden_runtime"), mock.patch.object( - hasher, "must_update", return_value=True + with ( + mock.patch.object(hasher, "harden_runtime"), + mock.patch.object(hasher, "must_update", return_value=True), ): # Correct password supplied, no hardening needed check_password("letmein", encoded) diff --git a/tests/auth_tests/test_views.py b/tests/auth_tests/test_views.py index ba0a77a4dcc5..f4cf6ed2f49a 100644 --- a/tests/auth_tests/test_views.py +++ b/tests/auth_tests/test_views.py @@ -818,9 +818,9 @@ def get_response(request): # Use POST request to log in SessionMiddleware(get_response).process_request(req) CsrfViewMiddleware(get_response).process_view(req, LoginView.as_view(), (), {}) - req.META[ - "SERVER_NAME" - ] = "testserver" # Required to have redirect work in login view + req.META["SERVER_NAME"] = ( + "testserver" # Required to have redirect work in login view + ) req.META["SERVER_PORT"] = 80 resp = CsrfViewMiddleware(LoginView.as_view())(req) csrf_cookie = resp.cookies.get(settings.CSRF_COOKIE_NAME, None) diff --git a/tests/backends/base/test_base.py b/tests/backends/base/test_base.py index 9f2fa4e57690..03356fbf1048 100644 --- a/tests/backends/base/test_base.py +++ b/tests/backends/base/test_base.py @@ -168,8 +168,9 @@ def test_database_queried(self): def test_nested_wrapper_invoked(self): outer_wrapper = self.mock_wrapper() inner_wrapper = self.mock_wrapper() - with connection.execute_wrapper(outer_wrapper), connection.execute_wrapper( - inner_wrapper + with ( + connection.execute_wrapper(outer_wrapper), + connection.execute_wrapper(inner_wrapper), ): self.call_execute(connection) self.assertEqual(inner_wrapper.call_count, 1) @@ -182,8 +183,10 @@ def blocker(*args): wrapper = self.mock_wrapper() c = connection # This alias shortens the next line. - with c.execute_wrapper(wrapper), c.execute_wrapper(blocker), c.execute_wrapper( - wrapper + with ( + c.execute_wrapper(wrapper), + c.execute_wrapper(blocker), + c.execute_wrapper(wrapper), ): with c.cursor() as cursor: cursor.execute("The database never sees this") diff --git a/tests/backends/test_utils.py b/tests/backends/test_utils.py index 03d4b036fdfd..704498836e40 100644 --- a/tests/backends/test_utils.py +++ b/tests/backends/test_utils.py @@ -1,4 +1,5 @@ """Tests for django.db.backends.utils""" + from decimal import Decimal, Rounded from django.db import NotSupportedError, connection diff --git a/tests/backends/tests.py b/tests/backends/tests.py index 5c562682f0a2..08a21d8dedba 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -1,4 +1,5 @@ """Tests related to django.db.backends that haven't been organized.""" + import datetime import threading import unittest diff --git a/tests/bash_completion/tests.py b/tests/bash_completion/tests.py index 856e351dfa1a..324e9809375e 100644 --- a/tests/bash_completion/tests.py +++ b/tests/bash_completion/tests.py @@ -1,6 +1,7 @@ """ A series of tests to establish that the command-line bash completion works. """ + import os import sys import unittest diff --git a/tests/basic/models.py b/tests/basic/models.py index 6802f825ffb9..236884f4ccc1 100644 --- a/tests/basic/models.py +++ b/tests/basic/models.py @@ -3,6 +3,7 @@ This is a basic model with only two non-primary-key fields. """ + import uuid from django.db import models diff --git a/tests/check_framework/test_security.py b/tests/check_framework/test_security.py index b1839f48c3d0..cb035a90a4b9 100644 --- a/tests/check_framework/test_security.py +++ b/tests/check_framework/test_security.py @@ -593,8 +593,9 @@ def test_with_referrer_policy(self): ("strict-origin", "origin"), ) for value in tests: - with self.subTest(value=value), override_settings( - SECURE_REFERRER_POLICY=value + with ( + self.subTest(value=value), + override_settings(SECURE_REFERRER_POLICY=value), ): self.assertEqual(base.check_referrer_policy(None), []) @@ -663,8 +664,11 @@ def test_no_coop(self): def test_with_coop(self): tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"] for value in tests: - with self.subTest(value=value), override_settings( - SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + with ( + self.subTest(value=value), + override_settings( + SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + ), ): self.assertEqual(base.check_cross_origin_opener_policy(None), []) diff --git a/tests/contenttypes_tests/test_management.py b/tests/contenttypes_tests/test_management.py index eb472d80cefe..14ff4e59521b 100644 --- a/tests/contenttypes_tests/test_management.py +++ b/tests/contenttypes_tests/test_management.py @@ -88,9 +88,10 @@ def test_unavailable_content_type_model(self): def test_contenttypes_removed_in_installed_apps_without_models(self): ContentType.objects.create(app_label="empty_models", model="Fake 1") ContentType.objects.create(app_label="no_models", model="Fake 2") - with mock.patch( - "builtins.input", return_value="yes" - ), captured_stdout() as stdout: + with ( + mock.patch("builtins.input", return_value="yes"), + captured_stdout() as stdout, + ): call_command("remove_stale_contenttypes", verbosity=2) self.assertNotIn( "Deleting stale content type 'empty_models | Fake 1'", @@ -106,9 +107,10 @@ def test_contenttypes_removed_in_installed_apps_without_models(self): def test_contenttypes_removed_for_apps_not_in_installed_apps(self): ContentType.objects.create(app_label="empty_models", model="Fake 1") ContentType.objects.create(app_label="no_models", model="Fake 2") - with mock.patch( - "builtins.input", return_value="yes" - ), captured_stdout() as stdout: + with ( + mock.patch("builtins.input", return_value="yes"), + captured_stdout() as stdout, + ): call_command( "remove_stale_contenttypes", include_stale_apps=True, verbosity=2 ) diff --git a/tests/contenttypes_tests/test_models.py b/tests/contenttypes_tests/test_models.py index 02036de83f00..88f715ceffcf 100644 --- a/tests/contenttypes_tests/test_models.py +++ b/tests/contenttypes_tests/test_models.py @@ -323,8 +323,9 @@ def test_multidb(self): db_for_read(). """ ContentType.objects.clear_cache() - with self.assertNumQueries(0, using="default"), self.assertNumQueries( - 1, using="other" + with ( + self.assertNumQueries(0, using="default"), + self.assertNumQueries(1, using="other"), ): ContentType.objects.get_for_model(Author) diff --git a/tests/contenttypes_tests/test_views.py b/tests/contenttypes_tests/test_views.py index 4d85d15065f8..75f39a7babc0 100644 --- a/tests/contenttypes_tests/test_views.py +++ b/tests/contenttypes_tests/test_views.py @@ -150,10 +150,8 @@ def test_shortcut_view_with_null_site_fk(self, get_model): """ The shortcut view works if a model's ForeignKey to site is None. """ - get_model.side_effect = ( - lambda *args, **kwargs: MockSite - if args[0] == "sites.Site" - else ModelWithNullFKToSite + get_model.side_effect = lambda *args, **kwargs: ( + MockSite if args[0] == "sites.Site" else ModelWithNullFKToSite ) obj = ModelWithNullFKToSite.objects.create(title="title") @@ -172,10 +170,8 @@ def test_shortcut_view_with_site_m2m(self, get_model): site if it's attached to the object or to the domain of the first site found in the m2m relationship. """ - get_model.side_effect = ( - lambda *args, **kwargs: MockSite - if args[0] == "sites.Site" - else ModelWithM2MToSite + get_model.side_effect = lambda *args, **kwargs: ( + MockSite if args[0] == "sites.Site" else ModelWithM2MToSite ) # get_current_site() will lookup a Site object, so these must match the diff --git a/tests/context_processors/tests.py b/tests/context_processors/tests.py index 23f9d591496b..ba92ff8b05e4 100644 --- a/tests/context_processors/tests.py +++ b/tests/context_processors/tests.py @@ -1,6 +1,7 @@ """ Tests for Django's bundled context processors. """ + from django.test import SimpleTestCase, TestCase, override_settings diff --git a/tests/custom_lookups/tests.py b/tests/custom_lookups/tests.py index 8fc31d4e6bca..f107c5320a2a 100644 --- a/tests/custom_lookups/tests.py +++ b/tests/custom_lookups/tests.py @@ -238,10 +238,11 @@ class LookupTests(TestCase): def test_custom_name_lookup(self): a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) - with register_lookup(models.DateField, YearTransform), register_lookup( - models.DateField, YearTransform, lookup_name="justtheyear" - ), register_lookup(YearTransform, Exactly), register_lookup( - YearTransform, Exactly, lookup_name="isactually" + with ( + register_lookup(models.DateField, YearTransform), + register_lookup(models.DateField, YearTransform, lookup_name="justtheyear"), + register_lookup(YearTransform, Exactly), + register_lookup(YearTransform, Exactly, lookup_name="isactually"), ): qs1 = Author.objects.filter(birthdate__testyear__exactly=1981) qs2 = Author.objects.filter(birthdate__justtheyear__isactually=1981) diff --git a/tests/db_functions/comparison/test_nullif.py b/tests/db_functions/comparison/test_nullif.py index 9839e6b4c510..cdbc3d69604e 100644 --- a/tests/db_functions/comparison/test_nullif.py +++ b/tests/db_functions/comparison/test_nullif.py @@ -23,9 +23,11 @@ def test_basic(self): [ ("smithj",), ( - "" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ), ], ) diff --git a/tests/db_functions/datetime/test_extract_trunc.py b/tests/db_functions/datetime/test_extract_trunc.py index 29212b6e2440..e576e6e46415 100644 --- a/tests/db_functions/datetime/test_extract_trunc.py +++ b/tests/db_functions/datetime/test_extract_trunc.py @@ -113,9 +113,11 @@ def create_model(self, start_datetime, end_datetime): end_date=end_datetime.date() if end_datetime else None, start_time=start_datetime.time() if start_datetime else None, end_time=end_datetime.time() if end_datetime else None, - duration=(end_datetime - start_datetime) - if start_datetime and end_datetime - else None, + duration=( + (end_datetime - start_datetime) + if start_datetime and end_datetime + else None + ), ) def test_extract_year_exact_lookup(self): diff --git a/tests/db_functions/models.py b/tests/db_functions/models.py index d6a06511bcc1..c126f1bae1ad 100644 --- a/tests/db_functions/models.py +++ b/tests/db_functions/models.py @@ -1,6 +1,7 @@ """ Tests for built in Function expressions. """ + from django.db import models diff --git a/tests/db_functions/text/test_md5.py b/tests/db_functions/text/test_md5.py index fd0aec58f2d4..4fd66f0397ea 100644 --- a/tests/db_functions/text/test_md5.py +++ b/tests/db_functions/text/test_md5.py @@ -35,9 +35,11 @@ def test_basic(self): "ca6d48f6772000141e66591aee49d56c", "bf2c13bc1154e3d2e7df848cbc8be73d", "d41d8cd98f00b204e9800998ecf8427e", - "d41d8cd98f00b204e9800998ecf8427e" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "d41d8cd98f00b204e9800998ecf8427e" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha1.py b/tests/db_functions/text/test_sha1.py index 175c5727ffc1..ef846d07aa5b 100644 --- a/tests/db_functions/text/test_sha1.py +++ b/tests/db_functions/text/test_sha1.py @@ -35,9 +35,11 @@ def test_basic(self): "0781e0745a2503e6ded05ed5bc554c421d781b0c", "198d15ea139de04060caf95bc3e0ec5883cba881", "da39a3ee5e6b4b0d3255bfef95601890afd80709", - "da39a3ee5e6b4b0d3255bfef95601890afd80709" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "da39a3ee5e6b4b0d3255bfef95601890afd80709" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha224.py b/tests/db_functions/text/test_sha224.py index a6254f43e3d6..60d9e378a69d 100644 --- a/tests/db_functions/text/test_sha224.py +++ b/tests/db_functions/text/test_sha224.py @@ -37,9 +37,11 @@ def test_basic(self): "2297904883e78183cb118fc3dc21a610d60daada7b6ebdbc85139f4d", "eba942746e5855121d9d8f79e27dfdebed81adc85b6bf41591203080", "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", - "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha256.py b/tests/db_functions/text/test_sha256.py index b399dbecd32a..0cf72783e7c6 100644 --- a/tests/db_functions/text/test_sha256.py +++ b/tests/db_functions/text/test_sha256.py @@ -35,9 +35,11 @@ def test_basic(self): "6e4cce20cd83fc7c202f21a8b2452a68509cf24d1c272a045b5e0cfc43f0d94e", "3ad2039e3ec0c88973ae1c0fce5a3dbafdd5a1627da0a92312c54ebfcf43988e", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha384.py b/tests/db_functions/text/test_sha384.py index 250cadda4a09..a4d07d32952c 100644 --- a/tests/db_functions/text/test_sha384.py +++ b/tests/db_functions/text/test_sha384.py @@ -39,10 +39,12 @@ def test_basic(self): "26676a43c7ba378621175853b0", "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede" "bfe76f65fbd51ad2f14898b95b", - "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274ede" - "bfe76f65fbd51ad2f14898b95b" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da27" + "4edebfe76f65fbd51ad2f14898b95b" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_functions/text/test_sha512.py b/tests/db_functions/text/test_sha512.py index f5a7ad4ae542..b4c7a4bbd8a4 100644 --- a/tests/db_functions/text/test_sha512.py +++ b/tests/db_functions/text/test_sha512.py @@ -39,10 +39,12 @@ def test_basic(self): "172d88798345a3a7666faf5f35a144c60812d3234dcd35f444624f2faee16857", "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", - "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" - "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" - if connection.features.interprets_empty_strings_as_nulls - else None, + ( + "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce" + "47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e" + if connection.features.interprets_empty_strings_as_nulls + else None + ), ], ) diff --git a/tests/db_utils/tests.py b/tests/db_utils/tests.py index a2d9cc7b5e89..4028a8acdf3e 100644 --- a/tests/db_utils/tests.py +++ b/tests/db_utils/tests.py @@ -1,4 +1,5 @@ """Tests for django.db.utils.""" + import unittest from django.core.exceptions import ImproperlyConfigured diff --git a/tests/dbshell/test_sqlite.py b/tests/dbshell/test_sqlite.py index faf9882ad91f..e795f7619b5a 100644 --- a/tests/dbshell/test_sqlite.py +++ b/tests/dbshell/test_sqlite.py @@ -35,8 +35,11 @@ def test_non_zero_exit_status_when_path_to_db_is_path(self): cmd_args = self.settings_to_cmd_args_env(sqlite_with_path)[0] msg = '"sqlite3 test.db.sqlite3" returned non-zero exit status 1.' - with mock.patch( - "django.db.backends.sqlite3.client.DatabaseClient.runshell", - side_effect=subprocess.CalledProcessError(returncode=1, cmd=cmd_args), - ), self.assertRaisesMessage(CommandError, msg): + with ( + mock.patch( + "django.db.backends.sqlite3.client.DatabaseClient.runshell", + side_effect=subprocess.CalledProcessError(returncode=1, cmd=cmd_args), + ), + self.assertRaisesMessage(CommandError, msg), + ): call_command("dbshell") diff --git a/tests/distinct_on_fields/tests.py b/tests/distinct_on_fields/tests.py index b80878bbf25d..93b3f27aec0d 100644 --- a/tests/distinct_on_fields/tests.py +++ b/tests/distinct_on_fields/tests.py @@ -76,9 +76,11 @@ def test_basic_distinct_on(self): (StaffTag.objects.distinct("staff", "tag"), [self.st1]), ( Tag.objects.order_by("parent__pk", "pk").distinct("parent"), - [self.t2, self.t4, self.t1] - if connection.features.nulls_order_largest - else [self.t1, self.t2, self.t4], + ( + [self.t2, self.t4, self.t1] + if connection.features.nulls_order_largest + else [self.t1, self.t2, self.t4] + ), ), ( StaffTag.objects.select_related("staff") diff --git a/tests/expressions/models.py b/tests/expressions/models.py index bd4db9050e6a..43dd235fb5ac 100644 --- a/tests/expressions/models.py +++ b/tests/expressions/models.py @@ -1,6 +1,7 @@ """ Tests for F() query expression syntax. """ + import uuid from django.db import models diff --git a/tests/file_uploads/tests.py b/tests/file_uploads/tests.py index 9fdef5732498..6db8f9022d73 100644 --- a/tests/file_uploads/tests.py +++ b/tests/file_uploads/tests.py @@ -452,9 +452,10 @@ def test_filename_overflow(self): def test_file_content(self): file = tempfile.NamedTemporaryFile - with file(suffix=".ctype_extra") as no_content_type, file( - suffix=".ctype_extra" - ) as simple_file: + with ( + file(suffix=".ctype_extra") as no_content_type, + file(suffix=".ctype_extra") as simple_file, + ): no_content_type.write(b"no content") no_content_type.seek(0) @@ -483,9 +484,10 @@ def test_file_content(self): def test_content_type_extra(self): """Uploaded files may have content type parameters available.""" file = tempfile.NamedTemporaryFile - with file(suffix=".ctype_extra") as no_content_type, file( - suffix=".ctype_extra" - ) as simple_file: + with ( + file(suffix=".ctype_extra") as no_content_type, + file(suffix=".ctype_extra") as simple_file, + ): no_content_type.write(b"something") no_content_type.seek(0) diff --git a/tests/file_uploads/uploadhandler.py b/tests/file_uploads/uploadhandler.py index a1e1a5af053d..d3c88ac305bf 100644 --- a/tests/file_uploads/uploadhandler.py +++ b/tests/file_uploads/uploadhandler.py @@ -1,6 +1,7 @@ """ Upload handlers to test the upload API. """ + import os from tempfile import NamedTemporaryFile diff --git a/tests/files/tests.py b/tests/files/tests.py index 7dc5c04668c3..9d3a471cb31b 100644 --- a/tests/files/tests.py +++ b/tests/files/tests.py @@ -144,35 +144,40 @@ def test_file_iteration_with_text(self): self.assertEqual(list(f), ["one\n", "two\n", "three"]) def test_readable(self): - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): self.assertTrue(test_file.readable()) self.assertFalse(test_file.readable()) def test_writable(self): - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): self.assertTrue(test_file.writable()) self.assertFalse(test_file.writable()) - with tempfile.TemporaryFile("rb") as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile("rb") as temp, + File(temp, name="something.txt") as test_file, + ): self.assertFalse(test_file.writable()) def test_seekable(self): - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): self.assertTrue(test_file.seekable()) self.assertFalse(test_file.seekable()) def test_io_wrapper(self): content = "vive l'été\n" - with tempfile.TemporaryFile() as temp, File( - temp, name="something.txt" - ) as test_file: + with ( + tempfile.TemporaryFile() as temp, + File(temp, name="something.txt") as test_file, + ): test_file.write(content.encode()) test_file.seek(0) wrapper = TextIOWrapper(test_file, "utf-8", newline="\n") diff --git a/tests/force_insert_update/models.py b/tests/force_insert_update/models.py index b95b197454d5..e6fdfbd827db 100644 --- a/tests/force_insert_update/models.py +++ b/tests/force_insert_update/models.py @@ -2,6 +2,7 @@ Tests for forcing insert and update queries (instead of Django's normal automatic behavior). """ + from django.db import models diff --git a/tests/forms_tests/field_tests/test_decimalfield.py b/tests/forms_tests/field_tests/test_decimalfield.py index 9d26bc88b0c0..cb13e5b71b02 100644 --- a/tests/forms_tests/field_tests/test_decimalfield.py +++ b/tests/forms_tests/field_tests/test_decimalfield.py @@ -80,8 +80,9 @@ def test_enter_a_number_error(self): "--0.12", ) for value in values: - with self.subTest(value=value), self.assertRaisesMessage( - ValidationError, "'Enter a number.'" + with ( + self.subTest(value=value), + self.assertRaisesMessage(ValidationError, "'Enter a number.'"), ): f.clean(value) diff --git a/tests/forms_tests/field_tests/test_filefield.py b/tests/forms_tests/field_tests/test_filefield.py index 11388bdc09df..9744981471a3 100644 --- a/tests/forms_tests/field_tests/test_filefield.py +++ b/tests/forms_tests/field_tests/test_filefield.py @@ -53,7 +53,8 @@ def test_filefield_1(self): self.assertIsInstance( f.clean( SimpleUploadedFile( - "我隻氣墊船裝滿晒鱔.txt", "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode() + "我隻氣墊船裝滿晒鱔.txt", + "मेरी मँडराने वाली नाव सर्पमीनों से भरी ह".encode(), ) ), SimpleUploadedFile, diff --git a/tests/forms_tests/tests/test_formsets.py b/tests/forms_tests/tests/test_formsets.py index 3c260010c25c..f80c1dc09e35 100644 --- a/tests/forms_tests/tests/test_formsets.py +++ b/tests/forms_tests/tests/test_formsets.py @@ -217,9 +217,12 @@ def mocked_func(*args, **kwargs): [("Calexico", "100"), ("Any1", "42"), ("Any2", "101")] ) - with mock.patch( - "django.forms.formsets.ManagementForm.is_valid", mocked_is_valid - ), mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean): + with ( + mock.patch( + "django.forms.formsets.ManagementForm.is_valid", mocked_is_valid + ), + mock.patch("django.forms.forms.BaseForm.full_clean", mocked_full_clean), + ): self.assertTrue(formset.is_valid()) self.assertEqual(is_valid_counter.call_count, 1) self.assertEqual(full_clean_counter.call_count, 4) diff --git a/tests/gis_tests/gdal_tests/test_raster.py b/tests/gis_tests/gdal_tests/test_raster.py index 67108cbb3291..a5f1edef0bb7 100644 --- a/tests/gis_tests/gdal_tests/test_raster.py +++ b/tests/gis_tests/gdal_tests/test_raster.py @@ -102,8 +102,9 @@ def test_geotransform_bad_inputs(self): ] msg = "Geotransform must consist of 6 numeric values." for geotransform in error_geotransforms: - with self.subTest(i=geotransform), self.assertRaisesMessage( - ValueError, msg + with ( + self.subTest(i=geotransform), + self.assertRaisesMessage(ValueError, msg), ): rsmem.geotransform = geotransform diff --git a/tests/gis_tests/geogapp/tests.py b/tests/gis_tests/geogapp/tests.py index 856560899383..cb783b946532 100644 --- a/tests/gis_tests/geogapp/tests.py +++ b/tests/gis_tests/geogapp/tests.py @@ -1,6 +1,7 @@ """ Tests for geography support in PostGIS """ + import os from django.contrib.gis.db import models diff --git a/tests/gis_tests/test_data.py b/tests/gis_tests/test_data.py index 0a949073208d..8dd6042175e6 100644 --- a/tests/gis_tests/test_data.py +++ b/tests/gis_tests/test_data.py @@ -2,6 +2,7 @@ This module has the mock object definitions used to hold reference geometry for the GEOS and GDAL tests. """ + import json import os diff --git a/tests/handlers/tests.py b/tests/handlers/tests.py index 76d99e25045f..7a5a287da7ca 100644 --- a/tests/handlers/tests.py +++ b/tests/handlers/tests.py @@ -240,8 +240,9 @@ def test_no_response(self): ("/no_response_cbv/", "handlers.views.NoResponse.__call__"), ) for url, view in tests: - with self.subTest(url=url), self.assertRaisesMessage( - ValueError, msg % view + with ( + self.subTest(url=url), + self.assertRaisesMessage(ValueError, msg % view), ): self.client.get(url) diff --git a/tests/httpwrappers/tests.py b/tests/httpwrappers/tests.py index cce8402d3fc0..2197c6f7ea18 100644 --- a/tests/httpwrappers/tests.py +++ b/tests/httpwrappers/tests.py @@ -352,9 +352,9 @@ def test_long_line(self): h.headers["Content-Disposition"] = 'attachment; filename="%s"' % f # This one is triggering https://bugs.python.org/issue20747, that is Python # will itself insert a newline in the header - h.headers[ - "Content-Disposition" - ] = 'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"' + h.headers["Content-Disposition"] = ( + 'attachment; filename="EdelRot_Blu\u0308te (3)-0.JPG"' + ) def test_newlines_in_headers(self): # Bug #10188: Do not allow newlines in headers (CR or LF) diff --git a/tests/invalid_models_tests/test_models.py b/tests/invalid_models_tests/test_models.py index f22f273c9a55..9d9a09d34e4b 100644 --- a/tests/invalid_models_tests/test_models.py +++ b/tests/invalid_models_tests/test_models.py @@ -1898,15 +1898,18 @@ class Meta: self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the nonexistent field 'missing_field'.", - obj=Model, - id="models.E012", - ), - ] - if connection.features.supports_table_check_constraints - else [], + ( + [ + Error( + "'constraints' refers to the nonexistent field " + "'missing_field'.", + obj=Model, + id="models.E012", + ), + ] + if connection.features.supports_table_check_constraints + else [] + ), ) @skipUnlessDBFeature("supports_table_check_constraints") @@ -2252,15 +2255,18 @@ class Meta: self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the nonexistent field 'missing_field'.", - obj=Model, - id="models.E012", - ), - ] - if connection.features.supports_partial_indexes - else [], + ( + [ + Error( + "'constraints' refers to the nonexistent field " + "'missing_field'.", + obj=Model, + id="models.E012", + ), + ] + if connection.features.supports_partial_indexes + else [] + ), ) def test_unique_constraint_condition_pointing_to_joined_fields(self): @@ -2280,15 +2286,17 @@ class Meta: self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the joined field 'parent__age__lt'.", - obj=Model, - id="models.E041", - ) - ] - if connection.features.supports_partial_indexes - else [], + ( + [ + Error( + "'constraints' refers to the joined field 'parent__age__lt'.", + obj=Model, + id="models.E041", + ) + ] + if connection.features.supports_partial_indexes + else [] + ), ) def test_unique_constraint_pointing_to_reverse_o2o(self): @@ -2307,15 +2315,17 @@ class Meta: self.assertEqual( Model.check(databases=self.databases), - [ - Error( - "'constraints' refers to the nonexistent field 'model'.", - obj=Model, - id="models.E012", - ), - ] - if connection.features.supports_partial_indexes - else [], + ( + [ + Error( + "'constraints' refers to the nonexistent field 'model'.", + obj=Model, + id="models.E012", + ), + ] + if connection.features.supports_partial_indexes + else [] + ), ) def test_deferrable_unique_constraint(self): diff --git a/tests/m2m_and_m2o/models.py b/tests/m2m_and_m2o/models.py index 6a5b0b29c984..4cbd1eb4e8c2 100644 --- a/tests/m2m_and_m2o/models.py +++ b/tests/m2m_and_m2o/models.py @@ -3,6 +3,7 @@ Make sure to set ``related_name`` if you use relationships to the same table. """ + from django.db import models diff --git a/tests/m2m_intermediary/models.py b/tests/m2m_intermediary/models.py index 1333d14b410a..f82498651f62 100644 --- a/tests/m2m_intermediary/models.py +++ b/tests/m2m_intermediary/models.py @@ -9,6 +9,7 @@ field, which specifies the ``Reporter``'s position for the given article (e.g. "Staff writer"). """ + from django.db import models diff --git a/tests/mail/tests.py b/tests/mail/tests.py index cd981b6e9ec1..dd6b72ab4907 100644 --- a/tests/mail/tests.py +++ b/tests/mail/tests.py @@ -1392,8 +1392,9 @@ def test_wrong_admins_managers(self): ): msg = "The %s setting must be a list of 2-tuples." % setting for value in tests: - with self.subTest(setting=setting, value=value), self.settings( - **{setting: value} + with ( + self.subTest(setting=setting, value=value), + self.settings(**{setting: value}), ): with self.assertRaisesMessage(ValueError, msg): mail_func("subject", "content") diff --git a/tests/many_to_many/models.py b/tests/many_to_many/models.py index 541928e94d64..42fc42699045 100644 --- a/tests/many_to_many/models.py +++ b/tests/many_to_many/models.py @@ -6,6 +6,7 @@ In this example, an ``Article`` can be published in multiple ``Publication`` objects, and a ``Publication`` has multiple ``Article`` objects. """ + from django.db import models diff --git a/tests/many_to_one/models.py b/tests/many_to_one/models.py index cca7e798179f..56e660592ab1 100644 --- a/tests/many_to_one/models.py +++ b/tests/many_to_one/models.py @@ -3,6 +3,7 @@ To define a many-to-one relationship, use ``ForeignKey()``. """ + from django.db import models diff --git a/tests/middleware/test_security.py b/tests/middleware/test_security.py index dd220b8f4c3d..339b9181c37b 100644 --- a/tests/middleware/test_security.py +++ b/tests/middleware/test_security.py @@ -248,8 +248,9 @@ def test_referrer_policy_on(self): (("strict-origin", "origin"), "strict-origin,origin"), ) for value, expected in tests: - with self.subTest(value=value), override_settings( - SECURE_REFERRER_POLICY=value + with ( + self.subTest(value=value), + override_settings(SECURE_REFERRER_POLICY=value), ): self.assertEqual( self.process_response().headers["Referrer-Policy"], @@ -287,8 +288,11 @@ def test_coop_on(self): """ tests = ["same-origin", "same-origin-allow-popups", "unsafe-none"] for value in tests: - with self.subTest(value=value), override_settings( - SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + with ( + self.subTest(value=value), + override_settings( + SECURE_CROSS_ORIGIN_OPENER_POLICY=value, + ), ): self.assertEqual( self.process_response().headers["Cross-Origin-Opener-Policy"], diff --git a/tests/middleware/tests.py b/tests/middleware/tests.py index 4dc1c83c42a3..4c17b4ec3484 100644 --- a/tests/middleware/tests.py +++ b/tests/middleware/tests.py @@ -854,9 +854,9 @@ class GZipMiddlewareTest(SimpleTestCase): def setUp(self): self.req = self.request_factory.get("/") self.req.META["HTTP_ACCEPT_ENCODING"] = "gzip, deflate" - self.req.META[ - "HTTP_USER_AGENT" - ] = "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1" + self.req.META["HTTP_USER_AGENT"] = ( + "Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1" + ) self.resp = HttpResponse() self.resp.status_code = 200 self.resp.content = self.compressible_string diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 263b25ab6145..1f8b3fb01149 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -3102,9 +3102,11 @@ def test_optimization(self): with open(initial_migration_file) as fp: content = fp.read() self.assertIn( - '("bool", models.BooleanField' - if HAS_BLACK - else "('bool', models.BooleanField", + ( + '("bool", models.BooleanField' + if HAS_BLACK + else "('bool', models.BooleanField" + ), content, ) self.assertEqual( @@ -3131,9 +3133,11 @@ def test_optimization_no_verbosity(self): with open(initial_migration_file) as fp: content = fp.read() self.assertIn( - '("bool", models.BooleanField' - if HAS_BLACK - else "('bool', models.BooleanField", + ( + '("bool", models.BooleanField' + if HAS_BLACK + else "('bool', models.BooleanField" + ), content, ) self.assertEqual(out.getvalue(), "") diff --git a/tests/migrations/test_executor.py b/tests/migrations/test_executor.py index 6232b44b986c..571cb3e1a269 100644 --- a/tests/migrations/test_executor.py +++ b/tests/migrations/test_executor.py @@ -405,9 +405,9 @@ def test_custom_user(self): migrations_apps = executor.loader.project_state( ("migrations", "0001_initial"), ).apps - global_apps.get_app_config("migrations").models[ - "author" - ] = migrations_apps.get_model("migrations", "author") + global_apps.get_app_config("migrations").models["author"] = ( + migrations_apps.get_model("migrations", "author") + ) try: migration = executor.loader.get_migration("auth", "0001_initial") self.assertIs(executor.detect_soft_applied(None, migration)[0], True) diff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py index 52e43d20f90a..5733ba761869 100644 --- a/tests/migrations/test_operations.py +++ b/tests/migrations/test_operations.py @@ -3614,15 +3614,17 @@ def test_rename_index(self): operation.state_forwards(app_label, new_state) # Rename index. expected_queries = 1 if connection.features.can_rename_index else 2 - with connection.schema_editor() as editor, self.assertNumQueries( - expected_queries + with ( + connection.schema_editor() as editor, + self.assertNumQueries(expected_queries), ): operation.database_forwards(app_label, editor, project_state, new_state) self.assertIndexNameNotExists(table_name, "pony_pink_idx") self.assertIndexNameExists(table_name, "new_pony_test_idx") # Reversal. - with connection.schema_editor() as editor, self.assertNumQueries( - expected_queries + with ( + connection.schema_editor() as editor, + self.assertNumQueries(expected_queries), ): operation.database_backwards(app_label, editor, new_state, project_state) self.assertIndexNameExists(table_name, "pony_pink_idx") @@ -4281,9 +4283,10 @@ def test_add_deferred_unique_constraint(self): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_deferrable_unique_constraints: @@ -4342,9 +4345,10 @@ def test_remove_deferred_unique_constraint(self): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) @@ -4405,9 +4409,10 @@ def test_add_covering_unique_constraint(self): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 1) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) Pony.objects.create(pink=1, weight=4.0) if connection.features.supports_covering_indexes: @@ -4453,9 +4458,10 @@ def test_remove_covering_unique_constraint(self): ) Pony = new_state.apps.get_model(app_label, "Pony") self.assertEqual(len(Pony._meta.constraints), 0) - with connection.schema_editor() as editor, CaptureQueriesContext( - connection - ) as ctx: + with ( + connection.schema_editor() as editor, + CaptureQueriesContext(connection) as ctx, + ): operation.database_forwards(app_label, editor, project_state, new_state) # Constraint doesn't work. Pony.objects.create(pink=1, weight=4.0) diff --git a/tests/model_inheritance/models.py b/tests/model_inheritance/models.py index 47aae186e037..ffb9f28cfa67 100644 --- a/tests/model_inheritance/models.py +++ b/tests/model_inheritance/models.py @@ -11,6 +11,7 @@ Both styles are demonstrated here. """ + from django.db import models # diff --git a/tests/model_inheritance/tests.py b/tests/model_inheritance/tests.py index 5bf1ef5db543..6b005fcef0ed 100644 --- a/tests/model_inheritance/tests.py +++ b/tests/model_inheritance/tests.py @@ -216,9 +216,11 @@ def b(): GrandChild().save() for i, test in enumerate([a, b]): - with self.subTest(i=i), self.assertNumQueries(4), CaptureQueriesContext( - connection - ) as queries: + with ( + self.subTest(i=i), + self.assertNumQueries(4), + CaptureQueriesContext(connection) as queries, + ): test() for query in queries: sql = query["sql"] diff --git a/tests/model_inheritance_regress/tests.py b/tests/model_inheritance_regress/tests.py index 1a9f953d6f1f..ba31048ac2fd 100644 --- a/tests/model_inheritance_regress/tests.py +++ b/tests/model_inheritance_regress/tests.py @@ -1,6 +1,7 @@ """ Regression tests for Model inheritance behavior. """ + import datetime from operator import attrgetter from unittest import expectedFailure diff --git a/tests/null_fk_ordering/models.py b/tests/null_fk_ordering/models.py index adfdbf3bea4f..d7b6ad82389d 100644 --- a/tests/null_fk_ordering/models.py +++ b/tests/null_fk_ordering/models.py @@ -5,6 +5,7 @@ unexpected results """ + from django.db import models diff --git a/tests/one_to_one/models.py b/tests/one_to_one/models.py index ca459e9edfec..20b2eeec7da4 100644 --- a/tests/one_to_one/models.py +++ b/tests/one_to_one/models.py @@ -5,6 +5,7 @@ In this example, a ``Place`` optionally can be a ``Restaurant``. """ + from django.db import models diff --git a/tests/order_with_respect_to/base_tests.py b/tests/order_with_respect_to/base_tests.py index ea548ca076e4..5170c6d957e2 100644 --- a/tests/order_with_respect_to/base_tests.py +++ b/tests/order_with_respect_to/base_tests.py @@ -2,6 +2,7 @@ The tests are shared with contenttypes_tests and so shouldn't import or reference any models directly. Subclasses should inherit django.test.TestCase. """ + from operator import attrgetter @@ -117,8 +118,11 @@ def db_for_write(self, model, **hints): return "other" with self.settings(DATABASE_ROUTERS=[WriteToOtherRouter()]): - with self.assertNumQueries(0, using="default"), self.assertNumQueries( - 1, - using="other", + with ( + self.assertNumQueries(0, using="default"), + self.assertNumQueries( + 1, + using="other", + ), ): self.q1.set_answer_order([3, 1, 2, 4]) diff --git a/tests/postgres_tests/fields.py b/tests/postgres_tests/fields.py index c2513fca0cb8..c5dddf197f06 100644 --- a/tests/postgres_tests/fields.py +++ b/tests/postgres_tests/fields.py @@ -2,6 +2,7 @@ Indirection layer for PostgreSQL-specific fields, so the tests don't fail when run with a backend other than PostgreSQL. """ + import enum from django.db import models diff --git a/tests/postgres_tests/test_constraints.py b/tests/postgres_tests/test_constraints.py index bf4783374305..e5a8e9dbe9ea 100644 --- a/tests/postgres_tests/test_constraints.py +++ b/tests/postgres_tests/test_constraints.py @@ -300,8 +300,9 @@ def test_invalid_expressions(self): def test_empty_expressions(self): msg = "At least one expression is required to define an exclusion constraint." for empty_expressions in (None, []): - with self.subTest(empty_expressions), self.assertRaisesMessage( - ValueError, msg + with ( + self.subTest(empty_expressions), + self.assertRaisesMessage(ValueError, msg), ): ExclusionConstraint( index_type="GIST", diff --git a/tests/postgres_tests/test_search.py b/tests/postgres_tests/test_search.py index 6f6318899c27..472dca6c7b70 100644 --- a/tests/postgres_tests/test_search.py +++ b/tests/postgres_tests/test_search.py @@ -5,6 +5,7 @@ All text copyright Python (Monty) Pictures. Thanks to sacred-texts.com for the transcript. """ + from django.db.models import F, Value from . import PostgreSQLSimpleTestCase, PostgreSQLTestCase diff --git a/tests/prefetch_related/tests.py b/tests/prefetch_related/tests.py index 08f87d55de15..a418beb5a52f 100644 --- a/tests/prefetch_related/tests.py +++ b/tests/prefetch_related/tests.py @@ -1620,8 +1620,9 @@ def test_using_is_honored_custom_qs(self): ) # Explicit using on a different db. - with self.assertNumQueries(1, using="default"), self.assertNumQueries( - 1, using="other" + with ( + self.assertNumQueries(1, using="default"), + self.assertNumQueries(1, using="other"), ): prefetch = Prefetch( "first_time_authors", queryset=Author.objects.using("default") diff --git a/tests/proxy_models/models.py b/tests/proxy_models/models.py index 604136b5ac66..c0277e093fbc 100644 --- a/tests/proxy_models/models.py +++ b/tests/proxy_models/models.py @@ -4,6 +4,7 @@ than using a new table of their own. This allows them to act as simple proxies, providing a modified interface to the data from the base class. """ + from django.db import models # A couple of managers for testing managing overriding in proxy model cases. diff --git a/tests/queries/models.py b/tests/queries/models.py index 23c41e33742e..9f4cf040b62a 100644 --- a/tests/queries/models.py +++ b/tests/queries/models.py @@ -1,6 +1,7 @@ """ Various complex queries that have been problematic in the past. """ + import datetime from django.db import models diff --git a/tests/requests_tests/test_accept_header.py b/tests/requests_tests/test_accept_header.py index c6eed0e4793e..5afb9e999325 100644 --- a/tests/requests_tests/test_accept_header.py +++ b/tests/requests_tests/test_accept_header.py @@ -68,9 +68,9 @@ def test_no_headers(self): def test_accept_headers(self): request = HttpRequest() - request.META[ - "HTTP_ACCEPT" - ] = "text/html, application/xhtml+xml,application/xml ;q=0.9,*/*;q=0.8" + request.META["HTTP_ACCEPT"] = ( + "text/html, application/xhtml+xml,application/xml ;q=0.9,*/*;q=0.8" + ) self.assertEqual( [str(accepted_type) for accepted_type in request.accepted_types], [ @@ -94,9 +94,9 @@ def test_request_accepts_none(self): def test_request_accepts_some(self): request = HttpRequest() - request.META[ - "HTTP_ACCEPT" - ] = "text/html,application/xhtml+xml,application/xml;q=0.9" + request.META["HTTP_ACCEPT"] = ( + "text/html,application/xhtml+xml,application/xml;q=0.9" + ) self.assertIs(request.accepts("text/html"), True) self.assertIs(request.accepts("application/xhtml+xml"), True) self.assertIs(request.accepts("application/xml"), True) diff --git a/tests/save_delete_hooks/models.py b/tests/save_delete_hooks/models.py index e7c598aeaedd..8b9826eb1452 100644 --- a/tests/save_delete_hooks/models.py +++ b/tests/save_delete_hooks/models.py @@ -4,6 +4,7 @@ To execute arbitrary code around ``save()`` and ``delete()``, just subclass the methods. """ + from django.db import models diff --git a/tests/schema/fields.py b/tests/schema/fields.py index 998cb28b8cfb..24a26b2c2c06 100644 --- a/tests/schema/fields.py +++ b/tests/schema/fields.py @@ -41,9 +41,11 @@ def __init__( related_name=related_name, related_query_name=related_query_name, limit_choices_to=limit_choices_to, - symmetrical=symmetrical - if symmetrical is not None - else (to == RECURSIVE_RELATIONSHIP_CONSTANT), + symmetrical=( + symmetrical + if symmetrical is not None + else (to == RECURSIVE_RELATIONSHIP_CONSTANT) + ), through=through, through_fields=through_fields, db_constraint=db_constraint, diff --git a/tests/schema/tests.py b/tests/schema/tests.py index 61244f75b4d3..3a026281bdec 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -640,9 +640,10 @@ def test_add_field(self): # Add the new field new_field = IntegerField(null=True) new_field.set_attributes_from_name("age") - with CaptureQueriesContext( - connection - ) as ctx, connection.schema_editor() as editor: + with ( + CaptureQueriesContext(connection) as ctx, + connection.schema_editor() as editor, + ): editor.add_field(Author, new_field) drop_default_sql = editor.sql_alter_column_no_default % { "column": editor.quote_name(new_field.name), @@ -2483,9 +2484,10 @@ class Meta: with self.assertRaises(DatabaseError): self.column_classes(new_field.remote_field.through) # Add the field - with CaptureQueriesContext( - connection - ) as ctx, connection.schema_editor() as editor: + with ( + CaptureQueriesContext(connection) as ctx, + connection.schema_editor() as editor, + ): editor.add_field(LocalAuthorWithM2M, new_field) # Table is not rebuilt. self.assertEqual( @@ -2963,9 +2965,11 @@ def test_remove_ignored_unique_constraint_not_create_fk_index(self): ) # Redundant foreign key index is not added. self.assertEqual( - len(old_constraints) - 1 - if connection.features.supports_partial_indexes - else len(old_constraints), + ( + len(old_constraints) - 1 + if connection.features.supports_partial_indexes + else len(old_constraints) + ), len(new_constraints), ) diff --git a/tests/serializers/models/base.py b/tests/serializers/models/base.py index c5a4a0f5802d..e4fcee366d5d 100644 --- a/tests/serializers/models/base.py +++ b/tests/serializers/models/base.py @@ -4,6 +4,7 @@ ``django.core.serializers`` provides interfaces to converting Django ``QuerySet`` objects to and from "flat" data (i.e. strings). """ + from decimal import Decimal from django.db import models diff --git a/tests/serializers/models/data.py b/tests/serializers/models/data.py index 3d863a3fb2b2..a0e8751461af 100644 --- a/tests/serializers/models/data.py +++ b/tests/serializers/models/data.py @@ -4,6 +4,7 @@ NULL values, where allowed. The basic idea is to have a model for each Django data type. """ + import uuid from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation diff --git a/tests/serializers/models/natural.py b/tests/serializers/models/natural.py index 1e439b34ebd2..cfc57b112785 100644 --- a/tests/serializers/models/natural.py +++ b/tests/serializers/models/natural.py @@ -1,4 +1,5 @@ """Models for test_natural.py""" + import uuid from django.db import models diff --git a/tests/serializers/test_data.py b/tests/serializers/test_data.py index e1cb776d8344..6361dc0c05f8 100644 --- a/tests/serializers/test_data.py +++ b/tests/serializers/test_data.py @@ -6,6 +6,7 @@ the serializers. This includes all valid data values, plus forward, backwards and self references. """ + import datetime import decimal import uuid diff --git a/tests/servers/tests.py b/tests/servers/tests.py index ea49c11534f4..05898009d53b 100644 --- a/tests/servers/tests.py +++ b/tests/servers/tests.py @@ -1,6 +1,7 @@ """ Tests for django.core.servers. """ + import errno import os import socket diff --git a/tests/sessions_tests/models.py b/tests/sessions_tests/models.py index 6eda26f22aff..93f80b347d64 100644 --- a/tests/sessions_tests/models.py +++ b/tests/sessions_tests/models.py @@ -3,6 +3,7 @@ real-world applications, it gives you the option of querying the database for all active sessions for a particular account. """ + from django.contrib.sessions.backends.db import SessionStore as DBStore from django.contrib.sessions.base_session import AbstractBaseSession from django.db import models diff --git a/tests/signals/models.py b/tests/signals/models.py index b758244749ae..5fb9f9f772cc 100644 --- a/tests/signals/models.py +++ b/tests/signals/models.py @@ -1,6 +1,7 @@ """ Testing signals before/after saving and deleting. """ + from django.db import models diff --git a/tests/template_tests/test_parser.py b/tests/template_tests/test_parser.py index e40a5611e21f..eb3bb4911380 100644 --- a/tests/template_tests/test_parser.py +++ b/tests/template_tests/test_parser.py @@ -2,6 +2,7 @@ Testing some internals of the template processing. These are *not* examples to be copied in user code. """ + from django.template import Library, TemplateSyntaxError from django.template.base import ( FilterExpression, diff --git a/tests/test_client/tests.py b/tests/test_client/tests.py index cfd040f7bce3..18b7aaef6c0f 100644 --- a/tests/test_client/tests.py +++ b/tests/test_client/tests.py @@ -19,6 +19,7 @@ rather than the HTML rendered to the end-user. """ + import copy import itertools import tempfile diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index a3545ebfc7aa..4d47fb63af59 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -1,6 +1,7 @@ """ Regression tests for the Test Client, especially the customized assertions. """ + import itertools import os diff --git a/tests/test_runner/test_discover_runner.py b/tests/test_runner/test_discover_runner.py index 5fc35b7bf212..a845f6dd67d4 100644 --- a/tests/test_runner/test_discover_runner.py +++ b/tests/test_runner/test_discover_runner.py @@ -658,9 +658,10 @@ def test_faulthandler_already_enabled(self, mocked_enable): @mock.patch("faulthandler.enable") def test_faulthandler_enabled_fileno(self, mocked_enable): # sys.stderr that is not an actual file. - with mock.patch( - "faulthandler.is_enabled", return_value=False - ), captured_stderr(): + with ( + mock.patch("faulthandler.is_enabled", return_value=False), + captured_stderr(), + ): DiscoverRunner(enable_faulthandler=True) mocked_enable.assert_called() diff --git a/tests/test_runner/tests.py b/tests/test_runner/tests.py index 569fd7e8621e..b900ff69ea0c 100644 --- a/tests/test_runner/tests.py +++ b/tests/test_runner/tests.py @@ -1,6 +1,7 @@ """ Tests for django test runner """ + import collections.abc import multiprocessing import os @@ -992,17 +993,21 @@ def test_run_checks_raises(self): """ Teardown functions are run when run_checks() raises SystemCheckError. """ - with mock.patch( - "django.test.runner.DiscoverRunner.setup_test_environment" - ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( - "django.test.runner.DiscoverRunner.build_suite" - ), mock.patch( - "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError - ), mock.patch( - "django.test.runner.DiscoverRunner.teardown_databases" - ) as teardown_databases, mock.patch( - "django.test.runner.DiscoverRunner.teardown_test_environment" - ) as teardown_test_environment: + with ( + mock.patch("django.test.runner.DiscoverRunner.setup_test_environment"), + mock.patch("django.test.runner.DiscoverRunner.setup_databases"), + mock.patch("django.test.runner.DiscoverRunner.build_suite"), + mock.patch( + "django.test.runner.DiscoverRunner.run_checks", + side_effect=SystemCheckError, + ), + mock.patch( + "django.test.runner.DiscoverRunner.teardown_databases" + ) as teardown_databases, + mock.patch( + "django.test.runner.DiscoverRunner.teardown_test_environment" + ) as teardown_test_environment, + ): runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( @@ -1016,18 +1021,22 @@ def test_run_checks_raises_and_teardown_raises(self): SystemCheckError is surfaced when run_checks() raises SystemCheckError and teardown databases() raises ValueError. """ - with mock.patch( - "django.test.runner.DiscoverRunner.setup_test_environment" - ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( - "django.test.runner.DiscoverRunner.build_suite" - ), mock.patch( - "django.test.runner.DiscoverRunner.run_checks", side_effect=SystemCheckError - ), mock.patch( - "django.test.runner.DiscoverRunner.teardown_databases", - side_effect=ValueError, - ) as teardown_databases, mock.patch( - "django.test.runner.DiscoverRunner.teardown_test_environment" - ) as teardown_test_environment: + with ( + mock.patch("django.test.runner.DiscoverRunner.setup_test_environment"), + mock.patch("django.test.runner.DiscoverRunner.setup_databases"), + mock.patch("django.test.runner.DiscoverRunner.build_suite"), + mock.patch( + "django.test.runner.DiscoverRunner.run_checks", + side_effect=SystemCheckError, + ), + mock.patch( + "django.test.runner.DiscoverRunner.teardown_databases", + side_effect=ValueError, + ) as teardown_databases, + mock.patch( + "django.test.runner.DiscoverRunner.teardown_test_environment" + ) as teardown_test_environment, + ): runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(SystemCheckError): runner.run_tests( @@ -1041,18 +1050,19 @@ def test_run_checks_passes_and_teardown_raises(self): Exceptions on teardown are surfaced if no exceptions happen during run_checks(). """ - with mock.patch( - "django.test.runner.DiscoverRunner.setup_test_environment" - ), mock.patch("django.test.runner.DiscoverRunner.setup_databases"), mock.patch( - "django.test.runner.DiscoverRunner.build_suite" - ), mock.patch( - "django.test.runner.DiscoverRunner.run_checks" - ), mock.patch( - "django.test.runner.DiscoverRunner.teardown_databases", - side_effect=ValueError, - ) as teardown_databases, mock.patch( - "django.test.runner.DiscoverRunner.teardown_test_environment" - ) as teardown_test_environment: + with ( + mock.patch("django.test.runner.DiscoverRunner.setup_test_environment"), + mock.patch("django.test.runner.DiscoverRunner.setup_databases"), + mock.patch("django.test.runner.DiscoverRunner.build_suite"), + mock.patch("django.test.runner.DiscoverRunner.run_checks"), + mock.patch( + "django.test.runner.DiscoverRunner.teardown_databases", + side_effect=ValueError, + ) as teardown_databases, + mock.patch( + "django.test.runner.DiscoverRunner.teardown_test_environment" + ) as teardown_test_environment, + ): runner = DiscoverRunner(verbosity=0, interactive=False) with self.assertRaises(ValueError): # Suppress the output when running TestDjangoTestCase. diff --git a/tests/transactions/models.py b/tests/transactions/models.py index 9506bace3516..3d4c7d7e4496 100644 --- a/tests/transactions/models.py +++ b/tests/transactions/models.py @@ -6,6 +6,7 @@ commit-on-success behavior. Alternatively, you can manage the transaction manually. """ + from django.db import models diff --git a/tests/urlpatterns_reverse/tests.py b/tests/urlpatterns_reverse/tests.py index 89dfd0deba4f..8384f55b3c51 100644 --- a/tests/urlpatterns_reverse/tests.py +++ b/tests/urlpatterns_reverse/tests.py @@ -1,6 +1,7 @@ """ Unit tests for reverse URL lookups. """ + import pickle import sys import threading diff --git a/tests/urls.py b/tests/urls.py index 7d3a3a790aee..67c4d4091b43 100644 --- a/tests/urls.py +++ b/tests/urls.py @@ -3,5 +3,4 @@ This helps the tests remain isolated. """ - urlpatterns = [] diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py index 07229f25ed99..d5d90b68fc08 100644 --- a/tests/utils_tests/test_datastructures.py +++ b/tests/utils_tests/test_datastructures.py @@ -1,6 +1,7 @@ """ Tests for stuff in django.utils.datastructures. """ + import collections.abc import copy import pickle diff --git a/tests/utils_tests/test_jslex.py b/tests/utils_tests/test_jslex.py index ee13eb4d64e6..59551930c6fc 100644 --- a/tests/utils_tests/test_jslex.py +++ b/tests/utils_tests/test_jslex.py @@ -1,4 +1,5 @@ """Tests for jslex.""" + # originally from https://bitbucket.org/ned/jslex from django.test import SimpleTestCase diff --git a/tests/view_tests/tests/test_debug.py b/tests/view_tests/tests/test_debug.py index 54c5da056e1e..03db07a61c3c 100644 --- a/tests/view_tests/tests/test_debug.py +++ b/tests/view_tests/tests/test_debug.py @@ -332,14 +332,19 @@ def test_template_loader_postmortem(self): with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile: tempdir = os.path.dirname(tmpfile.name) template_path = os.path.join(tempdir, template_name) - with override_settings( - TEMPLATES=[ - { - "BACKEND": "django.template.backends.django.DjangoTemplates", - "DIRS": [tempdir], - } - ] - ), self.assertLogs("django.request", "ERROR"): + with ( + override_settings( + TEMPLATES=[ + { + "BACKEND": ( + "django.template.backends.django.DjangoTemplates" + ), + "DIRS": [tempdir], + } + ] + ), + self.assertLogs("django.request", "ERROR"), + ): response = self.client.get( reverse( "raises_template_does_not_exist", kwargs={"path": template_name}