diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index 4f33992028..b9eb33329f 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -428,12 +428,11 @@ class AdminPasswordChangeForm(forms.Form): def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') - if password1 and password2: - if password1 != password2: - raise ValidationError( - self.error_messages['password_mismatch'], - code='password_mismatch', - ) + if password1 and password2 and password1 != password2: + raise ValidationError( + self.error_messages['password_mismatch'], + code='password_mismatch', + ) password_validation.validate_password(password2, self.user) return password2 diff --git a/django/contrib/gis/forms/fields.py b/django/contrib/gis/forms/fields.py index 3371c06456..301d770836 100644 --- a/django/contrib/gis/forms/fields.py +++ b/django/contrib/gis/forms/fields.py @@ -71,7 +71,7 @@ class GeometryField(forms.Field): # Ensuring that the geometry is of the correct type (indicated # using the OGC string label). - if str(geom.geom_type).upper() != self.geom_type and not self.geom_type == 'GEOMETRY': + if str(geom.geom_type).upper() != self.geom_type and self.geom_type != 'GEOMETRY': raise ValidationError(self.error_messages['invalid_geom_type'], code='invalid_geom_type') # Transforming the geometry if the SRID was set. diff --git a/django/contrib/staticfiles/finders.py b/django/contrib/staticfiles/finders.py index 53d31b9b1f..7f75af3f67 100644 --- a/django/contrib/staticfiles/finders.py +++ b/django/contrib/staticfiles/finders.py @@ -187,12 +187,11 @@ class AppDirectoriesFinder(BaseFinder): Find a requested static file in an app's static locations. """ storage = self.storages.get(app) - if storage: - # only try to find a file if the source dir actually exists - if storage.exists(path): - matched_path = storage.path(path) - if matched_path: - return matched_path + # Only try to find a file if the source dir actually exists. + if storage and storage.exists(path): + matched_path = storage.path(path) + if matched_path: + return matched_path class BaseStorageFinder(BaseFinder): diff --git a/django/core/management/commands/dumpdata.py b/django/core/management/commands/dumpdata.py index df9eecc0f8..194c169f67 100644 --- a/django/core/management/commands/dumpdata.py +++ b/django/core/management/commands/dumpdata.py @@ -113,9 +113,8 @@ class Command(BaseCommand): # We may have previously seen an "all-models" request for # this app (no model qualifier was given). In this case # there is no need adding specific models to the list. - if app_list_value is not None: - if model not in app_list_value: - app_list_value.append(model) + if app_list_value is not None and model not in app_list_value: + app_list_value.append(model) except ValueError: if primary_keys: raise CommandError("You can only use --pks option with one model") diff --git a/django/db/models/query.py b/django/db/models/query.py index 2c2b5d0883..7956b1695e 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -696,7 +696,7 @@ class QuerySet: field_name != 'pk' and not opts.get_field(field_name).unique and field_name not in unique_fields and - not self.query.distinct_fields == (field_name,) + self.query.distinct_fields != (field_name,) ): raise ValueError("in_bulk()'s field_name must be a unique field but %r isn't." % field_name) if id_list is not None: diff --git a/django/middleware/common.py b/django/middleware/common.py index 3af4759109..e42d05e255 100644 --- a/django/middleware/common.py +++ b/django/middleware/common.py @@ -104,9 +104,8 @@ class CommonMiddleware(MiddlewareMixin): """ # If the given URL is "Not Found", then check if we should redirect to # a path with a slash appended. - if response.status_code == 404: - if self.should_redirect_with_slash(request): - return self.response_redirect_class(self.get_full_path_with_slash(request)) + if response.status_code == 404 and self.should_redirect_with_slash(request): + return self.response_redirect_class(self.get_full_path_with_slash(request)) # Add the Content-Length header to non-streaming responses if not # already set. diff --git a/django/shortcuts.py b/django/shortcuts.py index eda6f8813c..d810471640 100644 --- a/django/shortcuts.py +++ b/django/shortcuts.py @@ -121,10 +121,9 @@ def resolve_url(to, *args, **kwargs): # further to some Python functions like urlparse. to = str(to) - if isinstance(to, str): - # Handle relative URLs - if to.startswith(('./', '../')): - return to + # Handle relative URLs + if isinstance(to, str) and to.startswith(('./', '../')): + return to # Next try a reverse URL resolution. try: diff --git a/django/test/html.py b/django/test/html.py index 3b04217822..486a0d358d 100644 --- a/django/test/html.py +++ b/django/test/html.py @@ -23,29 +23,26 @@ class Element: def append(self, element): if isinstance(element, str): element = normalize_whitespace(element) - if self.children: - if isinstance(self.children[-1], str): - self.children[-1] += element - self.children[-1] = normalize_whitespace(self.children[-1]) - return + if self.children and isinstance(self.children[-1], str): + self.children[-1] += element + self.children[-1] = normalize_whitespace(self.children[-1]) + return elif self.children: # removing last children if it is only whitespace # this can result in incorrect dom representations since # whitespace between inline tags like is significant - if isinstance(self.children[-1], str): - if self.children[-1].isspace(): - self.children.pop() + if isinstance(self.children[-1], str) and self.children[-1].isspace(): + self.children.pop() if element: self.children.append(element) def finalize(self): def rstrip_last_element(children): - if children: - if isinstance(children[-1], str): - children[-1] = children[-1].rstrip() - if not children[-1]: - children.pop() - children = rstrip_last_element(children) + if children and isinstance(children[-1], str): + children[-1] = children[-1].rstrip() + if not children[-1]: + children.pop() + children = rstrip_last_element(children) return children rstrip_last_element(self.children) @@ -79,12 +76,10 @@ class Element: return hash((self.name, *self.attributes)) def _count(self, element, count=True): - if not isinstance(element, str): - if self == element: - return 1 - if isinstance(element, RootElement): - if self.children == element.children: - return 1 + if not isinstance(element, str) and self == element: + return 1 + if isinstance(element, RootElement) and self.children == element.children: + return 1 i = 0 elem_child_idx = 0 for child in self.children: @@ -241,7 +236,6 @@ def parse_html(html): document = parser.root document.finalize() # Removing ROOT element if it's not necessary - if len(document.children) == 1: - if not isinstance(document.children[0], str): - document = document.children[0] + if len(document.children) == 1 and not isinstance(document.children[0], str): + document = document.children[0] return document diff --git a/django/utils/cache.py b/django/utils/cache.py index 51dd050452..bb756fe60c 100644 --- a/django/utils/cache.py +++ b/django/utils/cache.py @@ -180,10 +180,13 @@ def get_conditional_response(request, etag=None, last_modified=None, response=No return _precondition_failed(request) # Step 4: Test the If-Modified-Since precondition. - if (not if_none_match_etags and if_modified_since and - not _if_modified_since_passes(last_modified, if_modified_since)): - if request.method in ('GET', 'HEAD'): - return _not_modified(request, response) + if ( + not if_none_match_etags and + if_modified_since and + not _if_modified_since_passes(last_modified, if_modified_since) and + request.method in ('GET', 'HEAD') + ): + return _not_modified(request, response) # Step 5: Test the If-Range precondition (not supported). # Step 6: Return original response since there isn't a conditional response. diff --git a/tests/backends/tests.py b/tests/backends/tests.py index cf6bdbf25d..ed1847ede5 100644 --- a/tests/backends/tests.py +++ b/tests/backends/tests.py @@ -665,10 +665,9 @@ class ThreadTests(TransactionTestCase): # (the connection opened in the main thread will automatically be # closed on teardown). for conn in connections_dict.values(): - if conn is not connection: - if conn.allow_thread_sharing: - conn.close() - conn.dec_thread_sharing() + if conn is not connection and conn.allow_thread_sharing: + conn.close() + conn.dec_thread_sharing() def test_connections_thread_local(self): """ @@ -702,10 +701,9 @@ class ThreadTests(TransactionTestCase): # (the connection opened in the main thread will automatically be # closed on teardown). for conn in connections_dict.values(): - if conn is not connection: - if conn.allow_thread_sharing: - conn.close() - conn.dec_thread_sharing() + if conn is not connection and conn.allow_thread_sharing: + conn.close() + conn.dec_thread_sharing() def test_pass_connection_between_threads(self): """ diff --git a/tests/cache/tests.py b/tests/cache/tests.py index 1ef2cc1bc1..367d2d7119 100644 --- a/tests/cache/tests.py +++ b/tests/cache/tests.py @@ -1714,7 +1714,7 @@ class CacheUtils(SimpleTestCase): def _get_request_cache(self, method='GET', query_string=None, update_cache=None): request = self._get_request(self.host, self.path, method, query_string=query_string) - request._cache_update_cache = True if not update_cache else update_cache + request._cache_update_cache = update_cache if update_cache else True return request def test_patch_vary_headers(self): diff --git a/tests/schema/tests.py b/tests/schema/tests.py index a7743deba4..b986f27aa1 100644 --- a/tests/schema/tests.py +++ b/tests/schema/tests.py @@ -161,7 +161,7 @@ class SchemaTests(TransactionTestCase): schema_editor.add_field(model, field) cursor.execute("SELECT {} FROM {};".format(field_name, model._meta.db_table)) database_default = cursor.fetchall()[0][0] - if cast_function and not type(database_default) == type(expected_default): + if cast_function and type(database_default) != type(expected_default): database_default = cast_function(database_default) self.assertEqual(database_default, expected_default) diff --git a/tests/view_tests/tests/test_i18n.py b/tests/view_tests/tests/test_i18n.py index 0ec2bf877e..84dff20753 100644 --- a/tests/view_tests/tests/test_i18n.py +++ b/tests/view_tests/tests/test_i18n.py @@ -25,7 +25,7 @@ class SetLanguageTests(TestCase): def _get_inactive_language_code(self): """Return language code for a language which is not activated.""" current_language = get_language() - return [code for code, name in settings.LANGUAGES if not code == current_language][0] + return [code for code, name in settings.LANGUAGES if code != current_language][0] def test_setlang(self): """