Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Allow preserving address extra fields not present in allowed once during address validation (#18846)
Iga Karbowiak2451f31a6a79
diff --git a/saleor/account/i18n.py b/saleor/account/i18n.pyindex 3c3091c828..545681348f 100644--- a/saleor/account/i18n.py+++ b/saleor/account/i18n.py@@ -111,6 +111,9 @@ class AddressForm(forms.ModelForm):def __init__(self, *args, **kwargs):autocomplete_type = kwargs.pop("autocomplete_type", None)self.enable_normalization = kwargs.pop("enable_normalization", True)+ self.preserve_all_address_fields = kwargs.pop(+ "preserve_all_address_fields", False+ )super().__init__(*args, **kwargs)# countries order was taken as defined in the model,# not being sorted accordingly to the selected language@@ -175,9 +178,25 @@ class CountryAwareAddressForm(AddressForm):error_msg = "This value is not valid for the address."self.add_error(field, ValidationError(error_msg, code=error_code))+ def _restore_non_allowed_fields(self, data, original_data):+ """Restore original values for fields not allowed by country validation rules.++ This preserves fields that exist in the original address but are not part+ of the country's standard address format, preventing data loss during+ address normalization.+ """+ rules = i18naddress.get_validation_rules(+ {"country_code": data.get("country_code", "")}+ )+ for field in i18naddress.KNOWN_FIELDS - rules.allowed_fields:+ original_value = original_data.get(field)+ if original_value:+ data[field] = original_value+def validate_address(self, data):try:data["country_code"] = data.get("country", "")+ original_data = dict(data)street_address_1 = data.get("street_address_1", "")street_address_2 = data.get("street_address_2", "")@@ -189,6 +208,9 @@ class CountryAwareAddressForm(AddressForm):if getattr(self, "enable_normalization", True):data = normalized_datadel data["sorting_code"]++ if getattr(self, "preserve_all_address_fields", False):+ self._restore_non_allowed_fields(data, original_data)except i18naddress.InvalidAddressError as exc:self.add_field_errors(exc.errors)self.log_errors()diff --git a/saleor/account/tests/test_account.py b/saleor/account/tests/test_account.pyindex 4ad2203364..e632e796df 100644--- a/saleor/account/tests/test_account.py+++ b/saleor/account/tests/test_account.py@@ -392,3 +392,51 @@ def test_substitute_invalid_values(country_area_input, country_area_output, is_vassert "country_area" in errorselse:assert not errors+++def test_validate_address_switzerland_preserves_country_area_when_flag_enabled():+ # given - Switzerland doesn't have country_area in allowed fields+ data = {+ "first_name": "John",+ "last_name": "Doe",+ "country": "CH",+ "country_area": "Zurich",+ "city": "Zurich",+ "street_address_1": "Bahnhofstrasse 1",+ "postal_code": "8001",+ }++ # when+ form = forms.get_address_form(+ data, country_code="CH", preserve_all_address_fields=True+ )++ # then+ assert form.is_valid()+ cleaned_data = form.cleaned_data+ # country_area should be preserved even though it's not in CH allowed fields+ assert cleaned_data.get("country_area") == data["country_area"]+++def test_validate_address_switzerland_removes_country_area_when_flag_disabled():+ # given - Switzerland doesn't have country_area in allowed fields+ data = {+ "first_name": "John",+ "last_name": "Doe",+ "country": "CH",+ "country_area": "Zurich",+ "city": "Zurich",+ "street_address_1": "Bahnhofstrasse 1",+ "postal_code": "8001",+ }++ # when+ form = forms.get_address_form(+ data, country_code="CH", preserve_all_address_fields=False+ )++ # then+ assert form.is_valid()+ cleaned_data = form.cleaned_data+ # country_area should be removed during normalization+ assert not cleaned_data.get("country_area")diff --git a/saleor/graphql/account/i18n.py b/saleor/graphql/account/i18n.pyindex 7f30c9ddac..9e8803095c 100644--- a/saleor/graphql/account/i18n.py+++ b/saleor/graphql/account/i18n.py@@ -15,6 +15,7 @@ from ...permission.enums import ()from ...permission.utils import all_permissions_requiredfrom ..core import ResolveInfo+from ..site.dataloaders import get_site_promiseSKIP_ADDRESS_VALIDATION_PERMISSION_MAP: dict[str, list[BasePermissionEnum]] = {"addressCreate": [AccountPermissions.MANAGE_USERS],@@ -77,6 +78,7 @@ class I18nMixin:format_check=True,required_check=True,enable_normalization=True,+ preserve_all_address_fields=False,):phone = address_data.get("phone", None)params = {"address_type": address_type} if address_type else {}@@ -100,6 +102,7 @@ class I18nMixin:address_data.get("country"),instance=instance,enable_normalization=enable_normalization,+ preserve_all_address_fields=preserve_all_address_fields,)validation_skipped = Falseif not address_form.is_valid():@@ -152,10 +155,10 @@ class I18nMixin:def validate_address(cls,address_data: dict,+ info: ResolveInfo,*,address_type: str | None = None,instance: Address | None = None,- info=None,format_check=True,required_check=True,enable_normalization=True,@@ -174,12 +177,16 @@ class I18nMixin:cls.can_skip_address_validation(info)format_check = False+ site = get_site_promise(info.context).get()+ preserve_all_address_fields = site.settings.preserve_all_address_fields+address_form = cls._validate_address_form(address_data,address_type,format_check=format_check,required_check=required_check,enable_normalization=enable_normalization,+ preserve_all_address_fields=preserve_all_address_fields,)address_data = address_form.cleaned_datadiff --git a/saleor/graphql/account/tests/mutations/staff/test_address_create.py b/saleor/graphql/account/tests/mutations/staff/test_address_create.pyindex 2748c56ec5..96dc90f10f 100644--- a/saleor/graphql/account/tests/mutations/staff/test_address_create.py+++ b/saleor/graphql/account/tests/mutations/staff/test_address_create.py@@ -21,6 +21,7 @@ ADDRESS_CREATE_MUTATION = """address {idcity+ countryAreacountry {code}@@ -206,3 +207,68 @@ def test_create_address_skip_validation(assert new_address.postal_code == wrong_postal_codeassert new_address.validation_skipped is Trueassert new_address.metadata == {"public": "public_value"}+++def test_create_address_country_area_cleared_by_default(+ staff_api_client, customer_user, permission_manage_users, site_settings+):+ """Swiss addresses don't use country_area; it should be cleared by default."""+ # given+ user_id = graphene.Node.to_global_id("User", customer_user.id)+ address_data = {+ "firstName": "John",+ "lastName": "Doe",+ "streetAddress1": "Bahnhofstrasse 1",+ "city": "Zürich",+ "postalCode": "8001",+ "country": "CH",+ "countryArea": "Zürich",+ }+ variables = {"user": user_id, "address": address_data}++ # when+ response = staff_api_client.post_graphql(+ ADDRESS_CREATE_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["addressCreate"]+ assert not data["errors"]+ assert data["address"]["countryArea"] == ""+++def test_create_address_country_area_preserved_when_flag_enabled(+ staff_api_client, customer_user, permission_manage_users, site_settings+):+ """When preserve_all_address_fields is True, country_area should be kept."""+ # given+ site_settings.preserve_all_address_fields = True+ site_settings.save(update_fields=["preserve_all_address_fields"])++ user_id = graphene.Node.to_global_id("User", customer_user.id)+ address_data = {+ "firstName": "John",+ "lastName": "Doe",+ "streetAddress1": "Bahnhofstrasse 1",+ "city": "Zürich",+ "postalCode": "8001",+ "country": "CH",+ "countryArea": "Zürich",+ }+ variables = {"user": user_id, "address": address_data}++ # when+ response = staff_api_client.post_graphql(+ ADDRESS_CREATE_MUTATION,+ variables,+ permissions=[permission_manage_users],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["addressCreate"]+ assert not data["errors"]+ assert data["address"]["countryArea"] == address_data["countryArea"]diff --git a/saleor/graphql/account/tests/test_i18n.py b/saleor/graphql/account/tests/test_i18n.pyindex d405b674bc..c9bfae4c8b 100644--- a/saleor/graphql/account/tests/test_i18n.py+++ b/saleor/graphql/account/tests/test_i18n.py@@ -13,7 +13,7 @@ from ..i18n import I18nMixinlogger = logging.getLogger(__name__)-def test_validate_address():+def test_validate_address(info):# givenaddress_data = {"first_name": "John Saleor",@@ -29,14 +29,14 @@ def test_validate_address():}# whenaddress = I18nMixin.validate_address(- address_data, address_type=AddressType.SHIPPING+ address_data, address_type=AddressType.SHIPPING, info=info)# thenassert address-def test_validate_address_invalid_postal_code():+def test_validate_address_invalid_postal_code(info):# givenaddress_data = {"first_name": "John Saleor",@@ -53,13 +53,15 @@ def test_validate_address_invalid_postal_code():# whenwith pytest.raises(ValidationError) as error:- I18nMixin.validate_address(address_data, address_type=AddressType.SHIPPING)+ I18nMixin.validate_address(+ address_data, address_type=AddressType.SHIPPING, info=info+ )# thenassert len(error.value.error_dict["postal_code"]) == 2-def test_validate_address_no_country_code():+def test_validate_address_no_country_code(info):# givenaddress_data = {"first_name": "John Saleor",@@ -76,13 +78,15 @@ def test_validate_address_no_country_code():# whenwith pytest.raises(ValidationError) as error:- I18nMixin.validate_address(address_data, address_type=AddressType.SHIPPING)+ I18nMixin.validate_address(+ address_data, address_type=AddressType.SHIPPING, info=info+ )# thenassert len(error.value.error_dict["country"]) == 1-def test_validate_address_no_city():+def test_validate_address_no_city(info):# givenaddress_data = {"first_name": "John Saleor",@@ -99,7 +103,9 @@ def test_validate_address_no_city():# whenwith pytest.raises(ValidationError) as error:- I18nMixin.validate_address(address_data, address_type=AddressType.SHIPPING)+ I18nMixin.validate_address(+ address_data, address_type=AddressType.SHIPPING, info=info+ )# thenassert len(error.value.error_dict["city"]) == 1diff --git a/saleor/graphql/checkout/mutations/checkout_complete.py b/saleor/graphql/checkout/mutations/checkout_complete.pyindex 440a9b2ac5..0f570a5373 100644--- a/saleor/graphql/checkout/mutations/checkout_complete.py+++ b/saleor/graphql/checkout/mutations/checkout_complete.py@@ -173,6 +173,7 @@ class CheckoutComplete(BaseMutation, I18nMixin):cls,checkout_info: CheckoutInfo,lines: list[CheckoutLineInfo],+ info: ResolveInfo,):"""Validate checkout addresses.@@ -200,6 +201,7 @@ class CheckoutComplete(BaseMutation, I18nMixin):required_check=True,enable_normalization=True,instance=shipping_address,+ info=info,)if shipping_address_data != shipping_address.as_data():shipping_address.save()@@ -222,6 +224,7 @@ class CheckoutComplete(BaseMutation, I18nMixin):required_check=True,enable_normalization=True,instance=billing_address,+ info=info,)if billing_address_data != billing_address.as_data():billing_address.save()@@ -317,7 +320,7 @@ class CheckoutComplete(BaseMutation, I18nMixin):checkout_info = fetch_checkout_info(checkout, lines, manager)try:- cls.validate_checkout_addresses(checkout_info, lines)+ cls.validate_checkout_addresses(checkout_info, lines, info)except models.Checkout.DoesNotExist as e:order = order_models.Order.objects.get_by_checkout_token(checkout_info.checkout.tokendiff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex bbe9ef055c..68fb4fed3f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -14974,6 +14974,15 @@ type Shop implements ObjectWithMetadata {"""availableTaxApps: [App!]!+ """+ When enabled, address fields that are not valid for a given country (according to Google's i18n address data) will be preserved instead of being removed during validation. Validation errors are still returned.++ Added in Saleor 3.22.++ Requires one of the following permissions: MANAGE_SETTINGS.+ """+ preserveAllAddressFields: Boolean!+"""Include taxes in prices."""includeTaxesInPrices: Boolean! @deprecated(reason: "Use `Channel.taxConfiguration.pricesEnteredWithTax` to determine whether prices are entered with tax.")@@ -22965,6 +22974,13 @@ input ShopSettingsInput {"""privateMetadata: [MetadataInput!]+ """+ When enabled, address fields that are not valid for a given country (according to Google's i18n address data) will be preserved instead of being removed during validation. Validation errors are still returned.++ Added in Saleor 3.22.+ """+ preserveAllAddressFields: Boolean+"""Include taxes in prices."""includeTaxesInPrices: Boolean @deprecated(reason: "Use `taxConfigurationUpdate` mutation to configure this setting per channel or country.")diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.pyindex d17dbe80b0..b52c7ff465 100644--- a/saleor/graphql/shop/mutations/shop_settings_update.py+++ b/saleor/graphql/shop/mutations/shop_settings_update.py@@ -91,6 +91,15 @@ class ShopSettingsInput(graphene.InputObjectType):f"{MetadataInputDescription.PRIVATE_METADATA_INPUT}",required=False,)+ preserve_all_address_fields = graphene.Boolean(+ description=(+ "When enabled, address fields that are not valid for a given country "+ "(according to Google's i18n address data) will be preserved instead of "+ "being removed during validation. Validation errors are still returned."+ )+ + ADDED_IN_322,+ )+# deprecatedinclude_taxes_in_prices = graphene.Boolean(description=(diff --git a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.pyindex 2de7005625..5a4ef01b81 100644--- a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py@@ -24,6 +24,7 @@ SHOP_SETTINGS_UPDATE_MUTATION = """limitQuantityPerCheckoutallowLoginWithoutConfirmationuseLegacyUpdateWebhookEmission+ preserveAllAddressFields}errors {field@@ -68,6 +69,7 @@ def test_shop_digital_content_settings_mutation(assert site_settings.automatic_fulfillment_digital_productsassert site_settings.default_digital_max_downloads == max_downloadsassert site_settings.default_digital_url_valid_days == url_valid_days+ assert site_settings.preserve_all_address_fields is Falsedef test_shop_settings_mutation(@@ -307,6 +309,69 @@ def test_shop_customer_set_password_url_update_invalid_url(assert not site_settings.customer_set_password_url+MUTATION_UPDATE_PRESERVE_ALL_ADDRESS_FIELDS = """+ mutation updateSettings($input: ShopSettingsInput!) {+ shopSettingsUpdate(input: $input) {+ shop {+ preserveAllAddressFields+ }+ errors {+ field+ message+ code+ }+ }+ }+"""+++def test_shop_settings_update_preserve_all_address_fields_enable(+ staff_api_client, site_settings, permission_manage_settings+):+ # given+ assert site_settings.preserve_all_address_fields is False+ variables = {"input": {"preserveAllAddressFields": True}}++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PRESERVE_ALL_ADDRESS_FIELDS,+ variables,+ permissions=[permission_manage_settings],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["shopSettingsUpdate"]+ assert not data["errors"]+ assert data["shop"]["preserveAllAddressFields"] is True+ site_settings.refresh_from_db()+ assert site_settings.preserve_all_address_fields is True+++def test_shop_settings_update_preserve_all_address_fields_disable(+ staff_api_client, site_settings, permission_manage_settings+):+ # given+ site_settings.preserve_all_address_fields = True+ site_settings.save(update_fields=["preserve_all_address_fields"])+ variables = {"input": {"preserveAllAddressFields": False}}++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_PRESERVE_ALL_ADDRESS_FIELDS,+ variables,+ permissions=[permission_manage_settings],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["shopSettingsUpdate"]+ assert not data["errors"]+ assert data["shop"]["preserveAllAddressFields"] is False+ site_settings.refresh_from_db()+ assert site_settings.preserve_all_address_fields is False++MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS = """mutation updateDefaultSenderSettings($input: ShopSettingsInput!) {shopSettingsUpdate(input: $input) {diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex c17d3dc9be..777f391d0b 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -370,6 +370,18 @@ class Shop(graphene.ObjectType):],)+ preserve_all_address_fields = PermissionsField(+ graphene.Boolean,+ description=(+ "When enabled, address fields that are not valid for a given country "+ "(according to Google's i18n address data) will be preserved instead of "+ "being removed during validation. Validation errors are still returned."+ )+ + ADDED_IN_322,+ permissions=[SitePermissions.MANAGE_SETTINGS],+ required=True,+ )+# deprecatedinclude_taxes_in_prices = graphene.Boolean(description="Include taxes in prices.",@@ -675,6 +687,11 @@ class Shop(graphene.ObjectType):site.settings, info, keys=keys)+ @staticmethod+ @load_site_callback+ def resolve_preserve_all_address_fields(_, _info, site):+ return site.settings.preserve_all_address_fields+@staticmethod@load_site_callbackdef resolve_use_legacy_update_webhook_emission(_, _info, site):diff --git a/saleor/site/migrations/0044_sitesettings_preserve_all_address_fields.py b/saleor/site/migrations/0044_sitesettings_preserve_all_address_fields.pynew file mode 100644index 0000000000..9c9862e360--- /dev/null+++ b/saleor/site/migrations/0044_sitesettings_preserve_all_address_fields.py@@ -0,0 +1,20 @@+# Generated by Django 5.2.11 on 2026-02-16 11:43++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("site", "0043_sitesettings_use_legacy_update_webhook_emission"),+ ]++ operations = [+ migrations.AddField(+ model_name="sitesettings",+ name="preserve_all_address_fields",+ field=models.BooleanField(+ db_default=False,+ default=False,+ ),+ ),+ ]diff --git a/saleor/site/migrations/0045_merge_20260223_0944.py b/saleor/site/migrations/0045_merge_20260223_0944.pynew file mode 100644index 0000000000..7510c5a00e--- /dev/null+++ b/saleor/site/migrations/0045_merge_20260223_0944.py@@ -0,0 +1,12 @@+# Generated by Django 5.2.11 on 2026-02-23 08:44++from django.db import migrations+++class Migration(migrations.Migration):+ dependencies = [+ ("site", "0044_sitesettings_instance_id_and_more"),+ ("site", "0044_sitesettings_preserve_all_address_fields"),+ ]++ operations = []diff --git a/saleor/site/models.py b/saleor/site/models.pyindex 4e74ed4704..f32ff33cbe 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -71,6 +71,10 @@ class SiteSettings(ModelWithMetadata):customer_set_password_url = models.CharField(max_length=255, blank=True, null=True)fulfillment_auto_approve = models.BooleanField(default=True)fulfillment_allow_unpaid = models.BooleanField(default=True)+ preserve_all_address_fields = models.BooleanField(+ default=False,+ db_default=False,+ )# Duration in minutesreserve_stock_duration_anonymous_user = models.IntegerField(blank=True, null=True)