Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Create function for checking slug value from input and generating value if needed
IKarbowiak7c2df714e9f7
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.pyindex aa2785acde..cd0ac05965 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -121,7 +121,7 @@ def create_thumbnails(pk, model, size_set, image_attr=None):def generate_unique_slug(- instance: Type[Model], slugable_value, slug_field_name: str = "slug",+ instance: Type[Model], slugable_value: str, slug_field_name: str = "slug",) -> str:"""Create unique slug for model instance.diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.pyindex 38104fcd58..e23a530bbd 100644--- a/saleor/graphql/core/utils/__init__.py+++ b/saleor/graphql/core/utils/__init__.py@@ -1,11 +1,17 @@import binascii-from typing import Union+from typing import TYPE_CHECKING, Type, Unionimport grapheneimport graphene_django_optimizer as gql_optimizerfrom django.core.exceptions import ValidationErrorfrom graphene import ObjectType+from ....core.utils import generate_unique_slug++if TYPE_CHECKING:+ # flake8: noqa+ from django.db.models import Model+def clean_seo_fields(data):"""Extract and assign seo fields to given dictionary."""@@ -62,3 +68,32 @@ def get_node_optimized(qs, lookup, info):qs = qs.filter(**lookup)qs = gql_optimizer.query(qs, info)return qs[0] if qs else None+++def validate_slug_and_generate_if_needed(+ instance: Type["Model"],+ slugable_field: str,+ cleaned_input: dict,+ slug_field_name: str = "slug",+) -> dict:+ """Validate slug from input amd generate in create mutation if is not given."""+ # update mutation - just check if value is not empty+ if getattr(instance, slug_field_name):+ validate_slug_value(cleaned_input)+ return cleaned_input++ # create mutation - generate slug if slug value is empty+ slug = cleaned_input.get(slug_field_name)+ if not slug and slugable_field in cleaned_input:+ slug = generate_unique_slug(instance, cleaned_input[slugable_field])+ cleaned_input[slug_field_name] = slug+ return cleaned_input+++def validate_slug_value(cleaned_input, slug_field_name: str = "slug"):+ if slug_field_name in cleaned_input:+ slug = cleaned_input[slug_field_name]+ if not slug:+ raise ValidationError(+ f"{slug_field_name} cannot by blank.", code="required"+ )