1
0
mirror of https://github.com/django/django.git synced 2024-12-22 17:16:24 +00:00

Bumped minimum isort version to 5.1.0.

Fixed inner imports per isort 5.
isort 5.0.0 to 5.1.0 was unstable.
This commit is contained in:
David Smith 2020-07-24 07:25:47 +01:00 committed by Mariusz Felisiak
parent 1173db4a16
commit e74b3d724e
49 changed files with 115 additions and 59 deletions

View File

@ -128,6 +128,7 @@ class Apps:
"""Raise an exception if all apps haven't been imported yet."""
if not self.apps_ready:
from django.conf import settings
# If "not ready" is due to unconfigured settings, accessing
# INSTALLED_APPS raises a more helpful ImproperlyConfigured
# exception.

View File

@ -814,8 +814,7 @@ class ModelAdminChecks(BaseModelAdminChecks):
2. ('field', SomeFieldListFilter) - a field-based list filter class
3. SomeListFilter - a non-field list filter class
"""
from django.contrib.admin import ListFilter, FieldListFilter
from django.contrib.admin import FieldListFilter, ListFilter
if callable(item) and not isinstance(item, models.Field):
# If item is option 3, it should be a ListFilter...

View File

@ -10,7 +10,7 @@ def register(*models, site=None):
The `site` kwarg is an admin site to use instead of the default admin site.
"""
from django.contrib.admin import ModelAdmin
from django.contrib.admin.sites import site as default_site, AdminSite
from django.contrib.admin.sites import AdminSite, site as default_site
def _model_admin_wrapper(admin_class):
if not models:

View File

@ -808,7 +808,7 @@ class ModelAdmin(BaseModelAdmin):
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, ADDITION
from django.contrib.admin.models import ADDITION, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
@ -824,7 +824,7 @@ class ModelAdmin(BaseModelAdmin):
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, CHANGE
from django.contrib.admin.models import CHANGE, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
@ -841,7 +841,7 @@ class ModelAdmin(BaseModelAdmin):
The default implementation creates an admin LogEntry object.
"""
from django.contrib.admin.models import LogEntry, DELETION
from django.contrib.admin.models import DELETION, LogEntry
return LogEntry.objects.log_action(
user_id=request.user.pk,
content_type_id=get_content_type_for_model(object).pk,
@ -1910,6 +1910,7 @@ class ModelAdmin(BaseModelAdmin):
def history_view(self, request, object_id, extra_context=None):
"The 'history' admin view for this model."
from django.contrib.admin.models import LogEntry
# First check if the user can see this history.
model = self.model
obj = self.get_object(request, unquote(object_id))

View File

@ -240,11 +240,11 @@ class AdminSite:
return update_wrapper(inner, view)
def get_urls(self):
from django.urls import include, path, re_path
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.contenttypes.views imports ContentType.
from django.contrib.contenttypes import views as contenttype_views
from django.urls import include, path, re_path
def wrap(view, cacheable=False):
def wrapper(*args, **kwargs):
@ -385,11 +385,11 @@ class AdminSite:
index_path = reverse('admin:index', current_app=self.name)
return HttpResponseRedirect(index_path)
from django.contrib.auth.views import LoginView
# Since this module gets imported in the application's root package,
# it cannot import models from other applications at the module level,
# and django.contrib.admin.forms eventually imports User.
from django.contrib.admin.forms import AdminAuthenticationForm
from django.contrib.auth.views import LoginView
context = {
**self.each_context(request),
'title': _('Log in'),

View File

@ -186,11 +186,15 @@ class OracleOperations(BaseSpatialOperations, DatabaseOperations):
# Routines for getting the OGC-compliant models.
def geometry_columns(self):
from django.contrib.gis.db.backends.oracle.models import OracleGeometryColumns
from django.contrib.gis.db.backends.oracle.models import (
OracleGeometryColumns,
)
return OracleGeometryColumns
def spatial_ref_sys(self):
from django.contrib.gis.db.backends.oracle.models import OracleSpatialRefSys
from django.contrib.gis.db.backends.oracle.models import (
OracleSpatialRefSys,
)
return OracleSpatialRefSys
def modify_insert_params(self, placeholder, params):

View File

@ -189,11 +189,15 @@ class SpatiaLiteOperations(BaseSpatialOperations, DatabaseOperations):
# Routines for getting the OGC-compliant models.
def geometry_columns(self):
from django.contrib.gis.db.backends.spatialite.models import SpatialiteGeometryColumns
from django.contrib.gis.db.backends.spatialite.models import (
SpatialiteGeometryColumns,
)
return SpatialiteGeometryColumns
def spatial_ref_sys(self):
from django.contrib.gis.db.backends.spatialite.models import SpatialiteSpatialRefSys
from django.contrib.gis.db.backends.spatialite.models import (
SpatialiteSpatialRefSys,
)
return SpatialiteSpatialRefSys
def get_geometry_converter(self, expression):

View File

@ -83,6 +83,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor):
def delete_model(self, model, **kwargs):
from django.contrib.gis.db.models import GeometryField
# Drop spatial metadata (dropping the table does not automatically remove them)
for field in model._meta.local_fields:
if isinstance(field, GeometryField):
@ -113,6 +114,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor):
def remove_field(self, model, field):
from django.contrib.gis.db.models import GeometryField
# NOTE: If the field is a geometry field, the table is just recreated,
# the parent's remove_field can't be used cause it will skip the
# recreation if the field does not have a database type. Geometry fields
@ -125,6 +127,7 @@ class SpatialiteSchemaEditor(DatabaseSchemaEditor):
def alter_db_table(self, model, old_db_table, new_db_table, disable_constraints=True):
from django.contrib.gis.db.models import GeometryField
# Remove geometry-ness from temp table
for field in model._meta.local_fields:
if isinstance(field, GeometryField):

View File

@ -37,12 +37,13 @@ class GEOSGeometryBase(GEOSBase):
if cls is None:
if GEOSGeometryBase._GEOS_CLASSES is None:
# Inner imports avoid import conflicts with GEOSGeometry.
from .linestring import LineString, LinearRing
from .collections import (
GeometryCollection, MultiLineString, MultiPoint,
MultiPolygon,
)
from .linestring import LinearRing, LineString
from .point import Point
from .polygon import Polygon
from .collections import (
GeometryCollection, MultiPoint, MultiLineString, MultiPolygon,
)
GEOSGeometryBase._GEOS_CLASSES = {
0: Point,
1: LineString,

View File

@ -107,6 +107,7 @@ class Command(BaseCommand):
# Returning the output of ogrinspect with the given arguments
# and options.
from django.contrib.gis.utils.ogrinspect import _ogrinspect, mapping
# Filter options to params accepted by `_ogrinspect`
ogr_options = {k: v for k, v in options.items()
if k in get_func_args(_ogrinspect) and v is not None}

View File

@ -9,6 +9,8 @@ from django.core.exceptions import ImproperlyConfigured
try:
# LayerMapping requires DJANGO_SETTINGS_MODULE to be set,
# and ImproperlyConfigured is raised if that's not the case.
from django.contrib.gis.utils.layermapping import LayerMapping, LayerMapError # NOQA
from django.contrib.gis.utils.layermapping import ( # NOQA
LayerMapError, LayerMapping,
)
except ImproperlyConfigured:
pass

View File

@ -28,8 +28,10 @@ def _fd(f):
if os.name == 'nt':
import msvcrt
from ctypes import (sizeof, c_ulong, c_void_p, c_int64,
Structure, Union, POINTER, windll, byref)
from ctypes import (
POINTER, Structure, Union, byref, c_int64, c_ulong, c_void_p, sizeof,
windll,
)
from ctypes.wintypes import BOOL, DWORD, HANDLE
LOCK_SH = 0 # the default

View File

@ -39,7 +39,7 @@ class Command(BaseCommand):
)
def handle(self, **options):
from django.conf import settings, Settings, global_settings
from django.conf import Settings, global_settings, settings
# Because settings are imported lazily, we need to explicitly load them.
if not settings.configured:

View File

@ -41,6 +41,7 @@ class Command(BaseCommand):
def python(self, options):
import code
# Set up a dictionary to serve as the environment for the shell, so
# that tab completion works on objects that are imported at runtime.
imported_objects = {}

View File

@ -18,10 +18,9 @@ from django.db import models
# Use the C (faster) implementation if possible
try:
from yaml import CSafeLoader as SafeLoader
from yaml import CSafeDumper as SafeDumper
from yaml import CSafeDumper as SafeDumper, CSafeLoader as SafeLoader
except ImportError:
from yaml import SafeLoader, SafeDumper
from yaml import SafeDumper, SafeLoader
class DjangoSafeDumper(SafeDumper):

View File

@ -1,3 +1,4 @@
import _thread
import copy
import threading
import time
@ -5,7 +6,6 @@ import warnings
from collections import deque
from contextlib import contextmanager
import _thread
import pytz
from django.conf import settings

View File

@ -64,7 +64,9 @@ class RelatedIn(In):
# For multicolumn lookups we need to build a multicolumn where clause.
# This clause is either a SubqueryConstraint (for values that need to be compiled to
# SQL) or an OR-combined list of (col1 = val1 AND col2 = val2 AND ...) clauses.
from django.db.models.sql.where import WhereNode, SubqueryConstraint, AND, OR
from django.db.models.sql.where import (
AND, OR, SubqueryConstraint, WhereNode,
)
root_constraint = WhereNode(connector=OR)
if self.rhs_is_direct_value():
@ -120,7 +122,7 @@ class RelatedLookupMixin:
if isinstance(self.lhs, MultiColSource):
assert self.rhs_is_direct_value()
self.rhs = get_normalized_value(self.rhs, self.lhs)
from django.db.models.sql.where import WhereNode, AND
from django.db.models.sql.where import AND, WhereNode
root_constraint = WhereNode()
for target, source, val in zip(self.lhs.targets, self.lhs.sources, self.rhs):
lookup_class = target.get_lookup(self.lookup_name)

View File

@ -32,7 +32,9 @@ class FixDurationInputMixin:
if self.output_field.get_internal_type() == 'DurationField':
expression = self.get_source_expressions()[0]
options = self._get_repr_options()
from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval
from django.db.backends.oracle.functions import (
IntervalToSeconds, SecondsToInterval,
)
return compiler.compile(
SecondsToInterval(self.__class__(IntervalToSeconds(expression), **options))
)

View File

@ -29,7 +29,9 @@ class Lookup:
if bilateral_transforms:
# Warn the user as soon as possible if they are trying to apply
# a bilateral transformation on a nested QuerySet: that won't work.
from django.db.models.sql.query import Query # avoid circular import
from django.db.models.sql.query import ( # avoid circular import
Query,
)
if isinstance(rhs, Query):
raise NotImplementedError("Bilateral transformations on nested querysets are not implemented.")
self.bilateral_transforms = bilateral_transforms

View File

@ -815,7 +815,7 @@ class BaseModelFormSet(BaseFormSet):
def add_fields(self, form, index):
"""Add a hidden field for the object's primary key."""
from django.db.models import AutoField, OneToOneField, ForeignKey
from django.db.models import AutoField, ForeignKey, OneToOneField
self._pk_field = pk = self.model._meta.pk
# If a pk isn't editable, then it won't be on the form, so we need to
# add it here so we can tell which object is which when we get the

View File

@ -40,6 +40,7 @@ def debug(request):
if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
context_extras['debug'] = True
from django.db import connections
# Return a lazy reference that computes connection.queries on access,
# to ensure it contains queries triggered after this function runs.
context_extras['sql_queries'] = lazy(

View File

@ -428,7 +428,7 @@ class URLNode(Node):
self.asvar = asvar
def render(self, context):
from django.urls import reverse, NoReverseMatch
from django.urls import NoReverseMatch, reverse
args = [arg.resolve(context) for arg in self.args]
kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()}
view_name = self.view_name.resolve(context)

View File

@ -611,6 +611,7 @@ class ClientMixin:
def _login(self, user, backend=None):
from django.contrib.auth import login
# Create a fake request to store login details.
request = HttpRequest()
if self.session:

View File

@ -70,7 +70,9 @@ class SeleniumTestCaseBase(type(LiveServerTestCase)):
@classmethod
def get_capability(cls, browser):
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.desired_capabilities import (
DesiredCapabilities,
)
return getattr(DesiredCapabilities, browser.upper())
def create_options(self):

View File

@ -175,7 +175,9 @@ def static_finders_changed(**kwargs):
@receiver(setting_changed)
def auth_password_validators_changed(**kwargs):
if kwargs['setting'] == 'AUTH_PASSWORD_VALIDATORS':
from django.contrib.auth.password_validation import get_default_password_validators
from django.contrib.auth.password_validation import (
get_default_password_validators,
)
get_default_password_validators.cache_clear()

View File

@ -300,6 +300,7 @@ class BaseReloader:
logger.debug('Waiting for apps ready_event.')
self.wait_for_apps_ready(apps, django_main_thread)
from django.urls import get_resolver
# Prevent a race condition where URL modules aren't loaded when the
# reloader starts by accessing the urlconf_module property.
try:

View File

@ -56,7 +56,9 @@ class Trans:
from django.conf import settings
if settings.USE_I18N:
from django.utils.translation import trans_real as trans
from django.utils.translation.reloader import watch_for_translation_changes, translation_file_changed
from django.utils.translation.reloader import (
translation_file_changed, watch_for_translation_changes,
)
autoreload_started.connect(watch_for_translation_changes, dispatch_uid='translation_file_changed')
file_changed.connect(translation_file_changed, dispatch_uid='translation_file_changed')
else:

View File

@ -30,6 +30,7 @@ def translation_file_changed(sender, file_path, **kwargs):
"""Clear the internal translations cache if a .mo file is modified."""
if file_path.suffix == '.mo':
import gettext
from django.utils.translation import trans_real
gettext._translations = {}
trans_real._translations = {}

View File

@ -105,7 +105,7 @@ def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME):
"""
Default view used when request fails CSRF protection
"""
from django.middleware.csrf import REASON_NO_REFERER, REASON_NO_CSRF_COOKIE
from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER
c = {
'title': _("Forbidden"),
'main': _("CSRF verification failed. Request aborted."),

View File

@ -101,7 +101,7 @@ Imports
.. console::
$ python -m pip install isort
$ python -m pip install isort >= 5.1.0
$ isort -rc .
This runs ``isort`` recursively from your current directory, modifying any

View File

@ -80,7 +80,7 @@ version of Python. A list of default environments can be seen as follows:
py3
flake8
docs
isort
isort>=5.1.0
Testing other Python versions and database backends
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -26,6 +26,7 @@ def cxOracle_py3_bug(func):
we mark them as expected failures until someone fixes them in #23843.
"""
from unittest import expectedFailure
from django.db import connection
return expectedFailure(func) if connection.vendor == 'oracle' else func

View File

@ -13,6 +13,7 @@ except ImportError:
pass
else:
from psycopg2 import errorcodes
from django.db.backends.postgresql.creation import DatabaseCreation

View File

@ -129,10 +129,10 @@ class Tests(TestCase):
ISOLATION_LEVEL_READ_COMMITTED as read_committed,
ISOLATION_LEVEL_SERIALIZABLE as serializable,
)
# Since this is a django.test.TestCase, a transaction is in progress
# and the isolation level isn't reported as 0. This test assumes that
# PostgreSQL is configured with the default isolation level.
# Check the level on the psycopg2 connection, not the Django wrapper.
default_level = read_committed if psycopg2.__version__ < '2.7' else None
self.assertEqual(connection.connection.isolation_level, default_level)

View File

@ -142,7 +142,7 @@ class Geo3DTest(Geo3DLoadingHelper, TestCase):
Testing LayerMapping on 3D models.
"""
# Import here as GDAL is required for those imports
from django.contrib.gis.utils import LayerMapping, LayerMapError
from django.contrib.gis.utils import LayerMapError, LayerMapping
point_mapping = {'point': 'POINT'}
mpoint_mapping = {'mpoint': 'MULTIPOINT'}

View File

@ -143,7 +143,9 @@ class RasterFieldTest(TransactionTestCase):
unprojected coordinate systems. This test just checks that the lookup
can be called, but doesn't check if the result makes logical sense.
"""
from django.contrib.gis.db.backends.postgis.operations import PostGISOperations
from django.contrib.gis.db.backends.postgis.operations import (
PostGISOperations,
)
# Create test raster and geom.
rast = GDALRaster(json.loads(JSON_RASTER))

View File

@ -4,7 +4,9 @@ from django.core.exceptions import ImproperlyConfigured
from django.db import ProgrammingError
try:
from django.contrib.gis.db.backends.postgis.operations import PostGISOperations
from django.contrib.gis.db.backends.postgis.operations import (
PostGISOperations,
)
HAS_POSTGRES = True
except ImportError:
HAS_POSTGRES = False

View File

@ -53,11 +53,17 @@ spatialite = _default_db == 'spatialite'
gisfield_may_be_null = not mysql
if oracle and 'gis' in settings.DATABASES[DEFAULT_DB_ALIAS]['ENGINE']:
from django.contrib.gis.db.backends.oracle.models import OracleSpatialRefSys as SpatialRefSys
from django.contrib.gis.db.backends.oracle.models import (
OracleSpatialRefSys as SpatialRefSys,
)
elif postgis:
from django.contrib.gis.db.backends.postgis.models import PostGISSpatialRefSys as SpatialRefSys
from django.contrib.gis.db.backends.postgis.models import (
PostGISSpatialRefSys as SpatialRefSys,
)
elif spatialite:
from django.contrib.gis.db.backends.spatialite.models import SpatialiteSpatialRefSys as SpatialRefSys
from django.contrib.gis.db.backends.spatialite.models import (
SpatialiteSpatialRefSys as SpatialRefSys,
)
else:
SpatialRefSys = None

View File

@ -15,10 +15,9 @@ except ImproperlyConfigured:
if Image:
from .models import (
Person, PersonWithHeight, PersonWithHeightAndWidth,
PersonDimensionsFirst, PersonTwoImages, TestImageFieldFile,
Person, PersonDimensionsFirst, PersonTwoImages, PersonWithHeight,
PersonWithHeightAndWidth, TestImageFieldFile, temp_storage_dir,
)
from .models import temp_storage_dir
else:
# Pillow not available, create dummy classes (tests will be skipped anyway)
class Person:

View File

@ -30,7 +30,7 @@ from .models import (
)
if test_images:
from .models import ImageFile, OptionalImageFile, NoExtensionImageFile
from .models import ImageFile, NoExtensionImageFile, OptionalImageFile
class ImageFileForm(forms.ModelForm):
class Meta:

View File

@ -8,6 +8,7 @@ try:
from psycopg2.extras import (
DateRange, DateTimeRange, DateTimeTZRange, NumericRange,
)
from django.contrib.postgres.fields import (
DateRangeField, DateTimeRangeField, IntegerRangeField,
)

View File

@ -25,14 +25,17 @@ from .models import (
)
try:
from psycopg2.extras import NumericRange
from django.contrib.postgres.aggregates import ArrayAgg
from django.contrib.postgres.fields import ArrayField
from django.contrib.postgres.fields.array import IndexTransform, SliceTransform
from django.contrib.postgres.fields.array import (
IndexTransform, SliceTransform,
)
from django.contrib.postgres.forms import (
SimpleArrayField, SplitArrayField, SplitArrayWidget,
)
from django.db.backends.postgresql.base import PSYCOPG2_VERSION
from psycopg2.extras import NumericRange
except ImportError:
pass

View File

@ -7,7 +7,7 @@ from .models import (
)
try:
from psycopg2.extras import NumericRange, DateRange
from psycopg2.extras import DateRange, NumericRange
except ImportError:
pass # psycopg2 isn't installed.

View File

@ -14,10 +14,12 @@ from . import PostgreSQLTestCase
from .models import HotelReservation, RangesModel, Room, Scene
try:
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import DateTimeRangeField, RangeBoundary, RangeOperators
from psycopg2.extras import DateRange, NumericRange
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import (
DateTimeRangeField, RangeBoundary, RangeOperators,
)
except ImportError:
pass

View File

@ -1,7 +1,9 @@
try:
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.fields.jsonb import KeyTransform, KeyTextTransform
from django.contrib.postgres import forms
from django.contrib.postgres.fields import JSONField
from django.contrib.postgres.fields.jsonb import (
KeyTextTransform, KeyTransform,
)
except ImportError:
pass

View File

@ -11,11 +11,11 @@ from django.test.utils import CaptureQueriesContext
from . import PostgreSQLTestCase
try:
from django.contrib.postgres.indexes import BrinIndex, BTreeIndex
from django.contrib.postgres.operations import (
AddIndexConcurrently, BloomExtension, CreateExtension,
RemoveIndexConcurrently,
)
from django.contrib.postgres.indexes import BrinIndex, BTreeIndex
except ImportError:
pass

View File

@ -18,6 +18,7 @@ from .models import (
try:
from psycopg2.extras import DateRange, DateTimeTZRange, NumericRange
from django.contrib.postgres import fields as pg_fields, forms as pg_forms
from django.contrib.postgres.validators import (
RangeMaxValueValidator, RangeMinValueValidator,

View File

@ -4,7 +4,9 @@ from . import PostgreSQLTestCase
from .models import CharFieldModel, TextFieldModel
try:
from django.contrib.postgres.search import TrigramDistance, TrigramSimilarity
from django.contrib.postgres.search import (
TrigramDistance, TrigramSimilarity,
)
except ImportError:
pass

View File

@ -9,7 +9,7 @@ envlist =
py3
flake8
docs
isort
isort >= 5.1.0
# Add environment to use the default python3 installation
[testenv:py3]
@ -55,7 +55,7 @@ basepython = python3
usedevelop = false
deps = isort
changedir = {toxinidir}
commands = isort --recursive --check-only --diff django tests scripts
commands = isort --check-only --diff django tests scripts
[testenv:javascript]
usedevelop = false