Skip to content

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

Add translation interface

Pacu2d3a494791274
diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.py
index bd6e27ecf0..5e2e722b50 100644
--- a/saleor/checkout/views/__init__.py
+++ b/saleor/checkout/views/__init__.py
@@ -114,7 +114,7 @@ def cart_index(request, cart):
lines = lines.prefetch_related(
'variant__product__collections',
'variant__product__images',
- 'variant__product__product_type__variant_attributes')
+ 'variant__product__product_type__variant_attributes__translations')
for line in lines:
initial = {'quantity': line.quantity}
form = ReplaceCartLineForm(
@@ -217,7 +217,7 @@ def cart_summary(request, cart):
first_image = line.variant.get_first_image()
return {
'product': line.variant.product,
- 'variant': line.variant.name,
+ 'variant': line.variant,
'quantity': line.quantity,
'image': first_image,
'line_total': line.get_total(discounts, taxes),
diff --git a/saleor/core/context_processors.py b/saleor/core/context_processors.py
index 97af7f4754..794b4a166e 100644
--- a/saleor/core/context_processors.py
+++ b/saleor/core/context_processors.py
@@ -22,7 +22,8 @@ def default_currency(request):
# pylint: disable=W0613
def navigation(request):
menus = Menu.objects.prefetch_related(
- 'items__collection', 'items__category', 'items__page'
+ 'items__collection', 'items__category', 'items__page',
+ 'items__translations'
).filter(items__parent=None)
return {NAVIGATION_CONTEXT_NAME: list(menus)}
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index 519ec15a00..b7e8ba3ad0 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -7,8 +7,8 @@ from ...utils import create_superuser
from ...utils.random_data import (
add_address_to_admin, create_collections_by_schema, create_menus,
create_orders, create_page, create_product_sales,
- create_products_by_schema, create_shipping_methods, create_users,
- create_vouchers, set_featured_products)
+ create_products_by_schema, create_shipping_methods, create_translations,
+ create_users, create_vouchers, set_featured_products)
class Command(BaseCommand):
@@ -53,27 +53,27 @@ class Command(BaseCommand):
def handle(self, *args, **options):
self.make_database_faster()
create_images = not options['withoutimages']
- for msg in create_shipping_methods():
- self.stdout.write(msg)
- create_products_by_schema(self.placeholders_dir, 10, create_images,
- stdout=self.stdout)
- for msg in create_product_sales(5):
- self.stdout.write(msg)
- for msg in create_vouchers():
- self.stdout.write(msg)
- for msg in create_users(20):
- self.stdout.write(msg)
- for msg in create_orders(20):
- self.stdout.write(msg)
- for msg in set_featured_products(16):
- self.stdout.write(msg)
- for msg in create_collections_by_schema(self.placeholders_dir):
- self.stdout.write(msg)
- for msg in create_page():
- self.stdout.write(msg)
- for msg in create_menus():
- self.stdout.write(msg)
-
+ # for msg in create_shipping_methods():
+ # self.stdout.write(msg)
+ # create_products_by_schema(
+ # self.placeholders_dir, 10, create_images, stdout=self.stdout)
+ # for msg in create_product_sales(5):
+ # self.stdout.write(msg)
+ # for msg in create_vouchers():
+ # self.stdout.write(msg)
+ # for msg in create_users(20):
+ # self.stdout.write(msg)
+ # for msg in create_orders(20):
+ # self.stdout.write(msg)
+ # for msg in set_featured_products(16):
+ # self.stdout.write(msg)
+ # for msg in create_collections_by_schema(self.placeholders_dir):
+ # self.stdout.write(msg)
+ # for msg in create_page():
+ # self.stdout.write(msg)
+ # for msg in create_menus():
+ # self.stdout.write(msg)
+ create_translations()
if options['createsuperuser']:
credentials = {'email': '[email protected]', 'password': 'admin'}
msg = create_superuser(credentials)
diff --git a/saleor/core/templatetags/attributes.py b/saleor/core/templatetags/attributes.py
index 506e0c10c9..d68a163926 100644
--- a/saleor/core/templatetags/attributes.py
+++ b/saleor/core/templatetags/attributes.py
@@ -10,5 +10,5 @@ def get_object_properties(object, properties):
for property in properties:
attribute = getattr(object, property, '')
if attribute:
- return attribute
+ return getattr(object.translated, property)
return ''
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 0b28e0a3bc..770f66db95 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -22,7 +22,7 @@ from ...core.utils.taxes import get_tax_rate_by_name, get_taxes_for_country
from ...core.utils.text import strip_html_and_truncate
from ...discount import DiscountValueType, VoucherType
from ...discount.models import Sale, Voucher
-from ...menu.models import Menu
+from ...menu.models import Menu, MenuItem
from ...order.models import Fulfillment, Order, Payment
from ...order.utils import update_order_status
from ...page.models import Page
@@ -33,6 +33,7 @@ from ...product.thumbnails import create_product_thumbnails
from ...product.utils.attributes import get_name_from_attributes
from ...shipping.models import ANY_COUNTRY, ShippingMethod
from ...shipping.utils import get_taxed_shipping_price
+from ...site.models import SiteSettings
fake = Factory.create()
@@ -649,3 +650,70 @@ def get_product_list_images_dir(placeholder_dir):
def get_image(image_dir, image_name):
img_path = os.path.join(image_dir, image_name)
return File(open(img_path, 'rb'))
+
+
+def create_translations():
+ # Helper function for debugging storefront
+ from saleor.product.models import (
+ AttributeChoiceValueTranslation,
+ CategoryTranslation, CollectionTranslation, ProductTranslation,
+ ProductVariantTranslation, ProductAttributeTranslation)
+ from saleor.page.models import PageTranslation
+ from saleor.menu.models import MenuItemTranslation
+ from saleor.site.models import SiteSettingsTranslation
+
+ for i, category in enumerate(Category.objects.all()):
+ CategoryTranslation.objects.create(
+ language_code='pl', name='Kategoria %s' % category.pk,
+ category=category,
+ seo_title='Seo tytul kategoria %s' % category.pk,
+ seo_description='Seo opis kategoria %s' % category.pk)
+
+ for i, product in enumerate(Product.objects.all()):
+ ProductTranslation.objects.create(
+ language_code='pl', name='Produkt %s' % product.pk,
+ product=product, description='Opis produktu %s' % product.pk,
+ seo_title='Seo tytul produkt %s' % product.pk,
+ seo_description='Seo opis produkt %s' % product.pk)
+
+ for i, variant in enumerate(ProductVariant.objects.all()):
+ ProductVariantTranslation.objects.create(
+ language_code='pl',
+ name='Produkt %s Wariant %s' % (variant.product.pk, variant.pk),
+ product_variant=variant)
+
+ for i, collection in enumerate(Collection.objects.all()):
+ CollectionTranslation.objects.create(
+ language_code='pl', name='Kolekcja %s' % collection.pk,
+ collection=collection,
+ seo_title='Seo tytul kolekcja %s' % collection.pk,
+ seo_description='Seo opis kolekcja %s' % collection.pk)
+
+ for i, menu_item in enumerate(MenuItem.objects.all()):
+ name = 'Przedmiot %s' % menu_item.pk
+ MenuItemTranslation.objects.create(
+ language_code='pl', name=name,
+ menu_item=menu_item)
+
+ for i, page in enumerate(Page.objects.all()):
+ PageTranslation.objects.create(
+ language_code='pl', title='Strona %s' % page.pk,
+ page=page, content='Zawartosc strony %s' % page.pk,
+ seo_title='Seo tytul strona %s' % page.pk,
+ seo_description='Seo opis strona %s' % page.pk)
+
+ for attr in ProductAttribute.objects.all():
+ ProductAttributeTranslation.objects.create(
+ language_code='pl', name='Atrybut %s' % attr.pk,
+ product_attribute=attr)
+
+ for value in AttributeChoiceValue.objects.all():
+ AttributeChoiceValueTranslation.objects.create(
+ language_code='pl', name='Wartość %s' % value.pk,
+ attribute_choice_value=value)
+
+ for site_set in SiteSettings.objects.all():
+ SiteSettingsTranslation.objects.create(
+ site_settings=site_set, language_code='pl',
+ header_text='Tekst nagłówka po polsku %s' % site_set.pk,
+ description='Opis strony, tez po polsku %s' % site_set.pk)
diff --git a/saleor/core/utils/translations.py b/saleor/core/utils/translations.py
new file mode 100644
index 0000000000..86a32be820
--- /dev/null
+++ b/saleor/core/utils/translations.py
@@ -0,0 +1,28 @@
+from django.utils.translation import get_language
+
+
+class TranslationWrapper(object):
+ def __init__(self, instance, locale):
+ self.instance = instance
+ self.translation = next((
+ t for t in instance.translations.all()
+ if t.language_code == locale), None)
+
+ def __getattr__(self, item):
+ if all([
+ item not in ['id', 'pk'],
+ self.translation is not None,
+ hasattr(self.translation, item)]):
+ return getattr(self.translation, item)
+ return getattr(self.instance, item)
+
+ def __str__(self):
+ instance = self.translation or self.instance
+ return str(instance)
+
+
+class TranslationProxy(object):
+
+ def __get__(self, instance, owner):
+ locale = get_language()
+ return TranslationWrapper(instance, locale)
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index 745a50f4d9..43ba626b5d 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -251,8 +251,7 @@ class Category(CountableDjangoObjectType):
return self.children.distinct()
def resolve_url(self, info):
- ancestors = self.get_ancestors().distinct()
- return self.get_absolute_url(ancestors)
+ return self.get_absolute_url()
def resolve_products(self, info, **kwargs):
qs = models.Product.objects.available_products()
diff --git a/saleor/menu/models.py b/saleor/menu/models.py
index cb70c80b77..7f5251ac3f 100644
--- a/saleor/menu/models.py
+++ b/saleor/menu/models.py
@@ -4,6 +4,7 @@ from mptt.managers import TreeManager
from mptt.models import MPTTModel
from ..core.models import SortableModel
+from ..core.utils.translations import TranslationProxy
from ..page.models import Page
from ..product.models import Category, Collection
@@ -39,6 +40,7 @@ class MenuItem(MPTTModel, SortableModel):
objects = models.Manager()
tree = TreeManager()
+ translated = TranslationProxy()
class Meta:
ordering = ('sort_order',)
@@ -79,3 +81,18 @@ class MenuItem(MPTTModel, SortableModel):
def get_url(self):
linked_object = self.linked_object
return linked_object.get_absolute_url() if linked_object else self.url
+
+
+class MenuItemTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ menu_item = models.ForeignKey(
+ MenuItem, related_name='translations', on_delete=models.CASCADE)
+ name = models.CharField(max_length=128)
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, name=%r, menu_item_pk=%r)' % (
+ class_.__name__, self.pk, self.name, self.menu_item_id)
+
+ def __str__(self):
+ return self.name
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 544ff121d4..e56ef6362f 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -20,7 +20,6 @@ from ..core.models import BaseNote
from ..core.utils import build_absolute_uri
from ..core.utils.taxes import ZERO_TAXED_MONEY
from ..discount.models import Voucher
-from ..product.models import ProductVariant
from ..shipping.models import ShippingMethodCountry
@@ -181,7 +180,7 @@ class OrderLine(models.Model):
order = models.ForeignKey(
Order, related_name='lines', editable=False, on_delete=models.CASCADE)
variant = models.ForeignKey(
- ProductVariant, related_name='+', on_delete=models.SET_NULL,
+ 'product.ProductVariant', related_name='+', on_delete=models.SET_NULL,
blank=True, null=True)
# max_length is as produced by ProductVariant's display_product method
product_name = models.CharField(max_length=386)
diff --git a/saleor/page/models.py b/saleor/page/models.py
index a6db74ca4c..f966ad55f8 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -6,7 +6,8 @@ from django.urls import reverse
from django.utils.translation import pgettext_lazy
from ..core.utils import build_absolute_uri
-from ..seo.models import SeoModel
+from ..core.utils.translations import TranslationProxy
+from ..seo.models import SeoModel, SeoModelTranslation
class PageQuerySet(models.QuerySet):
@@ -26,6 +27,7 @@ class Page(SeoModel):
available_on = models.DateField(blank=True, null=True)
objects = PageQuerySet.as_manager()
+ translated = TranslationProxy()
class Meta:
ordering = ('slug',)
@@ -41,3 +43,19 @@ class Page(SeoModel):
def get_full_url(self):
return build_absolute_uri(self.get_absolute_url())
+
+
+class PageTranslation(SeoModelTranslation):
+ language_code = models.CharField(max_length=10)
+ page = models.ForeignKey(
+ Page, related_name='translations', on_delete=models.CASCADE)
+ title = models.CharField(max_length=255, blank=True)
+ content = models.TextField()
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, title=%r, page_pk=%r)' % (
+ class_.__name__, self.pk, self.title, self.page_id)
+
+ def __str__(self):
+ return self.title
diff --git a/saleor/product/filters.py b/saleor/product/filters.py
index c82e9a65bb..45792c9411 100644
--- a/saleor/product/filters.py
+++ b/saleor/product/filters.py
@@ -39,12 +39,12 @@ class ProductFilter(SortedFilterSet):
q_variant_attributes = self._get_variant_attributes_lookup()
product_attributes = (
ProductAttribute.objects.all()
- .prefetch_related('values')
+ .prefetch_related('translations', 'values__translations')
.filter(q_product_attributes)
.distinct())
variant_attributes = (
ProductAttribute.objects.all()
- .prefetch_related('values')
+ .prefetch_related('translations', 'values__translations')
.filter(q_variant_attributes)
.distinct())
return product_attributes, variant_attributes
@@ -60,7 +60,7 @@ class ProductFilter(SortedFilterSet):
for attribute in self.product_attributes:
filters[attribute.slug] = MultipleChoiceFilter(
name='attributes__%s' % attribute.pk,
- label=attribute.name,
+ label=attribute.translated.name,
widget=CheckboxSelectMultiple,
choices=self._get_attribute_choices(attribute))
return filters
@@ -70,13 +70,15 @@ class ProductFilter(SortedFilterSet):
for attribute in self.variant_attributes:
filters[attribute.slug] = MultipleChoiceFilter(
name='variants__attributes__%s' % attribute.pk,
- label=attribute.name,
+ label=attribute.translated.name,
widget=CheckboxSelectMultiple,
choices=self._get_attribute_choices(attribute))
return filters
def _get_attribute_choices(self, attribute):
- return [(choice.pk, choice.name) for choice in attribute.values.all()]
+ return [
+ (choice.pk, choice.translated.name)
+ for choice in attribute.values.all()]
def validate_sort_by(self, value):
if value.strip('-') not in SORT_BY_FIELDS:
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 49d67b3776..364f8676e8 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -21,8 +21,9 @@ from versatileimagefield.fields import PPOIField, VersatileImageField
from ..core.exceptions import InsufficientStock
from ..core.models import SortableModel
from ..core.utils.taxes import DEFAULT_TAX_RATE_NAME, apply_tax_to_price
+from ..core.utils.translations import TranslationProxy
from ..discount.utils import calculate_discounted_price
-from ..seo.models import SeoModel
+from ..seo.models import SeoModel, SeoModelTranslation
class Category(MPTTModel, SeoModel):
@@ -37,22 +38,31 @@ class Category(MPTTModel, SeoModel):
objects = models.Manager()
tree = TreeManager()
+ translated = TranslationProxy()
def __str__(self):
return self.name
- def get_absolute_url(self, ancestors=None):
- return reverse('product:category',
- kwargs={'path': self.get_full_path(ancestors),
- 'category_id': self.id})
+ def get_absolute_url(self):
+ return reverse(
+ 'product:category',
+ kwargs={'slug': self.slug, 'category_id': self.id})
- def get_full_path(self, ancestors=None):
- if not self.parent_id:
- return self.slug
- if not ancestors:
- ancestors = self.get_ancestors()
- nodes = [node for node in ancestors] + [self]
- return '/'.join([node.slug for node in nodes])
+
+class CategoryTranslation(SeoModelTranslation):
+ language_code = models.CharField(max_length=10)
+ category = models.ForeignKey(
+ Category, related_name='translations', on_delete=models.CASCADE)
+ name = models.CharField(max_length=128)
+ description = models.TextField(blank=True)
+
+ def __str__(self):
+ return self.name
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, name=%r, category_pk=%r)' % (
+ class_.__name__, self.pk, self.name, self.category_id)
class ProductType(models.Model):
@@ -106,6 +116,7 @@ class Product(SeoModel):
max_length=128, default=DEFAULT_TAX_RATE_NAME, blank=True)
objects = ProductQuerySet.as_manager()
+ translated = TranslationProxy()
class Meta:
app_label = 'product'
@@ -160,6 +171,22 @@ class Product(SeoModel):
return TaxedMoneyRange(start=price, stop=price)
+class ProductTranslation(SeoModelTranslation):
+ language_code = models.CharField(max_length=10)
+ product = models.ForeignKey(
+ Product, related_name='translations', on_delete=models.CASCADE)
+ name = models.CharField(max_length=128)
+ description = models.TextField()
+
+ def __str__(self):
+ return self.name
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, name=%r, product_pk=%r)' % (
+ class_.__name__, self.pk, self.name, self.product_id)
+
+
class ProductVariant(models.Model):
sku = models.CharField(max_length=32, unique=True)
name = models.CharField(max_length=255, blank=True)
@@ -179,6 +206,8 @@ class ProductVariant(models.Model):
currency=settings.DEFAULT_CURRENCY, max_digits=12,
decimal_places=settings.DEFAULT_DECIMAL_PLACES, blank=True, null=True)
+ translated = TranslationProxy()
+
class Meta:
app_label = 'product'
@@ -222,9 +251,9 @@ class ProductVariant(models.Model):
return self.quantity_available > 0
def display_product(self):
- variant_display = str(self)
+ variant_display = str(self.translated)
product_display = (
- '%s (%s)' % (self.product, variant_display)
+ '%s (%s)' % (self.product.translated, variant_display)
if variant_display else str(self.product))
return smart_text(product_display)
@@ -237,10 +266,29 @@ class ProductVariant(models.Model):
self.sku, self.display_product(), prices_i18n.amount(price))
+class ProductVariantTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ product_variant = models.ForeignKey(
+ ProductVariant, related_name='translations', on_delete=models.CASCADE)
+ name = models.CharField(max_length=255, blank=True)
+
+ translated = TranslationProxy()
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, name=%r, variant_pk=%r)' % (
+ class_.__name__, self.pk, self.name, self.product_variant_id)
+
+ def __str__(self):
+ return self.name or str(self.product_variant)
+
+
class ProductAttribute(models.Model):
slug = models.SlugField(max_length=50, unique=True)
name = models.CharField(max_length=100)
+ translated = TranslationProxy()
+
class Meta:
ordering = ('slug', )
@@ -254,12 +302,30 @@ class ProductAttribute(models.Model):
return self.values.exists()
+class ProductAttributeTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ product_attribute = models.ForeignKey(
+ ProductAttribute, related_name='translations',
+ on_delete=models.CASCADE)
+ name = models.CharField(max_length=100)
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, name=%r, attribute_pk=%r)' % (
+ class_.__name__, self.pk, self.name, self.product_attribute_id)
+
+ def __str__(self):
+ return self.name
+
+
class AttributeChoiceValue(SortableModel):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
attribute = models.ForeignKey(
ProductAttribute, related_name='values', on_delete=models.CASCADE)
+ translated = TranslationProxy()
+
class Meta:
ordering = ('sort_order',)
unique_together = ('name', 'attribute')
@@ -271,6 +337,23 @@ class AttributeChoiceValue(SortableModel):
return self.attribute.values.all()
+class AttributeChoiceValueTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ attribute_choice_value = models.ForeignKey(
+ AttributeChoiceValue, related_name='translations',
+ on_delete=models.CASCADE)
+ name = models.CharField(max_length=100)
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, name=%r, attribute_choice_value_pk=%r)' % (
+ class_.__name__, self.pk, self.name,
+ self.attribute_choice_value_id)
+
+ def __str__(self):
+ return self.name
+
+
class ProductImage(SortableModel):
product = models.ForeignKey(
Product, related_name='images', on_delete=models.CASCADE)
@@ -310,6 +393,7 @@ class Collection(SeoModel):
is_published = models.BooleanField(default=False)
objects = CollectionQuerySet.as_manager()
+ translated = TranslationProxy()
class Meta:
ordering = ['pk']
@@ -321,3 +405,19 @@ class Collection(SeoModel):
return reverse(
'product:collection',
kwargs={'pk': self.id, 'slug': self.slug})
+
+
+class CollectionTranslation(SeoModelTranslation):
+ language_code = models.CharField(max_length=10)
+ collection = models.ForeignKey(
+ Collection, related_name='translations',
+ on_delete=models.CASCADE)
+ name = models.CharField(max_length=128)
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, name=%r, collection_pk=%r)' % (
+ class_.__name__, self.pk, self.name, self.collection_id)
+
+ def __str__(self):
+ return self.name
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 199a876fa6..b0daea393e 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -23,8 +23,11 @@ def products_visible_to_user(user):
def products_with_details(user):
products = products_visible_to_user(user)
products = products.prefetch_related(
- 'category', 'collections', 'images', 'variants__variant_images__image',
- 'attributes__values', 'product_type__product_attributes__values')
+ 'translations', 'category__translations', 'collections__translations',
+ 'images', 'variants__variant_images__image',
+ 'attributes__values__translations',
+ 'product_type__product_attributes__translations',
+ 'product_type__product_attributes__values__translations')
return products
diff --git a/saleor/product/utils/attributes.py b/saleor/product/utils/attributes.py
index 1dbeba6c32..34596dbf1f 100644
--- a/saleor/product/utils/attributes.py
+++ b/saleor/product/utils/attributes.py
@@ -1,15 +1,14 @@
-from django.utils.encoding import smart_text
-
-
def get_product_attributes_data(product):
"""Returns attributes associated with the product,
as dict of ProductAttribute: AttributeChoiceValue values.
"""
attributes = product.product_type.product_attributes.all()
- attributes_map = {attribute.pk: attribute for attribute in attributes}
+ attributes_map = {
+ attribute.pk: attribute.translated for attribute in attributes}
values_map = get_attributes_display_map(product, attributes)
- return {attributes_map.get(attr_pk): value_obj
- for (attr_pk, value_obj) in values_map.items()}
+ return {
+ attributes_map[attr_pk]: value_obj.translated
+ for (attr_pk, value_obj) in values_map.items()}
def get_name_from_attributes(variant):
@@ -28,14 +27,10 @@ def get_attributes_display_map(obj, attributes):
"""
display_map = {}
for attribute in attributes:
- value = obj.attributes.get(smart_text(attribute.pk))
+ value = obj.attributes.get(str(attribute.pk))
if value:
- choices = {smart_text(a.pk): a for a in attribute.values.all()}
- choice_obj = choices.get(value)
- if choice_obj:
- display_map[attribute.pk] = choice_obj
- else:
- display_map[attribute.pk] = value
+ choices = {str(a.pk): a.translated for a in attribute.values.all()}
+ display_map[attribute.pk] = choices[value]
return display_map
@@ -47,7 +42,7 @@ def generate_name_from_values(attributes_dict):
attributes_dict: dict of attribute_pk: AttributeChoiceValue values
"""
return ' / '.join(
- smart_text(attributechoice_value)
+ str(attributechoice_value)
for attribute_pk, attributechoice_value in sorted(
attributes_dict.items(),
key=lambda x: x[0]))
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index 82488ba8f3..a2896efe99 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -48,12 +48,15 @@ def get_variant_picker_data(
if available_variants:
data['variantAttributes'].append({
'pk': attribute.pk,
- 'name': attribute.name,
- 'slug': attribute.slug,
+ 'name': attribute.translated.name,
+ 'slug': attribute.translated.slug,
'values': [
- {'pk': value.pk, 'name': value.name, 'slug': value.slug}
+ {
+ 'pk': value.pk, 'name': value.translated.name,
+ 'slug': value.translated.slug}
for value in attribute.values.filter(
- pk__in=available_variants)]})
+ pk__in=available_variants).prefetch_related(
+ 'translations')]})
data['availability'] = {
'discount': price_as_dict(availability.discount),
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 38061bca9e..ec53cac55a 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -111,12 +111,13 @@ def product_add_to_cart(request, slug, product_id):
return response
-def category_index(request, path, category_id):
- category = get_object_or_404(Category, id=category_id)
- actual_path = category.get_full_path()
- if actual_path != path:
- return redirect('product:category', permanent=True, path=actual_path,
- category_id=category_id)
+def category_index(request, slug, category_id):
+ categories = Category.objects.prefetch_related('translations')
+ category = get_object_or_404(categories, id=category_id)
+ if slug != category.slug:
+ return redirect(
+ 'product:category', permanent=True, slug=category.slug,
+ category_id=category_id)
# Check for subcategories
categories = category.get_descendants(include_self=True)
products = products_with_details(user=request.user).filter(
diff --git a/saleor/seo/models.py b/saleor/seo/models.py
index 8343fbf35f..c3ac151f0b 100644
--- a/saleor/seo/models.py
+++ b/saleor/seo/models.py
@@ -12,3 +12,15 @@ class SeoModel(models.Model):
class Meta:
abstract = True
+
+
+class SeoModelTranslation(models.Model):
+ seo_title = models.CharField(
+ max_length=70, blank=True, null=True,
+ validators=[MaxLengthValidator(70)])
+ seo_description = models.CharField(
+ max_length=300, blank=True, null=True,
+ validators=[MaxLengthValidator(300)])
+
+ class Meta:
+ abstract = True
diff --git a/saleor/site/models.py b/saleor/site/models.py
index aa41fccd29..b8d60eda6f 100644
--- a/saleor/site/models.py
+++ b/saleor/site/models.py
@@ -3,6 +3,7 @@ from django.db import models
from django.utils.translation import pgettext_lazy
from . import AuthenticationBackends
+from ..core.utils.translations import TranslationProxy
from .patch_sites import patch_contrib_sites
patch_contrib_sites()
@@ -24,6 +25,8 @@ class SiteSettings(models.Model):
charge_taxes_on_shipping = models.BooleanField(default=True)
track_inventory_by_default = models.BooleanField(default=True)
+ translated = TranslationProxy()
+
class Meta:
permissions = ((
'manage_settings', pgettext_lazy(
@@ -36,6 +39,22 @@ class SiteSettings(models.Model):
return self.authorizationkey_set.values_list('name', flat=True)
+class SiteSettingsTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ site_settings = models.ForeignKey(
+ SiteSettings, related_name='translations', on_delete=models.CASCADE)
+ header_text = models.CharField(max_length=200, blank=True)
+ description = models.CharField(max_length=500, blank=True)
+
+ def __repr__(self):
+ class_ = type(self)
+ return '%s(pk=%r, site_settings_pk=%r)' % (
+ class_.__name__, self.pk, self.site_settings_id)
+
+ def __str__(self):
+ return self.site_settings.site.name
+
+
class AuthorizationKey(models.Model):
site_settings = models.ForeignKey(SiteSettings, on_delete=models.CASCADE)
name = models.CharField(
diff --git a/templates/base.html b/templates/base.html
index f82bdc590e..442c099f54 100644
--- a/templates/base.html
+++ b/templates/base.html
@@ -17,7 +17,7 @@
<meta name="msapplication-TileColor" content="#2b5797">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
- <meta name="apple-mobile-web-app-title" content="{{ site.name }}">
+ <meta name="apple-mobile-web-app-title" content="{{ site.settings.translated.header_text }}">
<meta name="og:type" content="website">
{% get_available_languages as LANGUAGES %}
{% for lang_code, language_name in LANGUAGES %}
@@ -31,7 +31,9 @@
{% block stylesheet %}{% endblock stylesheet %}
{% block meta_tags %}
- <meta property="og:title" content="{{ site.name }}">
+ <meta property="og:title" content="{{ site.settings.translated.header_text }}">
+ <meta property="og:description" content="{{ site.settings.translated.description }}">
+ <meta name="description" content="{{ site.settings.translated.description }}">
<meta property="og:url" content="{{ request.build_absolute_uri }}">
<meta property="og:image" content="{% static "images/block1.png" %}">
{% endblock meta_tags %}
@@ -51,7 +53,7 @@
<div class=" d-none d-md-block container">
<div class="row">
<div class="col-6">
- <p class="text-left">{{ site.settings.header_text }}</p>
+ <p class="text-left">{{ site.settings.translated.header_text }}</p>
</div>
<div class="col-6">
<ul class="float-right">
diff --git a/templates/cart_dropdown.html b/templates/cart_dropdown.html
index c966ea9dc7..048a37115a 100644
--- a/templates/cart_dropdown.html
+++ b/templates/cart_dropdown.html
@@ -17,9 +17,9 @@
alt=""
src="{% placeholder size=120 %}">
<h3>
- {{ line.product }}
+ {{ line.product.translated }}
<span>x{{ line.quantity }}</span>
- <p>{{ line.variant }}</p>
+ <p>{{ line.variant.translated }}</p>
</h3>
</a>
</div>
diff --git a/templates/category/filters.html b/templates/category/filters.html
index ae12b94211..5dc033b732 100644
--- a/templates/category/filters.html
+++ b/templates/category/filters.html
@@ -7,7 +7,7 @@
<ul class="product-filters__categories__childs no-parent">
{% for child in children %}
<li>
- <a href="{{ child.get_absolute_url }}">{{ child.name }}</a>
+ <a href="{{ child.get_absolute_url }}">{{ child.translated.name }}</a>
</li>
{% endfor %}
</ul>
diff --git a/templates/category/index.html b/templates/category/index.html
index f5f4881c43..1ce5249e7c 100644
--- a/templates/category/index.html
+++ b/templates/category/index.html
@@ -7,10 +7,10 @@
<a href="{% url 'home' %}">{% trans "Home" context 'Category breadcrumbs home' %}</a>
</li>
{% for ancestor in object.get_ancestors %}
- <li><a href='{{ ancestor.get_absolute_url }}'>{{ ancestor.name }}</a>
+ <li><a href='{{ ancestor.get_absolute_url }}'>{{ ancestor.translated.name }}</a>
</li>
{% endfor %}
- <li><a href='{{ object.get_absolute_url }}'>{{ object.name }}</a></li>
+ <li><a href='{{ object.get_absolute_url }}'>{{ object.translated.name }}</a></li>
{% endblock %}
{% block filters %}
diff --git a/templates/checkout/details.html b/templates/checkout/details.html
index 283357fb1c..43339a84b1 100644
--- a/templates/checkout/details.html
+++ b/templates/checkout/details.html
@@ -36,8 +36,8 @@
{% for line, line_total in cart_lines %}
<div class="row">
<div class="col-8">
- <p><strong>{{ line.variant.product }}</strong> x {{ line.quantity }}<br>
- <span class="checkout__review__variant">{{ line.variant }}</span></p>
+ <p><strong>{{ line.variant.product.translated }}</strong> x {{ line.quantity }}<br>
+ <span class="checkout__review__variant">{{ line.variant.translated }}</span></p>
</div>
<div class="col-4">
<p class="float-right">
diff --git a/templates/checkout/index.html b/templates/checkout/index.html
index ea2ee06b86..6e14fe4f84 100644
--- a/templates/checkout/index.html
+++ b/templates/checkout/index.html
@@ -45,7 +45,7 @@
<img class="lazyload lazypreload" data-src="{% get_thumbnail line.variant.product.images.first.image method="crop" size="60x60" %}"
data-srcset="{% get_thumbnail line.variant.product.images.first.image method="crop" size="60x60" %} 1x, {% get_thumbnail line.variant.product.images.first.image method="crop" size="120x120" %} 2x"
alt="">
- <p>{{ line.variant.product }}<br><small>{{ line.variant }}</small></p>
+ <p>{{ line.variant.product.translated }}<br><small>{{ line.variant.translated }}</small></p>
</a>
</div>
<div class="col-5">
diff --git a/templates/collection/index.html b/templates/collection/index.html
index 6f4a7d9747..1d80676fbb 100644
--- a/templates/collection/index.html
+++ b/templates/collection/index.html
@@ -6,7 +6,7 @@
<li>
<a href="{% url 'home' %}">{% trans "Home" context 'Site breadcrumbs home' %}</a>
</li>
- <li><a href='{{ object.get_absolute_url }}'>{{ object.name }}</a></li>
+ <li><a href='{{ object.get_absolute_url }}'>{{ object.translated.name }}</a></li>
{% endblock %}
{% block collection_published_warning %}
diff --git a/templates/menu.html b/templates/menu.html
index 9206ab8fd8..d4d07bcff3 100644
--- a/templates/menu.html
+++ b/templates/menu.html
@@ -4,7 +4,7 @@
{% with children=item.get_children %}
<li class="{% if horizontal %}nav-item{% endif %} {% if children %}nav-item__dropdown{% endif %} menu__item">
<a class="{% if horizontal %}nav-link{% endif %}" href="{{ item.get_url }}">
- {{ item }}
+ {{ item.translated }}
</a>
{% if children %}
<div class="{% if horizontal %}nav-item__dropdown-content{% else %}nav-item__submenu{% endif %}">
@@ -14,9 +14,9 @@
<li>
<a href="{{ child.get_url }}">
{% if horizontal %}
- <strong>{{ child }}</strong>
+ <strong>{{ child.translated }}</strong>
{% else %}
- {{ child }}
+ {{ child.translated }}
{% endif %}
</a>
</li>
@@ -26,7 +26,7 @@
{% for grandchild in grandchildren %}
<li>
<a href="{{ grandchild.get_url }}">
- {{ grandchild }}
+ {{ grandchild.translated }}
</a>
</li>
{% endfor %}
diff --git a/templates/page/details.html b/templates/page/details.html
index 160a1fefb8..83ef3e0cd8 100644
--- a/templates/page/details.html
+++ b/templates/page/details.html
@@ -5,16 +5,16 @@
{% block title %}
{% if page.seo_title %}
- {{ page.seo_title }}
+ {{ page.translated.seo_title }}
{% else %}
- {{ page.title }} - {{ block.super }}
+ {{ page.translated.title }} - {{ block.super }}
{% endif %}
{% endblock %}
{% block meta_tags %}
- <meta property="og:title" content="{{ page.seo_title|default:page.title }}">
- <meta property="og:description" content="{{ page.seo_description|default:"" }}">
- <meta name="description" content="{{ page.seo_description|default:"" }}">
+ <meta property="og:title" content="{{ page.translated.seo_title|default:page.translated.title }}">
+ <meta property="og:description" content="{{ page.translated.seo_description|default:"" }}">
+ <meta name="description" content="{{ page.translated.seo_description|default:"" }}">
{% build_absolute_uri request=request location=page.get_absolute_url as page_url %}
<meta property="og:url" content="{{ page_url }}">
@@ -29,7 +29,7 @@
</li>
{% if page %}
<li>
- <a href="{{ page.get_absolute_url }}">{{ page.title }}</a>
+ <a href="{{ page.get_absolute_url }}">{{ page.translated.title }}</a>
</li>
{% endif %}
</ul>
@@ -52,6 +52,6 @@
</div>
{% endif %}
<div class="">
- {{ page.content|safe }}
+ {{ page.translated.content|safe }}
</div>
{% endblock %}
diff --git a/templates/product/_filters.html b/templates/product/_filters.html
index 814424cf73..1256e7821c 100644
--- a/templates/product/_filters.html
+++ b/templates/product/_filters.html
@@ -4,7 +4,7 @@
<div class="product-filters">
<div class="product-filters__title">
<h2>
- <strong>{{ object }}</strong>
+ <strong>{{ object.translated }}</strong>
</h2>
{% block title_tree %}{% endblock title_tree %}
</div>
diff --git a/templates/product/_items.html b/templates/product/_items.html
index ceb4979277..0037d51ec5 100644
--- a/templates/product/_items.html
+++ b/templates/product/_items.html
@@ -15,7 +15,7 @@
data-srcset="{% product_first_image product method="crop" size="255x255" %} 1x, {% product_first_image product method="crop" size="510x510" %} 2x"
alt=""
src="{% placeholder size=255 %}">
- <span class="product-list-item-name" title="{{ product }}">{{ product }}</span>
+ <span class="product-list-item-name" title="{{ product.translated }}">{{ product.translated }}</span>
</div>
<div class="panel-footer">
{% if availability.available %}
diff --git a/templates/product/details.html b/templates/product/details.html
index 5f70b6c829..003c62c7ab 100644
--- a/templates/product/details.html
+++ b/templates/product/details.html
@@ -12,16 +12,16 @@
{% block title %}
{% if product.seo_title %}
- {{ product.seo_title }}
+ {{ product.translated.seo_title }}
{% else %}
- {{ product.name }} - {{ block.super }}
+ {{ product.translated.name }} - {{ block.super }}
{% endif %}
{% endblock %}
{% block meta_tags %}
- <meta property="og:title" content="{{ product.seo_title|default:product.name }}">
- <meta property="og:description" content="{{ product.seo_description|default:"" }}">
- <meta name="description" content="{{ product.seo_description|default:"" }}">
+ <meta property="og:title" content="{{ product.translated.seo_title|default:product.translated.name }}">
+ <meta property="og:description" content="{{ product.translated.seo_description|default:"" }}">
+ <meta name="description" content="{{ product.translated.seo_description|default:"" }}">
{% build_absolute_uri request=request location=product.get_absolute_url as product_url %}
<meta property="og:url" content="{{ product_url }}">
@@ -46,11 +46,11 @@
</li>
{% if product.category %}
<li>
- <a href="{{ product.category.get_absolute_url }}">{{ product.category }}</a>
+ <a href="{{ product.category.get_absolute_url }}">{{ product.category.translated }}</a>
</li>
{% endif %}
<li>
- <a href="{{ product.get_absolute_url }}">{{ product }}</a>
+ <a href="{{ product.get_absolute_url }}">{{ product.translated }}</a>
</li>
</ul>
{% endblock breadcrumb %}
@@ -113,7 +113,7 @@
</div>
<div class="col-md-6 col-12 product__info">
<h1 class="product__info__name">
- {{ product }}
+ {{ product.translated }}
</h1>
{% if user.is_staff %}
<p>
@@ -190,14 +190,14 @@
<div class="product__info__description">
<h3>{% trans "Description" context "Product details title" %}</h3>
<hr>
- {{ product.description|safe }}
+ {{ product.translated.description|safe }}
</div>
<hr>
<table>
{% for attribute, value in product_attributes.items %}
<tr>
- <td>{{ attribute }}:</td>
- <td><strong>{{ value }}</strong></td>
+ <td>{{ attribute.translated }}:</td>
+ <td><strong>{{ value.translated }}</strong></td>
</tr>
{% endfor %}
</table>
diff --git a/templates/product/product_list_base.html b/templates/product/product_list_base.html
index 07637ea72a..ca9ac7324a 100644
--- a/templates/product/product_list_base.html
+++ b/templates/product/product_list_base.html
@@ -12,14 +12,14 @@
{% block title %}
{% if object.seo_title %}
- {{ object.seo_title }}
+ {{ object.translated.seo_title }}
{% else %}
- {{ object.name }} - {{ block.super }}
+ {{ object.translated.name }} - {{ block.super }}
{% endif %}
{% endblock %}
{% block meta_tags %}
- <meta property="og:title" content="{{ object.seo_title|default:object.name }}">
+ <meta property="og:title" content="{{ object.translated.seo_title|default:object.translated.name }}">
{% get_object_properties object=object properties="seo_description,description" as seo_description %}
<meta property="og:description" content="{{ seo_description }}">
<meta name="description" content="{{ seo_description }}">
diff --git a/tests/conftest.py b/tests/conftest.py
index 007ab31bbf..ac489cb6e9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -3,6 +3,7 @@ from io import BytesIO
from unittest.mock import MagicMock, Mock
import pytest
+
from django.contrib.auth.models import Permission
from django.contrib.sites.models import Site
from django.core.files import File
@@ -16,7 +17,6 @@ from graphql_jwt.shortcuts import get_token
from payments import FraudStatus, PaymentStatus
from PIL import Image
from prices import Money
-
from saleor.account.models import Address, User
from saleor.checkout import utils
from saleor.checkout.models import Cart
@@ -29,7 +29,8 @@ from saleor.order.models import Order
from saleor.order.utils import recalculate_order
from saleor.page.models import Page
from saleor.product.models import (
- AttributeChoiceValue, Category, Collection, Product, ProductAttribute,
+ AttributeChoiceValue, AttributeChoiceValueTranslation, Category,
+ Collection, Product, ProductAttribute, ProductAttributeTranslation,
ProductImage, ProductType, ProductVariant)
from saleor.shipping.models import ShippingMethod, ShippingMethodCountry
from saleor.site.models import AuthorizationKey, SiteSettings
@@ -142,7 +143,7 @@ def address(db): # pylint: disable=W0613
@pytest.fixture
-def customer_user(db, address): # pylint: disable=W0613
+def customer_user(address): # pylint: disable=W0613
default_address = address.get_copy()
user = User.objects.create_user(
@@ -540,7 +541,7 @@ def payment_input(order_with_lines):
@pytest.fixture()
-def sale(db, default_category, collection):
+def sale(default_category, collection):
sale = Sale.objects.create(name="Sale", value=5)
sale.categories.add(default_category)
sale.collections.add(collection)
@@ -548,7 +549,7 @@ def sale(db, default_category, collection):
@pytest.fixture
-def authorization_key(db, site_settings):
+def authorization_key(site_settings):
return AuthorizationKey.objects.create(
site_settings=site_settings, name='Backend', key='Key',
password='Password')
@@ -697,3 +698,27 @@ def vatlayer(db, settings, tax_rates, taxes):
'passenger transport': 7}}
VAT.objects.create(country_code='DE', data=tax_rates_2)
return taxes
+
+
+def translated_variant(product):
+ attribute = product.product_type.variant_attributes.first()
+ return ProductAttributeTranslation.objects.create(
+ language_code='fr', product_attribute=attribute,
+ name='Name tranlsated to french')
+
+
+def translated_product_attribute(product):
+ attribute = product.product_type.product_attributes.first()
+ return ProductAttributeTranslation.objects.create(
+ language_code='fr', product_attribute=attribute,
+ name='Name tranlsated to french')
+
+
+def attribute_choice_translation_fr(translated_product_attribute):
+ value = translated_product_attribute.product_attribute.values.first()
+ return AttributeChoiceValueTranslation.objects.create(
+ language_code='fr', attribute_choice_value=value,
+ name='French name')
diff --git a/tests/test_cart.py b/tests/test_cart.py
index 45afc1fa7b..57258ecbc9 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -521,7 +521,7 @@ def test_cart_summary_page(settings, client, request_cart_with_item, vatlayer):
assert len(content['lines']) == 1
cart_line = content['lines'][0]
variant = request_cart_with_item.lines.get().variant
- assert cart_line['variant'] == variant.name
+ assert cart_line['variant'] == variant
assert cart_line['quantity'] == 1
diff --git a/tests/test_product.py b/tests/test_product.py
index 08fe7c83c6..03d378153c 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -4,10 +4,10 @@ from decimal import Decimal
from unittest.mock import patch
import pytest
+
from django.core import serializers
from django.urls import reverse
from prices import Money, TaxedMoney, TaxedMoneyRange
-
from saleor.checkout import utils
from saleor.checkout.models import Cart
from saleor.checkout.utils import add_variant_to_cart
@@ -16,6 +16,7 @@ from saleor.product import ProductAvailabilityStatus, models
from saleor.product.thumbnails import create_product_thumbnails
from saleor.product.utils import (
allocate_stock, deallocate_stock, decrease_stock, increase_stock)
+from saleor.product.utils.attributes import get_product_attributes_data
from saleor.product.utils.availability import get_product_availability_status
from saleor.product.utils.variants_picker import get_variant_picker_data
@@ -197,7 +198,8 @@ def test_adding_to_cart_with_current_user_token(
def test_adding_to_cart_with_another_user_token(
- admin_user, admin_client, product, customer_user, request_cart_with_item):
+ admin_user, admin_client, product, customer_user,
+ request_cart_with_item):
client = admin_client
key = utils.COOKIE_NAME
request_cart_with_item.user = customer_user
@@ -292,7 +294,7 @@ def test_product_filter_before_filtering(
url = reverse(
'product:category',
kwargs={
- 'path': default_category.slug,
+ 'slug': default_category.slug,
'category_id': default_category.pk})
response = authorized_client.get(url)
@@ -309,7 +311,7 @@ def test_product_filter_product_exists(authorized_client, product,
url = reverse(
'product:category',
kwargs={
- 'path': default_category.slug,
+ 'slug': default_category.slug,
'category_id': default_category.pk})
data = {'price_0': [''], 'price_1': ['20']}
@@ -323,7 +325,7 @@ def test_product_filter_product_does_not_exist(
url = reverse(
'product:category',
kwargs={
- 'path': default_category.slug,
+ 'slug': default_category.slug,
'category_id': default_category.pk})
data = {'price_0': ['20'], 'price_1': ['']}
@@ -341,7 +343,7 @@ def test_product_filter_form(authorized_client, product,
url = reverse(
'product:category',
kwargs={
- 'path': default_category.slug,
+ 'slug': default_category.slug,
'category_id': default_category.pk})
response = authorized_client.get(url)
@@ -360,7 +362,7 @@ def test_product_filter_sorted_by_price_descending(
url = reverse(
'product:category',
kwargs={
- 'path': default_category.slug,
+ 'slug': default_category.slug,
'category_id': default_category.pk})
data = {'sort_by': '-price'}
@@ -374,7 +376,7 @@ def test_product_filter_sorted_by_wrong_parameter(
url = reverse(
'product:category',
kwargs={
- 'path': default_category.slug,
+ 'slug': default_category.slug,
'category_id': default_category.pk})
data = {'sort_by': 'aaa'}
@@ -411,11 +413,10 @@ def test_include_products_from_subcategories_in_main_view(
name='sub', slug='test', parent=default_category)
product.category = subcategory
product.save()
- path = default_category.get_full_path()
# URL to parent category view
url = reverse(
'product:category', kwargs={
- 'path': path, 'category_id': default_category.pk})
+ 'slug': default_category.slug, 'category_id': default_category.pk})
response = authorized_client.get(url)
assert product in response.context_data['products'][0]
@@ -584,7 +585,7 @@ def test_product_json_deserialization(default_category, product_type):
"pk": 60,
"fields": {{
"seo_title": null,
- "seo_description": "Future almost cup national. Study left manage we else.",
+ "seo_description": "Future almost cup national.",
"product_type": {product_type_pk},
"name": "Kelly-Clark",
"description": "Future almost cup national",
@@ -592,7 +593,7 @@ def test_product_json_deserialization(default_category, product_type):
"price": "35.98",
"available_on": null,
"is_published": true,
- "attributes": "{{\\"9\\": \\"24\\", \\"10\\": \\"26\\", \\"11\\": \\"29\\"}}",
+ "attributes": "{{\\"9\\": \\"24\\", \\"10\\": \\"26\\"}}",
"updated_at": "2018-07-19T13:30:24.195Z",
"is_featured": false,
"charge_taxes": true,
@@ -606,3 +607,29 @@ def test_product_json_deserialization(default_category, product_type):
product_deserialized.save()
product = models.Product.objects.first()
assert product.price == Money(Decimal('35.98'), 'USD')
+
+
+def test_variant_picker_data_with_translations(
+ product, translated_variant, settings):
+ settings.LANGUAGE_CODE = 'fr'
+ variant_picker_data = get_variant_picker_data(product)
+ attribute = variant_picker_data['variantAttributes'][0]
+ assert attribute['name'] == translated_variant.name
+
+
+def test_get_product_attributes_data_translation(
+ product, settings, translated_product_attribute):
+ settings.LANGUAGE_CODE = 'fr'
+ attributes_data = get_product_attributes_data(product)
+ attributes_keys = [attr.name for attr in attributes_data.keys()]
+ assert translated_product_attribute.name in attributes_keys
+
+
+def test_attribute_choice_value_translation_fr(
+ settings, product, attribute_choice_translation_fr):
+ attribute = product.product_type.product_attributes.first()
+ choice = attribute.values.first()
+ assert choice.translated.name == 'Red'
+
+ settings.LANGUAGE_CODE = 'fr'
+ assert choice.translated.name == 'French name'
diff --git a/tests/test_product_attributes.py b/tests/test_product_attributes.py
index 4fa29fda5a..75f5ec21d2 100644
--- a/tests/test_product_attributes.py
+++ b/tests/test_product_attributes.py
@@ -24,7 +24,8 @@ def test_get_attributes_display_map(product):
attr_value = product_attr.values.first()
assert len(attributes_display_map) == 1
- assert attributes_display_map == {product_attr.pk: attr_value}
+ assert {k: v.pk for k, v in attributes_display_map.items()} == {
+ product_attr.pk: attr_value.translated.pk}
def test_get_attributes_display_map_empty(product_with_no_attributes):
diff --git a/tests/test_templatetags.py b/tests/test_templatetags.py
index dbdcd58122..1837389d41 100644
--- a/tests/test_templatetags.py
+++ b/tests/test_templatetags.py
@@ -5,7 +5,7 @@ from saleor.core.templatetags.shop import get_sort_by_url, menu
def test_sort_by_url_ascending(admin_client, default_category):
url = reverse('product:category',
- kwargs={'path': default_category.slug,
+ kwargs={'slug': default_category.slug,
'category_id': default_category.id})
response = admin_client.get(url)
result = get_sort_by_url(response.context, 'name')
@@ -15,7 +15,7 @@ def test_sort_by_url_ascending(admin_client, default_category):
def test_sort_by_url_descending(admin_client, default_category):
url = reverse('product:category',
- kwargs={'path': default_category.slug,
+ kwargs={'slug': default_category.slug,
'category_id': default_category.id})
response = admin_client.get(url)
result = get_sort_by_url(response.context, 'name', descending=True)
diff --git a/tests/test_translation.py b/tests/test_translation.py
new file mode 100644
index 0000000000..6e86b081ee
--- /dev/null
+++ b/tests/test_translation.py
@@ -0,0 +1,105 @@
+import pytest
+
+from saleor.product.models import (
+ CategoryTranslation, CollectionTranslation, ProductTranslation,
+ ProductVariantTranslation, ProductAttributeTranslation)
+
+
+def product_translation_fr(db, product):
+ return ProductTranslation.objects.create(
+ language_code='fr', product=product, name='French name',
+ description='French description')
+
+
+def product_translation_pl(db, product):
+ return ProductTranslation.objects.create(
+ language_code='pl', product=product, name='Polish name',
+ description="Polish description")
+
+
+def test_translation(product, settings, product_translation_fr):
+ assert product.translated.name == 'Test product'
+ assert not product.translated.description
+
+ settings.LANGUAGE_CODE = 'fr'
+ assert product.translated.name == 'French name'
+ assert product.translated.description == 'French description'
+
+
+def test_translation_str_returns_str_of_instance(
+ product, product_translation_fr, settings):
+ assert str(product.translated) == str(product)
+ settings.LANGUAGE_CODE = 'fr'
+ assert str(
+ product.translated.translation) == str(product_translation_fr)
+
+
+def test_wrapper_gets_proper_wrapper(
+ product, product_translation_fr, settings, product_translation_pl):
+ assert product.translated.translation is None
+
+ settings.LANGUAGE_CODE = 'fr'
+ assert product.translated.translation == product_translation_fr
+
+ settings.LANGUAGE_CODE = 'pl'
+ assert product.translated.translation == product_translation_pl
+
+
+def test_getattr(
+ product, settings, product_translation_fr, product_type):
+ settings.LANGUAGE_CODE = 'fr'
+ assert product.translated.product_type == product_type
+
+
+def test_translation_not_override_id(
+ settings, product, product_translation_fr):
+ settings.LANGUAGE_CODE = 'fr'
+ translated_product = product.translated
+ assert translated_product.id == product.id
+ assert not translated_product.id == product_translation_fr
+
+
+def test_collection_translation(settings, collection):
+ settings.LANGUAGE_CODE = 'fr'
+ french_name = 'French name'
+ CollectionTranslation.objects.create(
+ language_code='fr', name=french_name, collection=collection)
+ assert collection.translated.name == french_name
+
+
+def test_category_translation(settings, default_category):
+ settings.LANGUAGE_CODE = 'fr'
+ french_name = 'French name'
+ french_description = 'French description'
+ CategoryTranslation.objects.create(
+ language_code='fr', name=french_name, description=french_description,
+ category=default_category)
+ assert default_category.translated.name == french_name
+ assert default_category.translated.description == french_description
+
+
+def test_product_variant_translation(settings, variant):
+ settings.LANGUAGE_CODE = 'fr'
+ french_name = 'French name'
+ ProductVariantTranslation.objects.create(
+ language_code='fr', name=french_name, product_variant=variant)
+ assert variant.translated.name == french_name
+
+
+def test_product_attribute_translation(settings, color_attribute):
+ ProductAttributeTranslation.objects.create(
+ language_code='fr', product_attribute=color_attribute,
+ name='French name')
+ assert not color_attribute.translated.name == 'French name'
+ settings.LANGUAGE_CODE = 'fr'
+ assert color_attribute.translated.name == 'French name'
+
+
+def test_attribute_choice_value_translation(
+ settings, product, attribute_choice_translation_fr):
+ attribute = product.product_type.product_attributes.first().values.first()
+ assert not attribute.translated.name == 'French name'
+ settings.LANGUAGE_CODE = 'fr'
+ assert attribute.translated.name == 'French name'