Used pyupgrade to remove Python 2 and 3.5 compatibility code

This commit is contained in:
Diederik van der Boor 2021-11-18 12:38:58 +01:00
parent 6c69ea2247
commit 8a5b55538d
No known key found for this signature in database
GPG Key ID: 4FA014E0305E73C1
31 changed files with 114 additions and 138 deletions

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# django-polymorphic documentation build configuration file, created by
# sphinx-quickstart on Sun May 19 12:20:47 2013.
@ -53,8 +52,8 @@ source_suffix = ".rst"
master_doc = "index"
# General information about the project.
project = u"django-polymorphic"
copyright = u"2013, Bert Constantin, Chris Glass, Diederik van der Boor"
project = "django-polymorphic"
copyright = "2013, Bert Constantin, Chris Glass, Diederik van der Boor"
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@ -198,8 +197,8 @@ latex_documents = [
(
"index",
"django-polymorphic.tex",
u"django-polymorphic Documentation",
u"Bert Constantin, Chris Glass, Diederik van der Boor",
"django-polymorphic Documentation",
"Bert Constantin, Chris Glass, Diederik van der Boor",
"manual",
)
]
@ -233,8 +232,8 @@ man_pages = [
(
"index",
"django-polymorphic",
u"django-polymorphic Documentation",
[u"Bert Constantin, Chris Glass, Diederik van der Boor"],
"django-polymorphic Documentation",
["Bert Constantin, Chris Glass, Diederik van der Boor"],
1,
)
]
@ -252,8 +251,8 @@ texinfo_documents = [
(
"index",
"django-polymorphic",
u"django-polymorphic Documentation",
u"Bert Constantin, Chris Glass, Diederik van der Boor",
"django-polymorphic Documentation",
"Bert Constantin, Chris Glass, Diederik van der Boor",
"django-polymorphic",
"One line description of project.",
"Miscellaneous",

View File

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models

View File

@ -35,7 +35,7 @@ class Payment(PolymorphicModel):
verbose_name_plural = _("Payments")
def __str__(self):
return "{0} {1}".format(self.currency, self.amount)
return f"{self.currency} {self.amount}"
class CreditCardPayment(Payment):

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
This module is a scratchpad for general development, testing & debugging
Well, even more so than pcmd.py. You best ignore p2cmd.py.

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
This module is a scratchpad for general development, testing & debugging
"""

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
This module is a scratchpad for general development, testing & debugging
"""

View File

@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import polymorphic.showfields

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import models
from polymorphic.models import PolymorphicModel
@ -41,7 +39,7 @@ class ProxyBase(PolymorphicModel):
title = models.CharField(max_length=200)
def __unicode__(self):
return u"<ProxyBase[type={0}]: {1}>".format(self.polymorphic_ctype, self.title)
return f"<ProxyBase[type={self.polymorphic_ctype}]: {self.title}>"
class Meta:
ordering = ("title",)
@ -52,7 +50,7 @@ class ProxyA(ProxyBase):
proxy = True
def __unicode__(self):
return u"<ProxyA: {0}>".format(self.title)
return f"<ProxyA: {self.title}>"
class ProxyB(ProxyBase):
@ -60,7 +58,7 @@ class ProxyB(ProxyBase):
proxy = True
def __unicode__(self):
return u"<ProxyB: {0}>".format(self.title)
return f"<ProxyB: {self.title}>"
# Internals for management command tests

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Seamless Polymorphic Inheritance for Django Models

View File

@ -47,7 +47,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
show_in_index = False
def __init__(self, model, admin_site, *args, **kwargs):
super(PolymorphicChildModelAdmin, self).__init__(
super().__init__(
model, admin_site, *args, **kwargs
)
@ -68,7 +68,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
if not self.fieldsets and not self.fields:
kwargs.setdefault("fields", "__all__")
return super(PolymorphicChildModelAdmin, self).get_form(request, obj, **kwargs)
return super().get_form(request, obj, **kwargs)
def get_model_perms(self, request):
match = resolve(request.path_info)
@ -79,7 +79,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
and match.url_name in ("index", "app_list")
):
return {"add": False, "change": False, "delete": False}
return super(PolymorphicChildModelAdmin, self).get_model_perms(request)
return super().get_model_perms(request)
@property
def change_form_template(self):
@ -91,7 +91,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
base_app_label = base_opts.app_label
return [
"admin/%s/%s/change_form.html" % (app_label, opts.object_name.lower()),
f"admin/{app_label}/{opts.object_name.lower()}/change_form.html",
"admin/%s/change_form.html" % app_label,
# Added:
"admin/%s/%s/change_form.html"
@ -132,7 +132,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
base_app_label = base_opts.app_label
return [
"admin/%s/%s/object_history.html" % (app_label, opts.object_name.lower()),
f"admin/{app_label}/{opts.object_name.lower()}/object_history.html",
"admin/%s/object_history.html" % app_label,
# Added:
"admin/%s/%s/object_history.html"
@ -147,7 +147,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
parent_model = self.model._meta.get_field("polymorphic_ctype").model
if parent_model == self.model:
# when parent_model is in among child_models, just return super instance
return super(PolymorphicChildModelAdmin, self)
return super()
try:
return self.admin_site._registry[parent_model]
@ -167,7 +167,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
# If we get this far without returning there is no admin available
raise ParentAdminNotRegistered(
"No parent admin was registered for a '{0}' model.".format(parent_model)
f"No parent admin was registered for a '{parent_model}' model."
)
def response_post_save_add(self, request, obj):
@ -180,13 +180,13 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
self, request, context, add=False, change=False, form_url="", obj=None
):
context.update({"base_opts": self.base_model._meta})
return super(PolymorphicChildModelAdmin, self).render_change_form(
return super().render_change_form(
request, context, add=add, change=change, form_url=form_url, obj=obj
)
def delete_view(self, request, object_id, context=None):
extra_context = {"base_opts": self.base_model._meta}
return super(PolymorphicChildModelAdmin, self).delete_view(
return super().delete_view(
request, object_id, extra_context
)
@ -195,7 +195,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
context = {"base_opts": self.base_model._meta}
if extra_context:
context.update(extra_context)
return super(PolymorphicChildModelAdmin, self).history_view(
return super().history_view(
request, object_id, extra_context=context
)
@ -209,7 +209,7 @@ class PolymorphicChildModelAdmin(admin.ModelAdmin):
# If subclass declares fieldsets or fields, this is respected
if self.fieldsets or self.fields or not self.base_fieldsets:
return super(PolymorphicChildModelAdmin, self).get_fieldsets(request, obj)
return super().get_fieldsets(request, obj)
# Have a reasonable default fieldsets,
# where the subclass fields are automatically included.

View File

@ -32,7 +32,7 @@ class PolymorphicChildModelFilter(admin.SimpleListFilter):
if choice_value == value:
return queryset.filter(polymorphic_ctype_id=choice_value)
raise PermissionDenied(
'Invalid ContentType "{0}". It must be registered as child model.'.format(
'Invalid ContentType "{}". It must be registered as child model.'.format(
value
)
)

View File

@ -17,5 +17,5 @@ class PolymorphicModelChoiceForm(forms.Form):
def __init__(self, *args, **kwargs):
# Allow to easily redefine the label (a commonly expected usecase)
super(PolymorphicModelChoiceForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.fields["ct_id"].label = self.type_label

View File

@ -35,7 +35,7 @@ class PolymorphicInlineAdminFormSet(InlineAdminFormSet):
# Assigned later via PolymorphicInlineSupportMixin later.
self.request = kwargs.pop("request", None)
self.obj = kwargs.pop("obj", None)
super(PolymorphicInlineAdminFormSet, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def __iter__(self):
"""
@ -111,7 +111,7 @@ class PolymorphicInlineAdminFormSet(InlineAdminFormSet):
)
class PolymorphicInlineSupportMixin(object):
class PolymorphicInlineSupportMixin:
"""
A Mixin to add to the regular admin, so it can work with our polymorphic inlines.
@ -132,9 +132,7 @@ class PolymorphicInlineSupportMixin(object):
polymorphic inline formset. This fixes the media and form appearance
of the inline polymorphic models.
"""
inline_admin_formsets = super(
PolymorphicInlineSupportMixin, self
).get_inline_formsets(request, formsets, inline_instances, obj=obj)
inline_admin_formsets = super().get_inline_formsets(request, formsets, inline_instances, obj=obj)
for admin_formset in inline_admin_formsets:
if isinstance(admin_formset.formset, BasePolymorphicModelFormSet):

View File

@ -57,7 +57,7 @@ class PolymorphicInlineModelAdmin(InlineModelAdmin):
child_inlines = ()
def __init__(self, parent_model, admin_site):
super(PolymorphicInlineModelAdmin, self).__init__(parent_model, admin_site)
super().__init__(parent_model, admin_site)
# Extra check to avoid confusion
# While we could monkeypatch the admin here, better stay explicit.
@ -97,7 +97,7 @@ class PolymorphicInlineModelAdmin(InlineModelAdmin):
return self._child_inlines_lookup[model]
except KeyError:
raise UnsupportedChildType(
"Model '{0}' not found in child_inlines".format(model.__name__)
f"Model '{model.__name__}' not found in child_inlines"
)
def get_formset(self, request, obj=None, **kwargs):
@ -109,7 +109,7 @@ class PolymorphicInlineModelAdmin(InlineModelAdmin):
:rtype: type
"""
# Construct the FormSet class
FormSet = super(PolymorphicInlineModelAdmin, self).get_formset(
FormSet = super().get_formset(
request, obj=obj, **kwargs
)
@ -152,7 +152,7 @@ class PolymorphicInlineModelAdmin(InlineModelAdmin):
# The media of the inline focuses on the admin settings,
# whether to expose the scripts for filter_horizontal etc..
# The admin helper exposes the inline + formset media.
base_media = super(PolymorphicInlineModelAdmin, self).media
base_media = super().media
all_media = Media()
add_media(all_media, base_media)

View File

@ -62,7 +62,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
pk_regex = r"(\d+|__fk__)"
def __init__(self, model, admin_site, *args, **kwargs):
super(PolymorphicParentModelAdmin, self).__init__(
super().__init__(
model, admin_site, *args, **kwargs
)
self._is_setup = False
@ -102,13 +102,13 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
if not issubclass(model, self.base_model):
raise TypeError(
"{0} should be a subclass of {1}".format(
"{} should be a subclass of {}".format(
model.__name__, self.base_model.__name__
)
)
if not issubclass(model_admin, admin.ModelAdmin):
raise TypeError(
"{0} should be a subclass of {1}".format(
"{} should be a subclass of {}".format(
model_admin.__name__, admin.ModelAdmin.__name__
)
)
@ -137,7 +137,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
content_types = ContentType.objects.get_for_models(*self.get_child_models(), for_concrete_models=False)
for model, ct in content_types.items():
perm_function_name = "has_{0}_permission".format(action)
perm_function_name = f"has_{action}_permission"
model_admin = self._get_real_admin_by_model(model)
perm_function = getattr(model_admin, perm_function_name)
if not perm_function(request):
@ -167,7 +167,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
model_class = ct.model_class()
if not model_class:
# Handle model deletion
raise Http404("No model found for '{0}.{1}'.".format(*ct.natural_key()))
raise Http404("No model found for '{}.{}'.".format(*ct.natural_key()))
return self._get_real_admin_by_model(model_class, super_if_self=super_if_self)
@ -176,7 +176,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
# Hence, make sure this is a derived object, or risk exposing other admin interfaces.
if model_class not in self._child_models:
raise PermissionDenied(
"Invalid model '{0}', it must be registered as child model.".format(
"Invalid model '{}', it must be registered as child model.".format(
model_class
)
)
@ -187,19 +187,19 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
real_admin = self._child_admin_site._registry[model_class]
except KeyError:
raise ChildAdminNotRegistered(
"No child admin site was registered for a '{0}' model.".format(
"No child admin site was registered for a '{}' model.".format(
model_class
)
)
if super_if_self and real_admin is self:
return super(PolymorphicParentModelAdmin, self)
return super()
else:
return real_admin
def get_queryset(self, request):
# optimize the list display.
qs = super(PolymorphicParentModelAdmin, self).get_queryset(request)
qs = super().get_queryset(request)
if not self.polymorphic_list:
qs = qs.non_polymorphic()
return qs
@ -236,7 +236,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
return real_admin.changeform_view(request, object_id, *args, **kwargs)
else:
# Add view. As it should already be handled via `add_view`, this means something custom is done here!
return super(PolymorphicParentModelAdmin, self).changeform_view(
return super().changeform_view(
request, object_id, *args, **kwargs
)
@ -259,13 +259,13 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
c = x.split("=")
request.GET[c[0]] = c[1]
del request.GET["_changelist_filters"]
return super(PolymorphicParentModelAdmin, self).get_preserved_filters(request)
return super().get_preserved_filters(request)
def get_urls(self):
"""
Expose the custom URLs for the subclasses and the URL resolver.
"""
urls = super(PolymorphicParentModelAdmin, self).get_urls()
urls = super().get_urls()
# At this point. all admin code needs to be known.
self._lazy_setup()
@ -287,7 +287,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
object_id = int(path[0:pos])
except ValueError:
raise Http404(
"No ct_id parameter, unable to find admin subclass for path '{0}'.".format(
"No ct_id parameter, unable to find admin subclass for path '{}'.".format(
path
)
)
@ -300,7 +300,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
resolver = URLResolver("^", real_admin.urls)
resolvermatch = resolver.resolve(path) # May raise Resolver404
if not resolvermatch:
raise Http404("No match for path '{0}' in admin subclass.".format(path))
raise Http404(f"No match for path '{path}' in admin subclass.")
return resolvermatch.func(request, *resolvermatch.args, **resolvermatch.kwargs)
@ -315,13 +315,13 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
if request.META["QUERY_STRING"]:
# QUERY_STRING is bytes in Python 3, using force_str() to decode it as string.
# See QueryDict how Django deals with that.
extra_qs = "&{0}".format(force_str(request.META["QUERY_STRING"]))
extra_qs = "&{}".format(force_str(request.META["QUERY_STRING"]))
choices = self.get_child_type_choices(request, "add")
if len(choices) == 0:
raise PermissionDenied
if len(choices) == 1:
return HttpResponseRedirect("?ct_id={0}{1}".format(choices[0][0], extra_qs))
return HttpResponseRedirect(f"?ct_id={choices[0][0]}{extra_qs}")
# Create form
form = self.add_type_form(
@ -332,7 +332,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
if form.is_valid():
return HttpResponseRedirect(
"?ct_id={0}{1}".format(form.cleaned_data["ct_id"], extra_qs)
"?ct_id={}{}".format(form.cleaned_data["ct_id"], extra_qs)
)
# Wrap in all admin layout
@ -368,7 +368,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
)
templates = self.add_type_template or [
"admin/%s/%s/add_type_form.html" % (app_label, opts.object_name.lower()),
f"admin/{app_label}/{opts.object_name.lower()}/add_type_form.html",
"admin/%s/add_type_form.html" % app_label,
"admin/polymorphic/add_type_form.html", # added default here
"admin/add_type_form.html",
@ -387,7 +387,7 @@ class PolymorphicParentModelAdmin(admin.ModelAdmin):
base_app_label = base_opts.app_label
return [
"admin/%s/%s/change_list.html" % (app_label, opts.object_name.lower()),
f"admin/{app_label}/{opts.object_name.lower()}/change_list.html",
"admin/%s/change_list.html" % app_label,
# Added base class:
"admin/%s/%s/change_list.html"

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
PolymorphicModel Meta Class
"""
@ -62,7 +61,7 @@ class PolymorphicModelBase(ModelBase):
# Workaround compatibility issue with six.with_metaclass() and custom Django model metaclasses:
if not attrs and model_name == "NewBase":
return super(PolymorphicModelBase, self).__new__(
return super().__new__(
self, model_name, bases, attrs, **kwargs
)
@ -118,7 +117,7 @@ class PolymorphicModelBase(ModelBase):
if do_app_label_workaround:
meta.app_label = "poly_dummy_app_label"
new_class = super(PolymorphicModelBase, self).__new__(
new_class = super().__new__(
self, model_name, bases, attrs, **kwargs
)
if do_app_label_workaround:
@ -156,7 +155,7 @@ class PolymorphicModelBase(ModelBase):
manager.queryset_class, PolymorphicQuerySet
):
e = (
'PolymorphicModel: "{0}.{1}" has been instantiated with a queryset class '
'PolymorphicModel: "{}.{}" has been instantiated with a queryset class '
"which is not a subclass of PolymorphicQuerySet (which is required)".format(
model_name, manager_name
)
@ -168,7 +167,7 @@ class PolymorphicModelBase(ModelBase):
def base_objects(self):
warnings.warn(
"Using PolymorphicModel.base_objects is deprecated.\n"
"Use {0}.objects.non_polymorphic() instead.".format(
"Use {}.objects.non_polymorphic() instead.".format(
self.__class__.__name__
),
DeprecationWarning,
@ -205,10 +204,10 @@ class PolymorphicModelBase(ModelBase):
if DUMPDATA_COMMAND in frm[1]:
return self._base_objects
manager = super(PolymorphicModelBase, self)._default_manager
manager = super()._default_manager
if not isinstance(manager, PolymorphicManager):
warnings.warn(
"{0}._default_manager is not a PolymorphicManager".format(
"{}._default_manager is not a PolymorphicManager".format(
self.__class__.__name__
),
ManagerInheritanceWarning,

View File

@ -20,7 +20,7 @@ __all__ = (
)
class PolymorphicFormSetMixin(object):
class PolymorphicFormSetMixin:
"""
Internal Mixin, that provides polymorphic integration with the ``extra_views`` package.
"""
@ -55,7 +55,7 @@ class PolymorphicFormSetMixin(object):
# Since `polymorphic_modelformset_factory` and `polymorphic_inlineformset_factory` mainly
# reuse the standard factories, and then add `child_forms`, the same can be done here.
# This makes sure the base class construction is completely honored.
FormSet = super(PolymorphicFormSetMixin, self).get_formset()
FormSet = super().get_formset()
FormSet.child_forms = polymorphic_child_forms_factory(
self.get_formset_children(), **self.get_formset_child_kwargs()
)

View File

@ -21,7 +21,7 @@ class GenericPolymorphicFormSetChild(PolymorphicFormSetChild):
def __init__(self, *args, **kwargs):
self.ct_field = kwargs.pop("ct_field", "content_type")
self.fk_field = kwargs.pop("fk_field", "object_id")
super(GenericPolymorphicFormSetChild, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def get_form(self, ct_field="content_type", fk_field="object_id", **kwargs):
"""
@ -50,7 +50,7 @@ class GenericPolymorphicFormSetChild(PolymorphicFormSetChild):
exclude.extend([ct_field.name, fk_field.name])
kwargs["exclude"] = exclude
return super(GenericPolymorphicFormSetChild, self).get_form(**kwargs)
return super().get_form(**kwargs)
class BaseGenericPolymorphicInlineFormSet(

View File

@ -22,7 +22,7 @@ class UnsupportedChildType(LookupError):
pass
class PolymorphicFormSetChild(object):
class PolymorphicFormSetChild:
"""
Metadata to define the inline of a polymorphic child.
Provide this information in the :func:'polymorphic_inlineformset_factory' construction.
@ -130,7 +130,7 @@ class BasePolymorphicModelFormSet(BaseModelFormSet):
child_forms = OrderedDict()
def __init__(self, *args, **kwargs):
super(BasePolymorphicModelFormSet, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.queryset_data = self.get_queryset()
def _construct_form(self, i, **kwargs):
@ -139,7 +139,7 @@ class BasePolymorphicModelFormSet(BaseModelFormSet):
"""
# BaseModelFormSet logic
if self.is_bound and i < self.initial_form_count():
pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name)
pk_key = f"{self.add_prefix(i)}-{self.model._meta.pk.name}"
pk = self.data[pk_key]
pk_field = self.model._meta.pk
to_python = self._get_to_python(pk_field)
@ -188,10 +188,10 @@ class BasePolymorphicModelFormSet(BaseModelFormSet):
# Note this completely tru
prefix = defaults["prefix"]
try:
ct_id = int(self.data["{0}-polymorphic_ctype".format(prefix)])
ct_id = int(self.data[f"{prefix}-polymorphic_ctype"])
except (KeyError, ValueError):
raise ValidationError(
"Formset row {0} has no 'polymorphic_ctype' defined!".format(
"Formset row {} has no 'polymorphic_ctype' defined!".format(
prefix
)
)
@ -200,7 +200,7 @@ class BasePolymorphicModelFormSet(BaseModelFormSet):
if model not in self.child_forms:
# Perform basic validation, as we skip the ChoiceField here.
raise UnsupportedChildType(
"Child model type {0} is not part of the formset".format(model)
f"Child model type {model} is not part of the formset"
)
else:
if "instance" in defaults:
@ -232,7 +232,7 @@ class BasePolymorphicModelFormSet(BaseModelFormSet):
form.fields["polymorphic_ctype"] = forms.TypedChoiceField(
choices=choices, initial=ct.pk, required=False, widget=forms.HiddenInput, coerce=int,
)
super(BasePolymorphicModelFormSet, self).add_fields(form, index)
super().add_fields(form, index)
def get_form_class(self, model):
"""
@ -240,17 +240,17 @@ class BasePolymorphicModelFormSet(BaseModelFormSet):
"""
if not self.child_forms:
raise ImproperlyConfigured(
"No 'child_forms' defined in {0}".format(self.__class__.__name__)
f"No 'child_forms' defined in {self.__class__.__name__}"
)
if not issubclass(model, PolymorphicModel):
raise TypeError("Expect polymorphic model type, not {0}".format(model))
raise TypeError(f"Expect polymorphic model type, not {model}")
try:
return self.child_forms[model]
except KeyError:
# This may happen when the query returns objects of a type that was not handled by the formset.
raise UnsupportedChildType(
"The '{0}' found a '{1}' model in the queryset, "
"The '{}' found a '{}' model in the queryset, "
"but no form class is registered to display it.".format(
self.__class__.__name__, model.__name__
)
@ -378,7 +378,7 @@ class BasePolymorphicInlineFormSet(BaseInlineFormSet, BasePolymorphicModelFormSe
"""
def _construct_form(self, i, **kwargs):
return super(BasePolymorphicInlineFormSet, self)._construct_form(i, **kwargs)
return super()._construct_form(i, **kwargs)
def polymorphic_inlineformset_factory(

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
The manager class for use in the models.
"""
@ -22,7 +21,7 @@ class PolymorphicManager(models.Manager):
@classmethod
def from_queryset(cls, queryset_class, class_name=None):
manager = super(PolymorphicManager, cls).from_queryset(
manager = super().from_queryset(
queryset_class, class_name=class_name
)
# also set our version, Django uses _queryset_class
@ -36,7 +35,7 @@ class PolymorphicManager(models.Manager):
return qs
def __str__(self):
return "%s (PolymorphicManager) using %s" % (
return "{} (PolymorphicManager) using {}".format(
self.__class__.__name__,
self.queryset_class.__name__,
)

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Seamless Polymorphic Inheritance for Django Models
"""
@ -88,7 +87,7 @@ class PolymorphicModel(with_metaclass(PolymorphicModelBase, models.Model)):
"""Calls :meth:`pre_save_polymorphic` and saves the model."""
using = kwargs.get("using", self._state.db or DEFAULT_DB_ALIAS)
self.pre_save_polymorphic(using=using)
return super(PolymorphicModel, self).save(*args, **kwargs)
return super().save(*args, **kwargs)
save.alters_data = True
@ -131,7 +130,7 @@ class PolymorphicModel(with_metaclass(PolymorphicModelBase, models.Model)):
)
):
raise PolymorphicTypeInvalid(
"ContentType {0} for {1} #{2} does not point to a subclass!".format(
"ContentType {} for {} #{} does not point to a subclass!".format(
self.polymorphic_ctype_id, model, self.pk
)
)
@ -195,7 +194,7 @@ class PolymorphicModel(with_metaclass(PolymorphicModelBase, models.Model)):
But they should not. So we replace them with our own accessors that use
our appropriate base_objects manager.
"""
super(PolymorphicModel, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
if self.__class__.polymorphic_super_sub_accessors_replaced:
return

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
QuerySet for PolymorphicModel
"""
@ -32,7 +31,7 @@ class PolymorphicModelIterable(ModelIterable):
"""
def __iter__(self):
base_iter = super(PolymorphicModelIterable, self).__iter__()
base_iter = super().__iter__()
if self.queryset.polymorphic_disabled:
return base_iter
return self._polymorphic_iterator(base_iter)
@ -102,7 +101,7 @@ class PolymorphicQuerySet(QuerySet):
"""
def __init__(self, *args, **kwargs):
super(PolymorphicQuerySet, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self._iterable_class = PolymorphicModelIterable
self.polymorphic_disabled = False
@ -111,11 +110,11 @@ class PolymorphicQuerySet(QuerySet):
# .defer() and .only() in order to be able to retranslate them when
# retrieving the real instance (so that the deferred fields apply
# to that queryset as well).
self.polymorphic_deferred_loading = (set([]), True)
self.polymorphic_deferred_loading = (set(), True)
def _clone(self, *args, **kwargs):
# Django's _clone only copies its own variables, so we need to copy ours here
new = super(PolymorphicQuerySet, self)._clone(*args, **kwargs)
new = super()._clone(*args, **kwargs)
new.polymorphic_disabled = self.polymorphic_disabled
new.polymorphic_deferred_loading = (
copy.copy(self.polymorphic_deferred_loading[0]),
@ -137,7 +136,7 @@ class PolymorphicQuerySet(QuerySet):
objs = list(objs)
for obj in objs:
obj.pre_save_polymorphic()
return super(PolymorphicQuerySet, self).bulk_create(objs, batch_size, ignore_conflicts=ignore_conflicts)
return super().bulk_create(objs, batch_size, ignore_conflicts=ignore_conflicts)
def non_polymorphic(self):
"""switch off polymorphic behaviour for this query.
@ -171,7 +170,7 @@ class PolymorphicQuerySet(QuerySet):
queryset_model=self.model, kwargs=kwargs, using=self.db
)
args = list(q_objects) + additional_args
return super(PolymorphicQuerySet, self)._filter_or_exclude(
return super()._filter_or_exclude(
negate=negate, args=args, kwargs=kwargs
)
else:
@ -184,7 +183,7 @@ class PolymorphicQuerySet(QuerySet):
additional_args = translate_polymorphic_filter_definitions_in_kwargs(
self.model, kwargs, using=self.db
)
return super(PolymorphicQuerySet, self)._filter_or_exclude(
return super()._filter_or_exclude(
negate, *(list(q_objects) + additional_args), **kwargs
)
@ -196,7 +195,7 @@ class PolymorphicQuerySet(QuerySet):
else a # allow expressions to pass unchanged
for a in field_names
]
return super(PolymorphicQuerySet, self).order_by(*field_names)
return super().order_by(*field_names)
def defer(self, *fields):
"""
@ -207,7 +206,7 @@ class PolymorphicQuerySet(QuerySet):
them again, as the model will have changed).
"""
new_fields = [translate_polymorphic_field_path(self.model, a) for a in fields]
clone = super(PolymorphicQuerySet, self).defer(*new_fields)
clone = super().defer(*new_fields)
clone._polymorphic_add_deferred_loading(fields)
return clone
@ -220,7 +219,7 @@ class PolymorphicQuerySet(QuerySet):
them again, as the model will have changed).
"""
new_fields = [translate_polymorphic_field_path(self.model, a) for a in fields]
clone = super(PolymorphicQuerySet, self).only(*new_fields)
clone = super().only(*new_fields)
clone._polymorphic_add_immediate_loading(fields)
return clone
@ -308,7 +307,7 @@ class PolymorphicQuerySet(QuerySet):
"""translate the polymorphic field paths in the kwargs, then call vanilla annotate.
_get_real_instances will do the rest of the job after executing the query."""
self._process_aggregate_args(args, kwargs)
return super(PolymorphicQuerySet, self).annotate(*args, **kwargs)
return super().annotate(*args, **kwargs)
def aggregate(self, *args, **kwargs):
"""translate the polymorphic field paths in the kwargs, then call vanilla aggregate.
@ -321,7 +320,7 @@ class PolymorphicQuerySet(QuerySet):
# same class as 'qs', so our polymorphic modifications would apply.
# We want to leave values queries untouched, so we set 'polymorphic_disabled'.
def _values(self, *args, **kwargs):
clone = super(PolymorphicQuerySet, self)._values(*args, **kwargs)
clone = super()._values(*args, **kwargs)
clone.polymorphic_disabled = True
return clone
@ -515,7 +514,7 @@ class PolymorphicQuerySet(QuerySet):
result = [repr(o) for o in self.all()]
return "[ " + ",\n ".join(result) + " ]"
else:
return super(PolymorphicQuerySet, self).__repr__(*args, **kwargs)
return super().__repr__(*args, **kwargs)
class _p_list_class(list):
def __repr__(self, *args, **kwargs):

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
PolymorphicQuerySet support functions
"""
@ -143,7 +142,7 @@ def translate_polymorphic_field_path(queryset_model, field_path):
Returns: translated path (unchanged, if no translation needed)
"""
if not isinstance(field_path, str):
raise ValueError("Expected field name as string: {0}".format(field_path))
raise ValueError(f"Expected field name as string: {field_path}")
classname, sep, pure_field_path = field_path.partition("___")
if not sep:
@ -159,7 +158,7 @@ def translate_polymorphic_field_path(queryset_model, field_path):
# the user has app label prepended to class name via __ => use Django's get_model function
appname, sep, classname = classname.partition("__")
model = apps.get_model(appname, classname)
assert model, "PolymorphicModel: model %s (in app %s) not found!" % (
assert model, "PolymorphicModel: model {} (in app {}) not found!".format(
model.__name__,
appname,
)
@ -192,7 +191,7 @@ def translate_polymorphic_field_path(queryset_model, field_path):
submodels = _get_all_sub_models(queryset_model)
model = submodels.get(classname, None)
assert model, "PolymorphicModel: model %s not found (not a subclass of %s)!" % (
assert model, "PolymorphicModel: model {} not found (not a subclass of {})!".format(
classname,
queryset_model.__name__,
)

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import re
from django.db import models
@ -6,7 +5,7 @@ from django.db import models
RE_DEFERRED = re.compile("_Deferred_.*")
class ShowFieldBase(object):
class ShowFieldBase:
""" base class for the ShowField... model mixins, does the work """
# cause nicer multiline PolymorphicQuery output
@ -124,7 +123,7 @@ class ShowFieldBase(object):
fields = self.get_deferred_fields()
if fields:
parts.append(
(False, "deferred[{0}]".format(",".join(sorted(fields))), "")
(False, "deferred[{}]".format(",".join(sorted(fields))), "")
)
# format result

View File

@ -20,7 +20,7 @@ class BreadcrumbScope(Node):
return cls(base_opts=base_opts, nodelist=nodelist)
else:
raise TemplateSyntaxError(
"{0} tag expects 1 argument".format(token.contents[0])
f"{token.contents[0]} tag expects 1 argument"
)
def render(self, context):

View File

@ -15,13 +15,11 @@ def include_empty_form(formset):
"""
Make sure the "empty form" is included when displaying a formset (typically table with input rows)
"""
for form in formset:
yield form
yield from formset
if hasattr(formset, "empty_forms"):
# BasePolymorphicModelFormSet
for form in formset.empty_forms:
yield form
yield from formset.empty_forms
else:
# Standard Django formset
yield formset.empty_form

View File

@ -21,13 +21,13 @@ class AdminTestCase(TestCase):
@classmethod
def setUpClass(cls):
super(AdminTestCase, cls).setUpClass()
super().setUpClass()
cls.admin_user = User.objects.create_superuser(
"admin", "admin@example.org", password="admin"
)
def setUp(self):
super(AdminTestCase, self).setUp()
super().setUp()
# Have a separate site, to avoid dependency on polymorphic wrapping or standard admin configuration
self.admin_site = AdminSite()
@ -60,11 +60,11 @@ class AdminTestCase(TestCase):
try:
return self.admin_site._registry[model]
except KeyError:
raise ValueError("Model not registered with admin: {}".format(model))
raise ValueError(f"Model not registered with admin: {model}")
@classmethod
def tearDownClass(cls):
super(AdminTestCase, cls).tearDownClass()
super().tearDownClass()
clear_url_caches()
set_urlconf(None)
@ -181,7 +181,7 @@ class AdminTestCase(TestCase):
)
response = admin_instance.delete_view(request, str(object_id))
self.assertEqual(
response.status_code, 302, "Form errors in calling {0}".format(request.path)
response.status_code, 302, f"Form errors in calling {request.path}"
)
return response
@ -229,11 +229,11 @@ class AdminTestCase(TestCase):
self.assertEqual(
response.status_code,
302,
"Form errors in calling {0}:\n{1}".format(
"Form errors in calling {}:\n{}".format(
request_url, errors.as_text()
),
)
self.assertTrue(
"/login/?next=" not in response["Location"],
"Received login response for {0}".format(request_url),
f"Received login response for {request_url}",
)

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import uuid
import django
@ -166,7 +165,7 @@ class MyManager(PolymorphicManager):
queryset_class = MyManagerQuerySet
def get_queryset(self):
return super(MyManager, self).get_queryset().order_by("-field1")
return super().get_queryset().order_by("-field1")
def my_queryset_foo(self):
return self.all().my_queryset_foo()
@ -288,7 +287,7 @@ class InitTestModel(ShowFieldType, PolymorphicModel):
def __init__(self, *args, **kwargs):
kwargs["bar"] = self.x()
super(InitTestModel, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
class InitTestModelSubclass(InitTestModel):

View File

@ -43,13 +43,13 @@ class PolymorphicAdminTests(AdminTestCase):
# -- add page
ct_id = ContentType.objects.get_for_model(Model2D).pk
self.admin_get_add(Model2A) # shows type page
self.admin_get_add(Model2A, qs="?ct_id={}".format(ct_id)) # shows type page
self.admin_get_add(Model2A, qs=f"?ct_id={ct_id}") # shows type page
self.admin_get_add(Model2A) # shows type page
self.admin_post_add(
Model2A,
{"field1": "A", "field2": "B", "field3": "C", "field4": "D"},
qs="?ct_id={}".format(ct_id),
qs=f"?ct_id={ct_id}",
)
d_obj = Model2A.objects.all()[0]

View File

@ -408,10 +408,10 @@ class PolymorphicTests(TransactionTestCase):
def test_create_instanceof_q(self):
q = query_translate.create_instanceof_q([Model2B])
expected = sorted(
[
ContentType.objects.get_for_model(m).pk
for m in [Model2B, Model2C, Model2D]
]
)
self.assertEqual(dict(q.children), dict(polymorphic_ctype__in=expected))
@ -538,7 +538,7 @@ class PolymorphicTests(TransactionTestCase):
def test_extra_method(self):
a, b, c, d = self.create_model2abcd()
objects = Model2A.objects.extra(where=["id IN ({}, {})".format(b.id, c.id)])
objects = Model2A.objects.extra(where=[f"id IN ({b.id}, {c.id})"])
self.assertQuerysetEqual(
objects, [Model2B, Model2C], transform=lambda o: o.__class__, ordered=False
)

View File

@ -13,10 +13,10 @@ warnings.simplefilter("always", DeprecationWarning)
# Give feedback on used versions
sys.stderr.write(
"Using Python version {0} from {1}\n".format(sys.version[:5], sys.executable)
f"Using Python version {sys.version[:5]} from {sys.executable}\n"
)
sys.stderr.write(
"Using Django version {0} from {1}\n".format(
"Using Django version {} from {}\n".format(
django.get_version(), dirname(abspath(django.__file__))
)
)