Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Replace Interpolation With Fstring (#11016)

Sagar Giri92a0c6c9f432
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.py
index d0d7fdde11..98656c7de8 100644
--- a/saleor/account/i18n.py
+++ b/saleor/account/i18n.py
@@ -121,10 +121,7 @@ class AddressForm(forms.ModelForm):
autocomplete_dict = defaultdict(lambda: "off", self.AUTOCOMPLETE_MAPPING)
for field_name, field in self.fields.items():
if autocomplete_type:
- autocomplete = "%s %s" % (
- autocomplete_type,
- autocomplete_dict[field_name],
- )
+ autocomplete = f"{autocomplete_type} {autocomplete_dict[field_name]}"
else:
autocomplete = autocomplete_dict[field_name]
field.widget.attrs["autocomplete"] = autocomplete
@@ -183,10 +180,9 @@ class CountryAwareAddressForm(AddressForm):
try:
data["country_code"] = data.get("country", "")
if data["street_address_1"] or data["street_address_2"]:
- data["street_address"] = "%s\n%s" % (
- data["street_address_1"],
- data["street_address_2"],
- )
+ data[
+ "street_address"
+ ] = f'{data["street_address_1"]}\n{data["street_address_2"]}'
normalized_data = i18naddress.normalize_address(data)
if getattr(self, "enable_normalization", True):
data = normalized_data
@@ -261,7 +257,7 @@ def update_base_fields(form_class, i18n_rules):
def construct_address_form(country_code, i18n_rules):
- class_name = "AddressForm%s" % country_code
+ class_name = f"AddressForm{country_code}"
base_class = CountryAwareAddressForm
form_kwargs = {
"Meta": type(str("Meta"), (base_class.Meta, object), {}),
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 94c1a7792e..1cb96317dc 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -98,11 +98,11 @@ class Address(models.Model):
@property
def full_name(self):
- return "%s %s" % (self.first_name, self.last_name)
+ return f"{self.first_name} {self.last_name}"
def __str__(self):
if self.company_name:
- return "%s - %s" % (self.company_name, self.full_name)
+ return f"{self.company_name} - {self.full_name}"
return self.full_name
def __eq__(self, other):
@@ -269,12 +269,12 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):
def get_full_name(self):
if self.first_name or self.last_name:
- return ("%s %s" % (self.first_name, self.last_name)).strip()
+ return f"{self.first_name} {self.last_name}".strip()
if self.default_billing_address:
first_name = self.default_billing_address.first_name
last_name = self.default_billing_address.last_name
if first_name or last_name:
- return ("%s %s" % (first_name, last_name)).strip()
+ return f"{first_name} {last_name}".strip()
return self.email
def get_short_name(self):
diff --git a/saleor/app/manifest_validations.py b/saleor/app/manifest_validations.py
index bf1eb0f241..85c68775f9 100644
--- a/saleor/app/manifest_validations.py
+++ b/saleor/app/manifest_validations.py
@@ -255,8 +255,8 @@ def validate_required_fields(manifest_data, errors):
if missing_fields := extension_required_fields.difference(extension_fields):
errors["extensions"].append(
ValidationError(
- "Missing required fields for app extension: %s."
- % ", ".join(missing_fields),
+ "Missing required fields for app extension: "
+ f'{", ".join(missing_fields)}.',
code=AppErrorCode.REQUIRED.value,
)
)
@@ -267,8 +267,8 @@ def validate_required_fields(manifest_data, errors):
if missing_fields := webhook_required_fields.difference(webhook_fields):
errors["webhooks"].append(
ValidationError(
- "Missing required fields for webhook: %s."
- % ", ".join(missing_fields),
+ f"Missing required fields for webhook: "
+ f'{", ".join(missing_fields)}.',
code=AppErrorCode.REQUIRED.value,
)
)
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index 6aa96612c8..15df203fb3 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -184,6 +184,6 @@ def validate_checkout(
manager.preprocess_order_creation(checkout_info, discounts, lines)
except TaxError as tax_error:
raise ValidationError(
- "Unable to calculate taxes - %s" % str(tax_error),
+ f"Unable to calculate taxes - {str(tax_error)}",
code=OrderCreateFromCheckoutErrorCode.TAX_ERROR.value,
)
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index e5551d4dd0..665aa07234 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -255,7 +255,7 @@ def _create_line_for_order(
unit_discount_reason = None
if sale_id:
- unit_discount_reason = "Sale: %s" % graphene.Node.to_global_id("Sale", sale_id)
+ unit_discount_reason = f'Sale: {graphene.Node.to_global_id("Sale", sale_id)}'
if voucher_code:
if unit_discount_reason:
unit_discount_reason += f" & Voucher code: {voucher_code}"
@@ -698,7 +698,7 @@ def _get_order_data(
raise ValidationError(e.message, code=e.code)
except TaxError as tax_error:
raise ValidationError(
- "Unable to calculate taxes - %s" % str(tax_error),
+ f"Unable to calculate taxes - {str(tax_error)}",
code=CheckoutErrorCode.TAX_ERROR.value,
)
return order_data
diff --git a/saleor/core/auth_backend.py b/saleor/core/auth_backend.py
index 5bbf3ca742..7561984559 100644
--- a/saleor/core/auth_backend.py
+++ b/saleor/core/auth_backend.py
@@ -44,11 +44,9 @@ class JSONWebTokenBackend(ModelBackend):
perm_cache_name = "_effective_permissions_cache"
if not getattr(user_obj, perm_cache_name, None):
- perms = getattr(self, "_get_%s_permissions" % from_name)(user_obj)
+ perms = getattr(self, f"_get_{from_name}_permissions")(user_obj)
perms = perms.values_list("content_type__app_label", "codename").order_by()
- setattr(
- user_obj, perm_cache_name, {"%s.%s" % (ct, name) for ct, name in perms}
- )
+ setattr(user_obj, perm_cache_name, {f"{ct}.{name}" for ct, name in perms})
return getattr(user_obj, perm_cache_name)
diff --git a/saleor/core/db/filters.py b/saleor/core/db/filters.py
index 9889302c5e..e96a83ba96 100644
--- a/saleor/core/db/filters.py
+++ b/saleor/core/db/filters.py
@@ -8,4 +8,4 @@ class PostgresILike(IContains):
lhs, lhs_params = self.process_lhs(compiler, connection)
rhs, rhs_params = self.process_rhs(compiler, connection)
params = lhs_params + rhs_params
- return "%s ILIKE %s" % (lhs, rhs), params
+ return f"{lhs} ILIKE {rhs}", params
diff --git a/saleor/core/postgres.py b/saleor/core/postgres.py
index 3158ef05ad..13361c029b 100644
--- a/saleor/core/postgres.py
+++ b/saleor/core/postgres.py
@@ -17,7 +17,7 @@ class NoValidationSearchVectorCombinable(SearchVectorCombinable):
if not isinstance(other, NoValidationSearchVectorCombinable):
raise TypeError(
"SearchVector can only be combined with other SearchVector "
- "instances, got %s." % type(other).__name__
+ f"instances, got {type(other).__name__}."
)
if reversed:
return NoValidationCombinedSearchVector(other, connector, self, self.config)
diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.py
index 23d55f9974..e6221469e8 100644
--- a/saleor/core/tests/test_core.py
+++ b/saleor/core/tests/test_core.py
@@ -218,7 +218,7 @@ def test_build_absolute_uri(site_settings, settings):
# Case when static url is resolved to relative url
logo_url = build_absolute_uri(static("images/close.svg"))
protocol = "https" if settings.ENABLE_SSL else "http"
- current_url = "%s://%s" % (protocol, site_settings.site.domain)
+ current_url = f"{protocol}://{site_settings.site.domain}"
logo_location = urljoin(current_url, static("images/close.svg"))
assert logo_url == logo_location
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 896fd4663e..ecc94a9f52 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -30,7 +30,7 @@ def build_absolute_uri(location: str, domain: Optional[str] = None) -> str:
"""
host = domain or Site.objects.get_current().domain
protocol = "https" if settings.ENABLE_SSL else "http"
- current_uri = "%s://%s" % (protocol, host)
+ current_uri = f"{protocol}://{host}"
location = urljoin(current_uri, location)
return iri_to_uri(location)
diff --git a/saleor/core/utils/json_serializer.py b/saleor/core/utils/json_serializer.py
index 0fae131e7c..7386687d8f 100644
--- a/saleor/core/utils/json_serializer.py
+++ b/saleor/core/utils/json_serializer.py
@@ -19,7 +19,7 @@ class CustomJsonEncoder(DjangoJSONEncoder):
return {"_type": MONEY_TYPE, "amount": obj.amount, "currency": obj.currency}
# Mirror implementation of django_measurement.MeasurementField.value_to_string
if isinstance(obj, Weight):
- return "%s:%s" % (obj.value, obj.unit)
+ return f"{obj.value}:{obj.unit}"
return super().default(obj)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 78c2d74366..6cd9baed05 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -491,10 +491,9 @@ fake.add_provider(SaleorProvider) # type: ignore
def get_email(first_name, last_name):
_first = unicodedata.normalize("NFD", first_name).encode("ascii", "ignore")
_last = unicodedata.normalize("NFD", last_name).encode("ascii", "ignore")
- return "%s.%[email protected]" % (
- _first.lower().decode("utf-8"),
- _last.lower().decode("utf-8"),
- )
+ decoded_first = _first.lower().decode("utf-8")
+ decoded_last = _last.lower().decode("utf-8")
+ return f"{decoded_first}.{decoded_last}@example.com"
def create_product_image(product, placeholder_dir, image_name):
@@ -851,7 +850,7 @@ def create_fake_order(discounts, max_order_lines=5, create_preorder_lines=False)
def create_fake_sale():
sale = Sale.objects.create(
- name="Happy %s day!" % fake.word(),
+ name=f"Happy {fake.word()} day!",
type=DiscountValueType.PERCENTAGE,
)
for channel in Channel.objects.all():
@@ -872,7 +871,7 @@ def create_fake_sale():
def create_users(user_password, how_many=10):
for _ in range(how_many):
user = create_fake_user(user_password)
- yield "User: %s" % (user.email,)
+ yield f"User: {user.email}"
def create_permission_groups(staff_password):
@@ -968,14 +967,14 @@ def create_orders(how_many=10):
discounts = fetch_discounts(timezone.now())
for _ in range(how_many):
order = create_fake_order(discounts)
- yield "Order: %s" % (order,)
+ yield f"Order: {order}"
def create_product_sales(how_many=5):
for _ in range(how_many):
sale = create_fake_sale()
update_products_discounted_prices_of_discount_task.delay(sale.pk)
- yield "Sale: %s" % (sale,)
+ yield f"Sale: {sale}"
def create_channel(channel_name, currency_code, slug=None, country=None):
@@ -1510,7 +1509,7 @@ def create_page_type():
pk = page_type_data.pop("pk")
defaults = dict(page_type_data["fields"])
page_type, _ = PageType.objects.update_or_create(pk=pk, defaults=defaults)
- yield "Page type %s created" % page_type.slug
+ yield f"Page type {page_type.slug} created"
def create_pages():
@@ -1523,7 +1522,7 @@ def create_pages():
defaults = dict(page_data["fields"])
defaults["page_type_id"] = defaults.pop("page_type")
page, _ = Page.objects.update_or_create(pk=pk, defaults=defaults)
- yield "Page %s created" % page.slug
+ yield f"Page {page.slug} created"
def create_menus():
@@ -1535,7 +1534,7 @@ def create_menus():
pk = menu["pk"]
defaults = menu["fields"]
menu, _ = Menu.objects.update_or_create(pk=pk, defaults=defaults)
- yield "Menu %s created" % menu.name
+ yield f"Menu {menu.name} created"
for menu_item in menu_item_data:
pk = menu_item["pk"]
defaults = dict(menu_item["fields"])
@@ -1545,7 +1544,7 @@ def create_menus():
defaults["page_id"] = defaults.pop("page")
defaults.pop("parent")
menu_item, _ = MenuItem.objects.update_or_create(pk=pk, defaults=defaults)
- yield "MenuItem %s created" % menu_item.name
+ yield f"MenuItem {menu_item.name} created"
for menu_item in menu_item_data:
pk = menu_item["pk"]
defaults = dict(menu_item["fields"])
diff --git a/saleor/discount/models.py b/saleor/discount/models.py
index 92dcd3d57e..182a2d3421 100644
--- a/saleor/discount/models.py
+++ b/saleor/discount/models.py
@@ -284,10 +284,7 @@ class Sale(ModelWithMetadata):
)
def __repr__(self):
- return "Sale(name=%r, type=%s)" % (
- str(self.name),
- self.get_type_display(),
- )
+ return f"Sale(name={str(self.name)}, type={self.get_type_display()})"
def __str__(self):
return self.name
diff --git a/saleor/graphql/account/sorters.py b/saleor/graphql/account/sorters.py
index 96c6fa3105..206d937d2f 100644
--- a/saleor/graphql/account/sorters.py
+++ b/saleor/graphql/account/sorters.py
@@ -17,7 +17,7 @@ class UserSortField(graphene.Enum):
if self.name in UserSortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort users by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_order_count(queryset: QuerySet, *, channel_slug=None) -> QuerySet:
@@ -39,7 +39,7 @@ class PermissionGroupSortField(graphene.Enum):
if self in [PermissionGroupSortField.NAME]:
sort_name = self.name.lower().replace("_", " ")
return f"Sort permission group accounts by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class PermissionGroupSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/app/sorters.py b/saleor/graphql/app/sorters.py
index 6062a2d039..086f116ac7 100644
--- a/saleor/graphql/app/sorters.py
+++ b/saleor/graphql/app/sorters.py
@@ -12,7 +12,7 @@ class AppSortField(graphene.Enum):
if self.name in AppSortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort apps by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class AppSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.py
index 985b63f035..5f0462106f 100644
--- a/saleor/graphql/attribute/mutations.py
+++ b/saleor/graphql/attribute/mutations.py
@@ -399,8 +399,7 @@ class AttributeMixin:
slug = slugify(unidecode(value_data["name"]))
if slug in existing_values:
msg = (
- "Value %s already exists within this attribute."
- % value_data["name"]
+ f'Value {value_data["name"]} already exists within this attribute.'
)
raise ValidationError(
{
@@ -561,7 +560,7 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
remove_values = cleaned_input.get("remove_values", [])
for value in remove_values:
if value.attribute != instance:
- msg = "Value %s does not belong to this attribute." % value
+ msg = f"Value {value} does not belong to this attribute."
raise ValidationError(
{
"remove_values": ValidationError(
diff --git a/saleor/graphql/attribute/sorters.py b/saleor/graphql/attribute/sorters.py
index 053190d024..456f82dab0 100644
--- a/saleor/graphql/attribute/sorters.py
+++ b/saleor/graphql/attribute/sorters.py
@@ -45,7 +45,7 @@ class AttributeSortField(graphene.Enum):
}
if self.name in descriptions:
return descriptions[self.name]
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class AttributeSortingInput(SortInputObjectType):
@@ -66,7 +66,7 @@ class AttributeChoicesSortField(graphene.Enum):
}
if self.name in descriptions:
return descriptions[self.name]
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class AttributeChoicesSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/checkout/sorters.py b/saleor/graphql/checkout/sorters.py
index 0af42432e5..eaafec9054 100644
--- a/saleor/graphql/checkout/sorters.py
+++ b/saleor/graphql/checkout/sorters.py
@@ -15,7 +15,7 @@ class CheckoutSortField(graphene.Enum):
if self.name in CheckoutSortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort checkouts by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_payment(queryset: QuerySet, **_kwargs) -> QuerySet:
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
index 694c008d53..37d9a33ece 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py
@@ -1032,6 +1032,9 @@ def test_checkout_lines_invalid_variant_id(user_api_client, checkout, stock):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
content = get_graphql_content(response)
data = content["data"]["checkoutLinesAdd"]
- error_msg = "Could not resolve to a node with the global id list of '%s'."
- assert data["errors"][0]["message"] == error_msg % [invalid_variant_id]
+ error_msg = (
+ "Could not resolve to a node with the global id list of "
+ f"'['{invalid_variant_id}']'."
+ )
+ assert data["errors"][0]["message"] == error_msg
assert data["errors"][0]["field"] == "variantId"
diff --git a/saleor/graphql/core/connection.py b/saleor/graphql/core/connection.py
index e0f6a9f015..4922b4a510 100644
--- a/saleor/graphql/core/connection.py
+++ b/saleor/graphql/core/connection.py
@@ -47,7 +47,7 @@ def get_field_value(instance: DjangoModel, field_name: str):
attr = getattr(attr, elem, None) # type:ignore
if callable(attr):
- return "%s" % attr()
+ return f"{attr()}"
return attr
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 885cd15029..63ce30c695 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -47,7 +47,7 @@ class OrderDirection(graphene.Enum):
return "Specifies an ascending sort order."
if self == OrderDirection.DESC:
return "Specifies a descending sort order."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class ReportingPeriod(graphene.Enum):
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index f09638ffb5..f139de9f05 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -251,7 +251,7 @@ class BaseMutation(graphene.Mutation):
raise ValidationError(
{
field: ValidationError(
- "Couldn't resolve to a node: %s" % node_id, code=code
+ f"Couldn't resolve to a node: {node_id}", code=code
)
}
)
diff --git a/saleor/graphql/core/types/converter.py b/saleor/graphql/core/types/converter.py
index 7b10ef5982..f08a1138aa 100644
--- a/saleor/graphql/core/types/converter.py
+++ b/saleor/graphql/core/types/converter.py
@@ -26,8 +26,8 @@ def get_form_field_description(field):
@singledispatch
def convert_form_field(field):
raise ImproperlyConfigured(
- "Don't know how to convert the Django form field %s (%s) "
- "to Graphene type" % (field, field.__class__)
+ f"Don't know how to convert the Django form field {field} ({field.__class__}) "
+ "to Graphene type"
)
diff --git a/saleor/graphql/csv/enums.py b/saleor/graphql/csv/enums.py
index e0d09af9a8..888e66f6c1 100644
--- a/saleor/graphql/csv/enums.py
+++ b/saleor/graphql/csv/enums.py
@@ -22,7 +22,7 @@ class ExportScope(graphene.Enum):
}
if self.name in description_mapping:
return description_mapping[self.name]
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class ProductFieldEnum(graphene.Enum):
diff --git a/saleor/graphql/csv/sorters.py b/saleor/graphql/csv/sorters.py
index bf5e72af0b..fa3a616766 100644
--- a/saleor/graphql/csv/sorters.py
+++ b/saleor/graphql/csv/sorters.py
@@ -24,7 +24,7 @@ class ExportFileSortField(graphene.Enum):
for self.name in ExportFileSortField.__enum__._member_names_:
return f"Sort export file by {descriptions[self.name]}"
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class ExportFileSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/discount/sorters.py b/saleor/graphql/discount/sorters.py
index 600c6a955b..1e7bbe0b5e 100644
--- a/saleor/graphql/discount/sorters.py
+++ b/saleor/graphql/discount/sorters.py
@@ -23,7 +23,7 @@ class SaleSortField(graphene.Enum):
if extras := descrption_extras.get(self.name):
description += "".join(extras)
return description
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_value(queryset: QuerySet, channel_slug: str) -> QuerySet:
@@ -62,7 +62,7 @@ class VoucherSortField(graphene.Enum):
if extras := descrption_extras.get(self.name):
description += "".join(extras)
return description
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_minimum_spent_amount(queryset: QuerySet, channel_slug: str) -> QuerySet:
diff --git a/saleor/graphql/giftcard/sorters.py b/saleor/graphql/giftcard/sorters.py
index bb2e5cb3e0..7c9311278a 100644
--- a/saleor/graphql/giftcard/sorters.py
+++ b/saleor/graphql/giftcard/sorters.py
@@ -18,7 +18,7 @@ class GiftCardSortField(graphene.Enum):
if self.name == "CREATED_AT":
description += ADDED_IN_38
return description
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class GiftCardSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/menu/enums.py b/saleor/graphql/menu/enums.py
index ba17dfb7bf..9f098645ec 100644
--- a/saleor/graphql/menu/enums.py
+++ b/saleor/graphql/menu/enums.py
@@ -11,4 +11,4 @@ class NavigationType(graphene.Enum):
return "Main storefront navigation."
if self == NavigationType.SECONDARY:
return "Secondary storefront navigation."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
diff --git a/saleor/graphql/menu/sorters.py b/saleor/graphql/menu/sorters.py
index 99367117e1..d1769e2dac 100644
--- a/saleor/graphql/menu/sorters.py
+++ b/saleor/graphql/menu/sorters.py
@@ -13,7 +13,7 @@ class MenuSortField(graphene.Enum):
if self.name in MenuSortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort menus by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_items_count(queryset: QuerySet, **_kwargs) -> QuerySet:
@@ -34,7 +34,7 @@ class MenuItemsSortField(graphene.Enum):
if self.name in MenuItemsSortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort menu items by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class MenuItemSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.py
index 0c98d89c17..f362352485 100644
--- a/saleor/graphql/order/mutations/draft_order_create.py
+++ b/saleor/graphql/order/mutations/draft_order_create.py
@@ -362,7 +362,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
)
except TaxError as tax_error:
raise ValidationError(
- "Unable to calculate taxes - %s" % str(tax_error),
+ f"Unable to calculate taxes - {str(tax_error)}",
code=OrderErrorCode.TAX_ERROR.value,
)
diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.py
index 6d41d3c685..8bdac3852b 100644
--- a/saleor/graphql/order/mutations/order_lines_create.py
+++ b/saleor/graphql/order/mutations/order_lines_create.py
@@ -139,7 +139,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):
added_lines.append(line)
except TaxError as tax_error:
raise ValidationError(
- "Unable to calculate taxes - %s" % str(tax_error),
+ f"Unable to calculate taxes - {str(tax_error)}",
code=OrderErrorCode.TAX_ERROR.value,
)
return added_lines
diff --git a/saleor/graphql/order/sorters.py b/saleor/graphql/order/sorters.py
index fc99e3bac1..d9ca5d4eaf 100644
--- a/saleor/graphql/order/sorters.py
+++ b/saleor/graphql/order/sorters.py
@@ -34,7 +34,7 @@ class OrderSortField(graphene.Enum):
sort_name = self.name.lower().replace("_", " ")
return f"Sort orders by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_payment(queryset: QuerySet, **_kwargs) -> QuerySet:
diff --git a/saleor/graphql/page/sorters.py b/saleor/graphql/page/sorters.py
index 2aa812ceca..75ee726be9 100644
--- a/saleor/graphql/page/sorters.py
+++ b/saleor/graphql/page/sorters.py
@@ -25,7 +25,7 @@ class PageSortField(graphene.Enum):
if self.name == "CREATED_AT":
description += ADDED_IN_38
return description
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class PageSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/payment/enums.py b/saleor/graphql/payment/enums.py
index b6e7f6d412..c6aae29b9b 100644
--- a/saleor/graphql/payment/enums.py
+++ b/saleor/graphql/payment/enums.py
@@ -35,7 +35,7 @@ class OrderAction(graphene.Enum):
return "Represents a refund action."
if self == OrderAction.VOID:
return "Represents a void action."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
def description(enum):
diff --git a/saleor/graphql/plugins/sorters.py b/saleor/graphql/plugins/sorters.py
index 0e630ff319..bfd1dc8fb7 100644
--- a/saleor/graphql/plugins/sorters.py
+++ b/saleor/graphql/plugins/sorters.py
@@ -54,7 +54,7 @@ class PluginSortField(graphene.Enum):
}
if self.name in descriptions:
return f"Sort plugins by {descriptions[self.name]}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class PluginSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index b0f2d9dca2..19992927e2 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -850,7 +850,7 @@ class ProductVariantStocksUpdate(ProductVariantStocksCreate):
raise ValidationError(
{
"sku": ValidationError(
- "Couldn't resolve to a node: %s" % sku, code="not_found"
+ f"Couldn't resolve to a node: {sku}", code="not_found"
)
}
)
@@ -943,7 +943,7 @@ class ProductVariantStocksDelete(BaseMutation):
raise ValidationError(
{
"sku": ValidationError(
- "Couldn't resolve to a node: %s" % sku, code="not_found"
+ f"Couldn't resolve to a node: {sku}", code="not_found"
)
}
)
diff --git a/saleor/graphql/product/mutations/channels.py b/saleor/graphql/product/mutations/channels.py
index 4ab490024b..36e166a824 100644
--- a/saleor/graphql/product/mutations/channels.py
+++ b/saleor/graphql/product/mutations/channels.py
@@ -533,7 +533,7 @@ class ProductVariantChannelListingUpdate(BaseMutation):
raise ValidationError(
{
"sku": ValidationError(
- "Couldn't resolve to a node: %s" % sku, code="not_found"
+ f"Couldn't resolve to a node: {sku}", code="not_found"
)
}
)
diff --git a/saleor/graphql/product/mutations/digital_contents.py b/saleor/graphql/product/mutations/digital_contents.py
index 4d713f4246..40b6448c9d 100644
--- a/saleor/graphql/product/mutations/digital_contents.py
+++ b/saleor/graphql/product/mutations/digital_contents.py
@@ -232,7 +232,7 @@ class DigitalContentUpdate(BaseMutation):
)
if not hasattr(variant, "digital_content"):
- msg = "Variant %s doesn't have any digital content" % variant.id
+ msg = f"Variant {variant.id} doesn't have any digital content"
raise ValidationError(
{
"variantId": ValidationError(
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 82c8235995..b1c3a71176 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1124,7 +1124,7 @@ class ProductVariantCreate(ModelMutation):
raise ValidationError(
{
"sku": ValidationError(
- "Couldn't resolve to a node: %s" % object_sku,
+ f"Couldn't resolve to a node: {object_sku}",
code="not_found",
)
}
@@ -1290,7 +1290,7 @@ class ProductVariantDelete(ModelDeleteMutation):
raise ValidationError(
{
"sku": ValidationError(
- "Couldn't resolve to a node: %s" % node_sku,
+ f"Couldn't resolve to a node: {node_sku}",
code="not_found",
)
}
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index 266240b2c6..61d3964905 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -40,7 +40,7 @@ class CategorySortField(graphene.Enum):
]:
sort_name = self.name.lower().replace("_", " ")
return f"Sort categories by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_product_count(queryset: QuerySet, **_kwargs) -> QuerySet:
@@ -92,7 +92,7 @@ class CollectionSortField(graphene.Enum):
if extras := descrption_extras.get(self.name):
description += "".join(extras)
return description
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_product_count(queryset: QuerySet, **_kwargs) -> QuerySet:
@@ -184,7 +184,7 @@ class ProductOrderField(graphene.Enum):
}
if self.name in descriptions:
return f"Sort products by {descriptions[self.name]}"
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
@staticmethod
def qs_with_price(queryset: QuerySet, channel_slug: str) -> QuerySet:
@@ -270,7 +270,7 @@ class ProductVariantSortField(graphene.Enum):
sort_name = self.name.lower().replace("_", " ")
return f"Sort products variants by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class ProductVariantSortingInput(SortInputObjectType):
@@ -294,7 +294,7 @@ class ProductTypeSortField(graphene.Enum):
}
if self.name in descriptions:
return f"Sort products by {descriptions[self.name]}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class ProductTypeSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/shipping/utils.py b/saleor/graphql/shipping/utils.py
index 1acdd9e42d..cb32845943 100644
--- a/saleor/graphql/shipping/utils.py
+++ b/saleor/graphql/shipping/utils.py
@@ -16,7 +16,7 @@ def get_shipping_model_by_object_id(
raise ValidationError(
{
"id": ValidationError(
- "Couldn't resolve to a node: %s" % object_id, code="not_found"
+ f"Couldn't resolve to a node: {object_id}", code="not_found"
)
}
)
diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.py
index f87170322e..e938d8de47 100644
--- a/saleor/graphql/utils/filters.py
+++ b/saleor/graphql/utils/filters.py
@@ -10,13 +10,13 @@ def reporting_period_to_date(period):
elif period == ReportingPeriod.THIS_MONTH:
start_date = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
else:
- raise ValueError("Unknown period: %s" % period)
+ raise ValueError(f"Unknown period: {period}")
return start_date
def filter_by_period(queryset, period, field_name):
start_date = reporting_period_to_date(period)
- return queryset.filter(**{"%s__gte" % field_name: start_date})
+ return queryset.filter(**{f"{field_name}__gte": start_date})
def filter_range_field(qs, field, value):
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index 26a2cad685..b40b01a8f2 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -91,9 +91,7 @@ class GraphQLView(View):
module = importlib.import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError):
- raise ImportError(
- "Cannot import '%s' graphene middleware!" % middleware_name
- )
+ raise ImportError(f"Cannot import '{middleware_name}' graphene middleware!")
@observability.report_view
def dispatch(self, request, *args, **kwargs):
diff --git a/saleor/graphql/warehouse/sorters.py b/saleor/graphql/warehouse/sorters.py
index 6bcb7b42c3..c42821eec5 100644
--- a/saleor/graphql/warehouse/sorters.py
+++ b/saleor/graphql/warehouse/sorters.py
@@ -11,7 +11,7 @@ class WarehouseSortField(graphene.Enum):
if self.name in WarehouseSortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort warehouses by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class WarehouseSortingInput(SortInputObjectType):
diff --git a/saleor/graphql/webhook/mutations.py b/saleor/graphql/webhook/mutations.py
index 4d0214fb54..3b7370efd7 100644
--- a/saleor/graphql/webhook/mutations.py
+++ b/saleor/graphql/webhook/mutations.py
@@ -258,7 +258,7 @@ class WebhookDelete(ModelDeleteMutation):
app.webhooks.get(id=object_id)
except models.Webhook.DoesNotExist:
raise ValidationError(
- "Couldn't resolve to a node: %s" % node_id,
+ f"Couldn't resolve to a node: {node_id}",
code=WebhookErrorCode.GRAPHQL_ERROR,
)
diff --git a/saleor/graphql/webhook/sorters.py b/saleor/graphql/webhook/sorters.py
index 660652dc3f..11db56edac 100644
--- a/saleor/graphql/webhook/sorters.py
+++ b/saleor/graphql/webhook/sorters.py
@@ -11,7 +11,7 @@ class EventDeliverySortField(graphene.Enum):
if self.name in EventDeliverySortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort event deliveries by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class EventDeliverySortingInput(SortInputObjectType):
@@ -28,7 +28,7 @@ class EventDeliveryAttemptSortField(graphene.Enum):
if self.name in EventDeliveryAttemptSortField.__enum__._member_names_:
sort_name = self.name.lower().replace("_", " ")
return f"Sort event delivery attempts by {sort_name}."
- raise ValueError("Unsupported enum value: %s" % self.value)
+ raise ValueError(f"Unsupported enum value: {self.value}")
class EventDeliveryAttemptSortingInput(SortInputObjectType):
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 60b8d5e791..14cee02cf2 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -696,7 +696,7 @@ class Fulfillment(ModelWithMetadata):
@property
def composed_id(self):
- return "%s-%s" % (self.order.number, self.fulfillment_order)
+ return f"{self.order.number}-{self.fulfillment_order}"
def can_edit(self):
return self.status != FulfillmentStatus.CANCELED
diff --git a/saleor/payment/gateways/stripe/deprecated/tests/test_utils.py b/saleor/payment/gateways/stripe/deprecated/tests/test_utils.py
index 88b5a56b39..bf6e7edbaf 100644
--- a/saleor/payment/gateways/stripe/deprecated/tests/test_utils.py
+++ b/saleor/payment/gateways/stripe/deprecated/tests/test_utils.py
@@ -53,11 +53,10 @@ def test_get_currency_from_stripe():
def test_get_payment_billing_fullname(payment_dummy):
payment_info = create_payment_information(payment_dummy)
+ billing_last_name = payment_dummy.billing_last_name
+ billing_first_name = payment_dummy.billing_first_name
+ expected_fullname = f"{billing_last_name} {billing_first_name}"
- expected_fullname = "%s %s" % (
- payment_dummy.billing_last_name,
- payment_dummy.billing_first_name,
- )
assert get_payment_billing_fullname(payment_info) == expected_fullname
diff --git a/saleor/payment/gateways/stripe/deprecated/utils.py b/saleor/payment/gateways/stripe/deprecated/utils.py
index 7ecd9825a8..8bdd476125 100644
--- a/saleor/payment/gateways/stripe/deprecated/utils.py
+++ b/saleor/payment/gateways/stripe/deprecated/utils.py
@@ -80,7 +80,7 @@ def get_payment_billing_fullname(payment_information: PaymentData) -> str:
payment_billing = payment_information.billing
if not payment_billing:
return ""
- return "%s %s" % (payment_billing.last_name, payment_billing.first_name)
+ return f"{payment_billing.last_name} {payment_billing.first_name}"
def shipping_to_stripe_dict(shipping: AddressData) -> Dict:
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 2b96dc6eaf..2c8f21f364 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -207,11 +207,9 @@ class Payment(ModelWithMetadata):
]
def __repr__(self):
- return "Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)" % (
- self.gateway,
- self.is_active,
- self.created_at,
- self.charge_status,
+ return (
+ f"Payment(gateway={self.gateway}, is_active={self.is_active}, "
+ f"created={self.created_at}, charge_status={self.charge_status})"
)
def get_last_transaction(self):
@@ -335,10 +333,9 @@ class Transaction(models.Model):
ordering = ("pk",)
def __repr__(self):
- return "Transaction(type=%s, is_success=%s, created=%s)" % (
- self.kind,
- self.is_success,
- self.created_at,
+ return (
+ f"Transaction(type={self.kind}, is_success={self.is_success}, "
+ f"created={self.created_at})"
)
def get_amount(self):
diff --git a/saleor/plugins/__init__.py b/saleor/plugins/__init__.py
index 7cbc63325a..868e317e95 100644
--- a/saleor/plugins/__init__.py
+++ b/saleor/plugins/__init__.py
@@ -10,9 +10,7 @@ def discover_plugins_modules(plugins: List[str]):
try:
module_path, class_name = dotted_path.rsplit(".", 1)
except ValueError as err:
- raise ImportError(
- "%s doesn't look like a module path" % dotted_path
- ) from err
+ raise ImportError(f"{dotted_path} doesn't look like a module path") from err
module = importlib.import_module(module_path)
plugins_modules.append(module.__package__)
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index fefe83c357..6312b280dd 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -615,7 +615,7 @@ def get_order_tax_data(
) -> Dict[str, Any]:
data = get_order_request_data(order, config, tax_included)
response = get_cached_response_or_fetch(
- data, "order_%s" % order.id, config, force_refresh
+ data, f"order_{order.id}", config, force_refresh
)
if response and "error" in response:
raise TaxError(response.get("error"))
diff --git a/saleor/plugins/webhook/tasks.py b/saleor/plugins/webhook/tasks.py
index 4042800bb6..b2b4bebca3 100644
--- a/saleor/plugins/webhook/tasks.py
+++ b/saleor/plugins/webhook/tasks.py
@@ -153,7 +153,7 @@ def create_delivery_for_subscription_sync_event(
# in separate PR to ensure proper handling for all sync events.
# It was implemented when sync webhooks were handling payment events only.
raise PaymentError(
- "No payload was generated with subscription for event: %s" % event_type
+ f"No payload was generated with subscription for event: {event_type}"
)
event_payload = EventPayload.objects.create(payload=json.dumps({**data}))
event_delivery = EventDelivery.objects.create(
diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.py
index 8e205a9ce2..912df3138b 100644
--- a/saleor/product/tests/test_product.py
+++ b/saleor/product/tests/test_product.py
@@ -276,7 +276,7 @@ def test_digital_product_view(client, digital_content_url):
assert response.status_code == 200
assert response["content-type"] == "image/jpeg"
- assert response["content-disposition"] == 'attachment; filename="%s"' % filename
+ assert response["content-disposition"] == f'attachment; filename="{filename}"'
# Ensure an event was generated from downloading a digital good.
# The validity of this event is checked in test_digital_product_increment_download
diff --git a/saleor/settings.py b/saleor/settings.py
index 36bca8f95a..af1a586383 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -108,10 +108,11 @@ EMAIL_URL = os.environ.get("EMAIL_URL")
SENDGRID_USERNAME = os.environ.get("SENDGRID_USERNAME")
SENDGRID_PASSWORD = os.environ.get("SENDGRID_PASSWORD")
if not EMAIL_URL and SENDGRID_USERNAME and SENDGRID_PASSWORD:
- EMAIL_URL = "smtp://%s:%[email protected]:587/?tls=True" % (
- SENDGRID_USERNAME,
- SENDGRID_PASSWORD,
+ EMAIL_URL = (
+ f"smtp://{SENDGRID_USERNAME}"
+ f":{SENDGRID_PASSWORD}@smtp.sendgrid.net:587/?tls=True"
)
+
email_config = dj_email_url.parse(
EMAIL_URL or "console://[email protected]:console@example/"
)
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 497822f85d..00a493b656 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -216,13 +216,11 @@ class ShippingMethod(ModelWithMetadata):
def __repr__(self):
if self.type == ShippingMethodType.PRICE_BASED:
- return "ShippingMethod(type=%s)" % (self.type,)
- return "ShippingMethod(type=%s weight_range=(%s)" % (
- self.type,
- _get_weight_type_display(
- self.minimum_order_weight, self.maximum_order_weight
- ),
+ return f"ShippingMethod(type={self.type})"
+ weight_type_display = _get_weight_type_display(
+ self.minimum_order_weight, self.maximum_order_weight
)
+ return f"ShippingMethod(type={self.type} weight_range=({weight_type_display})"
class ShippingMethodPostalCodeRule(models.Model):
diff --git a/saleor/thumbnail/utils.py b/saleor/thumbnail/utils.py
index db5bc91c8c..119fa1f409 100644
--- a/saleor/thumbnail/utils.py
+++ b/saleor/thumbnail/utils.py
@@ -149,10 +149,8 @@ class ProcessedImage:
# Ensure any embedded ICC profile is preserved
save_kwargs["icc_profile"] = image.info.get("icc_profile")
- if hasattr(self, "preprocess_%s" % format):
- image, addl_save_kwargs = getattr(self, "preprocess_%s" % format)(
- image=image
- )
+ if hasattr(self, f"preprocess_{format}"):
+ image, addl_save_kwargs = getattr(self, f"preprocess_{format}")(image=image)
save_kwargs.update(addl_save_kwargs)
return image, save_kwargs