diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 1c3571406f..d6ea11e8e0 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 8b96e91ea8..7415143848 100644
--- a/django/__main__.py
+++ b/django/__main__.py
@@ -3,6 +3,7 @@ Invokes django-admin when the django module is run as a script.
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 06dedf8727..675c4a5d49 100644
--- a/django/contrib/admin/filters.py
+++ b/django/contrib/admin/filters.py
@@ -5,6 +5,7 @@ Filters are specified in models with the "list_filter" option.
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 e3703f5866..d97597fe66 100644
--- a/django/contrib/admin/options.py
+++ b/django/contrib/admin/options.py
@@ -1759,9 +1759,9 @@ class ModelAdmin(BaseModelAdmin):
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 @@ class ModelAdmin(BaseModelAdmin):
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 2dcdf62afb..0c32290b6c 100644
--- a/django/contrib/admin/templatetags/admin_list.py
+++ b/django/contrib/admin/templatetags/admin_list.py
@@ -171,9 +171,9 @@ def result_headers(cl):
"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 items_for_result(cl, result, form):
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 3352e75e79..216b87671b 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 ccfe19fcc1..0c9538d69d 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 ad31a6e68f..b29a980cb2 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 6d650cca67..75ef68ff68 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 @@ class Command(BaseCommand):
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 f06f73148e..af749c3435 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 ed86985cf8..eb86dc39de 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 c95f903253..c9715e1756 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 2f4393d25e..8bc16a1abb 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 b7b568274a..e35ef75ce9 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 7cc98ae126..0f5f7b55ef 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 8a3d84b5de..3d10a53641 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 419b64c5e8..acbaa5ffc0 100644
--- a/django/contrib/gis/db/models/functions.py
+++ b/django/contrib/gis/db/models/functions.py
@@ -127,9 +127,11 @@ class SQLiteDecimalToFloatMixin:
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 @@ class Distance(DistanceResultMixin, OracleToleranceMixin, GeoFunc):
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 4db365dc16..b415e147fc 100644
--- a/django/contrib/gis/db/models/proxy.py
+++ b/django/contrib/gis/db/models/proxy.py
@@ -5,6 +5,7 @@ objects corresponding to geographic model fields.
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 be712319fb..7802b2dd1e 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 9ed6e31156..e63808d39d 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 8900777117..2ce859ad13 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 4c2c1e4a1a..05832bd7cc 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 f4ba5816a2..4c1f74d4b0 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 e3ef2699e9..71148f1b55 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 52bb7cb083..d37e81cdf6 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 230e56f665..4d34a96e70 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 17ee4a1926..d1dd9ec4e2 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 dccc9cfab4..a1ab62f37a 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 9417c6684d..0a8d95c1fc 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 27de1ca8e6..f50cd19856 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 abfec8af3d..35262a5622 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 0ff4ecb2e5..15400e08fe 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 00b36af0a6..8bbe2c264a 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 d7898065f0..8dd3f289e6 100644
--- a/django/contrib/gis/geos/io.py
+++ b/django/contrib/gis/geos/io.py
@@ -3,6 +3,7 @@ Module that holds classes for performing I/O operations on GEOS geometry
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 1121b4f715..b883c6c090 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 a527f513a7..42b24c2891 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 fccd0ecc9e..bd5859e79b 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 32b790173a..dd07cbfb26 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 e61eae964a..9323bb2d16 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 12f032c665..f42fa90226 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 40ca0cb461..76c8bfbcfa 100644
--- a/django/contrib/gis/utils/ogrinspect.py
+++ b/django/contrib/gis/utils/ogrinspect.py
@@ -3,6 +3,7 @@ This module is for inspecting OGR data sources and generating either
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 936709c2f8..4d279857c6 100644
--- a/django/contrib/postgres/search.py
+++ b/django/contrib/postgres/search.py
@@ -116,9 +116,11 @@ class SearchVector(SearchVectorCombinable, Func):
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 603d2fe12c..8809dd36f7 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 83d04d4cec..3fb2677322 100644
--- a/django/contrib/staticfiles/views.py
+++ b/django/contrib/staticfiles/views.py
@@ -3,6 +3,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 os
import posixpath
diff --git a/django/core/cache/__init__.py b/django/core/cache/__init__.py
index eb7fa5b2e9..444d958e68 100644
--- a/django/core/cache/__init__.py
+++ b/django/core/cache/__init__.py
@@ -12,6 +12,7 @@ object.
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 2a2288ff4d..31c18ee7e1 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 6a603f24fc..7c1532ac8f 100644
--- a/django/core/files/images.py
+++ b/django/core/files/images.py
@@ -3,6 +3,7 @@ Utility functions for handling images.
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 c0f471f87d..a7a7a22dce 100644
--- a/django/core/files/locks.py
+++ b/django/core/files/locks.py
@@ -16,6 +16,7 @@ Example Usage::
... 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 b6c185e8fc..ab86f7fede 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 dc63e8702c..676326697b 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 ee5dd28504..2d7c778cc1 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 344350e891..f5473da952 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 1ee48269ae..6820148ac1 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 631c761c00..4c47e1c6e5 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 @@ class BaseCommand:
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 @@ class BaseCommand:
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 20dffac05f..1fbca9244b 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 3f9955aa23..16b69770f6 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 f01abf46b0..242083b850 100644
--- a/django/db/backends/base/schema.py
+++ b/django/db/backends/base/schema.py
@@ -724,9 +724,9 @@ class BaseDatabaseSchemaEditor:
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 @@ class BaseDatabaseSchemaEditor:
"""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 412d07a993..75787ef8ab 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 f36139881d..b8d2d09c94 100644
--- a/django/db/backends/mysql/base.py
+++ b/django/db/backends/mysql/base.py
@@ -3,6 +3,7 @@ MySQL database backend for Django.
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 2d91468d25..f626c4d2d4 100644
--- a/django/db/backends/oracle/base.py
+++ b/django/db/backends/oracle/base.py
@@ -3,6 +3,7 @@ Oracle database backend for Django.
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 df773bff8c..b0a5177728 100644
--- a/django/db/backends/oracle/creation.py
+++ b/django/db/backends/oracle/creation.py
@@ -133,20 +133,20 @@ class DatabaseCreation(BaseDatabaseCreation):
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 cba89e0cc7..8349d8f310 100644
--- a/django/db/backends/postgresql/base.py
+++ b/django/db/backends/postgresql/base.py
@@ -226,9 +226,11 @@ class DatabaseWrapper(BaseDatabaseWrapper):
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 5dc93a27d0..842830be30 100644
--- a/django/db/backends/postgresql/schema.py
+++ b/django/db/backends/postgresql/schema.py
@@ -267,9 +267,9 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
% {
"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 7e86950f7d..0171b60f38 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 08de0bad5a..10a296c992 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 6b01403d18..f000d9fcaa 100644
--- a/django/db/migrations/autodetector.py
+++ b/django/db/migrations/autodetector.py
@@ -620,11 +620,12 @@ class MigrationAutodetector:
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 @@ class MigrationAutodetector:
(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 81dcd06e04..50445f3101 100644
--- a/django/db/migrations/loader.py
+++ b/django/db/migrations/loader.py
@@ -131,11 +131,11 @@ class MigrationLoader:
"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 b24a8f6557..38c68f3ff3 100644
--- a/django/db/migrations/operations/models.py
+++ b/django/db/migrations/operations/models.py
@@ -56,11 +56,11 @@ class CreateModel(ModelOperation):
_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 5ffd7fc07a..42a2c80a5e 100644
--- a/django/db/migrations/state.py
+++ b/django/db/migrations/state.py
@@ -524,11 +524,11 @@ class ProjectState:
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 a778cd413b..0cbffacd1b 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 61925f63ea..c1f78d0632 100644
--- a/django/db/models/base.py
+++ b/django/db/models/base.py
@@ -2265,9 +2265,11 @@ class Model(AltersData, metaclass=ModelBase):
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 a0c99c95fc..cec1b9b90f 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 f25ad1af12..6d329ae85d 100644
--- a/django/db/models/expressions.py
+++ b/django/db/models/expressions.py
@@ -204,9 +204,11 @@ class BaseExpression:
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 @@ class BaseExpression:
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 @@ class BaseExpression:
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 @@ class BaseExpression:
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 f5a81ab49c..62ddfc60b3 100644
--- a/django/db/models/fields/related_descriptors.py
+++ b/django/db/models/fields/related_descriptors.py
@@ -62,6 +62,7 @@ and two directions (forward and reverse) for a total of six combinations.
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 c74e92ba89..144cce6142 100644
--- a/django/db/models/fields/reverse_related.py
+++ b/django/db/models/fields/reverse_related.py
@@ -8,6 +8,7 @@ in the ``remote_field`` attribute of the field.
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 ae41f1da95..6db81d6f46 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 fca211e065..9937e79f6f 100644
--- a/django/db/models/functions/datetime.py
+++ b/django/db/models/functions/datetime.py
@@ -318,9 +318,11 @@ class TruncBase(TimezoneMixin, Transform):
"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 @@ class TruncBase(TimezoneMixin, Transform):
"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 460143ba5a..5fa4654a84 100644
--- a/django/db/models/functions/math.py
+++ b/django/db/models/functions/math.py
@@ -47,9 +47,11 @@ class ATan2(NumericOutputFieldMixin, Func):
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 661eee1c13..0f6f0a2aa8 100644
--- a/django/db/models/functions/mixins.py
+++ b/django/db/models/functions/mixins.py
@@ -14,9 +14,11 @@ class FixDecimalInputMixin:
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 392061880c..df826ffdb5 100644
--- a/django/db/models/functions/text.py
+++ b/django/db/models/functions/text.py
@@ -89,9 +89,11 @@ class ConcatPair(Func):
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 b5451f9e24..0ddfefec38 100644
--- a/django/db/models/indexes.py
+++ b/django/db/models/indexes.py
@@ -196,9 +196,11 @@ class Index:
"" 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 4a6e2b3241..139875eed5 100644
--- a/django/db/models/lookups.py
+++ b/django/db/models/lookups.py
@@ -273,9 +273,11 @@ class FieldGetDbPrepValueMixin:
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 61d4002000..b9e2d1f7e5 100644
--- a/django/db/models/query.py
+++ b/django/db/models/query.py
@@ -109,9 +109,11 @@ class ModelIterable(BaseIterable):
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 @@ class QuerySet(AltersData):
clone._iterable_class = (
NamedValuesListIterable
if named
- else FlatValuesListIterable
- if flat
- else ValuesListIterable
+ else FlatValuesListIterable if flat else ValuesListIterable
)
return clone
@@ -1659,9 +1659,11 @@ class QuerySet(AltersData):
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 4f3358eb8d..e1041b9653 100644
--- a/django/db/models/query_utils.py
+++ b/django/db/models/query_utils.py
@@ -5,6 +5,7 @@ Factored out from django.db.models.query to avoid making the main module very
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 10338259d5..9a0d2eb4e7 100644
--- a/django/db/models/sql/compiler.py
+++ b/django/db/models/sql/compiler.py
@@ -1224,9 +1224,9 @@ class SQLCompiler:
"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 5eaa8c25f6..7c0c14a46e 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 ce4fafb1e2..6e8813b5e7 100644
--- a/django/db/models/sql/query.py
+++ b/django/db/models/sql/query.py
@@ -6,6 +6,7 @@ themselves do not have to (and could be backed by things other than SQL
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 8423fcb528..0fded5cce3 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 6a2608c0b3..cd6986d72a 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 @@ class BaseModelFormSet(BaseFormSet, AltersData):
)
# 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 2c734052d5..4fae110d5e 100644
--- a/django/forms/widgets.py
+++ b/django/forms/widgets.py
@@ -101,9 +101,11 @@ class Media:
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 @@ class Media:
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 dfd406c35e..58b8546be7 100644
--- a/django/http/multipartparser.py
+++ b/django/http/multipartparser.py
@@ -4,6 +4,7 @@ Multi-part parsing for file uploads.
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 fe15a173be..4c27d576ba 100644
--- a/django/http/request.py
+++ b/django/http/request.py
@@ -170,9 +170,11 @@ class HttpRequest:
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 2c0d2cc120..f7943494ba 100644
--- a/django/middleware/csrf.py
+++ b/django/middleware/csrf.py
@@ -4,6 +4,7 @@ Cross Site Request Forgery Middleware.
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 822e6107ac..b8b5be1f5f 100644
--- a/django/shortcuts.py
+++ b/django/shortcuts.py
@@ -3,6 +3,7 @@ This module collects helper functions and classes that "span" multiple levels
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 1e1bdbc5c9..a08ce2710d 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 40c2917f56..dd0a6b3579 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 f2215c0e4e..9882d3a16d 100644
--- a/django/template/engine.py
+++ b/django/template/engine.py
@@ -70,9 +70,11 @@ class Engine:
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 5b15a5a476..0a917c2aaa 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 6da79d6fb2..33d1d4dafb 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 40708028a3..bb61063d77 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 89ae18694c..3607c84228 100644
--- a/django/urls/resolvers.py
+++ b/django/urls/resolvers.py
@@ -5,6 +5,7 @@ URLResolver is the main class here. Its resolve() method takes a URL (as
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 @@ class ResolverMatch:
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 71ec2d0015..56f34c0038 100644
--- a/django/utils/archive.py
+++ b/django/utils/archive.py
@@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
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 cf797d0279..3b014fbe51 100644
--- a/django/utils/cache.py
+++ b/django/utils/cache.py
@@ -14,6 +14,7 @@ cache keys to prevent delivery of wrong content.
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 1c0e7001c6..5134b854d6 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 a6c315e4cf..a3274b901c 100644
--- a/django/utils/dateformat.py
+++ b/django/utils/dateformat.py
@@ -10,6 +10,7 @@ Usage:
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 f8754c1974..2e5463a651 100644
--- a/django/utils/deconstruct.py
+++ b/django/utils/deconstruct.py
@@ -42,9 +42,11 @@ def deconstructible(*args, path=None):
"#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 31ca9a2db9..3bd456ca68 100644
--- a/django/utils/feedgenerator.py
+++ b/django/utils/feedgenerator.py
@@ -21,6 +21,7 @@ Sample usage:
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 93a1a2e972..fc46a686c7 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 9ee82e1a9b..b71298e399 100644
--- a/django/utils/regex_helper.py
+++ b/django/utils/regex_helper.py
@@ -5,6 +5,7 @@ Used internally by Django and not intended for external use.
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 0b3f78e486..0618f02159 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 872c80b00f..a629528717 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 5d5dcbc790..a4c1ebc31e 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 df46c53093..b24f0e30f9 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 7d55cb0333..77e24ff0eb 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 07f2e20a1c..d40f4b4cb4 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 b7bd22d9c1..3cc96cce84 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 61ec9295eb..fc8e928890 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 8bdfb1e38b..b472f092e9 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 1e7ac4f0ba..b4a1537896 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 c7909c8a4b..15bef9b5fb 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 84fe3cb768..b36f884096 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 6871d43d7b..49b69bf066 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 be031f1f68..72c986cfc7 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 13a76188bb..65dc132a94 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 9cdadbe286..8cb5dd5d5a 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 23cfa833e0..e85ba9c36a 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 9ae9d4f03a..3f17a68574 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 eee1c66d56..9db029cc60 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 8ebb4f5116..3e357cba17 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 f0ed8f4169..145334c238 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 b5213ee207..d98fad2c66 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 de3ed69a70..526bb1d66e 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 746eaae836..6b18bace4f 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 6c9d35b533..87550ff46d 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 75d33b5e7e..de2bc51cda 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 880f606aae..6625b6946c 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 9a91ceb469..3e3bbe19d6 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 2447697de4..dfd36a64ae 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 48c5605ff4..ac5b34dae0 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 9146ecc2f7..63a6bc2d66 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 53ce716a4d..e2a37296b7 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 0e696badc0..911c282157 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 a4d973ebb4..6a577dd8ad 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 cd05db2cf8..14a58c4c00 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 03afaa33d9..94a6a8eb6c 100644
--- a/tests/admin_changelist/test_date_hierarchy.py
+++ b/tests/admin_changelist/test_date_hierarchy.py
@@ -90,7 +90,8 @@ class DateHierarchyTests(TestCase):
{"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 a8d2ee02e1..eca5bae422 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 7f39d7fcfc..50e8d4a3b1 100644
--- a/tests/admin_scripts/tests.py
+++ b/tests/admin_scripts/tests.py
@@ -3,6 +3,7 @@ A series of tests to establish that the command-line management tools work as
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 @@ class DjangoAdminSettingsDirectory(AdminScriptTestCase):
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 6dc2011b24..17b6498aab 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 e3429ec4bc..4b30c5c30f 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 bfb3919b23..9199bf3eba 100644
--- a/tests/aggregation_regress/tests.py
+++ b/tests/aggregation_regress/tests.py
@@ -1564,8 +1564,9 @@ class AggregationTests(TestCase):
"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 52d28bd276..385de4e846 100644
--- a/tests/auth_tests/models/custom_permissions.py
+++ b/tests/auth_tests/models/custom_permissions.py
@@ -3,6 +3,7 @@ The CustomPermissionsUser users email as the identifier, but uses the normal
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 14d71572da..14604cd2e6 100644
--- a/tests/auth_tests/test_forms.py
+++ b/tests/auth_tests/test_forms.py
@@ -486,8 +486,9 @@ class AuthenticationFormTest(TestDataMixin, TestCase):
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 @@ class UserChangeFormTest(TestDataMixin, TestCase):
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 e0b640a998..1b0d2c65be 100644
--- a/tests/auth_tests/test_hashers.py
+++ b/tests/auth_tests/test_hashers.py
@@ -213,8 +213,9 @@ class TestUtilsHashPass(SimpleTestCase):
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 @@ class TestUtilsHashPass(SimpleTestCase):
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 @@ class TestUtilsHashPass(SimpleTestCase):
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 ba0a77a4dc..f4cf6ed2f4 100644
--- a/tests/auth_tests/test_views.py
+++ b/tests/auth_tests/test_views.py
@@ -818,9 +818,9 @@ class LoginTest(AuthViewsTestCase):
# 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 9f2fa4e576..03356fbf10 100644
--- a/tests/backends/base/test_base.py
+++ b/tests/backends/base/test_base.py
@@ -168,8 +168,9 @@ class ExecuteWrapperTests(TestCase):
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 @@ class ExecuteWrapperTests(TestCase):
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 03d4b036fd..704498836e 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 5c562682f0..08a21d8ded 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 856e351dfa..324e980937 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 6802f825ff..236884f4cc 100644
--- a/tests/basic/models.py
+++ b/tests/basic/models.py
@@ -3,6 +3,7 @@ Bare-bones model
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 b1839f48c3..cb035a90a4 100644
--- a/tests/check_framework/test_security.py
+++ b/tests/check_framework/test_security.py
@@ -593,8 +593,9 @@ class CheckReferrerPolicyTest(SimpleTestCase):
("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 @@ class CheckCrossOriginOpenerPolicyTest(SimpleTestCase):
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 eb472d80ce..14ff4e5952 100644
--- a/tests/contenttypes_tests/test_management.py
+++ b/tests/contenttypes_tests/test_management.py
@@ -88,9 +88,10 @@ class RemoveStaleContentTypesTests(TestCase):
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 @@ class RemoveStaleContentTypesTests(TestCase):
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 02036de83f..88f715ceff 100644
--- a/tests/contenttypes_tests/test_models.py
+++ b/tests/contenttypes_tests/test_models.py
@@ -323,8 +323,9 @@ class ContentTypesMultidbTests(TestCase):
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 4d85d15065..75f39a7bab 100644
--- a/tests/contenttypes_tests/test_views.py
+++ b/tests/contenttypes_tests/test_views.py
@@ -150,10 +150,8 @@ class ContentTypesViewsSiteRelTests(TestCase):
"""
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 @@ class ContentTypesViewsSiteRelTests(TestCase):
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 23f9d59149..ba92ff8b05 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 8fc31d4e6b..f107c5320a 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 9839e6b4c5..cdbc3d6960 100644
--- a/tests/db_functions/comparison/test_nullif.py
+++ b/tests/db_functions/comparison/test_nullif.py
@@ -23,9 +23,11 @@ class NullIfTests(TestCase):
[
("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 29212b6e24..e576e6e464 100644
--- a/tests/db_functions/datetime/test_extract_trunc.py
+++ b/tests/db_functions/datetime/test_extract_trunc.py
@@ -113,9 +113,11 @@ class DateFunctionTests(TestCase):
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 d6a06511bc..c126f1bae1 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 fd0aec58f2..4fd66f0397 100644
--- a/tests/db_functions/text/test_md5.py
+++ b/tests/db_functions/text/test_md5.py
@@ -35,9 +35,11 @@ class MD5Tests(TestCase):
"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 175c5727ff..ef846d07aa 100644
--- a/tests/db_functions/text/test_sha1.py
+++ b/tests/db_functions/text/test_sha1.py
@@ -35,9 +35,11 @@ class SHA1Tests(TestCase):
"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 a6254f43e3..60d9e378a6 100644
--- a/tests/db_functions/text/test_sha224.py
+++ b/tests/db_functions/text/test_sha224.py
@@ -37,9 +37,11 @@ class SHA224Tests(TestCase):
"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 b399dbecd3..0cf72783e7 100644
--- a/tests/db_functions/text/test_sha256.py
+++ b/tests/db_functions/text/test_sha256.py
@@ -35,9 +35,11 @@ class SHA256Tests(TestCase):
"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 250cadda4a..a4d07d3295 100644
--- a/tests/db_functions/text/test_sha384.py
+++ b/tests/db_functions/text/test_sha384.py
@@ -39,10 +39,12 @@ class SHA384Tests(TestCase):
"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 f5a7ad4ae5..b4c7a4bbd8 100644
--- a/tests/db_functions/text/test_sha512.py
+++ b/tests/db_functions/text/test_sha512.py
@@ -39,10 +39,12 @@ class SHA512Tests(TestCase):
"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 a2d9cc7b5e..4028a8acdf 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 faf9882ad9..e795f7619b 100644
--- a/tests/dbshell/test_sqlite.py
+++ b/tests/dbshell/test_sqlite.py
@@ -35,8 +35,11 @@ class SqliteDbshellCommandTestCase(SimpleTestCase):
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 b80878bbf2..93b3f27aec 100644
--- a/tests/distinct_on_fields/tests.py
+++ b/tests/distinct_on_fields/tests.py
@@ -76,9 +76,11 @@ class DistinctOnTests(TestCase):
(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 bd4db9050e..43dd235fb5 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 9fdef57324..6db8f9022d 100644
--- a/tests/file_uploads/tests.py
+++ b/tests/file_uploads/tests.py
@@ -452,9 +452,10 @@ class FileUploadTests(TestCase):
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 @@ class FileUploadTests(TestCase):
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 a1e1a5af05..d3c88ac305 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 7dc5c04668..9d3a471cb3 100644
--- a/tests/files/tests.py
+++ b/tests/files/tests.py
@@ -144,35 +144,40 @@ class FileTests(unittest.TestCase):
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 b95b197454..e6fdfbd827 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 9d26bc88b0..cb13e5b71b 100644
--- a/tests/forms_tests/field_tests/test_decimalfield.py
+++ b/tests/forms_tests/field_tests/test_decimalfield.py
@@ -80,8 +80,9 @@ class DecimalFieldTest(FormFieldAssertionsMixin, SimpleTestCase):
"--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 11388bdc09..9744981471 100644
--- a/tests/forms_tests/field_tests/test_filefield.py
+++ b/tests/forms_tests/field_tests/test_filefield.py
@@ -53,7 +53,8 @@ class FileFieldTest(SimpleTestCase):
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 3c260010c2..f80c1dc09e 100644
--- a/tests/forms_tests/tests/test_formsets.py
+++ b/tests/forms_tests/tests/test_formsets.py
@@ -217,9 +217,12 @@ class FormsFormsetTestCase(SimpleTestCase):
[("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 67108cbb32..a5f1edef0b 100644
--- a/tests/gis_tests/gdal_tests/test_raster.py
+++ b/tests/gis_tests/gdal_tests/test_raster.py
@@ -102,8 +102,9 @@ class GDALRasterTests(SimpleTestCase):
]
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 8565608993..cb783b9465 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 0a94907320..8dd6042175 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 76d99e2504..7a5a287da7 100644
--- a/tests/handlers/tests.py
+++ b/tests/handlers/tests.py
@@ -240,8 +240,9 @@ class HandlerRequestTests(SimpleTestCase):
("/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 cce8402d3f..2197c6f7ea 100644
--- a/tests/httpwrappers/tests.py
+++ b/tests/httpwrappers/tests.py
@@ -352,9 +352,9 @@ class HttpResponseTests(SimpleTestCase):
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 f22f273c9a..9d9a09d34e 100644
--- a/tests/invalid_models_tests/test_models.py
+++ b/tests/invalid_models_tests/test_models.py
@@ -1898,15 +1898,18 @@ class ConstraintsTests(TestCase):
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 ConstraintsTests(TestCase):
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 ConstraintsTests(TestCase):
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 ConstraintsTests(TestCase):
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 6a5b0b29c9..4cbd1eb4e8 100644
--- a/tests/m2m_and_m2o/models.py
+++ b/tests/m2m_and_m2o/models.py
@@ -3,6 +3,7 @@ Many-to-many and many-to-one relationships to the same table
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 1333d14b41..f82498651f 100644
--- a/tests/m2m_intermediary/models.py
+++ b/tests/m2m_intermediary/models.py
@@ -9,6 +9,7 @@ each ``Article``-``Reporter`` combination (a ``Writer``) has a ``position``
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 cd981b6e9e..dd6b72ab49 100644
--- a/tests/mail/tests.py
+++ b/tests/mail/tests.py
@@ -1392,8 +1392,9 @@ class BaseEmailBackendTests(HeadersCheckMixin):
):
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 541928e94d..42fc426990 100644
--- a/tests/many_to_many/models.py
+++ b/tests/many_to_many/models.py
@@ -6,6 +6,7 @@ To define a many-to-many relationship, use ``ManyToManyField()``.
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 cca7e79817..56e660592a 100644
--- a/tests/many_to_one/models.py
+++ b/tests/many_to_one/models.py
@@ -3,6 +3,7 @@ Many-to-one relationships
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 dd220b8f4c..339b9181c3 100644
--- a/tests/middleware/test_security.py
+++ b/tests/middleware/test_security.py
@@ -248,8 +248,9 @@ class SecurityMiddlewareTest(SimpleTestCase):
(("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 @@ class SecurityMiddlewareTest(SimpleTestCase):
"""
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 4dc1c83c42..4c17b4ec34 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 263b25ab61..1f8b3fb011 100644
--- a/tests/migrations/test_commands.py
+++ b/tests/migrations/test_commands.py
@@ -3102,9 +3102,11 @@ class OptimizeMigrationTests(MigrationTestBase):
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 @@ class OptimizeMigrationTests(MigrationTestBase):
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 6232b44b98..571cb3e1a2 100644
--- a/tests/migrations/test_executor.py
+++ b/tests/migrations/test_executor.py
@@ -405,9 +405,9 @@ class ExecutorTests(MigrationTestBase):
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 52e43d20f9..5733ba7618 100644
--- a/tests/migrations/test_operations.py
+++ b/tests/migrations/test_operations.py
@@ -3614,15 +3614,17 @@ class OperationTests(OperationTestBase):
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 @@ class OperationTests(OperationTestBase):
)
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 @@ class OperationTests(OperationTestBase):
)
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 @@ class OperationTests(OperationTestBase):
)
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 @@ class OperationTests(OperationTestBase):
)
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 47aae186e0..ffb9f28cfa 100644
--- a/tests/model_inheritance/models.py
+++ b/tests/model_inheritance/models.py
@@ -11,6 +11,7 @@ Model inheritance exists in two varieties:
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 5bf1ef5db5..6b005fcef0 100644
--- a/tests/model_inheritance/tests.py
+++ b/tests/model_inheritance/tests.py
@@ -216,9 +216,11 @@ class ModelInheritanceTests(TestCase):
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 1a9f953d6f..ba31048ac2 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 adfdbf3bea..d7b6ad8238 100644
--- a/tests/null_fk_ordering/models.py
+++ b/tests/null_fk_ordering/models.py
@@ -5,6 +5,7 @@ Regression tests for proper working of ForeignKey(null=True). Tests these bugs:
unexpected results
"""
+
from django.db import models
diff --git a/tests/one_to_one/models.py b/tests/one_to_one/models.py
index ca459e9edf..20b2eeec7d 100644
--- a/tests/one_to_one/models.py
+++ b/tests/one_to_one/models.py
@@ -5,6 +5,7 @@ To define a one-to-one relationship, use ``OneToOneField()``.
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 ea548ca076..5170c6d957 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 @@ class BaseOrderWithRespectToTests:
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 c2513fca0c..c5dddf197f 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 bf47833743..e5a8e9dbe9 100644
--- a/tests/postgres_tests/test_constraints.py
+++ b/tests/postgres_tests/test_constraints.py
@@ -300,8 +300,9 @@ class ExclusionConstraintTests(PostgreSQLTestCase):
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 6f6318899c..472dca6c7b 100644
--- a/tests/postgres_tests/test_search.py
+++ b/tests/postgres_tests/test_search.py
@@ -5,6 +5,7 @@ These tests use dialogue from the 1975 film Monty Python and the Holy Grail.
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 08f87d55de..a418beb5a5 100644
--- a/tests/prefetch_related/tests.py
+++ b/tests/prefetch_related/tests.py
@@ -1620,8 +1620,9 @@ class MultiDbTests(TestCase):
)
# 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 604136b5ac..c0277e093f 100644
--- a/tests/proxy_models/models.py
+++ b/tests/proxy_models/models.py
@@ -4,6 +4,7 @@ they will take data directly from the table of their base class table rather
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 23c41e3374..9f4cf040b6 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 c6eed0e479..5afb9e9993 100644
--- a/tests/requests_tests/test_accept_header.py
+++ b/tests/requests_tests/test_accept_header.py
@@ -68,9 +68,9 @@ class AcceptHeaderTests(TestCase):
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 @@ class AcceptHeaderTests(TestCase):
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 e7c598aeae..8b9826eb14 100644
--- a/tests/save_delete_hooks/models.py
+++ b/tests/save_delete_hooks/models.py
@@ -4,6 +4,7 @@ Adding hooks before/after saving and deleting
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 998cb28b8c..24a26b2c2c 100644
--- a/tests/schema/fields.py
+++ b/tests/schema/fields.py
@@ -41,9 +41,11 @@ class CustomManyToManyField(RelatedField):
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 61244f75b4..3a026281bd 100644
--- a/tests/schema/tests.py
+++ b/tests/schema/tests.py
@@ -640,9 +640,10 @@ class SchemaTests(TransactionTestCase):
# 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 SchemaTests(TransactionTestCase):
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 @@ class SchemaTests(TransactionTestCase):
)
# 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 c5a4a0f580..e4fcee366d 100644
--- a/tests/serializers/models/base.py
+++ b/tests/serializers/models/base.py
@@ -4,6 +4,7 @@ Serialization
``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 3d863a3fb2..a0e8751461 100644
--- a/tests/serializers/models/data.py
+++ b/tests/serializers/models/data.py
@@ -4,6 +4,7 @@ The following classes are for testing basic data marshalling, including
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 1e439b34eb..cfc57b1127 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 e1cb776d83..6361dc0c05 100644
--- a/tests/serializers/test_data.py
+++ b/tests/serializers/test_data.py
@@ -6,6 +6,7 @@ test case that is capable of testing the capabilities of
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 ea49c11534..05898009d5 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 6eda26f22a..93f80b347d 100644
--- a/tests/sessions_tests/models.py
+++ b/tests/sessions_tests/models.py
@@ -3,6 +3,7 @@ This custom Session model adds an extra column to store an account ID. In
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 b758244749..5fb9f9f772 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 e40a5611e2..eb3bb49113 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 cfd040f7bc..18b7aaef6c 100644
--- a/tests/test_client/tests.py
+++ b/tests/test_client/tests.py
@@ -19,6 +19,7 @@ testing against the contexts and templates produced by a view,
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 a3545ebfc7..4d47fb63af 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 5fc35b7bf2..a845f6dd67 100644
--- a/tests/test_runner/test_discover_runner.py
+++ b/tests/test_runner/test_discover_runner.py
@@ -658,9 +658,10 @@ class DiscoverRunnerTests(SimpleTestCase):
@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 569fd7e862..b900ff69ea 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 @@ class RunTestsExceptionHandlingTests(unittest.TestCase):
"""
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 @@ class RunTestsExceptionHandlingTests(unittest.TestCase):
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 @@ class RunTestsExceptionHandlingTests(unittest.TestCase):
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 9506bace35..3d4c7d7e44 100644
--- a/tests/transactions/models.py
+++ b/tests/transactions/models.py
@@ -6,6 +6,7 @@ each transaction upon a write, but you can decorate a function to get
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 89dfd0deba..8384f55b3c 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 7d3a3a790a..67c4d4091b 100644
--- a/tests/urls.py
+++ b/tests/urls.py
@@ -3,5 +3,4 @@ should be added within the test folders, and use TestCase.urls to set them.
This helps the tests remain isolated.
"""
-
urlpatterns = []
diff --git a/tests/utils_tests/test_datastructures.py b/tests/utils_tests/test_datastructures.py
index 07229f25ed..d5d90b68fc 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 ee13eb4d64..59551930c6 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 54c5da056e..03db07a61c 100644
--- a/tests/view_tests/tests/test_debug.py
+++ b/tests/view_tests/tests/test_debug.py
@@ -332,14 +332,19 @@ class DebugViewTests(SimpleTestCase):
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}