diff --git a/django/apps/config.py b/django/apps/config.py index 157fda7238cd7..f5f913b99f123 100644 --- a/django/apps/config.py +++ b/django/apps/config.py @@ -71,7 +71,7 @@ def _path_from_module(self, module): "The app module %r has multiple filesystem locations (%r); " "you must configure this app with an AppConfig subclass " "with a 'path' class attribute." % (module, paths)) - elif not paths: + if not paths: raise ImproperlyConfigured( "The app module %r has no filesystem location, " "you must configure this app with an AppConfig subclass " diff --git a/django/conf/urls/static.py b/django/conf/urls/static.py index 150f4ffd3f0bb..83ebda4367f50 100644 --- a/django/conf/urls/static.py +++ b/django/conf/urls/static.py @@ -19,7 +19,7 @@ def static(prefix, view=serve, **kwargs): """ if not prefix: raise ImproperlyConfigured("Empty static prefix not permitted") - elif not settings.DEBUG or '://' in prefix: + if not settings.DEBUG or '://' in prefix: # No-op if not in debug mode or a non-local prefix. return [] return [ diff --git a/django/contrib/admin/checks.py b/django/contrib/admin/checks.py index 26c5c3eef6a6b..4d7e804400324 100644 --- a/django/contrib/admin/checks.py +++ b/django/contrib/admin/checks.py @@ -87,11 +87,10 @@ def _check_autocomplete_fields(self, obj): """ if not isinstance(obj.autocomplete_fields, (list, tuple)): return must_be('a list or tuple', option='autocomplete_fields', obj=obj, id='admin.E036') - else: - return list(chain.from_iterable([ - self._check_autocomplete_fields_item(obj, obj.model, field_name, 'autocomplete_fields[%d]' % index) - for index, field_name in enumerate(obj.autocomplete_fields) - ])) + return list(chain.from_iterable([ + self._check_autocomplete_fields_item(obj, obj.model, field_name, 'autocomplete_fields[%d]' % index) + for index, field_name in enumerate(obj.autocomplete_fields) + ])) def _check_autocomplete_fields_item(self, obj, model, field_name, label): """ @@ -103,78 +102,71 @@ def _check_autocomplete_fields_item(self, obj, model, field_name, label): field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E037') - else: - if not field.many_to_many and not isinstance(field, models.ForeignKey): - return must_be( - 'a foreign key or a many-to-many field', - option=label, obj=obj, id='admin.E038' + if not field.many_to_many and not isinstance(field, models.ForeignKey): + return must_be( + 'a foreign key or a many-to-many field', + option=label, obj=obj, id='admin.E038' + ) + related_admin = obj.admin_site._registry.get(field.remote_field.model) + if related_admin is None: + return [ + checks.Error( + 'An admin for model "%s" has to be registered ' + 'to be referenced by %s.autocomplete_fields.' % ( + field.remote_field.model.__name__, + type(obj).__name__, + ), + obj=obj.__class__, + id='admin.E039', ) - related_admin = obj.admin_site._registry.get(field.remote_field.model) - if related_admin is None: - return [ - checks.Error( - 'An admin for model "%s" has to be registered ' - 'to be referenced by %s.autocomplete_fields.' % ( - field.remote_field.model.__name__, - type(obj).__name__, - ), - obj=obj.__class__, - id='admin.E039', - ) - ] - elif not related_admin.search_fields: - return [ - checks.Error( - '%s must define "search_fields", because it\'s ' - 'referenced by %s.autocomplete_fields.' % ( - related_admin.__class__.__name__, - type(obj).__name__, - ), - obj=obj.__class__, - id='admin.E040', - ) - ] - return [] + ] + if not related_admin.search_fields: + return [ + checks.Error( + '%s must define "search_fields", because it\'s ' + 'referenced by %s.autocomplete_fields.' % ( + related_admin.__class__.__name__, + type(obj).__name__, + ), + obj=obj.__class__, + id='admin.E040', + ) + ] + return [] def _check_raw_id_fields(self, obj): """ Check that `raw_id_fields` only contains field names that are listed on the model. """ - if not isinstance(obj.raw_id_fields, (list, tuple)): return must_be('a list or tuple', option='raw_id_fields', obj=obj, id='admin.E001') - else: - return list(chain.from_iterable( - self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index) - for index, field_name in enumerate(obj.raw_id_fields) - )) + return list(chain.from_iterable( + self._check_raw_id_fields_item(obj, obj.model, field_name, 'raw_id_fields[%d]' % index) + for index, field_name in enumerate(obj.raw_id_fields) + )) def _check_raw_id_fields_item(self, obj, model, field_name, label): """ Check an item of `raw_id_fields`, i.e. check that field named `field_name` exists in model `model` and is a ForeignKey or a ManyToManyField. """ - try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E002') - else: - if not field.many_to_many and not isinstance(field, models.ForeignKey): - return must_be('a foreign key or a many-to-many field', - option=label, obj=obj, id='admin.E003') - else: - return [] + if not field.many_to_many and not isinstance(field, models.ForeignKey): + return must_be('a foreign key or a many-to-many field', + option=label, obj=obj, id='admin.E003') + return [] def _check_fields(self, obj): """ Check that `fields` only refer to existing fields, doesn't contain duplicates. Check if at most one of `fields` and `fieldsets` is defined. """ - if obj.fields is None: return [] - elif not isinstance(obj.fields, (list, tuple)): + if not isinstance(obj.fields, (list, tuple)): return must_be('a list or tuple', option='fields', obj=obj, id='admin.E004') - elif obj.fieldsets: + if obj.fieldsets: return [ checks.Error( "Both 'fieldsets' and 'fields' are specified.", @@ -200,28 +192,25 @@ def _check_fields(self, obj): def _check_fieldsets(self, obj): """ Check that fieldsets is properly formatted and doesn't contain duplicates. """ - if obj.fieldsets is None: return [] - elif not isinstance(obj.fieldsets, (list, tuple)): + if not isinstance(obj.fieldsets, (list, tuple)): return must_be('a list or tuple', option='fieldsets', obj=obj, id='admin.E007') - else: - return list(chain.from_iterable( - self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index) - for index, fieldset in enumerate(obj.fieldsets) - )) + return list(chain.from_iterable( + self._check_fieldsets_item(obj, obj.model, fieldset, 'fieldsets[%d]' % index) + for index, fieldset in enumerate(obj.fieldsets) + )) def _check_fieldsets_item(self, obj, model, fieldset, label): """ Check an item of `fieldsets`, i.e. check that this is a pair of a set name and a dictionary containing "fields" key. """ - if not isinstance(fieldset, (list, tuple)): return must_be('a list or tuple', option=label, obj=obj, id='admin.E008') - elif len(fieldset) != 2: + if len(fieldset) != 2: return must_be('of length 2', option=label, obj=obj, id='admin.E009') - elif not isinstance(fieldset[1], dict): + if not isinstance(fieldset[1], dict): return must_be('a dictionary', option='%s[1]' % label, obj=obj, id='admin.E010') - elif 'fields' not in fieldset[1]: + if 'fields' not in fieldset[1]: return [ checks.Error( "The value of '%s[1]' must contain the key 'fields'." % label, @@ -229,7 +218,7 @@ def _check_fieldsets_item(self, obj, model, fieldset, label): id='admin.E011', ) ] - elif not isinstance(fieldset[1]['fields'], (list, tuple)): + if not isinstance(fieldset[1]['fields'], (list, tuple)): return must_be('a list or tuple', option="%s[1]['fields']" % label, obj=obj, id='admin.E008') fields = flatten(fieldset[1]['fields']) @@ -250,14 +239,12 @@ def _check_field_spec(self, obj, model, fields, label): """ `fields` should be an item of `fields` or an item of fieldset[1]['fields'] for any `fieldset` in `fieldsets`. It should be a field name or a tuple of field names. """ - if isinstance(fields, tuple): return list(chain.from_iterable( self._check_field_spec_item(obj, model, field_name, "%s[%d]" % (label, index)) for index, field_name in enumerate(fields) )) - else: - return self._check_field_spec_item(obj, model, fields, label) + return self._check_field_spec_item(obj, model, fields, label) def _check_field_spec_item(self, obj, model, field_name, label): if field_name in obj.readonly_fields: @@ -265,36 +252,32 @@ def _check_field_spec_item(self, obj, model, field_name, label): # it's in readonly_fields, readonly_fields will handle the # validation of such things. return [] - else: - try: - field = model._meta.get_field(field_name) - except FieldDoesNotExist: - # If we can't find a field on the model that matches, it could - # be an extra field on the form. - return [] - else: - if (isinstance(field, models.ManyToManyField) and - not field.remote_field.through._meta.auto_created): - return [ - checks.Error( - "The value of '%s' cannot include the ManyToManyField '%s', " - "because that field manually specifies a relationship model." - % (label, field_name), - obj=obj.__class__, - id='admin.E013', - ) - ] - else: - return [] + try: + field = model._meta.get_field(field_name) + except FieldDoesNotExist: + # If it isn't a field on the model, it could be an extra field on + # the form. + return [] + if (isinstance(field, models.ManyToManyField) and + not field.remote_field.through._meta.auto_created): + return [ + checks.Error( + "The value of '%s' cannot include the ManyToManyField '%s', " + "because that field manually specifies a relationship model." + % (label, field_name), + obj=obj.__class__, + id='admin.E013', + ) + ] + return [] def _check_exclude(self, obj): """ Check that exclude is a sequence without duplicates. """ - if obj.exclude is None: # default value is None return [] - elif not isinstance(obj.exclude, (list, tuple)): + if not isinstance(obj.exclude, (list, tuple)): return must_be('a list or tuple', option='exclude', obj=obj, id='admin.E014') - elif len(obj.exclude) > len(set(obj.exclude)): + if len(obj.exclude) > len(set(obj.exclude)): return [ checks.Error( "The value of 'exclude' contains duplicate field(s).", @@ -302,92 +285,78 @@ def _check_exclude(self, obj): id='admin.E015', ) ] - else: - return [] + return [] def _check_form(self, obj): """ Check that form subclasses BaseModelForm. """ if not issubclass(obj.form, BaseModelForm): - return must_inherit_from(parent='BaseModelForm', option='form', - obj=obj, id='admin.E016') - else: - return [] + return must_inherit_from(parent='BaseModelForm', option='form', obj=obj, id='admin.E016') + return [] def _check_filter_vertical(self, obj): """ Check that filter_vertical is a sequence of field names. """ if not isinstance(obj.filter_vertical, (list, tuple)): return must_be('a list or tuple', option='filter_vertical', obj=obj, id='admin.E017') - else: - return list(chain.from_iterable( - self._check_filter_item(obj, obj.model, field_name, "filter_vertical[%d]" % index) - for index, field_name in enumerate(obj.filter_vertical) - )) + return list(chain.from_iterable( + self._check_filter_item(obj, obj.model, field_name, 'filter_vertical[%d]' % index) + for index, field_name in enumerate(obj.filter_vertical) + )) def _check_filter_horizontal(self, obj): """ Check that filter_horizontal is a sequence of field names. """ if not isinstance(obj.filter_horizontal, (list, tuple)): return must_be('a list or tuple', option='filter_horizontal', obj=obj, id='admin.E018') - else: - return list(chain.from_iterable( - self._check_filter_item(obj, obj.model, field_name, "filter_horizontal[%d]" % index) - for index, field_name in enumerate(obj.filter_horizontal) - )) + return list(chain.from_iterable( + self._check_filter_item(obj, obj.model, field_name, 'filter_horizontal[%d]' % index) + for index, field_name in enumerate(obj.filter_horizontal) + )) def _check_filter_item(self, obj, model, field_name, label): """ Check one item of `filter_vertical` or `filter_horizontal`, i.e. check that given field exists and is a ManyToManyField. """ - try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E019') - else: - if not field.many_to_many: - return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020') - else: - return [] + if not field.many_to_many: + return must_be('a many-to-many field', option=label, obj=obj, id='admin.E020') + return [] def _check_radio_fields(self, obj): """ Check that `radio_fields` is a dictionary. """ if not isinstance(obj.radio_fields, dict): return must_be('a dictionary', option='radio_fields', obj=obj, id='admin.E021') - else: - return list(chain.from_iterable( - self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') + - self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name) - for field_name, val in obj.radio_fields.items() - )) + return list(chain.from_iterable( + self._check_radio_fields_key(obj, obj.model, field_name, 'radio_fields') + + self._check_radio_fields_value(obj, val, 'radio_fields["%s"]' % field_name) + for field_name, val in obj.radio_fields.items() + )) def _check_radio_fields_key(self, obj, model, field_name, label): """ Check that a key of `radio_fields` dictionary is name of existing field and that the field is a ForeignKey or has `choices` defined. """ - try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E022') - else: - if not (isinstance(field, models.ForeignKey) or field.choices): - return [ - checks.Error( - "The value of '%s' refers to '%s', which is not an " - "instance of ForeignKey, and does not have a 'choices' definition." % ( - label, field_name - ), - obj=obj.__class__, - id='admin.E023', - ) - ] - else: - return [] + if not (isinstance(field, models.ForeignKey) or field.choices): + return [ + checks.Error( + "The value of '%s' refers to '%s', which is not an instance " + "of ForeignKey, and does not have a 'choices' definition." % ( + label, field_name + ), + obj=obj.__class__, + id='admin.E023', + ) + ] + return [] def _check_radio_fields_value(self, obj, val, label): """ Check type of a value of `radio_fields` dictionary. """ - from django.contrib.admin.options import HORIZONTAL, VERTICAL - if val not in (HORIZONTAL, VERTICAL): return [ checks.Error( @@ -396,8 +365,7 @@ def _check_radio_fields_value(self, obj, val, label): id='admin.E024', ) ] - else: - return [] + return [] def _check_view_on_site_url(self, obj): if not callable(obj.view_on_site) and not isinstance(obj.view_on_site, bool): @@ -408,84 +376,71 @@ def _check_view_on_site_url(self, obj): id='admin.E025', ) ] - else: - return [] + return [] def _check_prepopulated_fields(self, obj): """ Check that `prepopulated_fields` is a dictionary containing allowed field types. """ if not isinstance(obj.prepopulated_fields, dict): return must_be('a dictionary', option='prepopulated_fields', obj=obj, id='admin.E026') - else: - return list(chain.from_iterable( - self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') + - self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name) - for field_name, val in obj.prepopulated_fields.items() - )) + return list(chain.from_iterable( + self._check_prepopulated_fields_key(obj, obj.model, field_name, 'prepopulated_fields') + + self._check_prepopulated_fields_value(obj, obj.model, val, 'prepopulated_fields["%s"]' % field_name) + for field_name, val in obj.prepopulated_fields.items() + )) def _check_prepopulated_fields_key(self, obj, model, field_name, label): """ Check a key of `prepopulated_fields` dictionary, i.e. check that it is a name of existing field and the field is one of the allowed types. """ - try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E027') - else: - if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): - return [ - checks.Error( - "The value of '%s' refers to '%s', which must not be a DateTimeField, " - "a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name), - obj=obj.__class__, - id='admin.E028', - ) - ] - else: - return [] + if isinstance(field, (models.DateTimeField, models.ForeignKey, models.ManyToManyField)): + return [ + checks.Error( + "The value of '%s' refers to '%s', which must not be a DateTimeField, " + "a ForeignKey, a OneToOneField, or a ManyToManyField." % (label, field_name), + obj=obj.__class__, + id='admin.E028', + ) + ] + return [] def _check_prepopulated_fields_value(self, obj, model, val, label): """ Check a value of `prepopulated_fields` dictionary, i.e. it's an iterable of existing fields. """ - if not isinstance(val, (list, tuple)): return must_be('a list or tuple', option=label, obj=obj, id='admin.E029') - else: - return list(chain.from_iterable( - self._check_prepopulated_fields_value_item(obj, model, subfield_name, "%s[%r]" % (label, index)) - for index, subfield_name in enumerate(val) - )) + return list(chain.from_iterable( + self._check_prepopulated_fields_value_item(obj, model, subfield_name, '%s[%r]' % (label, index)) + for index, subfield_name in enumerate(val) + )) def _check_prepopulated_fields_value_item(self, obj, model, field_name, label): """ For `prepopulated_fields` equal to {"slug": ("title",)}, `field_name` is "title". """ - try: model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E030') - else: - return [] + return [] def _check_ordering(self, obj): """ Check that ordering refers to existing fields or is random. """ - - # ordering = None if obj.ordering is None: # The default value is None return [] - elif not isinstance(obj.ordering, (list, tuple)): + if not isinstance(obj.ordering, (list, tuple)): return must_be('a list or tuple', option='ordering', obj=obj, id='admin.E031') - else: - return list(chain.from_iterable( - self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index) - for index, field_name in enumerate(obj.ordering) - )) + return list(chain.from_iterable( + self._check_ordering_item(obj, obj.model, field_name, 'ordering[%d]' % index) + for index, field_name in enumerate(obj.ordering) + )) def _check_ordering_item(self, obj, model, field_name, label): """ Check that `ordering` refers to existing fields. """ - if field_name == '?' and len(obj.ordering) != 1: return [ checks.Error( @@ -496,59 +451,57 @@ def _check_ordering_item(self, obj, model, field_name, label): id='admin.E032', ) ] - elif field_name == '?': + if field_name == '?': return [] - elif LOOKUP_SEP in field_name: + if LOOKUP_SEP in field_name: # Skip ordering in the format field1__field2 (FIXME: checking # this format would be nice, but it's a little fiddly). return [] - else: - if field_name.startswith('-'): - field_name = field_name[1:] - if field_name == 'pk': - return [] - try: - model._meta.get_field(field_name) - except FieldDoesNotExist: - return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033') - else: - return [] + if field_name.startswith('-'): + field_name = field_name[1:] + if field_name == 'pk': + return [] + try: + model._meta.get_field(field_name) + except FieldDoesNotExist: + return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E033') + return [] def _check_readonly_fields(self, obj): """ Check that readonly_fields refers to proper attribute or field. """ - if obj.readonly_fields == (): return [] - elif not isinstance(obj.readonly_fields, (list, tuple)): + if not isinstance(obj.readonly_fields, (list, tuple)): return must_be('a list or tuple', option='readonly_fields', obj=obj, id='admin.E034') - else: - return list(chain.from_iterable( - self._check_readonly_fields_item(obj, obj.model, field_name, "readonly_fields[%d]" % index) - for index, field_name in enumerate(obj.readonly_fields) - )) + return list(chain.from_iterable( + self._check_readonly_fields_item(obj, obj.model, field_name, 'readonly_fields[%d]' % index) + for index, field_name in enumerate(obj.readonly_fields) + )) def _check_readonly_fields_item(self, obj, model, field_name, label): if callable(field_name): return [] - elif hasattr(obj, field_name): + if hasattr(obj, field_name): return [] - elif hasattr(model, field_name): + if hasattr(model, field_name): return [] - else: - try: - model._meta.get_field(field_name) - except FieldDoesNotExist: - return [ - checks.Error( - "The value of '%s' is not a callable, an attribute of '%s', or an attribute of '%s.%s'." % ( - label, obj.__class__.__name__, model._meta.app_label, model._meta.object_name - ), - obj=obj.__class__, - id='admin.E035', - ) - ] - else: - return [] + try: + model._meta.get_field(field_name) + except FieldDoesNotExist: + return [ + checks.Error( + "The value of '%s' is not a callable, an attribute of " + "'%s', or an attribute of '%s.%s'." % ( + label, + obj.__class__.__name__, + model._meta.app_label, + model._meta.object_name + ), + obj=obj.__class__, + id='admin.E035', + ) + ] + return [] class ModelAdminChecks(BaseModelAdminChecks): @@ -572,32 +525,24 @@ def check(self, admin_obj, **kwargs): def _check_save_as(self, obj): """ Check save_as is a boolean. """ - if not isinstance(obj.save_as, bool): - return must_be('a boolean', option='save_as', - obj=obj, id='admin.E101') - else: - return [] + return must_be('a boolean', option='save_as', obj=obj, id='admin.E101') + return [] def _check_save_on_top(self, obj): """ Check save_on_top is a boolean. """ - if not isinstance(obj.save_on_top, bool): - return must_be('a boolean', option='save_on_top', - obj=obj, id='admin.E102') - else: - return [] + return must_be('a boolean', option='save_on_top', obj=obj, id='admin.E102') + return [] def _check_inlines(self, obj): """ Check all inline model admin classes. """ - if not isinstance(obj.inlines, (list, tuple)): return must_be('a list or tuple', option='inlines', obj=obj, id='admin.E103') - else: - return list(chain.from_iterable( - self._check_inlines_item(obj, obj.model, item, "inlines[%d]" % index) - for index, item in enumerate(obj.inlines) - )) + return list(chain.from_iterable( + self._check_inlines_item(obj, obj.model, item, 'inlines[%d]' % index) + for index, item in enumerate(obj.inlines) + )) def _check_inlines_item(self, obj, model, inline, label): """ Check one inline model admin. """ @@ -613,7 +558,7 @@ def _check_inlines_item(self, obj, model, inline, label): id='admin.E104', ) ] - elif not inline.model: + if not inline.model: return [ checks.Error( "'%s' must have a 'model' attribute." % inline_label, @@ -621,69 +566,61 @@ def _check_inlines_item(self, obj, model, inline, label): id='admin.E105', ) ] - elif not issubclass(inline.model, models.Model): + if not issubclass(inline.model, models.Model): return must_be('a Model', option='%s.model' % inline_label, obj=obj, id='admin.E106') - else: - return inline(model, obj.admin_site).check() + return inline(model, obj.admin_site).check() def _check_list_display(self, obj): - """ Check that list_display only contains fields or usable attributes. - """ - + """Check that list_display only contains fields or usable attributes.""" if not isinstance(obj.list_display, (list, tuple)): return must_be('a list or tuple', option='list_display', obj=obj, id='admin.E107') - else: - return list(chain.from_iterable( - self._check_list_display_item(obj, obj.model, item, "list_display[%d]" % index) - for index, item in enumerate(obj.list_display) - )) + return list(chain.from_iterable( + self._check_list_display_item(obj, obj.model, item, 'list_display[%d]' % index) + for index, item in enumerate(obj.list_display) + )) def _check_list_display_item(self, obj, model, item, label): if callable(item): return [] - elif hasattr(obj, item): + if hasattr(obj, item): return [] - elif hasattr(model, item): + if hasattr(model, item): try: field = model._meta.get_field(item) except FieldDoesNotExist: return [] - else: - if isinstance(field, models.ManyToManyField): - return [ - checks.Error( - "The value of '%s' must not be a ManyToManyField." % label, - obj=obj.__class__, - id='admin.E109', - ) - ] - return [] - else: - return [ - checks.Error( - "The value of '%s' refers to '%s', which is not a callable, " - "an attribute of '%s', or an attribute or method on '%s.%s'." % ( - label, item, obj.__class__.__name__, - model._meta.app_label, model._meta.object_name, - ), - obj=obj.__class__, - id='admin.E108', - ) - ] + if isinstance(field, models.ManyToManyField): + return [ + checks.Error( + "The value of '%s' must not be a ManyToManyField." % label, + obj=obj.__class__, + id='admin.E109', + ) + ] + return [] + return [ + checks.Error( + "The value of '%s' refers to '%s', which is not a callable, " + "an attribute of '%s', or an attribute or method on '%s.%s'." % ( + label, item, obj.__class__.__name__, + model._meta.app_label, model._meta.object_name, + ), + obj=obj.__class__, + id='admin.E108', + ) + ] def _check_list_display_links(self, obj): - """ Check that list_display_links is a unique subset of list_display. - """ + """Check that list_display_links is a unique subset of list_display.""" from django.contrib.admin.options import ModelAdmin - if obj.list_display_links is None: return [] - elif not isinstance(obj.list_display_links, (list, tuple)): + if not isinstance(obj.list_display_links, (list, tuple)): return must_be('a list, a tuple, or None', option='list_display_links', obj=obj, id='admin.E110') # Check only if ModelAdmin.get_list_display() isn't overridden. - elif obj.get_list_display.__func__ is ModelAdmin.get_list_display: + if obj.get_list_display.__func__ is ModelAdmin.get_list_display: return list(chain.from_iterable( - self._check_list_display_links_item(obj, field_name, "list_display_links[%d]" % index) + self._check_list_display_links_item(obj, field_name, 'list_display_links[%d]' % index) for index, field_name in enumerate(obj.list_display_links) )) return [] @@ -692,24 +629,21 @@ def _check_list_display_links_item(self, obj, field_name, label): if field_name not in obj.list_display: return [ checks.Error( - "The value of '%s' refers to '%s', which is not defined in 'list_display'." % ( - label, field_name - ), + "The value of '%s' refers to '%s', which is not defined " + "in 'list_display'." % (label, field_name), obj=obj.__class__, id='admin.E111', ) ] - else: - return [] + return [] def _check_list_filter(self, obj): if not isinstance(obj.list_filter, (list, tuple)): return must_be('a list or tuple', option='list_filter', obj=obj, id='admin.E112') - else: - return list(chain.from_iterable( - self._check_list_filter_item(obj, obj.model, item, "list_filter[%d]" % index) - for index, item in enumerate(obj.list_filter) - )) + return list(chain.from_iterable( + self._check_list_filter_item(obj, obj.model, item, 'list_filter[%d]' % index) + for index, item in enumerate(obj.list_filter) + )) def _check_list_filter_item(self, obj, model, item, label): """ @@ -719,16 +653,14 @@ def _check_list_filter_item(self, obj, model, item, label): 2. ('field', SomeFieldListFilter) - a field-based list filter class 3. SomeListFilter - a non-field list filter class """ - from django.contrib.admin import ListFilter, FieldListFilter - if callable(item) and not isinstance(item, models.Field): # If item is option 3, it should be a ListFilter... if not issubclass(item, ListFilter): return must_inherit_from(parent='ListFilter', option=label, obj=obj, id='admin.E113') # ... but not a FieldListFilter. - elif issubclass(item, FieldListFilter): + if issubclass(item, FieldListFilter): return [ checks.Error( "The value of '%s' must not inherit from 'FieldListFilter'." % label, @@ -736,149 +668,130 @@ def _check_list_filter_item(self, obj, model, item, label): id='admin.E114', ) ] - else: - return [] - elif isinstance(item, (tuple, list)): + return [] + if isinstance(item, (tuple, list)): # item is option #2 field, list_filter_class = item if not issubclass(list_filter_class, FieldListFilter): return must_inherit_from(parent='FieldListFilter', option='%s[1]' % label, obj=obj, id='admin.E115') - else: - return [] - else: - # item is option #1 - field = item + return [] + # item is option #1 + field = item - # Validate the field string - try: - get_fields_from_path(model, field) - except (NotRelationField, FieldDoesNotExist): - return [ - checks.Error( - "The value of '%s' refers to '%s', which does not refer to a Field." % (label, field), - obj=obj.__class__, - id='admin.E116', - ) - ] - else: - return [] + # Validate the field string + try: + get_fields_from_path(model, field) + except (NotRelationField, FieldDoesNotExist): + return [ + checks.Error( + "The value of '%s' refers to '%s', which does not refer " + "to a Field." % (label, field), + obj=obj.__class__, + id='admin.E116', + ) + ] + return [] def _check_list_select_related(self, obj): """ Check that list_select_related is a boolean, a list or a tuple. """ - if not isinstance(obj.list_select_related, (bool, list, tuple)): return must_be('a boolean, tuple or list', option='list_select_related', obj=obj, id='admin.E117') - else: - return [] + return [] def _check_list_per_page(self, obj): """ Check that list_per_page is an integer. """ - if not isinstance(obj.list_per_page, int): return must_be('an integer', option='list_per_page', obj=obj, id='admin.E118') - else: - return [] + return [] def _check_list_max_show_all(self, obj): """ Check that list_max_show_all is an integer. """ - if not isinstance(obj.list_max_show_all, int): return must_be('an integer', option='list_max_show_all', obj=obj, id='admin.E119') - else: - return [] + return [] def _check_list_editable(self, obj): """ Check that list_editable is a sequence of editable fields from list_display without first element. """ - if not isinstance(obj.list_editable, (list, tuple)): return must_be('a list or tuple', option='list_editable', obj=obj, id='admin.E120') - else: - return list(chain.from_iterable( - self._check_list_editable_item(obj, obj.model, item, "list_editable[%d]" % index) - for index, item in enumerate(obj.list_editable) - )) + return list(chain.from_iterable( + self._check_list_editable_item(obj, obj.model, item, 'list_editable[%d]' % index) + for index, item in enumerate(obj.list_editable) + )) def _check_list_editable_item(self, obj, model, field_name, label): try: field = model._meta.get_field(field_name) except FieldDoesNotExist: return refer_to_missing_field(field=field_name, option=label, model=model, obj=obj, id='admin.E121') - else: - if field_name not in obj.list_display: - return [ - checks.Error( - "The value of '%s' refers to '%s', which is not " - "contained in 'list_display'." % (label, field_name), - obj=obj.__class__, - id='admin.E122', - ) - ] - elif obj.list_display_links and field_name in obj.list_display_links: - return [ - checks.Error( - "The value of '%s' cannot be in both 'list_editable' and 'list_display_links'." % field_name, - obj=obj.__class__, - id='admin.E123', - ) - ] - # If list_display[0] is in list_editable, check that - # list_display_links is set. See #22792 and #26229 for use cases. - elif (obj.list_display[0] == field_name and not obj.list_display_links and - obj.list_display_links is not None): - return [ - checks.Error( - "The value of '%s' refers to the first field in 'list_display' ('%s'), " - "which cannot be used unless 'list_display_links' is set." % ( - label, obj.list_display[0] - ), - obj=obj.__class__, - id='admin.E124', - ) - ] - elif not field.editable: - return [ - checks.Error( - "The value of '%s' refers to '%s', which is not editable through the admin." % ( - label, field_name - ), - obj=obj.__class__, - id='admin.E125', - ) - ] - else: - return [] + if field_name not in obj.list_display: + return [ + checks.Error( + "The value of '%s' refers to '%s', which is not " + "contained in 'list_display'." % (label, field_name), + obj=obj.__class__, + id='admin.E122', + ) + ] + if obj.list_display_links and field_name in obj.list_display_links: + return [ + checks.Error( + "The value of '%s' cannot be in both 'list_editable' and " + "'list_display_links'." % field_name, + obj=obj.__class__, + id='admin.E123', + ) + ] + # If list_display[0] is in list_editable, check that + # list_display_links is set. See #22792 and #26229 for use cases. + if (obj.list_display[0] == field_name and not obj.list_display_links and + obj.list_display_links is not None): + return [ + checks.Error( + "The value of '%s' refers to the first field in 'list_display' ('%s'), " + "which cannot be used unless 'list_display_links' is set." % ( + label, obj.list_display[0] + ), + obj=obj.__class__, + id='admin.E124', + ) + ] + if not field.editable: + return [ + checks.Error( + "The value of '%s' refers to '%s', which is not editable " + "through the admin." % (label, field_name), + obj=obj.__class__, + id='admin.E125', + ) + ] + return [] def _check_search_fields(self, obj): """ Check search_fields is a sequence. """ - if not isinstance(obj.search_fields, (list, tuple)): return must_be('a list or tuple', option='search_fields', obj=obj, id='admin.E126') - else: - return [] + return [] def _check_date_hierarchy(self, obj): """ Check that date_hierarchy refers to DateField or DateTimeField. """ - if obj.date_hierarchy is None: return [] - else: - try: - field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] - except (NotRelationField, FieldDoesNotExist): - return [ - checks.Error( - "The value of 'date_hierarchy' refers to '%s', which " - "does not refer to a Field." % obj.date_hierarchy, - obj=obj.__class__, - id='admin.E127', - ) - ] - else: - if not isinstance(field, (models.DateField, models.DateTimeField)): - return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128') - else: - return [] + try: + field = get_fields_from_path(obj.model, obj.date_hierarchy)[-1] + except (NotRelationField, FieldDoesNotExist): + return [ + checks.Error( + "The value of 'date_hierarchy' refers to '%s', which " + "does not refer to a Field." % obj.date_hierarchy, + obj=obj.__class__, + id='admin.E127', + ) + ] + if not isinstance(field, (models.DateField, models.DateTimeField)): + return must_be('a DateField or DateTimeField', option='date_hierarchy', obj=obj, id='admin.E128') + return [] class InlineModelAdminChecks(BaseModelAdminChecks): @@ -921,52 +834,43 @@ def _check_exclude_of_parent_model(self, obj, parent_model): id='admin.E201', ) ] - else: - return [] + return [] def _check_relation(self, obj, parent_model): try: _get_foreign_key(parent_model, obj.model, fk_name=obj.fk_name) except ValueError as e: return [checks.Error(e.args[0], obj=obj.__class__, id='admin.E202')] - else: - return [] + return [] def _check_extra(self, obj): """ Check that extra is an integer. """ - if not isinstance(obj.extra, int): return must_be('an integer', option='extra', obj=obj, id='admin.E203') - else: - return [] + return [] def _check_max_num(self, obj): """ Check that max_num is an integer. """ - if obj.max_num is None: return [] - elif not isinstance(obj.max_num, int): + if not isinstance(obj.max_num, int): return must_be('an integer', option='max_num', obj=obj, id='admin.E204') - else: - return [] + return [] def _check_min_num(self, obj): """ Check that min_num is an integer. """ - if obj.min_num is None: return [] - elif not isinstance(obj.min_num, int): + if not isinstance(obj.min_num, int): return must_be('an integer', option='min_num', obj=obj, id='admin.E205') - else: - return [] + return [] def _check_formset(self, obj): """ Check formset is a subclass of BaseModelFormSet. """ if not issubclass(obj.formset, BaseModelFormSet): return must_inherit_from(parent='BaseModelFormSet', option='formset', obj=obj, id='admin.E206') - else: - return [] + return [] def must_be(type, option, obj, id): diff --git a/django/contrib/admin/models.py b/django/contrib/admin/models.py index 2f8ecc88df5b6..951065aba402b 100644 --- a/django/contrib/admin/models.py +++ b/django/contrib/admin/models.py @@ -68,14 +68,13 @@ def __repr__(self): def __str__(self): if self.is_addition(): return gettext('Added "%(object)s".') % {'object': self.object_repr} - elif self.is_change(): + if self.is_change(): return gettext('Changed "%(object)s" - %(changes)s') % { 'object': self.object_repr, 'changes': self.get_change_message(), } - elif self.is_deletion(): + if self.is_deletion(): return gettext('Deleted "%(object)s."') % {'object': self.object_repr} - return gettext('LogEntry Object') def is_addition(self): diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py index d37615b1e545c..244da2fba3782 100644 --- a/django/contrib/admin/options.py +++ b/django/contrib/admin/options.py @@ -936,9 +936,9 @@ def get_search_results(self, request, queryset, search_term): def construct_search(field_name): if field_name.startswith('^'): return "%s__istartswith" % field_name[1:] - elif field_name.startswith('='): + if field_name.startswith('='): return "%s__iexact" % field_name[1:] - elif field_name.startswith('@'): + if field_name.startswith('@'): return "%s__search" % field_name[1:] # Use field_name if it includes a lookup. opts = queryset.model._meta diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index 367a794d5970d..c8c6f16633115 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -31,13 +31,14 @@ def paginator_number(cl, i): """ if i == DOT: return '... ' - elif i == cl.page_num: + if i == cl.page_num: return format_html('{} ', i + 1) - else: - return format_html('{} ', - cl.get_query_string({PAGE_VAR: i}), - mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''), - i + 1) + return format_html( + '{} ', + cl.get_query_string({PAGE_VAR: i}), + mark_safe(' class="end"' if i == cl.paginator.num_pages - 1 else ''), + i + 1, + ) @register.inclusion_tag('admin/pagination.html') diff --git a/django/contrib/admin/utils.py b/django/contrib/admin/utils.py index 849a695276b56..bf1d3d9f08b6f 100644 --- a/django/contrib/admin/utils.py +++ b/django/contrib/admin/utils.py @@ -393,22 +393,21 @@ def display_for_field(value, field, empty_value_display): return dict(field.flatchoices).get(value, empty_value_display) # NullBooleanField needs special-case null-handling, so it comes # before the general null test. - elif isinstance(field, (models.BooleanField, models.NullBooleanField)): + if isinstance(field, (models.BooleanField, models.NullBooleanField)): return _boolean_icon(value) - elif value is None: + if value is None: return empty_value_display - elif isinstance(field, models.DateTimeField): + if isinstance(field, models.DateTimeField): return formats.localize(timezone.template_localtime(value)) - elif isinstance(field, (models.DateField, models.TimeField)): + if isinstance(field, (models.DateField, models.TimeField)): return formats.localize(value) - elif isinstance(field, models.DecimalField): + if isinstance(field, models.DecimalField): return formats.number_format(value, field.decimal_places) - elif isinstance(field, (models.IntegerField, models.FloatField)): + if isinstance(field, (models.IntegerField, models.FloatField)): return formats.number_format(value) - elif isinstance(field, models.FileField) and value: + if isinstance(field, models.FileField) and value: return format_html('{}', value.url, value) - else: - return display_for_value(value, empty_value_display) + return display_for_value(value, empty_value_display) def display_for_value(value, empty_value_display, boolean=False): @@ -416,18 +415,17 @@ def display_for_value(value, empty_value_display, boolean=False): if boolean: return _boolean_icon(value) - elif value is None: + if value is None: return empty_value_display - elif isinstance(value, datetime.datetime): + if isinstance(value, datetime.datetime): return formats.localize(timezone.template_localtime(value)) - elif isinstance(value, (datetime.date, datetime.time)): + if isinstance(value, (datetime.date, datetime.time)): return formats.localize(value) - elif isinstance(value, (int, decimal.Decimal, float)): + if isinstance(value, (int, decimal.Decimal, float)): return formats.number_format(value) - elif isinstance(value, (list, tuple)): + if isinstance(value, (list, tuple)): return ', '.join(str(v) for v in value) - else: - return str(value) + return str(value) class NotRelationField(Exception): @@ -437,8 +435,7 @@ class NotRelationField(Exception): def get_model_from_relation(field): if hasattr(field, 'get_path_info'): return field.get_path_info()[-1].to_opts.model - else: - raise NotRelationField + raise NotRelationField def reverse_field_path(model, path): diff --git a/django/contrib/admindocs/views.py b/django/contrib/admindocs/views.py index 438da150fc0fa..e1e43f6899846 100644 --- a/django/contrib/admindocs/views.py +++ b/django/contrib/admindocs/views.py @@ -370,7 +370,7 @@ def get_return_data_type(func_name): if func_name.startswith('get_'): if func_name.endswith('_list'): return 'List' - elif func_name.endswith('_count'): + if func_name.endswith('_count'): return 'Integer' return '' diff --git a/django/contrib/auth/forms.py b/django/contrib/auth/forms.py index e857f95cb264d..54f794152312a 100644 --- a/django/contrib/auth/forms.py +++ b/django/contrib/auth/forms.py @@ -202,8 +202,7 @@ def clean(self): else: self.confirm_login_allowed(self.user_cache) raise self.get_invalid_login_error() - else: - self.confirm_login_allowed(self.user_cache) + self.confirm_login_allowed(self.user_cache) return self.cleaned_data diff --git a/django/contrib/auth/hashers.py b/django/contrib/auth/hashers.py index c14ece20fbde0..6fc443fa189da 100644 --- a/django/contrib/auth/hashers.py +++ b/django/contrib/auth/hashers.py @@ -114,18 +114,16 @@ def get_hasher(algorithm='default'): """ if hasattr(algorithm, 'algorithm'): return algorithm - - elif algorithm == 'default': + if algorithm == 'default': return get_hashers()[0] - - else: - hashers = get_hashers_by_algorithm() - try: - return hashers[algorithm] - except KeyError: - raise ValueError("Unknown password hashing algorithm '%s'. " - "Did you specify it in the PASSWORD_HASHERS " - "setting?" % algorithm) + hashers = get_hashers_by_algorithm() + try: + return hashers[algorithm] + except KeyError: + raise ValueError( + "Unknown password hashing algorithm '%s'. Did you specify it in " + "the PASSWORD_HASHERS setting?" % algorithm + ) def identify_hasher(encoded): diff --git a/django/contrib/contenttypes/fields.py b/django/contrib/contenttypes/fields.py index d186e1f39a691..9185574851481 100644 --- a/django/contrib/contenttypes/fields.py +++ b/django/contrib/contenttypes/fields.py @@ -138,7 +138,7 @@ def _check_content_type_field(self): id='contenttypes.E003', ) ] - elif field.remote_field.model != ContentType: + if field.remote_field.model != ContentType: return [ checks.Error( "'%s.%s' is not a ForeignKey to 'contenttypes.ContentType'." % ( @@ -152,8 +152,7 @@ def _check_content_type_field(self): id='contenttypes.E004', ) ] - else: - return [] + return [] def get_cache_name(self): return self.name @@ -162,11 +161,10 @@ def get_content_type(self, obj=None, id=None, using=None): if obj is not None: return ContentType.objects.db_manager(obj._state.db).get_for_model( obj, for_concrete_model=self.for_concrete_model) - elif id is not None: + if id is not None: return ContentType.objects.db_manager(using).get_for_id(id) - else: - # This should never happen. I love comments like this, don't you? - raise Exception("Impossible arguments to GFK.get_content_type!") + # This should never happen. + raise Exception("Impossible arguments to GFK.get_content_type!") def get_prefetch_queryset(self, instances, queryset=None): if queryset is not None: diff --git a/django/contrib/gis/db/backends/base/models.py b/django/contrib/gis/db/backends/base/models.py index c25c1ccdee1a8..50ecd971f215f 100644 --- a/django/contrib/gis/db/backends/base/models.py +++ b/django/contrib/gis/db/backends/base/models.py @@ -96,10 +96,9 @@ def units(self): "Return a tuple of the units and the name." if self.projected or self.local: return (self.linear_units, self.linear_name) - elif self.geographic: + if self.geographic: return (self.angular_units, self.angular_name) - else: - return (None, None) + return (None, None) @classmethod def get_units(cls, wkt): diff --git a/django/contrib/gis/db/backends/base/operations.py b/django/contrib/gis/db/backends/base/operations.py index 1b786f7897b31..3109f73523028 100644 --- a/django/contrib/gis/db/backends/base/operations.py +++ b/django/contrib/gis/db/backends/base/operations.py @@ -98,11 +98,10 @@ def transform_value(value, field): self.spatial_function_name('Transform'), self.from_text, value.srid, f.srid, ) - elif self.connection.features.has_spatialrefsys_table: + if self.connection.features.has_spatialrefsys_table: return '%s(%%s,%s)' % (self.from_text, f.srid) - else: - # For backwards compatibility on MySQL (#27464). - return '%s(%%s)' % self.from_text + # For backwards compatibility on MySQL (#27464). + return '%s(%%s)' % self.from_text def check_expression_support(self, expression): if isinstance(expression, self.disallowed_aggregates): @@ -145,10 +144,9 @@ def get_area_att_for_field(self, field): if self.connection.features.supports_area_geodetic: return 'sq_m' raise NotImplementedError('Area on geodetic coordinate systems not supported.') - else: - units_name = field.units_name(self.connection) - if units_name: - return AreaMeasure.unit_attname(units_name) + units_name = field.units_name(self.connection) + if units_name: + return AreaMeasure.unit_attname(units_name) def get_distance_att_for_field(self, field): dist_att = None diff --git a/django/contrib/gis/db/models/lookups.py b/django/contrib/gis/db/models/lookups.py index 6d5df2c10fdd5..632879103f394 100644 --- a/django/contrib/gis/db/models/lookups.py +++ b/django/contrib/gis/db/models/lookups.py @@ -282,7 +282,7 @@ class DistanceLookupBase(GISLookup): def process_rhs_params(self): if not 1 <= len(self.rhs_params) <= 3: raise ValueError("2, 3, or 4-element tuple required for '%s' lookup." % self.lookup_name) - elif len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid': + if len(self.rhs_params) == 3 and self.rhs_params[2] != 'spheroid': raise ValueError("For 4-element tuples the last argument must be the 'spheroid' directive.") # Check if the second parameter is a band index. diff --git a/django/contrib/gis/gdal/envelope.py b/django/contrib/gis/gdal/envelope.py index bbcc5d068ff85..0d3e040c1c605 100644 --- a/django/contrib/gis/gdal/envelope.py +++ b/django/contrib/gis/gdal/envelope.py @@ -48,8 +48,7 @@ def __init__(self, *args): # A tuple was passed in. if len(args[0]) != 4: raise GDALException('Incorrect number of tuple elements (%d).' % len(args[0])) - else: - self._from_sequence(args[0]) + self._from_sequence(args[0]) else: raise TypeError('Incorrect type of argument: %s' % type(args[0])) elif len(args) == 4: @@ -73,11 +72,10 @@ def __eq__(self, other): if isinstance(other, Envelope): return (self.min_x == other.min_x) and (self.min_y == other.min_y) and \ (self.max_x == other.max_x) and (self.max_y == other.max_y) - elif isinstance(other, tuple) and len(other) == 4: + if isinstance(other, tuple) and len(other) == 4: return (self.min_x == other[0]) and (self.min_y == other[1]) and \ (self.max_x == other[2]) and (self.max_y == other[3]) - else: - raise GDALException('Equivalence testing only works with other Envelopes.') + raise GDALException('Equivalence testing only works with other Envelopes.') def __str__(self): "Return a string representation of the tuple." @@ -104,13 +102,13 @@ def expand_to_include(self, *args): if len(args) == 1: if isinstance(args[0], Envelope): return self.expand_to_include(args[0].tuple) - elif hasattr(args[0], 'x') and hasattr(args[0], 'y'): + if hasattr(args[0], 'x') and hasattr(args[0], 'y'): return self.expand_to_include(args[0].x, args[0].y, args[0].x, args[0].y) - elif isinstance(args[0], (tuple, list)): + if isinstance(args[0], (tuple, list)): # A tuple was passed in. if len(args[0]) == 2: return self.expand_to_include((args[0][0], args[0][1], args[0][0], args[0][1])) - elif len(args[0]) == 4: + if len(args[0]) == 4: (minx, miny, maxx, maxy) = args[0] if minx < self._envelope.MinX: self._envelope.MinX = minx @@ -126,7 +124,7 @@ def expand_to_include(self, *args): raise TypeError('Incorrect type of argument: %s' % type(args[0])) elif len(args) == 2: # An x and an y parameter were passed in - return self.expand_to_include((args[0], args[1], args[0], args[1])) + return self.expand_to_include((args[0], args[1], args[0], args[1])) elif len(args) == 4: # Individual parameters passed in. return self.expand_to_include(args) diff --git a/django/contrib/gis/gdal/error.py b/django/contrib/gis/gdal/error.py index e394b6077c826..353629a87a199 100644 --- a/django/contrib/gis/gdal/error.py +++ b/django/contrib/gis/gdal/error.py @@ -54,8 +54,7 @@ def check_err(code, cpl=False): if code == ERR_NONE: return - elif code in err_dict: + if code in err_dict: e, msg = err_dict[code] raise e(msg) - else: - raise GDALException('Unknown error code: "%s"' % code) + raise GDALException('Unknown error code: "%s"' % code) diff --git a/django/contrib/gis/gdal/geometries.py b/django/contrib/gis/gdal/geometries.py index 42fbeecd08da6..3933f126f116a 100644 --- a/django/contrib/gis/gdal/geometries.py +++ b/django/contrib/gis/gdal/geometries.py @@ -541,7 +541,7 @@ def tuple(self): "Return the tuple of this point." if self.coord_dim == 2: return (self.x, self.y) - elif self.coord_dim == 3: + if self.coord_dim == 3: return (self.x, self.y, self.z) coords = tuple @@ -556,9 +556,9 @@ def __getitem__(self, index): dim = self.coord_dim if dim == 1: return (x.value,) - elif dim == 2: + if dim == 2: return (x.value, y.value) - elif dim == 3: + if dim == 3: return (x.value, y.value, z.value) else: raise IndexError('Index out of range when accessing points of a line string: %s.' % index) diff --git a/django/contrib/gis/gdal/geomtype.py b/django/contrib/gis/gdal/geomtype.py index 2c6798a00df2e..3062960b987e0 100644 --- a/django/contrib/gis/gdal/geomtype.py +++ b/django/contrib/gis/gdal/geomtype.py @@ -61,12 +61,11 @@ def __eq__(self, other): """ if isinstance(other, OGRGeomType): return self.num == other.num - elif isinstance(other, str): + if isinstance(other, str): return self.name.lower() == other.lower() - elif isinstance(other, int): + if isinstance(other, int): return self.num == other - else: - return False + return False @property def name(self): diff --git a/django/contrib/gis/gdal/srs.py b/django/contrib/gis/gdal/srs.py index b2e0b090bc06e..86bf755d81c1e 100644 --- a/django/contrib/gis/gdal/srs.py +++ b/django/contrib/gis/gdal/srs.py @@ -82,8 +82,7 @@ def __init__(self, srs_input='', srs_type='user'): # If the pointer is NULL, throw an exception. if not srs: raise SRSException('Could not create spatial reference from: %s' % srs_input) - else: - self.ptr = srs + self.ptr = srs # Importing from either the user input string or an integer SRID. if srs_type == 'user': @@ -170,12 +169,11 @@ def name(self): "Return the name of this Spatial Reference." if self.projected: return self.attr_value('PROJCS') - elif self.geographic: + if self.geographic: return self.attr_value('GEOGCS') - elif self.local: + if self.local: return self.attr_value('LOCAL_CS') - else: - return None + return None @property def srid(self): diff --git a/django/contrib/gis/geoip2/base.py b/django/contrib/gis/geoip2/base.py index b1035ac6ff31e..620b5426de5dc 100644 --- a/django/contrib/gis/geoip2/base.py +++ b/django/contrib/gis/geoip2/base.py @@ -115,17 +115,13 @@ def __init__(self, path=None, cache=0, country=None, city=None): @property def _reader(self): - if self._country: - return self._country - else: - return self._city + return self._country or self._city @property def _country_or_city(self): if self._country: return self._country.country - else: - return self._city.city + return self._city.city def __del__(self): # Cleanup any GeoIP file handles lying around. @@ -151,9 +147,9 @@ def _check_query(self, query, country=False, city=False, city_or_country=False): # Extra checks for the existence of country and city databases. if city_or_country and not (self._country or self._city): raise GeoIP2Exception('Invalid GeoIP country and city data files.') - elif country and not self._country: + if country and not self._country: raise GeoIP2Exception('Invalid GeoIP country data file: %s' % self._country_file) - elif city and not self._city: + if city and not self._city: raise GeoIP2Exception('Invalid GeoIP city data file: %s' % self._city_file) # Return the query string back to the caller. GeoIP2 only takes IP addresses. diff --git a/django/contrib/gis/geos/mutable_list.py b/django/contrib/gis/geos/mutable_list.py index 90fcc6d587a06..43ff3a9cdac90 100644 --- a/django/contrib/gis/geos/mutable_list.py +++ b/django/contrib/gis/geos/mutable_list.py @@ -160,7 +160,7 @@ def __lt__(self, other): return True if c: return c - elif other[i] < self[i]: + if other[i] < self[i]: return False return len(self) < olen diff --git a/django/contrib/gis/geos/point.py b/django/contrib/gis/geos/point.py index ccf5b9dbaf235..eaf7bb6ea4448 100644 --- a/django/contrib/gis/geos/point.py +++ b/django/contrib/gis/geos/point.py @@ -91,15 +91,14 @@ def __len__(self): return 0 if self.hasz: return 3 - else: - return 2 + return 2 def _get_single_external(self, index): if index == 0: return self.x - elif index == 1: + if index == 1: return self.y - elif index == 2: + if index == 2: return self.z _get_single_internal = _get_single_external diff --git a/django/contrib/gis/geos/prototypes/errcheck.py b/django/contrib/gis/geos/prototypes/errcheck.py index 7d5f8422e0fc1..b2dac465a59ac 100644 --- a/django/contrib/gis/geos/prototypes/errcheck.py +++ b/django/contrib/gis/geos/prototypes/errcheck.py @@ -45,10 +45,9 @@ def check_predicate(result, func, cargs): "Error checking for unary/binary predicate functions." if result == 1: return True - elif result == 0: + if result == 0: return False - else: - raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__) + raise GEOSException('Error encountered on GEOS C predicate function "%s".' % func.__name__) def check_sized_string(result, func, cargs): diff --git a/django/contrib/gis/geos/prototypes/io.py b/django/contrib/gis/geos/prototypes/io.py index 97f49c206938b..a2c17724d88a4 100644 --- a/django/contrib/gis/geos/prototypes/io.py +++ b/django/contrib/gis/geos/prototypes/io.py @@ -147,10 +147,9 @@ def read(self, wkb): if isinstance(wkb, memoryview): wkb_s = bytes(wkb) return wkb_reader_read(self.ptr, wkb_s, len(wkb_s)) - elif isinstance(wkb, (bytes, str)): + if isinstance(wkb, (bytes, str)): return wkb_reader_read_hex(self.ptr, wkb, len(wkb)) - else: - raise TypeError + raise TypeError # ### WKB/WKT Writer Classes ### diff --git a/django/contrib/gis/measure.py b/django/contrib/gis/measure.py index 3bb23d9b6416f..1d0eb64f8643a 100644 --- a/django/contrib/gis/measure.py +++ b/django/contrib/gis/measure.py @@ -209,12 +209,11 @@ def unit_attname(cls, unit_str): lower = unit_str.lower() if unit_str in cls.UNITS: return unit_str - elif lower in cls.UNITS: + if lower in cls.UNITS: return lower - elif lower in cls.LALIAS: + if lower in cls.LALIAS: return cls.LALIAS[lower] - else: - raise Exception('Could not find a unit keyword associated with "%s"' % unit_str) + raise Exception('Could not find a unit keyword associated with "%s"' % unit_str) class Distance(MeasureBase): @@ -300,15 +299,14 @@ def __mul__(self, other): default_unit=AREA_PREFIX + self._default_unit, **{AREA_PREFIX + self.STANDARD_UNIT: (self.standard * other.standard)} ) - elif isinstance(other, NUMERIC_TYPES): + if isinstance(other, NUMERIC_TYPES): return self.__class__( default_unit=self._default_unit, **{self.STANDARD_UNIT: (self.standard * other)} ) - else: - raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % { - "distance": pretty_name(self.__class__), - }) + raise TypeError('%(distance)s must be multiplied with number or %(distance)s' % { + "distance": pretty_name(self.__class__), + }) class Area(MeasureBase): diff --git a/django/contrib/gis/utils/layermapping.py b/django/contrib/gis/utils/layermapping.py index e4baf56dcb43f..5c6fcca109568 100644 --- a/django/contrib/gis/utils/layermapping.py +++ b/django/contrib/gis/utils/layermapping.py @@ -154,12 +154,10 @@ def check_fid_range(self, fid_range): if fid_range: if isinstance(fid_range, (tuple, list)): return slice(*fid_range) - elif isinstance(fid_range, slice): + if isinstance(fid_range, slice): return fid_range - else: - raise TypeError - else: - return None + raise TypeError + return None def check_layer(self): """ diff --git a/django/contrib/gis/utils/ogrinspect.py b/django/contrib/gis/utils/ogrinspect.py index 9a091602fced0..d183e8ec0303f 100644 --- a/django/contrib/gis/utils/ogrinspect.py +++ b/django/contrib/gis/utils/ogrinspect.py @@ -144,10 +144,9 @@ def _ogrinspect(data_source, model_name, geom_name='geom', layer_key=0, srid=Non def process_kwarg(kwarg): if isinstance(kwarg, (list, tuple)): return [s.lower() for s in kwarg] - elif kwarg: + if kwarg: return [s.lower() for s in ogr_fields] - else: - return [] + return [] null_fields = process_kwarg(null) blank_fields = process_kwarg(blank) decimal_fields = process_kwarg(decimal) @@ -161,8 +160,7 @@ def get_kwargs_str(field_name): kwlist.append('blank=True') if kwlist: return ', ' + ', '.join(kwlist) - else: - return '' + return '' # For those wishing to disable the imports. if imports: diff --git a/django/contrib/humanize/templatetags/humanize.py b/django/contrib/humanize/templatetags/humanize.py index 7b99d78f1e746..4f1c09ea894cb 100644 --- a/django/contrib/humanize/templatetags/humanize.py +++ b/django/contrib/humanize/templatetags/humanize.py @@ -197,9 +197,9 @@ def naturalday(value, arg=None): delta = value - today if delta.days == 0: return _('today') - elif delta.days == 1: + if delta.days == 1: return _('tomorrow') - elif delta.days == -1: + if delta.days == -1: return _('yesterday') return defaultfilters.date(value, arg) @@ -222,53 +222,50 @@ def naturaltime(value): return pgettext( 'naturaltime', '%(delta)s ago' ) % {'delta': defaultfilters.timesince(value, now)} - elif delta.seconds == 0: + if delta.seconds == 0: return _('now') - elif delta.seconds < 60: + if delta.seconds < 60: return ngettext( # Translators: please keep a non-breaking space (U+00A0) # between count and time unit. 'a second ago', '%(count)s seconds ago', delta.seconds ) % {'count': delta.seconds} - elif delta.seconds // 60 < 60: + if delta.seconds // 60 < 60: count = delta.seconds // 60 return ngettext( # Translators: please keep a non-breaking space (U+00A0) # between count and time unit. 'a minute ago', '%(count)s minutes ago', count ) % {'count': count} - else: - count = delta.seconds // 60 // 60 - return ngettext( - # Translators: please keep a non-breaking space (U+00A0) - # between count and time unit. - 'an hour ago', '%(count)s hours ago', count - ) % {'count': count} - else: - delta = value - now - if delta.days != 0: - return pgettext( - 'naturaltime', '%(delta)s from now' - ) % {'delta': defaultfilters.timeuntil(value, now)} - elif delta.seconds == 0: - return _('now') - elif delta.seconds < 60: - return ngettext( - # Translators: please keep a non-breaking space (U+00A0) - # between count and time unit. - 'a second from now', '%(count)s seconds from now', delta.seconds - ) % {'count': delta.seconds} - elif delta.seconds // 60 < 60: - count = delta.seconds // 60 - return ngettext( - # Translators: please keep a non-breaking space (U+00A0) - # between count and time unit. - 'a minute from now', '%(count)s minutes from now', count - ) % {'count': count} - else: - count = delta.seconds // 60 // 60 - return ngettext( - # Translators: please keep a non-breaking space (U+00A0) - # between count and time unit. - 'an hour from now', '%(count)s hours from now', count - ) % {'count': count} + count = delta.seconds // 60 // 60 + return ngettext( + # Translators: please keep a non-breaking space (U+00A0) + # between count and time unit. + 'an hour ago', '%(count)s hours ago', count + ) % {'count': count} + delta = value - now + if delta.days != 0: + return pgettext( + 'naturaltime', '%(delta)s from now' + ) % {'delta': defaultfilters.timeuntil(value, now)} + if delta.seconds == 0: + return _('now') + if delta.seconds < 60: + return ngettext( + # Translators: please keep a non-breaking space (U+00A0) + # between count and time unit. + 'a second from now', '%(count)s seconds from now', delta.seconds + ) % {'count': delta.seconds} + if delta.seconds // 60 < 60: + count = delta.seconds // 60 + return ngettext( + # Translators: please keep a non-breaking space (U+00A0) + # between count and time unit. + 'a minute from now', '%(count)s minutes from now', count + ) % {'count': count} + count = delta.seconds // 60 // 60 + return ngettext( + # Translators: please keep a non-breaking space (U+00A0) + # between count and time unit. + 'an hour from now', '%(count)s hours from now', count + ) % {'count': count} diff --git a/django/contrib/postgres/fields/ranges.py b/django/contrib/postgres/fields/ranges.py index 0bb914d383ef6..3f0f1fbb0b98e 100644 --- a/django/contrib/postgres/fields/ranges.py +++ b/django/contrib/postgres/fields/ranges.py @@ -38,9 +38,9 @@ def model(self, model): def get_prep_value(self, value): if value is None: return None - elif isinstance(value, Range): + if isinstance(value, Range): return value - elif isinstance(value, (list, tuple)): + if isinstance(value, (list, tuple)): return self.range_type(value[0], value[1]) return value diff --git a/django/contrib/postgres/forms/jsonb.py b/django/contrib/postgres/forms/jsonb.py index bb681e0be3db7..6418f261edc28 100644 --- a/django/contrib/postgres/forms/jsonb.py +++ b/django/contrib/postgres/forms/jsonb.py @@ -25,7 +25,7 @@ def to_python(self, value): return value if value in self.empty_values: return None - elif isinstance(value, (list, dict, int, float, JSONString)): + if isinstance(value, (list, dict, int, float, JSONString)): return value try: converted = json.loads(value) @@ -37,8 +37,7 @@ def to_python(self, value): ) if isinstance(converted, str): return JSONString(converted) - else: - return converted + return converted def bound_data(self, data, initial): if self.disabled: diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py index 35798dbdf782d..674914e73fe40 100644 --- a/django/contrib/sessions/backends/base.py +++ b/django/contrib/sessions/backends/base.py @@ -103,10 +103,9 @@ def decode(self, session_data): # could produce ValueError if there is no ':' hash, serialized = encoded_data.split(b':', 1) expected_hash = self._hash(serialized) - if not constant_time_compare(hash.decode(), expected_hash): - raise SuspiciousSession("Session data corrupted") - else: + if constant_time_compare(hash.decode(), expected_hash): return self.serializer().loads(serialized) + raise SuspiciousSession('Session data corrupted') except Exception as e: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). diff --git a/django/contrib/sites/models.py b/django/contrib/sites/models.py index 19f52e4487116..f67167dd73c54 100644 --- a/django/contrib/sites/models.py +++ b/django/contrib/sites/models.py @@ -58,7 +58,7 @@ def get_current(self, request=None): if getattr(settings, 'SITE_ID', ''): site_id = settings.SITE_ID return self._get_site_by_id(site_id) - elif request: + if request: return self._get_site_by_request(request) raise ImproperlyConfigured( diff --git a/django/core/checks/registry.py b/django/core/checks/registry.py index 9d4494001611c..5936b8f5ce335 100644 --- a/django/core/checks/registry.py +++ b/django/core/checks/registry.py @@ -50,10 +50,9 @@ def inner(check): if callable(check): return inner(check) - else: - if check: - tags += (check,) - return inner + if check: + tags += (check,) + return inner def run_checks(self, app_configs=None, tags=None, include_deployment_checks=False): """ diff --git a/django/core/checks/urls.py b/django/core/checks/urls.py index e51ca3fc1fa6d..5cf566b644e0f 100644 --- a/django/core/checks/urls.py +++ b/django/core/checks/urls.py @@ -21,10 +21,9 @@ def check_resolver(resolver): check_method = getattr(resolver, 'check', None) if check_method is not None: return check_method() - elif not hasattr(resolver, 'resolve'): + if not hasattr(resolver, 'resolve'): return get_warning_for_invalid_pattern(resolver) - else: - return [] + return [] @register(Tags.urls) diff --git a/django/core/management/base.py b/django/core/management/base.py index 41b6b0fa91faf..a8c5366e9fb39 100644 --- a/django/core/management/base.py +++ b/django/core/management/base.py @@ -408,9 +408,7 @@ def check(self, app_configs=None, tags=None, display_num_errors=False, if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues): msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer raise SystemCheckError(msg) - else: - msg = header + body + footer - + msg = header + body + footer if msg: if visible_issue_count: self.stderr.write(msg, lambda x: x) diff --git a/django/core/serializers/json.py b/django/core/serializers/json.py index 5d35440a6c627..4a42d400a9766 100644 --- a/django/core/serializers/json.py +++ b/django/core/serializers/json.py @@ -87,18 +87,17 @@ def default(self, o): if r.endswith('+00:00'): r = r[:-6] + 'Z' return r - elif isinstance(o, datetime.date): + if isinstance(o, datetime.date): return o.isoformat() - elif isinstance(o, datetime.time): + if isinstance(o, datetime.time): if is_aware(o): raise ValueError("JSON can't represent timezone-aware times.") r = o.isoformat() if o.microsecond: r = r[:12] return r - elif isinstance(o, datetime.timedelta): + if isinstance(o, datetime.timedelta): return duration_iso_string(o) - elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): + if isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): return str(o) - else: - return super().default(o) + return super().default(o) diff --git a/django/db/backends/base/base.py b/django/db/backends/base/base.py index 53c3c30063d24..a0a7eb6387eb0 100644 --- a/django/db/backends/base/base.py +++ b/django/db/backends/base/base.py @@ -125,12 +125,11 @@ def timezone(self): """ if not settings.USE_TZ: return None - elif self.features.supports_timezones: + if self.features.supports_timezones: return None - elif self.settings_dict['TIME_ZONE'] is None: + if self.settings_dict['TIME_ZONE'] is None: return timezone.utc - else: - return pytz.timezone(self.settings_dict['TIME_ZONE']) + return pytz.timezone(self.settings_dict['TIME_ZONE']) @cached_property def timezone_name(self): @@ -139,10 +138,9 @@ def timezone_name(self): """ if not settings.USE_TZ: return settings.TIME_ZONE - elif self.settings_dict['TIME_ZONE'] is None: + if self.settings_dict['TIME_ZONE'] is None: return 'UTC' - else: - return self.settings_dict['TIME_ZONE'] + return self.settings_dict['TIME_ZONE'] @property def queries_logged(self): @@ -204,7 +202,7 @@ def check_settings(self): raise ImproperlyConfigured( "Connection '%s' cannot set TIME_ZONE because USE_TZ is " "False." % self.alias) - elif self.features.supports_timezones: + if self.features.supports_timezones: raise ImproperlyConfigured( "Connection '%s' cannot set TIME_ZONE because its engine " "handles time zones conversions natively." % self.alias) diff --git a/django/db/backends/base/operations.py b/django/db/backends/base/operations.py index f6d8925278fc1..0da27d2a89b34 100644 --- a/django/db/backends/base/operations.py +++ b/django/db/backends/base/operations.py @@ -166,8 +166,7 @@ def distinct_sql(self, fields): """ if fields: raise NotSupportedError('DISTINCT ON fields is not supported by this database backend') - else: - return 'DISTINCT' + return 'DISTINCT' def fetch_returned_insert_id(self, cursor): """ @@ -207,7 +206,7 @@ def _get_limit_offset_params(self, low_mark, high_mark): offset = low_mark or 0 if high_mark is not None: return (high_mark - offset), offset - elif offset: + if offset: return self.connection.ops.no_limit_value(), offset return None, offset @@ -472,14 +471,13 @@ def adapt_unknown_value(self, value): """ if isinstance(value, datetime.datetime): # must be before date return self.adapt_datetimefield_value(value) - elif isinstance(value, datetime.date): + if isinstance(value, datetime.date): return self.adapt_datefield_value(value) - elif isinstance(value, datetime.time): + if isinstance(value, datetime.time): return self.adapt_timefield_value(value) - elif isinstance(value, decimal.Decimal): + if isinstance(value, decimal.Decimal): return self.adapt_decimalfield_value(value) - else: - return value + return value def adapt_datefield_value(self, value): """ @@ -626,9 +624,9 @@ def window_frame_start(self, start): if isinstance(start, int): if start < 0: return '%d %s' % (abs(start), self.PRECEDING) - elif start == 0: + if start == 0: return self.CURRENT_ROW - elif start is None: + if start is None: return self.UNBOUNDED_PRECEDING raise ValueError("start argument must be a negative integer, zero, or None, but got '%s'." % start) @@ -636,9 +634,9 @@ def window_frame_end(self, end): if isinstance(end, int): if end == 0: return self.CURRENT_ROW - elif end > 0: + if end > 0: return '%d %s' % (end, self.FOLLOWING) - elif end is None: + if end is None: return self.UNBOUNDED_FOLLOWING raise ValueError("end argument must be a positive integer, zero, or None, but got '%s'." % end) diff --git a/django/db/backends/base/schema.py b/django/db/backends/base/schema.py index e06cc50fc8867..cc4d63b708729 100644 --- a/django/db/backends/base/schema.py +++ b/django/db/backends/base/schema.py @@ -487,18 +487,18 @@ def alter_field(self, model, old_field, new_field, strict=False): "db_type (are you using a badly-written custom field?)" % (old_field, new_field), ) - elif old_type is None and new_type is None and ( + if old_type is None and new_type is None and ( old_field.remote_field.through and new_field.remote_field.through and old_field.remote_field.through._meta.auto_created and new_field.remote_field.through._meta.auto_created): return self._alter_many_to_many(model, old_field, new_field, strict) - elif old_type is None and new_type is None and ( + if old_type is None and new_type is None and ( old_field.remote_field.through and new_field.remote_field.through and not old_field.remote_field.through._meta.auto_created and not new_field.remote_field.through._meta.auto_created): # Both sides have through models; this is a no-op. return - elif old_type is None or new_type is None: + if old_type is None or new_type is None: raise ValueError( "Cannot alter field %s into %s - they are not compatible types " "(you cannot alter to or from M2M fields, or add or remove " diff --git a/django/db/backends/mysql/introspection.py b/django/db/backends/mysql/introspection.py index 9520e890eafda..5d59bb9519000 100644 --- a/django/db/backends/mysql/introspection.py +++ b/django/db/backends/mysql/introspection.py @@ -41,12 +41,12 @@ def get_field_type(self, data_type, description): if 'auto_increment' in description.extra: if field_type == 'IntegerField': return 'AutoField' - elif field_type == 'BigIntegerField': + if field_type == 'BigIntegerField': return 'BigAutoField' if description.is_unsigned: if field_type == 'IntegerField': return 'PositiveIntegerField' - elif field_type == 'SmallIntegerField': + if field_type == 'SmallIntegerField': return 'PositiveSmallIntegerField' return field_type diff --git a/django/db/backends/mysql/operations.py b/django/db/backends/mysql/operations.py index ad4c13652e302..af347a8cf4c5e 100644 --- a/django/db/backends/mysql/operations.py +++ b/django/db/backends/mysql/operations.py @@ -49,12 +49,11 @@ def date_trunc_sql(self, lookup_type, field_name): if lookup_type in fields: format_str = fields[lookup_type] return "CAST(DATE_FORMAT(%s, '%s') AS DATE)" % (field_name, format_str) - elif lookup_type == 'quarter': + if lookup_type == 'quarter': return "MAKEDATE(YEAR(%s), 1) + INTERVAL QUARTER(%s) QUARTER - INTERVAL 1 QUARTER" % ( field_name, field_name ) - else: - return "DATE(%s)" % (field_name) + return "DATE(%s)" % (field_name) def _convert_field_to_tz(self, field_name, tzname): if settings.USE_TZ: @@ -204,9 +203,9 @@ def combine_expression(self, connector, sub_expressions): return 'POW(%s)' % ','.join(sub_expressions) # Convert the result to a signed integer since MySQL's binary operators # return an unsigned integer. - elif connector in ('&', '|', '<<'): + if connector in ('&', '|', '<<'): return 'CONVERT(%s, SIGNED)' % connector.join(sub_expressions) - elif connector == '>>': + if connector == '>>': lhs, rhs = sub_expressions return 'FLOOR(%(lhs)s / POW(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} return super().combine_expression(connector, sub_expressions) diff --git a/django/db/backends/oracle/introspection.py b/django/db/backends/oracle/introspection.py index f7ede7db13e21..dea4c17d93cdb 100644 --- a/django/db/backends/oracle/introspection.py +++ b/django/db/backends/oracle/introspection.py @@ -34,13 +34,12 @@ def get_field_type(self, data_type, description): if scale == 0: if precision > 11: return 'BigAutoField' if description.is_autofield else 'BigIntegerField' - elif precision == 1: + if precision == 1: return 'BooleanField' - elif description.is_autofield: + if description.is_autofield: return 'AutoField' - else: - return 'IntegerField' - elif scale == -127: + return 'IntegerField' + if scale == -127: return 'FloatField' return super().get_field_type(data_type, description) diff --git a/django/db/backends/oracle/operations.py b/django/db/backends/oracle/operations.py index 1b0c6e9ed8530..50bf868133bdc 100644 --- a/django/db/backends/oracle/operations.py +++ b/django/db/backends/oracle/operations.py @@ -62,23 +62,21 @@ def date_extract_sql(self, lookup_type, field_name): if lookup_type == 'week_day': # TO_CHAR(field, 'D') returns an integer from 1-7, where 1=Sunday. return "TO_CHAR(%s, 'D')" % field_name - elif lookup_type == 'week': + if lookup_type == 'week': # IW = ISO week number return "TO_CHAR(%s, 'IW')" % field_name - elif lookup_type == 'quarter': + if lookup_type == 'quarter': return "TO_CHAR(%s, 'Q')" % field_name - else: - # https://docs.oracle.com/database/121/SQLRF/functions067.htm#SQLRF00639 - return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) + # https://docs.oracle.com/database/121/SQLRF/functions067.htm#SQLRF00639 + return "EXTRACT(%s FROM %s)" % (lookup_type.upper(), field_name) def date_trunc_sql(self, lookup_type, field_name): # https://docs.oracle.com/database/121/SQLRF/functions271.htm#SQLRF52058 if lookup_type in ('year', 'month'): return "TRUNC(%s, '%s')" % (field_name, lookup_type.upper()) - elif lookup_type == 'quarter': + if lookup_type == 'quarter': return "TRUNC(%s, 'Q')" % field_name - else: - return "TRUNC(%s)" % field_name + return "TRUNC(%s)" % field_name # Oracle crashes with "ORA-03113: end-of-file on communication channel" # if the time zone name is passed in parameter. Use interpolation instead. @@ -499,15 +497,15 @@ def combine_expression(self, connector, sub_expressions): lhs, rhs = sub_expressions if connector == '%%': return 'MOD(%s)' % ','.join(sub_expressions) - elif connector == '&': + if connector == '&': return 'BITAND(%s)' % ','.join(sub_expressions) - elif connector == '|': + if connector == '|': return 'BITAND(-%(lhs)s-1,%(rhs)s)+%(lhs)s' % {'lhs': lhs, 'rhs': rhs} - elif connector == '<<': + if connector == '<<': return '(%(lhs)s * POWER(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} - elif connector == '>>': + if connector == '>>': return 'FLOOR(%(lhs)s / POWER(2, %(rhs)s))' % {'lhs': lhs, 'rhs': rhs} - elif connector == '^': + if connector == '^': return 'POWER(%s)' % ','.join(sub_expressions) return super().combine_expression(connector, sub_expressions) diff --git a/django/db/backends/oracle/schema.py b/django/db/backends/oracle/schema.py index 39c3b7e83db7d..5ab14fb523bea 100644 --- a/django/db/backends/oracle/schema.py +++ b/django/db/backends/oracle/schema.py @@ -20,14 +20,13 @@ class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): def quote_value(self, value): if isinstance(value, (datetime.date, datetime.time, datetime.datetime)): return "'%s'" % value - elif isinstance(value, str): + if isinstance(value, str): return "'%s'" % value.replace("\'", "\'\'") - elif isinstance(value, (bytes, bytearray, memoryview)): + if isinstance(value, (bytes, bytearray, memoryview)): return "'%s'" % value.hex() - elif isinstance(value, bool): + if isinstance(value, bool): return "1" if value else "0" - else: - return str(value) + return str(value) def remove_field(self, model, field): # If the column is an identity column, drop the identity before diff --git a/django/db/backends/postgresql/introspection.py b/django/db/backends/postgresql/introspection.py index 859282057af12..3306d5a824a05 100644 --- a/django/db/backends/postgresql/introspection.py +++ b/django/db/backends/postgresql/introspection.py @@ -44,7 +44,7 @@ def get_field_type(self, data_type, description): if description.default and 'nextval' in description.default: if field_type == 'IntegerField': return 'AutoField' - elif field_type == 'BigIntegerField': + if field_type == 'BigIntegerField': return 'BigAutoField' return field_type diff --git a/django/db/backends/postgresql/schema.py b/django/db/backends/postgresql/schema.py index 18388cc5237cd..62756d9929951 100644 --- a/django/db/backends/postgresql/schema.py +++ b/django/db/backends/postgresql/schema.py @@ -50,7 +50,7 @@ def _create_like_index_sql(self, model, field): return None if db_type.startswith('varchar'): return self._create_index_sql(model, [field], suffix='_like', sql=self.sql_create_varchar_index) - elif db_type.startswith('text'): + if db_type.startswith('text'): return self._create_index_sql(model, [field], suffix='_like', sql=self.sql_create_text_index) return None diff --git a/django/db/backends/sqlite3/base.py b/django/db/backends/sqlite3/base.py index fd489e34de113..5dd200b5aacae 100644 --- a/django/db/backends/sqlite3/base.py +++ b/django/db/backends/sqlite3/base.py @@ -314,12 +314,11 @@ def _sqlite_date_extract(lookup_type, dt): return None if lookup_type == 'week_day': return (dt.isoweekday() % 7) + 1 - elif lookup_type == 'week': + if lookup_type == 'week': return dt.isocalendar()[1] - elif lookup_type == 'quarter': + if lookup_type == 'quarter': return math.ceil(dt.month / 3) - else: - return getattr(dt, lookup_type) + return getattr(dt, lookup_type) def _sqlite_date_trunc(lookup_type, dt): @@ -329,12 +328,12 @@ def _sqlite_date_trunc(lookup_type, dt): return None if lookup_type == 'year': return "%i-01-01" % dt.year - elif lookup_type == 'quarter': + if lookup_type == 'quarter': month_in_quarter = dt.month - (dt.month - 1) % 3 return '%i-%02i-01' % (dt.year, month_in_quarter) - elif lookup_type == 'month': + if lookup_type == 'month': return "%i-%02i-01" % (dt.year, dt.month) - elif lookup_type == 'day': + if lookup_type == 'day': return "%i-%02i-%02i" % (dt.year, dt.month, dt.day) @@ -345,9 +344,9 @@ def _sqlite_time_trunc(lookup_type, dt): return None if lookup_type == 'hour': return "%02i:00:00" % dt.hour - elif lookup_type == 'minute': + if lookup_type == 'minute': return "%02i:%02i:00" % (dt.hour, dt.minute) - elif lookup_type == 'second': + if lookup_type == 'second': return "%02i:%02i:%02i" % (dt.hour, dt.minute, dt.second) @@ -383,12 +382,11 @@ def _sqlite_datetime_extract(lookup_type, dt, tzname): return None if lookup_type == 'week_day': return (dt.isoweekday() % 7) + 1 - elif lookup_type == 'week': + if lookup_type == 'week': return dt.isocalendar()[1] - elif lookup_type == 'quarter': + if lookup_type == 'quarter': return math.ceil(dt.month / 3) - else: - return getattr(dt, lookup_type) + return getattr(dt, lookup_type) def _sqlite_datetime_trunc(lookup_type, dt, tzname): @@ -397,18 +395,18 @@ def _sqlite_datetime_trunc(lookup_type, dt, tzname): return None if lookup_type == 'year': return "%i-01-01 00:00:00" % dt.year - elif lookup_type == 'quarter': + if lookup_type == 'quarter': month_in_quarter = dt.month - (dt.month - 1) % 3 return '%i-%02i-01 00:00:00' % (dt.year, month_in_quarter) - elif lookup_type == 'month': + if lookup_type == 'month': return "%i-%02i-01 00:00:00" % (dt.year, dt.month) - elif lookup_type == 'day': + if lookup_type == 'day': return "%i-%02i-%02i 00:00:00" % (dt.year, dt.month, dt.day) - elif lookup_type == 'hour': + if lookup_type == 'hour': return "%i-%02i-%02i %02i:00:00" % (dt.year, dt.month, dt.day, dt.hour) - elif lookup_type == 'minute': + if lookup_type == 'minute': return "%i-%02i-%02i %02i:%02i:00" % (dt.year, dt.month, dt.day, dt.hour, dt.minute) - elif lookup_type == 'second': + if lookup_type == 'second': return "%i-%02i-%02i %02i:%02i:%02i" % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) diff --git a/django/db/backends/sqlite3/operations.py b/django/db/backends/sqlite3/operations.py index 69744365a2af4..ee992e6ebc83b 100644 --- a/django/db/backends/sqlite3/operations.py +++ b/django/db/backends/sqlite3/operations.py @@ -30,10 +30,9 @@ def bulk_batch_size(self, fields, objs): """ if len(fields) == 1: return 500 - elif len(fields) > 1: + if fields: return self.connection.features.max_query_params // len(fields) - else: - return len(objs) + return len(objs) def check_expression_support(self, expression): bad_fields = (fields.DateField, fields.DateTimeField, fields.TimeField) diff --git a/django/db/backends/sqlite3/schema.py b/django/db/backends/sqlite3/schema.py index b27d39d7325ec..f64ee439a3c1c 100644 --- a/django/db/backends/sqlite3/schema.py +++ b/django/db/backends/sqlite3/schema.py @@ -41,19 +41,18 @@ def quote_value(self, value): # Manual emulation of SQLite parameter quoting if isinstance(value, bool): return str(int(value)) - elif isinstance(value, (Decimal, float, int)): + if isinstance(value, (Decimal, float, int)): return str(value) - elif isinstance(value, str): + if isinstance(value, str): return "'%s'" % value.replace("\'", "\'\'") - elif value is None: + if value is None: return "NULL" - elif isinstance(value, (bytes, bytearray, memoryview)): + if isinstance(value, (bytes, bytearray, memoryview)): # Bytes are only allowed for BLOB fields, encoded as string # literals containing hexadecimal data and preceded by a single "X" # character. return "X'%s'" % value.hex() - else: - raise ValueError("Cannot quote parameter value %r of type %s" % (value, type(value))) + raise ValueError('Cannot quote parameter value %r of type %s' % (value, type(value))) def _is_referenced_by_fk_constraint(self, table_name, column_name=None, ignore_self=False): """ diff --git a/django/db/backends/utils.py b/django/db/backends/utils.py index a574d64562154..904d71478f54b 100644 --- a/django/db/backends/utils.py +++ b/django/db/backends/utils.py @@ -58,11 +58,10 @@ def callproc(self, procname, params=None, kparams=None): with self.db.wrap_database_errors: if params is None and kparams is None: return self.cursor.callproc(procname) - elif kparams is None: + if kparams is None: return self.cursor.callproc(procname, params) - else: - params = params or () - return self.cursor.callproc(procname, params, kparams) + params = params or () + return self.cursor.callproc(procname, params, kparams) def execute(self, sql, params=None): return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) diff --git a/django/db/migrations/autodetector.py b/django/db/migrations/autodetector.py index 0f022137d0bdc..0a688715434d7 100644 --- a/django/db/migrations/autodetector.py +++ b/django/db/migrations/autodetector.py @@ -55,22 +55,22 @@ def deep_deconstruct(self, obj): """ if isinstance(obj, list): return [self.deep_deconstruct(value) for value in obj] - elif isinstance(obj, tuple): + if isinstance(obj, tuple): return tuple(self.deep_deconstruct(value) for value in obj) - elif isinstance(obj, dict): + if isinstance(obj, dict): return { key: self.deep_deconstruct(value) for key, value in obj.items() } - elif isinstance(obj, functools.partial): + if isinstance(obj, functools.partial): return (obj.func, self.deep_deconstruct(obj.args), self.deep_deconstruct(obj.keywords)) - elif isinstance(obj, COMPILED_REGEX_TYPE): + if isinstance(obj, COMPILED_REGEX_TYPE): return RegexObject(obj) - elif isinstance(obj, type): + if isinstance(obj, type): # If this is a type that implements 'deconstruct' as an instance method, # avoid treating this as being deconstructible itself - see #22951 return obj - elif hasattr(obj, 'deconstruct'): + if hasattr(obj, 'deconstruct'): deconstructed = obj.deconstruct() if isinstance(obj, models.Field): # we have a field which also returns a name @@ -84,8 +84,7 @@ def deep_deconstruct(self, obj): for key, value in kwargs.items() }, ) - else: - return obj + return obj def only_relation_agnostic_fields(self, fields): """ @@ -370,7 +369,7 @@ def check_dependency(self, operation, dependency): operation.name_lower == dependency[1].lower() ) # Created field - elif dependency[2] is not None and dependency[3] is True: + if dependency[2] is not None and dependency[3] is True: return ( ( isinstance(operation, operations.CreateModel) and @@ -384,42 +383,41 @@ def check_dependency(self, operation, dependency): ) ) # Removed field - elif dependency[2] is not None and dependency[3] is False: + if dependency[2] is not None and dependency[3] is False: return ( isinstance(operation, operations.RemoveField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # Removed model - elif dependency[2] is None and dependency[3] is False: + if dependency[2] is None and dependency[3] is False: return ( isinstance(operation, operations.DeleteModel) and operation.name_lower == dependency[1].lower() ) # Field being altered - elif dependency[2] is not None and dependency[3] == "alter": + if dependency[2] is not None and dependency[3] == "alter": return ( isinstance(operation, operations.AlterField) and operation.model_name_lower == dependency[1].lower() and operation.name_lower == dependency[2].lower() ) # order_with_respect_to being unset for a field - elif dependency[2] is not None and dependency[3] == "order_wrt_unset": + if dependency[2] is not None and dependency[3] == "order_wrt_unset": return ( isinstance(operation, operations.AlterOrderWithRespectTo) and operation.name_lower == dependency[1].lower() and (operation.order_with_respect_to or "").lower() != dependency[2].lower() ) # Field is removed and part of an index/unique_together - elif dependency[2] is not None and dependency[3] == "foo_together_change": + if dependency[2] is not None and dependency[3] == "foo_together_change": return ( isinstance(operation, (operations.AlterUniqueTogether, operations.AlterIndexTogether)) and operation.name_lower == dependency[1].lower() ) # Unknown dependency. Raise an error. - else: - raise ValueError("Can't handle dependency %r" % (dependency,)) + raise ValueError("Can't handle dependency %r" % (dependency,)) def add_operation(self, app_label, operation, dependencies=None, beginning=False): # Dependencies are (app_label, model_name, field_name, create/delete as True/False) @@ -1231,11 +1229,11 @@ def suggest_name(cls, ops): if len(ops) == 1: if isinstance(ops[0], operations.CreateModel): return ops[0].name_lower - elif isinstance(ops[0], operations.DeleteModel): + if isinstance(ops[0], operations.DeleteModel): return "delete_%s" % ops[0].name_lower - elif isinstance(ops[0], operations.AddField): + if isinstance(ops[0], operations.AddField): return "%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) - elif isinstance(ops[0], operations.RemoveField): + if isinstance(ops[0], operations.RemoveField): return "remove_%s_%s" % (ops[0].model_name_lower, ops[0].name_lower) elif ops: if all(isinstance(o, operations.CreateModel) for o in ops): diff --git a/django/db/migrations/operations/base.py b/django/db/migrations/operations/base.py index 3fb1002c4452e..fbfea87efd368 100644 --- a/django/db/migrations/operations/base.py +++ b/django/db/migrations/operations/base.py @@ -121,17 +121,16 @@ def reduce(self, operation, in_between, app_label=None): """ if self.elidable: return [operation] - elif operation.elidable: + if operation.elidable: return [self] return False def _get_model_tuple(self, remote_model, app_label, model_name): if remote_model == RECURSIVE_RELATIONSHIP_CONSTANT: return app_label, model_name.lower() - elif '.' in remote_model: + if '.' in remote_model: return tuple(remote_model.lower().split('.')) - else: - return app_label, remote_model.lower() + return app_label, remote_model.lower() def __repr__(self): return "<%s %s%s>" % ( diff --git a/django/db/migrations/operations/fields.py b/django/db/migrations/operations/fields.py index 96b0045744ac6..2ae9fb6d87037 100644 --- a/django/db/migrations/operations/fields.py +++ b/django/db/migrations/operations/fields.py @@ -104,9 +104,9 @@ def reduce(self, operation, in_between, app_label=None): field=operation.field, ), ] - elif isinstance(operation, RemoveField): + if isinstance(operation, RemoveField): return [] - elif isinstance(operation, RenameField): + if isinstance(operation, RenameField): return [ AddField( model_name=self.model_name, @@ -226,7 +226,7 @@ def describe(self): def reduce(self, operation, in_between, app_label=None): if isinstance(operation, RemoveField) and self.is_same_field_operation(operation): return [operation] - elif isinstance(operation, RenameField) and self.is_same_field_operation(operation): + if isinstance(operation, RenameField) and self.is_same_field_operation(operation): return [ operation, AlterField( diff --git a/django/db/migrations/operations/models.py b/django/db/migrations/operations/models.py index 857981bcb8d8d..fe0646b1f5d4c 100644 --- a/django/db/migrations/operations/models.py +++ b/django/db/migrations/operations/models.py @@ -127,15 +127,14 @@ def model_to_key(self, model): """ if isinstance(model, str): return model.split(".", 1) - else: - return model._meta.app_label, model._meta.object_name + return model._meta.app_label, model._meta.object_name def reduce(self, operation, in_between, app_label=None): if (isinstance(operation, DeleteModel) and self.name_lower == operation.name_lower and not self.options.get("proxy", False)): return [] - elif isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower: + if isinstance(operation, RenameModel) and self.name_lower == operation.old_name_lower: return [ CreateModel( operation.new_name, @@ -155,7 +154,7 @@ def reduce(self, operation, in_between, app_label=None): managers=self.managers, ), ] - elif isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower: + if isinstance(operation, FieldOperation) and self.name_lower == operation.model_name_lower: if isinstance(operation, AddField): # Don't allow optimizations of FKs through models they reference if hasattr(operation.field, "remote_field") and operation.field.remote_field: @@ -178,7 +177,7 @@ def reduce(self, operation, in_between, app_label=None): managers=self.managers, ), ] - elif isinstance(operation, AlterField): + if isinstance(operation, AlterField): return [ CreateModel( self.name, @@ -191,7 +190,7 @@ def reduce(self, operation, in_between, app_label=None): managers=self.managers, ), ] - elif isinstance(operation, RemoveField): + if isinstance(operation, RemoveField): return [ CreateModel( self.name, @@ -205,7 +204,7 @@ def reduce(self, operation, in_between, app_label=None): managers=self.managers, ), ] - elif isinstance(operation, RenameField): + if isinstance(operation, RenameField): return [ CreateModel( self.name, diff --git a/django/db/migrations/state.py b/django/db/migrations/state.py index f41d1edf2c55d..0cf0227770192 100644 --- a/django/db/migrations/state.py +++ b/django/db/migrations/state.py @@ -21,8 +21,7 @@ def _get_app_label_and_model_name(model, app_label=''): if isinstance(model, str): split = model.split('.', 1) return tuple(split) if len(split) == 2 else (app_label, split[0]) - else: - return model._meta.app_label, model._meta.model_name + return model._meta.app_label, model._meta.model_name def _get_related_models(m): diff --git a/django/db/models/base.py b/django/db/models/base.py index 972da7bb06664..1272c4cffe963 100644 --- a/django/db/models/base.py +++ b/django/db/models/base.py @@ -1453,8 +1453,7 @@ def _check_index_together(cls): id='models.E008', ) ] - - elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together): + if any(not isinstance(fields, (tuple, list)) for fields in cls._meta.index_together): return [ checks.Error( "All 'index_together' elements must be lists or tuples.", @@ -1462,12 +1461,10 @@ def _check_index_together(cls): id='models.E009', ) ] - - else: - errors = [] - for fields in cls._meta.index_together: - errors.extend(cls._check_local_fields(fields, "index_together")) - return errors + errors = [] + for fields in cls._meta.index_together: + errors.extend(cls._check_local_fields(fields, 'index_together')) + return errors @classmethod def _check_unique_together(cls): @@ -1481,7 +1478,7 @@ def _check_unique_together(cls): ) ] - elif any(not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together): + if any(not isinstance(fields, (tuple, list)) for fields in cls._meta.unique_together): return [ checks.Error( "All 'unique_together' elements must be lists or tuples.", @@ -1490,11 +1487,10 @@ def _check_unique_together(cls): ) ] - else: - errors = [] - for fields in cls._meta.unique_together: - errors.extend(cls._check_local_fields(fields, "unique_together")) - return errors + errors = [] + for fields in cls._meta.unique_together: + errors.extend(cls._check_local_fields(fields, 'unique_together')) + return errors @classmethod def _check_indexes(cls): diff --git a/django/db/models/expressions.py b/django/db/models/expressions.py index f7b1baad3a0a3..77974391bc6cb 100644 --- a/django/db/models/expressions.py +++ b/django/db/models/expressions.py @@ -298,9 +298,9 @@ def convert_value(self): internal_type = field.get_internal_type() if internal_type == 'FloatField': return lambda value, expression, connection: None if value is None else float(value) - elif internal_type.endswith('IntegerField'): + if internal_type.endswith('IntegerField'): return lambda value, expression, connection: None if value is None else int(value) - elif internal_type == 'DecimalField': + if internal_type == 'DecimalField': return lambda value, expression, connection: None if value is None else Decimal(value) return self._convert_value_noop diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 6ddd8f033abd1..c645e6b61aeed 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -221,7 +221,7 @@ def _check_field_name(self): id='fields.E001', ) ] - elif LOOKUP_SEP in self.name: + if LOOKUP_SEP in self.name: return [ checks.Error( 'Field names must not contain "%s".' % (LOOKUP_SEP,), @@ -229,7 +229,7 @@ def _check_field_name(self): id='fields.E002', ) ] - elif self.name == 'pk': + if self.name == 'pk': return [ checks.Error( "'pk' is a reserved word that cannot be used as a field name.", @@ -237,8 +237,7 @@ def _check_field_name(self): id='fields.E003', ) ] - else: - return [] + return [] def _check_choices(self): if self.choices: @@ -250,9 +249,8 @@ def _check_choices(self): id='fields.E004', ) ] - elif any(isinstance(choice, str) or - not is_iterable(choice) or len(choice) != 2 - for choice in self.choices): + if any(isinstance(choice, str) or not is_iterable(choice) or + len(choice) != 2 for choice in self.choices): return [ checks.Error( "'choices' must be an iterable containing " @@ -261,10 +259,7 @@ def _check_choices(self): id='fields.E005', ) ] - else: - return [] - else: - return [] + return [] def _check_db_index(self): if self.db_index not in (None, True, False): @@ -275,8 +270,7 @@ def _check_db_index(self): id='fields.E006', ) ] - else: - return [] + return [] def _check_null_allowed_for_primary_keys(self): if (self.primary_key and self.null and @@ -293,8 +287,7 @@ def _check_null_allowed_for_primary_keys(self): id='fields.E007', ) ] - else: - return [] + return [] def _check_backend_specific_checks(self, **kwargs): app_label = self.model._meta.app_label @@ -336,7 +329,7 @@ def _check_deprecation_details(self): id=self.system_check_removed_details.get('id', 'fields.EXXX'), ) ] - elif self.system_check_deprecated_details is not None: + if self.system_check_deprecated_details is not None: return [ checks.Warning( self.system_check_deprecated_details.get( @@ -1053,7 +1046,7 @@ def _check_max_length_attribute(self, **kwargs): id='fields.E120', ) ] - elif (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or + if (not isinstance(self.max_length, int) or isinstance(self.max_length, bool) or self.max_length <= 0): return [ checks.Error( @@ -1062,8 +1055,7 @@ def _check_max_length_attribute(self, **kwargs): id='fields.E121', ) ] - else: - return [] + return [] def cast_db_type(self, connection): if self.max_length is None: @@ -1348,7 +1340,7 @@ def get_internal_type(self): def to_python(self, value): if value is None: - return value + return None if isinstance(value, datetime.datetime): return value if isinstance(value, datetime.date): diff --git a/django/db/models/fields/related.py b/django/db/models/fields/related.py index d07a5a879a554..f3b0dc1ce014f 100644 --- a/django/db/models/fields/related.py +++ b/django/db/models/fields/related.py @@ -358,7 +358,7 @@ def get_reverse_related_filter(self, obj): base_q = Q(**base_filter) if isinstance(descriptor_filter, dict): return base_q & Q(**descriptor_filter) - elif descriptor_filter: + if descriptor_filter: return base_q & descriptor_filter return base_q @@ -834,7 +834,7 @@ def _check_on_delete(self): id='fields.E320', ) ] - elif on_delete == SET_DEFAULT and not self.has_default(): + if on_delete == SET_DEFAULT and not self.has_default(): return [ checks.Error( 'Field specifies on_delete=SET_DEFAULT, but has no default value.', @@ -843,8 +843,7 @@ def _check_on_delete(self): id='fields.E321', ) ] - else: - return [] + return [] def _check_unique(self, **kwargs): return [ @@ -1501,11 +1500,10 @@ def _get_m2m_db_table(self, opts): """ if self.remote_field.through is not None: return self.remote_field.through._meta.db_table - elif self.db_table: + if self.db_table: return self.db_table - else: - m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name) - return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) + m2m_table_name = '%s_%s' % (utils.strip_quotes(opts.db_table), self.name) + return utils.truncate_name(m2m_table_name, connection.ops.max_name_length()) def _get_m2m_attr(self, related, attr): """ diff --git a/django/db/models/functions/datetime.py b/django/db/models/functions/datetime.py index 44bcb731e670e..ced659cf2cb73 100644 --- a/django/db/models/functions/datetime.py +++ b/django/db/models/functions/datetime.py @@ -198,7 +198,7 @@ def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize raise ValueError("Cannot truncate DateField '%s' to %s. " % ( field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField' )) - elif isinstance(field, TimeField) and ( + if isinstance(field, TimeField) and ( isinstance(output_field, DateTimeField) or copy.kind in ('year', 'quarter', 'month', 'day', 'date')): raise ValueError("Cannot truncate TimeField '%s' to %s. " % ( field.name, output_field.__class__.__name__ if has_explicit_output_field else 'DateTimeField' diff --git a/django/db/models/query.py b/django/db/models/query.py index ab5de74ac0685..0c083da12c941 100644 --- a/django/db/models/query.py +++ b/django/db/models/query.py @@ -1092,10 +1092,9 @@ def ordered(self): """ if self.query.extra_order_by or self.query.order_by: return True - elif self.query.default_ordering and self.query.get_meta().ordering: + if self.query.default_ordering and self.query.get_meta().ordering: return True - else: - return False + return False @property def db(self): diff --git a/django/db/models/query_utils.py b/django/db/models/query_utils.py index 1dcf22fda8d91..8190119713ab5 100644 --- a/django/db/models/query_utils.py +++ b/django/db/models/query_utils.py @@ -68,7 +68,7 @@ def _combine(self, other, conn): if not other: return copy.deepcopy(self) # Or if this Q is empty, ignore it and just use `other`. - elif not self: + if not self: return copy.deepcopy(other) obj = type(self)() diff --git a/django/db/models/sql/compiler.py b/django/db/models/sql/compiler.py index ddbcb0eb9a521..09e40817c5a3d 100644 --- a/django/db/models/sql/compiler.py +++ b/django/db/models/sql/compiler.py @@ -497,9 +497,9 @@ def as_sql(self, with_limits=True, with_col_aliases=False): # possible deadlock. if nowait and not self.connection.features.has_select_for_update_nowait: raise NotSupportedError('NOWAIT is not supported on this database backend.') - elif skip_locked and not self.connection.features.has_select_for_update_skip_locked: + if skip_locked and not self.connection.features.has_select_for_update_skip_locked: raise NotSupportedError('SKIP LOCKED is not supported on this database backend.') - elif of and not self.connection.features.has_select_for_update_of: + if of and not self.connection.features.has_select_for_update_of: raise NotSupportedError('FOR UPDATE OF is not supported on this database backend.') for_update_part = self.connection.ops.for_update_sql( nowait=nowait, @@ -1159,9 +1159,8 @@ def prepare_value(self, field, value): raise FieldError("Aggregate functions are not allowed in this query") if value.contains_over_clause: raise FieldError('Window expressions are not allowed in this query.') - else: - value = field.get_db_prep_save(value, connection=self.connection) - return value + return value + return field.get_db_prep_save(value, connection=self.connection) def pre_save_val(self, field, obj): """ diff --git a/django/db/models/sql/query.py b/django/db/models/sql/query.py index bfee2256e6477..cf6b9f4ee5b66 100644 --- a/django/db/models/sql/query.py +++ b/django/db/models/sql/query.py @@ -1941,16 +1941,15 @@ def annotation_select(self): """ if self._annotation_select_cache is not None: return self._annotation_select_cache - elif not self._annotations: + if not self._annotations: return {} - elif self.annotation_select_mask is not None: + if self.annotation_select_mask is not None: self._annotation_select_cache = OrderedDict( (k, v) for k, v in self.annotations.items() if k in self.annotation_select_mask ) return self._annotation_select_cache - else: - return self.annotations + return self.annotations @property def extra_select(self): @@ -1958,14 +1957,13 @@ def extra_select(self): return self._extra_select_cache if not self._extra: return {} - elif self.extra_select_mask is not None: + if self.extra_select_mask is not None: self._extra_select_cache = OrderedDict( (k, v) for k, v in self.extra.items() if k in self.extra_select_mask ) return self._extra_select_cache - else: - return self.extra + return self.extra def trim_start(self, names_with_path): """ diff --git a/django/db/models/sql/where.py b/django/db/models/sql/where.py index d913abab2e6e5..476144fe78193 100644 --- a/django/db/models/sql/where.py +++ b/django/db/models/sql/where.py @@ -95,13 +95,11 @@ def as_sql(self, compiler, connection): if empty_needed == 0: if self.negated: return '', [] - else: - raise EmptyResultSet + raise EmptyResultSet if full_needed == 0: if self.negated: raise EmptyResultSet - else: - return '', [] + return '', [] conn = ' %s ' % self.connector sql_string = conn.join(result) if sql_string: diff --git a/django/forms/boundfield.py b/django/forms/boundfield.py index 27e80c65e77a5..3c9d286971870 100644 --- a/django/forms/boundfield.py +++ b/django/forms/boundfield.py @@ -193,7 +193,7 @@ def auto_id(self): auto_id = self.form.auto_id # Boolean or string if auto_id and '%s' in str(auto_id): return auto_id % self.html_name - elif auto_id: + if auto_id: return self.html_name return '' diff --git a/django/forms/fields.py b/django/forms/fields.py index 61f5ccfe58816..e6dad89a9132d 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -738,10 +738,9 @@ def to_python(self, value): """ if value in (True, 'True', 'true', '1'): return True - elif value in (False, 'False', 'false', '0'): + if value in (False, 'False', 'false', '0'): return False - else: - return None + return None def validate(self, value): pass @@ -855,7 +854,7 @@ class MultipleChoiceField(ChoiceField): def to_python(self, value): if not value: return [] - elif not isinstance(value, (list, tuple)): + if not isinstance(value, (list, tuple)): raise ValidationError(self.error_messages['invalid_list'], code='invalid_list') return [str(val) for val in value] @@ -1004,8 +1003,7 @@ def clean(self, value): if not value or not [v for v in value if v not in self.empty_values]: if self.required: raise ValidationError(self.error_messages['required'], code='required') - else: - return self.compress([]) + return self.compress([]) else: raise ValidationError(self.error_messages['invalid'], code='invalid') for i, field in enumerate(self.fields): diff --git a/django/forms/models.py b/django/forms/models.py index 727cdb814a560..1f428d55a2da3 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -1279,7 +1279,7 @@ def clean(self, value): value = self.prepare_value(value) if self.required and not value: raise ValidationError(self.error_messages['required'], code='required') - elif not self.required and not value: + if not self.required and not value: return self.queryset.none() if not isinstance(value, (list, tuple)): raise ValidationError(self.error_messages['list'], code='list') diff --git a/django/middleware/csrf.py b/django/middleware/csrf.py index ce1329bfa678f..f5f43baba479f 100644 --- a/django/middleware/csrf.py +++ b/django/middleware/csrf.py @@ -106,9 +106,9 @@ def _sanitize_token(token): # Allow only ASCII alphanumerics if re.search('[^a-zA-Z0-9]', token): return _get_new_csrf_token() - elif len(token) == CSRF_TOKEN_LENGTH: + if len(token) == CSRF_TOKEN_LENGTH: return token - elif len(token) == CSRF_SECRET_LENGTH: + if len(token) == CSRF_SECRET_LENGTH: # Older Django versions set cookies to values of CSRF_SECRET_LENGTH # alphanumeric characters. For backwards compatibility, accept # such values as unsalted secrets. diff --git a/django/template/base.py b/django/template/base.py index 9c81a361f26e5..f5f6121ed1142 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -806,8 +806,7 @@ def resolve(self, context): msgid = mark_safe(msgid) if is_safe else msgid if self.message_context: return pgettext_lazy(self.message_context, msgid) - else: - return gettext_lazy(msgid) + return gettext_lazy(msgid) return value def __repr__(self): diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index 6d8813b2fe736..d95c3b739c378 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -241,7 +241,7 @@ def render(self, context): state_frame[self] = compare_to # render true block if not already rendered return nodelist_true_output or self.nodelist_true.render(context) - elif self.nodelist_false: + if self.nodelist_false: return self.nodelist_false.render(context) return '' diff --git a/django/template/loader.py b/django/template/loader.py index 2492aee760ac2..ddf4136ba1770 100644 --- a/django/template/loader.py +++ b/django/template/loader.py @@ -45,8 +45,7 @@ def select_template(template_name_list, using=None): if template_name_list: raise TemplateDoesNotExist(', '.join(template_name_list), chain=chain) - else: - raise TemplateDoesNotExist("No template names provided") + raise TemplateDoesNotExist('No template names provided') def render_to_string(template_name, context=None, request=None, using=None): diff --git a/django/template/loaders/cached.py b/django/template/loaders/cached.py index b0799a2d0ed0c..f078e69785e34 100644 --- a/django/template/loaders/cached.py +++ b/django/template/loaders/cached.py @@ -47,7 +47,7 @@ def get_template(self, template_name, skip=None): if cached: if isinstance(cached, type) and issubclass(cached, TemplateDoesNotExist): raise cached(template_name) - elif isinstance(cached, TemplateDoesNotExist): + if isinstance(cached, TemplateDoesNotExist): raise copy_exception(cached) return cached @@ -56,9 +56,7 @@ def get_template(self, template_name, skip=None): except TemplateDoesNotExist as e: self.get_template_cache[key] = copy_exception(e) if self.engine.debug else TemplateDoesNotExist raise - else: - self.get_template_cache[key] = template - + self.get_template_cache[key] = template return template def get_template_sources(self, template_name): diff --git a/django/template/response.py b/django/template/response.py index 5631c785b9892..ec1dd8a65bca2 100644 --- a/django/template/response.py +++ b/django/template/response.py @@ -61,10 +61,9 @@ def resolve_template(self, template): """Accept a template object, path-to-template, or list of paths.""" if isinstance(template, (list, tuple)): return select_template(template, using=self.using) - elif isinstance(template, str): + if isinstance(template, str): return get_template(template, using=self.using) - else: - return template + return template def resolve_context(self, context): return context diff --git a/django/test/utils.py b/django/test/utils.py index c1c38ca096fdf..a982e79604442 100644 --- a/django/test/utils.py +++ b/django/test/utils.py @@ -66,8 +66,7 @@ def __getitem__(self, key): if key in subcontext: return subcontext[key] raise KeyError(key) - else: - return super().__getitem__(key) + return super().__getitem__(key) def get(self, key, default=None): try: @@ -374,7 +373,7 @@ def inner(*args, **kwargs): def __call__(self, decorated): if isinstance(decorated, type): return self.decorate_class(decorated) - elif callable(decorated): + if callable(decorated): return self.decorate_callable(decorated) raise TypeError('Cannot decorate object of type %s' % type(decorated)) diff --git a/django/utils/archive.py b/django/utils/archive.py index 879f3c49f7c3a..fa984f6283163 100644 --- a/django/utils/archive.py +++ b/django/utils/archive.py @@ -112,10 +112,9 @@ def split_leading_dir(self, path): path = path.lstrip('/').lstrip('\\') if '/' in path and (('\\' in path and path.find('/') < path.find('\\')) or '\\' not in path): return path.split('/', 1) - elif '\\' in path: + if '\\' in path: return path.split('\\', 1) - else: - return path, '' + return path, '' def has_leading_dir(self, paths): """ @@ -127,7 +126,7 @@ def has_leading_dir(self, paths): prefix, rest = self.split_leading_dir(path) if not prefix: return False - elif common_prefix is None: + if common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False diff --git a/django/utils/datastructures.py b/django/utils/datastructures.py index 127c6dc77434f..973a1d793f27a 100644 --- a/django/utils/datastructures.py +++ b/django/utils/datastructures.py @@ -236,8 +236,7 @@ def __new__(cls, *args, warning='ImmutableList object is immutable.', **kwargs): def complain(self, *wargs, **kwargs): if isinstance(self.warning, Exception): raise self.warning - else: - raise AttributeError(self.warning) + raise AttributeError(self.warning) # All list mutation functions complain. __delitem__ = complain diff --git a/django/utils/formats.py b/django/utils/formats.py index bba45e367757a..bec9fb12f8089 100644 --- a/django/utils/formats.py +++ b/django/utils/formats.py @@ -193,15 +193,15 @@ def localize(value, use_l10n=None): """ if isinstance(value, str): # Handle strings first for performance reasons. return value - elif isinstance(value, bool): # Make sure booleans don't get treated as numbers + if isinstance(value, bool): # Make sure booleans don't get treated as numbers return str(value) - elif isinstance(value, (decimal.Decimal, float, int)): + if isinstance(value, (decimal.Decimal, float, int)): return number_format(value, use_l10n=use_l10n) - elif isinstance(value, datetime.datetime): + if isinstance(value, datetime.datetime): return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n) - elif isinstance(value, datetime.date): + if isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) - elif isinstance(value, datetime.time): + if isinstance(value, datetime.time): return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n) return value @@ -213,19 +213,19 @@ def localize_input(value, default=None): """ if isinstance(value, str): # Handle strings first for performance reasons. return value - elif isinstance(value, bool): # Don't treat booleans as numbers. + if isinstance(value, bool): # Don't treat booleans as numbers. return str(value) - elif isinstance(value, (decimal.Decimal, float, int)): + if isinstance(value, (decimal.Decimal, float, int)): return number_format(value) - elif isinstance(value, datetime.datetime): + if isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = default or get_format('DATETIME_INPUT_FORMATS')[0] return value.strftime(format) - elif isinstance(value, datetime.date): + if isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = default or get_format('DATE_INPUT_FORMATS')[0] return value.strftime(format) - elif isinstance(value, datetime.time): + if isinstance(value, datetime.time): format = default or get_format('TIME_INPUT_FORMATS')[0] return value.strftime(format) return value diff --git a/django/utils/functional.py b/django/utils/functional.py index 146a2e8dc2813..4dffcb486294c 100644 --- a/django/utils/functional.py +++ b/django/utils/functional.py @@ -121,10 +121,9 @@ def __bytes_cast_encoded(self): def __cast(self): if self._delegate_bytes: return self.__bytes_cast() - elif self._delegate_text: + if self._delegate_text: return self.__text_cast() - else: - return func(*self.__args, **self.__kw) + return func(*self.__args, **self.__kw) def __str__(self): # object defines __str__(), so __prepare_class__() won't overload diff --git a/django/utils/ipv6.py b/django/utils/ipv6.py index ddb8c8091d2f2..a3c0d7753fa1c 100644 --- a/django/utils/ipv6.py +++ b/django/utils/ipv6.py @@ -26,12 +26,10 @@ def clean_ipv6_address(ip_str, unpack_ipv4=False, addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) except ValueError: raise ValidationError(error_message, code='invalid') - if unpack_ipv4 and addr.ipv4_mapped: return str(addr.ipv4_mapped) - elif addr.ipv4_mapped: + if addr.ipv4_mapped: return '::ffff:%s' % str(addr.ipv4_mapped) - return str(addr) diff --git a/django/utils/safestring.py b/django/utils/safestring.py index 2da467a079ced..b6fa2cf95e36a 100644 --- a/django/utils/safestring.py +++ b/django/utils/safestring.py @@ -34,7 +34,7 @@ def __add__(self, rhs): t = super().__add__(rhs) if isinstance(rhs, SafeText): return SafeText(t) - elif isinstance(rhs, SafeBytes): + if isinstance(rhs, SafeBytes): return SafeBytes(t) return t diff --git a/django/views/generic/dates.py b/django/views/generic/dates.py index 1673a7a263fa4..5da5d9a5b88b0 100644 --- a/django/views/generic/dates.py +++ b/django/views/generic/dates.py @@ -109,8 +109,7 @@ def _get_next_month(self, date): return date.replace(year=date.year + 1, month=1, day=1) except ValueError: raise Http404(_("Date out of range")) - else: - return date.replace(month=date.month + 1, day=1) + return date.replace(month=date.month + 1, day=1) def _get_current_month(self, date): """Return the start date of the previous interval.""" diff --git a/django/views/generic/detail.py b/django/views/generic/detail.py index 6d5b8a3f5cc3b..f1bc0c9de2690 100644 --- a/django/views/generic/detail.py +++ b/django/views/generic/detail.py @@ -82,10 +82,9 @@ def get_context_object_name(self, obj): """Get the name to use for the object.""" if self.context_object_name: return self.context_object_name - elif isinstance(obj, models.Model): + if isinstance(obj, models.Model): return obj._meta.model_name - else: - return None + return None def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" diff --git a/django/views/generic/list.py b/django/views/generic/list.py index 00e5e5df2b878..a8f0e4d79f742 100644 --- a/django/views/generic/list.py +++ b/django/views/generic/list.py @@ -105,10 +105,9 @@ def get_context_object_name(self, object_list): """Get the name of the item to be used in the context.""" if self.context_object_name: return self.context_object_name - elif hasattr(object_list, 'model'): + if hasattr(object_list, 'model'): return '%s_list' % object_list.model._meta.model_name - else: - return None + return None def get_context_data(self, *, object_list=None, **kwargs): """Get the context for this view.""" diff --git a/scripts/manage_translations.py b/scripts/manage_translations.py index 5397d35bae646..83815684e1d10 100644 --- a/scripts/manage_translations.py +++ b/scripts/manage_translations.py @@ -63,8 +63,7 @@ def _tx_resource_for_name(name): """ Return the Transifex resource name """ if name == 'core': return "django.core" - else: - return "django.contrib-%s" % name + return "django.contrib-%s" % name def _check_diff(cat_name, base_path): diff --git a/tests/admin_filters/tests.py b/tests/admin_filters/tests.py index 200c8c8db1777..4949c60362629 100644 --- a/tests/admin_filters/tests.py +++ b/tests/admin_filters/tests.py @@ -51,8 +51,7 @@ def lookups(self, request, model_admin): def queryset(self, request, queryset): if self.value() == 'the 90s': return queryset.filter(year__gte=1990, year__lte=1999) - else: - return queryset.exclude(year__gte=1990, year__lte=1999) + return queryset.exclude(year__gte=1990, year__lte=1999) class DecadeListFilterWithTitleAndParameter(DecadeListFilter): @@ -127,10 +126,9 @@ class DepartmentListFilterLookupWithDynamicValue(DecadeListFilterWithTitleAndPar def lookups(self, request, model_admin): if self.value() == 'the 80s': return (('the 90s', "the 1990's"),) - elif self.value() == 'the 90s': + if self.value() == 'the 90s': return (('the 80s', "the 1980's"),) - else: - return (('the 80s', "the 1980's"), ('the 90s', "the 1990's"),) + return (('the 80s', "the 1980's"), ('the 90s', "the 1990's"),) class CustomUserAdmin(UserAdmin): diff --git a/tests/admin_ordering/models.py b/tests/admin_ordering/models.py index fbddeaa283345..5a4994f0778b8 100644 --- a/tests/admin_ordering/models.py +++ b/tests/admin_ordering/models.py @@ -35,5 +35,4 @@ class DynOrderingBandAdmin(admin.ModelAdmin): def get_ordering(self, request): if request.user.is_superuser: return ['rank'] - else: - return ['name'] + return ['name'] diff --git a/tests/admin_views/admin.py b/tests/admin_views/admin.py index 1e4124fca57dc..7effa94629f10 100644 --- a/tests/admin_views/admin.py +++ b/tests/admin_views/admin.py @@ -450,8 +450,7 @@ class PostAdmin(admin.ModelAdmin): def coolness(self, instance): if instance.pk: return "%d amount of cool." % instance.pk - else: - return "Unknown coolness." + return "Unknown coolness." def value(self, instance): return 1000 diff --git a/tests/auth_tests/test_auth_backends.py b/tests/auth_tests/test_auth_backends.py index 86d535703d91c..1c2d2c53ce31a 100644 --- a/tests/auth_tests/test_auth_backends.py +++ b/tests/auth_tests/test_auth_backends.py @@ -332,9 +332,9 @@ def has_perm(self, user, perm, obj=None): if isinstance(obj, TestObj): if user.username == 'test2': return True - elif user.is_anonymous and perm == 'anon': + if user.is_anonymous and perm == 'anon': return True - elif not user.is_active and perm == 'inactive': + if not user.is_active and perm == 'inactive': return True return False @@ -354,8 +354,7 @@ def get_all_permissions(self, user, obj=None): return ['anon'] if user.username == 'test2': return ['simple', 'advanced'] - else: - return ['simple'] + return ['simple'] def get_group_permissions(self, user, obj=None): if not obj: @@ -366,8 +365,7 @@ def get_group_permissions(self, user, obj=None): if 'test_group' in [group.name for group in user.groups.all()]: return ['group_perm'] - else: - return ['none'] + return ['none'] @modify_settings(AUTHENTICATION_BACKENDS={ diff --git a/tests/builtin_server/tests.py b/tests/builtin_server/tests.py index 73e3d0c07e95d..8c6ce80e27362 100644 --- a/tests/builtin_server/tests.py +++ b/tests/builtin_server/tests.py @@ -20,7 +20,7 @@ def write(self, data): if not self.status: raise AssertionError("write() before start_response()") - elif not self.headers_sent: + if not self.headers_sent: # Before the first output, send the stored headers self.bytes_sent = len(data) # make sure we know content-length self.send_headers() diff --git a/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py b/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py index 3a1527dc03e16..62464ea62ac53 100644 --- a/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py +++ b/tests/contenttypes_tests/operations_migrations/0002_rename_foo.py @@ -10,7 +10,7 @@ def assert_foo_contenttype_not_cached(apps, schema_editor): else: if not ContentType.objects.filter(app_label='contenttypes_tests', model='foo').exists(): raise AssertionError('The contenttypes_tests.Foo ContentType should not be cached.') - elif content_type.model != 'foo': + if content_type.model != 'foo': raise AssertionError( "The cached contenttypes_tests.Foo ContentType should have " "its model set to 'foo'." diff --git a/tests/file_uploads/views.py b/tests/file_uploads/views.py index 5c35a5a378de9..c1cefbf1589b3 100644 --- a/tests/file_uploads/views.py +++ b/tests/file_uploads/views.py @@ -22,8 +22,7 @@ def file_upload_view(request): if os.path.dirname(form_data['file_field'].name) != '': return HttpResponseServerError() return HttpResponse('') - else: - return HttpResponseServerError() + return HttpResponseServerError() def file_upload_view_verify(request): @@ -77,10 +76,7 @@ def file_upload_unicode_name(request): obj.delete() os.unlink(full_name) - if response: - return response - else: - return HttpResponse('') + return response or HttpResponse('') def file_upload_echo(request): diff --git a/tests/forms_tests/field_tests/test_filepathfield.py b/tests/forms_tests/field_tests/test_filepathfield.py index 44f6aff52136c..dff1597e27e5b 100644 --- a/tests/forms_tests/field_tests/test_filepathfield.py +++ b/tests/forms_tests/field_tests/test_filepathfield.py @@ -11,12 +11,11 @@ def fix_os_paths(x): if x.startswith(PATH): x = x[len(PATH):] return x.replace('\\', '/') - elif isinstance(x, tuple): + if isinstance(x, tuple): return tuple(fix_os_paths(list(x))) - elif isinstance(x, list): + if isinstance(x, list): return [fix_os_paths(y) for y in x] - else: - return x + return x class FilePathFieldTest(SimpleTestCase): diff --git a/tests/gis_tests/tests.py b/tests/gis_tests/tests.py index 20b66cd39be44..7e0a5dcda8556 100644 --- a/tests/gis_tests/tests.py +++ b/tests/gis_tests/tests.py @@ -26,8 +26,7 @@ def _get_postgis_func(self, func): if func == 'postgis_lib_version': if self.version is None: raise ProgrammingError - else: - return self.version + return self.version elif func == 'version': pass else: diff --git a/tests/gis_tests/utils.py b/tests/gis_tests/utils.py index b30da7e40dba0..ad44274f0f4bb 100644 --- a/tests/gis_tests/utils.py +++ b/tests/gis_tests/utils.py @@ -31,8 +31,7 @@ def no_backend(test_func, backend): def inner(): pass return inner - else: - return test_func + return test_func # Decorators to disable entire test functions for specific diff --git a/tests/humanize_tests/tests.py b/tests/humanize_tests/tests.py index df9ae4f35d992..4a202bafcdf39 100644 --- a/tests/humanize_tests/tests.py +++ b/tests/humanize_tests/tests.py @@ -277,8 +277,7 @@ class DocumentedMockDateTime(datetime.datetime): def now(cls, tz=None): if tz is None or tz.utcoffset(documented_now) is None: return documented_now - else: - return documented_now.replace(tzinfo=tz) + tz.utcoffset(now) + return documented_now.replace(tzinfo=tz) + tz.utcoffset(now) orig_humanize_datetime = humanize.datetime humanize.datetime = DocumentedMockDateTime diff --git a/tests/i18n/test_extraction.py b/tests/i18n/test_extraction.py index fc8eaa2b8f8c9..b2fcfce6ef57e 100644 --- a/tests/i18n/test_extraction.py +++ b/tests/i18n/test_extraction.py @@ -79,8 +79,7 @@ def _assertPoLocComment(self, assert_presence, po_filename, line_number, *commen pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE) if assert_presence: return self.assertRegex(po_contents, pattern, '"%s" not found in final .po file.' % needle) - else: - return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle) + return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle) def _get_token_line_number(self, path, token): with open(path) as f: diff --git a/tests/introspection/tests.py b/tests/introspection/tests.py index a66ecaba034a1..8a4f866ab95f1 100644 --- a/tests/introspection/tests.py +++ b/tests/introspection/tests.py @@ -211,5 +211,4 @@ def datatype(dbtype, description): dt = connection.introspection.get_field_type(dbtype, description) if type(dt) is tuple: return dt[0] - else: - return dt + return dt diff --git a/tests/migrations/routers.py b/tests/migrations/routers.py index 21dfc561bd715..91c17c5b26bdc 100644 --- a/tests/migrations/routers.py +++ b/tests/migrations/routers.py @@ -9,5 +9,5 @@ def allow_migrate(self, db, app_label, model_name=None, **hints): """ if model_name == 'tribble': return db == 'other' - elif db == 'other': + if db == 'other': return False diff --git a/tests/migrations/test_commands.py b/tests/migrations/test_commands.py index 8caa0b5deb910..46e720f7117c3 100644 --- a/tests/migrations/test_commands.py +++ b/tests/migrations/test_commands.py @@ -698,8 +698,7 @@ def test_makemigrations_consistency_checks_respect_routers(self): def patched_has_table(migration_recorder): if migration_recorder.connection is connections['other']: raise Exception('Other connection') - else: - return mock.DEFAULT + return mock.DEFAULT self.assertTableNotExists('migrations_unicodemodel') apps.register_model('migrations', UnicodeModel) diff --git a/tests/model_forms/models.py b/tests/model_forms/models.py index aecbeb18f396b..74d6fa68132f6 100644 --- a/tests/model_forms/models.py +++ b/tests/model_forms/models.py @@ -377,9 +377,9 @@ class CustomErrorMessage(models.Model): def clean(self): if self.name1 == 'FORBIDDEN_VALUE': raise ValidationError({'name1': [ValidationError('Model.clean() error messages.')]}) - elif self.name1 == 'FORBIDDEN_VALUE2': + if self.name1 == 'FORBIDDEN_VALUE2': raise ValidationError({'name1': 'Model.clean() error messages (simpler syntax).'}) - elif self.name1 == 'GLOBAL_ERROR': + if self.name1 == 'GLOBAL_ERROR': raise ValidationError("Global error message.") diff --git a/tests/multiple_database/tests.py b/tests/multiple_database/tests.py index ab88ecf875199..546c6fd76ea47 100644 --- a/tests/multiple_database/tests.py +++ b/tests/multiple_database/tests.py @@ -1577,8 +1577,7 @@ class AntiPetRouter: def allow_migrate(self, db, app_label, model_name=None, **hints): if db == 'other': return model_name == 'pet' - else: - return model_name != 'pet' + return model_name != 'pet' class FixtureTestCase(TestCase): diff --git a/tests/runtests.py b/tests/runtests.py index ae2d693ac2dec..f8253576f2591 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -236,10 +236,8 @@ def actual_test_processes(parallel): # This doesn't work before django.setup() on some databases. if all(conn.features.can_clone_databases for conn in connections.all()): return default_test_processes() - else: - return 1 - else: - return parallel + return 1 + return parallel class ActionSelenium(argparse.Action): diff --git a/tests/servers/test_basehttp.py b/tests/servers/test_basehttp.py index 83723366efdd8..5ddc3acf31fe6 100644 --- a/tests/servers/test_basehttp.py +++ b/tests/servers/test_basehttp.py @@ -101,7 +101,7 @@ def close(self): def makefile(mode, *a, **kw): if mode == 'rb': return rfile - elif mode == 'wb': + if mode == 'wb': return wfile request = Stub(makefile=makefile) diff --git a/tests/template_tests/utils.py b/tests/template_tests/utils.py index 66a173396c091..b0cae08fa6567 100644 --- a/tests/template_tests/utils.py +++ b/tests/template_tests/utils.py @@ -115,7 +115,7 @@ def method5(self): def __getitem__(self, key): if key == 'silent_fail_key': raise SomeException - elif key == 'noisy_fail_key': + if key == 'noisy_fail_key': raise SomeOtherException raise KeyError diff --git a/tests/test_client/views.py b/tests/test_client/views.py index 3387008d66f07..87b4133bd37f2 100644 --- a/tests/test_client/views.py +++ b/tests/test_client/views.py @@ -33,20 +33,19 @@ def trace_view(request): """ if request.method.upper() != "TRACE": return HttpResponseNotAllowed("TRACE") - elif request.body: + if request.body: return HttpResponseBadRequest("TRACE requests MUST NOT include an entity") - else: - protocol = request.META["SERVER_PROTOCOL"] - t = Template( - '{{ method }} {{ uri }} {{ version }}', - name="TRACE Template", - ) - c = Context({ - 'method': request.method, - 'uri': request.path, - 'version': protocol, - }) - return HttpResponse(t.render(c)) + protocol = request.META['SERVER_PROTOCOL'] + t = Template( + '{{ method }} {{ uri }} {{ version }}', + name="TRACE Template", + ) + c = Context({ + 'method': request.method, + 'uri': request.path, + 'version': protocol, + }) + return HttpResponse(t.render(c)) def post_view(request): diff --git a/tests/test_client_regress/views.py b/tests/test_client_regress/views.py index 5e4c9968fd7a7..e03f0e4ef65fa 100644 --- a/tests/test_client_regress/views.py +++ b/tests/test_client_regress/views.py @@ -52,8 +52,7 @@ def view_with_argument(request, name): """ if name == 'Arthur Dent': return HttpResponse('Hi, Arthur') - else: - return HttpResponse('Howdy, %s' % name) + return HttpResponse('Howdy, %s' % name) def nested_view(request): diff --git a/tests/utils_tests/test_lazyobject.py b/tests/utils_tests/test_lazyobject.py index 2bba558843d3c..b6c8919ccd2ef 100644 --- a/tests/utils_tests/test_lazyobject.py +++ b/tests/utils_tests/test_lazyobject.py @@ -376,7 +376,7 @@ def __eq__(self, other): for attr in ['bar', 'baz', 'quux']: if hasattr(self, attr) != hasattr(other, attr): return False - elif getattr(self, attr, None) != getattr(other, attr, None): + if getattr(self, attr, None) != getattr(other, attr, None): return False return True