Skip to content

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

Rename ProductImage to ProductMedia, update the migrations, change tests (#6838)

Grzegorz Derdak67b0ea899bcf
diff --git a/.isort.cfg b/.isort.cfg
index cb4ef6b8ff..07a165dee8 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = Adyen,PIL,authorizenet,babel,boto3,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,urllib3,versatileimagefield,weasyprint
+known_third_party = Adyen,PIL,authorizenet,babel,boto3,braintree,celery,dj_database_url,dj_email_url,django,django_cache_url,django_countries,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,faker,freezegun,google,google_measurement_protocol,graphene,graphene_django,graphene_federation,graphql,graphql_relay,html_to_draftjs,i18naddress,jaeger_client,jwt,kombu,lxml,markdown,measurement,micawber,mptt,oauthlib,openpyxl,opentracing,petl,phonenumber_field,phonenumbers,pkg_resources,prices,promise,pytest,pythonjsonlogger,pytimeparse,pytz,razorpay,requests,sentry_sdk,storages,stripe,templated_email,tqdm,urllib3,versatileimagefield,weasyprint
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 950c7af94e..8e4e5b1c89 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -89,6 +89,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add SearchRank to search product by name and description. New enum added to `ProductOrderField` - `RANK` - which returns results sorted by search rank - #6872 by @d-wysocki
- Allocate stocks for order lines in a bulk way - #6877 by @IKarbowiak
- Add product description_plaintext to populatedb - #6894 by @d-wysocki
+- Add uploading video URLs to product's gallery - #6838 by @GrzegorzDerdak
- Deallocate stocks for order lines in a bulk way - #6896 by @IKarbowiak
- Prevent negative available quantity - #6897 by @d-wysocki
- Fix CheckoutLinesInfoByCheckoutTokenLoader dataloader - #6929 by @IKarbowiak
diff --git a/poetry.lock b/poetry.lock
index a551db1653..54766569b3 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -165,20 +165,20 @@ d = ["aiohttp (>=3.3.2)", "aiohttp-cors"]
[[package]]
name = "boto3"
-version = "1.17.27"
+version = "1.17.28"
description = "The AWS SDK for Python"
category = "main"
optional = false
python-versions = ">= 2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*"
[package.dependencies]
-botocore = ">=1.20.27,<1.21.0"
+botocore = ">=1.20.28,<1.21.0"
jmespath = ">=0.7.1,<1.0.0"
s3transfer = ">=0.3.0,<0.4.0"
[[package]]
name = "botocore"
-version = "1.20.27"
+version = "1.20.28"
description = "Low-level, data-driven core of boto 3."
category = "main"
optional = false
@@ -779,7 +779,7 @@ testing = ["pre-commit"]
[[package]]
name = "faker"
-version = "6.6.0"
+version = "6.6.1"
description = "Faker is a Python package that generates fake data for you."
category = "main"
optional = false
@@ -1372,6 +1372,14 @@ python-versions = "*"
[package.dependencies]
sympy = ">=0.7.3"
+[[package]]
+name = "micawber"
+version = "0.5.3"
+description = "a small library for extracting rich content from urls"
+category = "main"
+optional = false
+python-versions = "*"
+
[[package]]
name = "mpmath"
version = "1.2.1"
@@ -2349,16 +2357,16 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
[[package]]
name = "urllib3"
-version = "1.26.3"
+version = "1.26.4"
description = "HTTP library with thread-safe connection pooling, file post, and more."
category = "main"
optional = false
python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4"
[package.extras]
-brotli = ["brotlipy (>=0.6.0)"]
secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "ipaddress"]
socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"]
+brotli = ["brotlipy (>=0.6.0)"]
[[package]]
name = "uvicorn"
@@ -2419,7 +2427,7 @@ python-versions = ">=3.6"
[[package]]
name = "virtualenv"
-version = "20.4.2"
+version = "20.4.3"
description = "Virtual Python Environment builder"
category = "dev"
optional = false
@@ -2512,7 +2520,7 @@ multidict = ">=4.0"
[metadata]
lock-version = "1.1"
python-versions = "~3.9"
-content-hash = "ef6711ecd50e4aa2bf13e5b5a2aa018f2092dd5d5e85eca4c27b971e4d8da34c"
+content-hash = "6258c30df02c1e4a43ce9ce921fcf3eba7c8623ebe900cc6c5806a1a6493dec5"
[metadata.files]
adyen = [
@@ -2571,16 +2579,15 @@ billiard = [
{file = "billiard-3.6.3.0.tar.gz", hash = "sha256:d91725ce6425f33a97dfa72fb6bfef0e47d4652acd98a032bd1a7fbf06d5fa6a"},
]
black = [
- {file = "black-20.8b1-py3-none-any.whl", hash = "sha256:70b62ef1527c950db59062cda342ea224d772abdf6adc58b86a45421bab20a6b"},
{file = "black-20.8b1.tar.gz", hash = "sha256:1c02557aa099101b9d21496f8a914e9ed2222ef70336404eeeac8edba836fbea"},
]
boto3 = [
- {file = "boto3-1.17.27-py2.py3-none-any.whl", hash = "sha256:6758751f1181b9363e4e7559dcbd5ac0fc7147b73f429c976ec5ecd1688c9ec7"},
- {file = "boto3-1.17.27.tar.gz", hash = "sha256:fa41987f9f71368013767306d9522b627946a01b4843938a26fb19cc8adb06c0"},
+ {file = "boto3-1.17.28-py2.py3-none-any.whl", hash = "sha256:442c8579541661ab1dbbd2013d646506633bd1435368c217bd38acc01696992d"},
+ {file = "boto3-1.17.28.tar.gz", hash = "sha256:ba13bda83ca1a26469fdf5130bb7a8f671dd807d0551e3242cafc8c44caab057"},
]
botocore = [
- {file = "botocore-1.20.27-py2.py3-none-any.whl", hash = "sha256:57e45c9d443163da7312cae61bcc60382e6d0b3aecda68e850d6438162fe7b5b"},
- {file = "botocore-1.20.27.tar.gz", hash = "sha256:4477803f07649f4d80b17d054820e7a09bb2cb0792d0decc2812108bc3759c4a"},
+ {file = "botocore-1.20.28-py2.py3-none-any.whl", hash = "sha256:75e6cfa246ec14863742c79ab8ddd887bd1b48c3d44268d53d69a5c6f472dee0"},
+ {file = "botocore-1.20.28.tar.gz", hash = "sha256:6dde07154c37b552f52cbf8041541c5460a29d916f527b2098a36d44496c7126"},
]
braintree = [
{file = "braintree-4.6.0-py2.py3-none-any.whl", hash = "sha256:d3aa0e29eb3923574a58e8ee3219566c918ff161c98f2de715ba29cb715169c7"},
@@ -2688,6 +2695,9 @@ coverage = [
{file = "coverage-5.5-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:8963a499849a1fc54b35b1c9f162f4108017b2e6db2c46c1bed93a72262ed083"},
{file = "coverage-5.5-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:869a64f53488f40fa5b5b9dcb9e9b2962a66a87dab37790f3fcfb5144b996ef5"},
{file = "coverage-5.5-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:4a7697d8cb0f27399b0e393c0b90f0f1e40c82023ea4d45d22bce7032a5d7b81"},
+ {file = "coverage-5.5-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:8d0a0725ad7c1a0bcd8d1b437e191107d457e2ec1084b9f190630a4fb1af78e6"},
+ {file = "coverage-5.5-cp310-cp310-manylinux1_x86_64.whl", hash = "sha256:51cb9476a3987c8967ebab3f0fe144819781fca264f57f89760037a2ea191cb0"},
+ {file = "coverage-5.5-cp310-cp310-win_amd64.whl", hash = "sha256:c0891a6a97b09c1f3e073a890514d5012eb256845c451bd48f7968ef939bf4ae"},
{file = "coverage-5.5-cp35-cp35m-macosx_10_9_x86_64.whl", hash = "sha256:3487286bc29a5aa4b93a072e9592f22254291ce96a9fbc5251f566b6b7343cdb"},
{file = "coverage-5.5-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:deee1077aae10d8fa88cb02c845cfba9b62c55e1183f52f6ae6a2df6a2187160"},
{file = "coverage-5.5-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:f11642dddbb0253cc8853254301b51390ba0081750a8ac03f20ea8103f0c56b6"},
@@ -2848,8 +2858,8 @@ execnet = [
{file = "execnet-1.8.0.tar.gz", hash = "sha256:b73c5565e517f24b62dea8a5ceac178c661c4309d3aa0c3e420856c072c411b4"},
]
faker = [
- {file = "Faker-6.6.0-py3-none-any.whl", hash = "sha256:38bd2ff0afb7d9956fed477a2cd1007a7012b401a9ffd3de5fb909d739880582"},
- {file = "Faker-6.6.0.tar.gz", hash = "sha256:0a68a539b236a614157581a135c82a27024a66dc96b9a491883fe583ae3689f9"},
+ {file = "Faker-6.6.1-py3-none-any.whl", hash = "sha256:8814597d2c9d02824d2590e282ea0c57d1f302ae4f91e85ace0b7e710bd628a5"},
+ {file = "Faker-6.6.1.tar.gz", hash = "sha256:14e23b25d00168f09b2cf8182a17d1fe615ab26666f564248b34ef04f060bd42"},
]
filelock = [
{file = "filelock-3.0.12-py3-none-any.whl", hash = "sha256:929b7d63ec5b7d6b71b0fa5ac14e030b3f70b75747cef1b10da9b879fef15836"},
@@ -3190,6 +3200,9 @@ mccabe = [
measurement = [
{file = "measurement-3.2.0.tar.gz", hash = "sha256:352b20f7f0e553236af7c5ed48d091a51cf26061c1a063f46b31706ff7c0d57a"},
]
+micawber = [
+ {file = "micawber-0.5.3.tar.gz", hash = "sha256:05ef4c89e307e3031dd1d85a3a557cd7f9f900f7dbbbcb33dde454940ca38460"},
+]
mpmath = [
{file = "mpmath-1.2.1-py3-none-any.whl", hash = "sha256:604bc21bd22d2322a177c73bdb573994ef76e62edd595d17e00aff24b0667e5c"},
{file = "mpmath-1.2.1.tar.gz", hash = "sha256:79ffb45cf9f4b101a807595bcb3e72e0396202e0b1d25d689134b48c4216a81a"},
@@ -3394,8 +3407,11 @@ psycopg2-binary = [
{file = "psycopg2_binary-2.8.6-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:2dac98e85565d5688e8ab7bdea5446674a83a3945a8f416ad0110018d1501b94"},
{file = "psycopg2_binary-2.8.6-cp38-cp38-win32.whl", hash = "sha256:bd1be66dde2b82f80afb9459fc618216753f67109b859a361cf7def5c7968729"},
{file = "psycopg2_binary-2.8.6-cp38-cp38-win_amd64.whl", hash = "sha256:8cd0fb36c7412996859cb4606a35969dd01f4ea34d9812a141cd920c3b18be77"},
+ {file = "psycopg2_binary-2.8.6-cp39-cp39-macosx_10_9_x86_64.macosx_10_9_intel.macosx_10_10_intel.macosx_10_10_x86_64.whl", hash = "sha256:89705f45ce07b2dfa806ee84439ec67c5d9a0ef20154e0e475e2b2ed392a5b83"},
{file = "psycopg2_binary-2.8.6-cp39-cp39-manylinux1_i686.whl", hash = "sha256:42ec1035841b389e8cc3692277a0bd81cdfe0b65d575a2c8862cec7a80e62e52"},
{file = "psycopg2_binary-2.8.6-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:7312e931b90fe14f925729cde58022f5d034241918a5c4f9797cac62f6b3a9dd"},
+ {file = "psycopg2_binary-2.8.6-cp39-cp39-win32.whl", hash = "sha256:6422f2ff0919fd720195f64ffd8f924c1395d30f9a495f31e2392c2efafb5056"},
+ {file = "psycopg2_binary-2.8.6-cp39-cp39-win_amd64.whl", hash = "sha256:15978a1fbd225583dd8cdaf37e67ccc278b5abecb4caf6b2d6b8e2b948e953f6"},
]
purl = [
{file = "purl-1.5-py2.py3-none-any.whl", hash = "sha256:5ac0e85979da0172d80156701cb3eb9b1eff31f3b43e981ef6dc06251c53a3a4"},
@@ -3796,8 +3812,8 @@ unidecode = [
{file = "Unidecode-1.2.0.tar.gz", hash = "sha256:8d73a97d387a956922344f6b74243c2c6771594659778744b2dbdaad8f6b727d"},
]
urllib3 = [
- {file = "urllib3-1.26.3-py2.py3-none-any.whl", hash = "sha256:1b465e494e3e0d8939b50680403e3aedaa2bc434b7d5af64dfd3c958d7f5ae80"},
- {file = "urllib3-1.26.3.tar.gz", hash = "sha256:de3eedaad74a2683334e282005cd8d7f22f4d55fa690a2a1020a416cb0a47e73"},
+ {file = "urllib3-1.26.4-py2.py3-none-any.whl", hash = "sha256:2f4da4594db7e1e110a944bb1b551fdf4e6c136ad42e4234131391e21eb5b0df"},
+ {file = "urllib3-1.26.4.tar.gz", hash = "sha256:e7b021f7241115872f92f43c6508082facffbd1c048e3c6e2bb9c2a157e28937"},
]
uvicorn = [
{file = "uvicorn-0.13.4-py3-none-any.whl", hash = "sha256:7587f7b08bd1efd2b9bad809a3d333e972f1d11af8a5e52a9371ee3a5de71524"},
@@ -3824,8 +3840,8 @@ vine = [
{file = "vine-5.0.0.tar.gz", hash = "sha256:7d3b1624a953da82ef63462013bbd271d3eb75751489f9807598e8f340bd637e"},
]
virtualenv = [
- {file = "virtualenv-20.4.2-py2.py3-none-any.whl", hash = "sha256:2be72df684b74df0ea47679a7df93fd0e04e72520022c57b479d8f881485dbe3"},
- {file = "virtualenv-20.4.2.tar.gz", hash = "sha256:147b43894e51dd6bba882cf9c282447f780e2251cd35172403745fc381a0a80d"},
+ {file = "virtualenv-20.4.3-py2.py3-none-any.whl", hash = "sha256:83f95875d382c7abafe06bd2a4cdd1b363e1bb77e02f155ebe8ac082a916b37c"},
+ {file = "virtualenv-20.4.3.tar.gz", hash = "sha256:49ec4eb4c224c6f7dd81bb6d0a28a09ecae5894f4e593c89b0db0885f565a107"},
]
watchgod = [
{file = "watchgod-0.7-py3-none-any.whl", hash = "sha256:d6c1ea21df37847ac0537ca0d6c2f4cdf513562e95f77bb93abbcf05573407b7"},
diff --git a/pyproject.toml b/pyproject.toml
index d0c0a9e35b..40fbe956cc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -69,6 +69,7 @@ google-cloud-pubsub = ">=1.7,<3.0"
uvicorn = {extras = ["standard"], version = ">=0.12.2,<0.14.0"}
gunicorn = "^20.0.4"
authorizenet = "^1.1.3"
+micawber = "^0.5.2"
[tool.poetry.dev-dependencies]
black = "20.8b1"
diff --git a/requirements.txt b/requirements.txt
index b5e282e5f5..2077fdd4d0 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -79,6 +79,7 @@ lxml==4.6.2; python_version >= "2.7" and python_full_version < "3.0.0" or python
markdown==3.3.4; python_version >= "3.6"
maxminddb==2.0.3; python_version >= "3.6"
measurement==3.2.0
+micawber==0.5.2
mpmath==1.2.1; python_version >= "3.6"
mypy-extensions==0.4.3; python_version >= "3.6"
oauthlib==3.1.0; (python_version >= "2.7" and python_full_version < "3.0.0") or (python_full_version >= "3.4.0")
diff --git a/requirements_dev.txt b/requirements_dev.txt
index 6b5402596b..d29b06d523 100644
--- a/requirements_dev.txt
+++ b/requirements_dev.txt
@@ -107,6 +107,7 @@ markupsafe==1.1.1; python_version >= "2.7" and python_full_version < "3.0.0" or
maxminddb==2.0.3; python_version >= "3.6"
mccabe==0.6.1; python_version >= "3.6" and python_full_version < "3.0.0" and python_version < "4.0" or python_version >= "3.6" and python_version < "4.0" and python_full_version >= "3.5.0"
measurement==3.2.0
+micawber==0.5.2
mpmath==1.2.1; python_version >= "3.6"
multidict==5.1.0; python_version >= "3.6"
mypy-extensions==0.4.3; python_version >= "3.6"
diff --git a/saleor/core/management/commands/create_thumbnails.py b/saleor/core/management/commands/create_thumbnails.py
index 05d7f2d1ab..59e6aafac6 100644
--- a/saleor/core/management/commands/create_thumbnails.py
+++ b/saleor/core/management/commands/create_thumbnails.py
@@ -3,7 +3,7 @@ import logging
from django.core.management.base import BaseCommand
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
-from ....product.models import ProductImage
+from ....product.models import ProductMedia
logger = logging.getLogger(__name__)
@@ -17,7 +17,7 @@ class Command(BaseCommand):
def warm_products(self):
self.stdout.write("Products thumbnails generation:")
warmer = VersatileImageFieldWarmer(
- instance_or_queryset=ProductImage.objects.all(),
+ instance_or_queryset=ProductMedia.objects.all(),
rendition_key_set="products",
image_attr="image",
verbose=True,
diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.py
index 853fb2d312..e646b237ad 100644
--- a/saleor/core/tests/test_core.py
+++ b/saleor/core/tests/test_core.py
@@ -16,7 +16,7 @@ from ...channel.models import Channel
from ...discount.models import Sale, SaleChannelListing, Voucher, VoucherChannelListing
from ...giftcard.models import GiftCard
from ...order.models import Order
-from ...product.models import ProductImage, ProductType
+from ...product.models import ProductMedia, ProductType
from ...shipping.models import ShippingZone
from ..storages import S3MediaStorage
from ..templatetags.placeholder import placeholder
@@ -188,7 +188,7 @@ def test_create_gift_card(db):
def test_create_thumbnails(product_with_image, settings, monkeypatch):
monkeypatch.setattr("django.core.cache.cache.get", Mock(return_value=None))
sizeset = settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETS["products"]
- product_image = product_with_image.images.first()
+ product_image = product_with_image.media.first()
# There's no way to list images created by versatile prewarmer
# So we delete all created thumbnails/crops and count them
@@ -199,7 +199,7 @@ def test_create_thumbnails(product_with_image, settings, monkeypatch):
# Image didn't have any thumbnails/crops created, so there's no log
assert not log_deleted_images
- create_thumbnails(product_image.pk, ProductImage, "products")
+ create_thumbnails(product_image.pk, ProductMedia, "products")
log_deleted_images = io.StringIO()
with redirect_stdout(log_deleted_images):
product_image.image.delete_all_created_images()
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 4d4099e47a..24941b9e5a 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -64,11 +64,11 @@ from ...product.models import (
CollectionProduct,
Product,
ProductChannelListing,
- ProductImage,
+ ProductMedia,
ProductType,
ProductVariant,
ProductVariantChannelListing,
- VariantImage,
+ VariantMedia,
)
from ...product.tasks import update_products_discounted_prices_of_discount_task
from ...product.thumbnails import (
@@ -300,8 +300,8 @@ def create_product_variants(variants_data, create_images):
product.default_variant = variant
product.save(update_fields=["default_variant", "updated_at"])
if create_images:
- image = variant.product.images.filter().first()
- VariantImage.objects.get_or_create(variant=variant, image=image)
+ image = variant.product.get_first_image()
+ VariantMedia.objects.get_or_create(variant=variant, media=image)
quantity = random.randint(100, 500)
create_stocks(variant, quantity=quantity)
@@ -473,9 +473,9 @@ def get_email(first_name, last_name):
def create_product_image(product, placeholder_dir, image_name):
image = get_image(placeholder_dir, image_name)
# We don't want to create duplicated product images
- if product.images.count() >= len(IMAGES_MAPPING.get(product.pk, [])):
+ if product.media.count() >= len(IMAGES_MAPPING.get(product.pk, [])):
return None
- product_image = ProductImage(product=product, image=image)
+ product_image = ProductMedia(product=product, image=image)
product_image.save()
create_product_thumbnails.delay(product_image.pk)
return product_image
diff --git a/saleor/core/utils/validators.py b/saleor/core/utils/validators.py
new file mode 100644
index 0000000000..3b708a0dd3
--- /dev/null
+++ b/saleor/core/utils/validators.py
@@ -0,0 +1,34 @@
+from typing import Any, Dict, Tuple
+
+import micawber
+from django.core.exceptions import ValidationError
+
+from ...product import ProductMediaTypes
+from ...product.error_codes import ProductErrorCode
+
+SUPPORTED_MEDIA_TYPES = {
+ "photo": ProductMediaTypes.IMAGE,
+ "video": ProductMediaTypes.VIDEO,
+}
+MEDIA_MAX_WIDTH = 1920
+MEDIA_MAX_HEIGHT = 1080
+
+
+def get_oembed_data(url: str, field_name: str) -> Tuple[Dict[str, Any], str]:
+ """Get the oembed data from URL or raise an ValidationError."""
+ providers = micawber.bootstrap_basic()
+
+ try:
+ oembed_data = providers.request(
+ url, maxwidth=MEDIA_MAX_WIDTH, maxheight=MEDIA_MAX_HEIGHT
+ )
+ return oembed_data, SUPPORTED_MEDIA_TYPES[oembed_data["type"]]
+ except (micawber.exceptions.ProviderException, KeyError):
+ raise ValidationError(
+ {
+ field_name: ValidationError(
+ "Unsupported media provider or incorrect URL.",
+ code=ProductErrorCode.UNSUPPORTED_MEDIA_PROVIDER.value,
+ )
+ }
+ )
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index a443f6a465..411072d0ff 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -5,7 +5,7 @@ from measurement.measures import Weight
from .....attribute.models import Attribute, AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
from .....channel.models import Channel
-from .....product.models import Product, ProductVariant, VariantImage
+from .....product.models import Product, ProductVariant, VariantMedia
from .....warehouse.models import Warehouse
from ....utils import ProductExportFields
from ....utils.products_data import get_products_data
@@ -31,7 +31,7 @@ def test_get_products_data(product, product_with_image, collection, image, chann
collection.products.add(product)
variant = product.variants.first()
- VariantImage.objects.create(variant=variant, image=product.images.first())
+ VariantMedia.objects.create(variant=variant, media=product.media.first())
products = Product.objects.all()
export_fields = set(
@@ -83,10 +83,10 @@ def test_get_products_data(product, product_with_image, collection, image, chann
if product.weight
else ""
),
- "images__image": (
+ "media__image": (
""
- if not product.images.all()
- else "http://mirumee.com{}".format(product.images.first().image.url)
+ if not product.media.all()
+ else "http://mirumee.com{}".format(product.media.first().image.url)
),
}
@@ -100,10 +100,10 @@ def test_get_products_data(product, product_with_image, collection, image, chann
for variant in product.variants.all():
data = {
"variants__sku": variant.sku,
- "variants__images__image": (
+ "variants__media__image": (
""
- if not variant.images.all()
- else "http://mirumee.com{}".format(variant.images.first().image.url)
+ if not variant.media.all()
+ else "http://mirumee.com{}".format(variant.media.first().image.url)
),
"variant_weight": (
"{} g".foramt(int(variant.weight.value * 1000))
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index c6105b558f..70a446722c 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -2,7 +2,7 @@ from unittest.mock import patch
from .....attribute.models import Attribute, AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
-from .....product.models import Product, ProductImage, ProductVariant, VariantImage
+from .....product.models import Product, ProductMedia, ProductVariant, VariantMedia
from .....warehouse.models import Warehouse
from ....utils import ProductExportFields
from ....utils.products_data import (
@@ -32,7 +32,7 @@ def test_get_products_relations_data(prepare_products_data_mocked, product_list)
qs = Product.objects.all()
export_fields = {
"collections__slug",
- "images__image",
+ "media__image",
"name",
"description",
}
@@ -49,7 +49,7 @@ def test_get_products_relations_data(prepare_products_data_mocked, product_list)
qs.values_list("pk", flat=True)
)
assert args[1:] == (
- {"collections__slug", "images__image"},
+ {"collections__slug", "media__image"},
attribute_ids,
channel_ids,
)
@@ -197,10 +197,10 @@ def test_prepare_products_relations_data(
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
- for image in product_with_image.images.all()
+ for image in product_with_image.media.all()
]
)
- expected_result = {pk: {"collections__slug": collections, "images__image": images}}
+ expected_result = {pk: {"collections__slug": collections, "media__image": images}}
expected_result = add_product_attribute_data_to_expected_data(
expected_result, product_with_image, attribute_ids, pk
@@ -296,7 +296,7 @@ def test_get_variants_relations_data(prepare_variants_data_mocked, product_list)
export_fields = {
"collections__slug",
"variants__sku",
- "variants__images__image",
+ "variants__media__image",
}
attribute_ids = []
warehouse_ids = []
@@ -314,7 +314,7 @@ def test_get_variants_relations_data(prepare_variants_data_mocked, product_list)
qs.values_list("pk", flat=True)
)
assert args[1:] == (
- {"variants__images__image"},
+ {"variants__media__image"},
attribute_ids,
warehouse_ids,
channel_ids,
@@ -519,12 +519,12 @@ def test_prepare_variants_relations_data(
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
- product_image = ProductImage.objects.create(
+ product_image = ProductMedia.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
- VariantImage.objects.create(variant=variant, image=product_image)
+ VariantMedia.objects.create(variant=variant, media=product_image)
- fields = {"variants__images__image"}
+ fields = {"variants__media__image"}
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
warehouse_ids = [str(w.pk) for w in Warehouse.objects.all()]
channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]
@@ -541,10 +541,10 @@ def test_prepare_variants_relations_data(
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
- for image in variant.images.all()
+ for image in variant.media.all()
]
)
- expected_result[pk] = {"variants__images__image": images} if images else {}
+ expected_result[pk] = {"variants__media__image": images} if images else {}
expected_result = add_variant_attribute_data_to_expected_data(
expected_result, variant, attribute_ids, pk
)
@@ -565,12 +565,12 @@ def test_prepare_variants_relations_data_only_fields(
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
- product_image = ProductImage.objects.create(
+ product_image = ProductMedia.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
- VariantImage.objects.create(variant=variant, image=product_image)
+ VariantMedia.objects.create(variant=variant, media=product_image)
- fields = {"variants__images__image"}
+ fields = {"variants__media__image"}
attribute_ids = []
warehouse_ids = []
channel_ids = []
@@ -585,10 +585,10 @@ def test_prepare_variants_relations_data_only_fields(
images = ", ".join(
[
"http://mirumee.com/media/" + image.image.name
- for image in variant.images.all()
+ for image in variant.media.all()
]
)
- expected_result = {pk: {"variants__images__image": images}}
+ expected_result = {pk: {"variants__media__image": images}}
assert result == expected_result
@@ -599,10 +599,10 @@ def test_prepare_variants_relations_data_attributes_ids(
# given
qs = Product.objects.all()
variant = product_with_variant_with_two_attributes.variants.first()
- product_image = ProductImage.objects.create(
+ product_image = ProductMedia.objects.create(
product=product_with_variant_with_two_attributes, image=image
)
- VariantImage.objects.create(variant=variant, image=product_image)
+ VariantMedia.objects.create(variant=variant, media=product_image)
fields = set()
attribute_ids = [str(attr.pk) for attr in Attribute.objects.all()]
@@ -724,7 +724,7 @@ def test_add_image_uris_to_data(product):
# given
pk = product.pk
image_path = "test/path/image.jpg"
- field = "variant_images"
+ field = "variant_media"
input_data = {pk: {}}
# when
@@ -739,8 +739,8 @@ def test_add_image_uris_to_data_update_images(product):
pk = product.pk
old_path = "http://mirumee.com/media/test/image0.jpg"
image_path = "test/path/image.jpg"
- input_data = {pk: {"product_images": {old_path}}}
- field = "product_images"
+ input_data = {pk: {"product_media": {old_path}}}
+ field = "product_media"
# when
result = add_image_uris_to_data(product.pk, image_path, field, input_data)
@@ -756,9 +756,7 @@ def test_add_image_uris_to_data_no_image_path(product):
input_data = {pk: {"name": "test"}}
# when
- result = add_image_uris_to_data(
- product.pk, image_path, "product_images", input_data
- )
+ result = add_image_uris_to_data(product.pk, image_path, "product_media", input_data)
# then
assert result == input_data
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index 65ed78a80c..40cf7db83f 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -15,9 +15,9 @@ class ProductExportFields:
},
"product_many_to_many": {
"collections": "collections__slug",
- "product images": "images__image",
+ "product media": "media__image",
},
- "variant_many_to_many": {"variant images": "variants__images__image"},
+ "variant_many_to_many": {"variant media": "variants__media__image"},
}
PRODUCT_ATTRIBUTE_FIELDS = {
diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.py
index 5918022cf1..f2ebacf447 100644
--- a/saleor/csv/utils/export.py
+++ b/saleor/csv/utils/export.py
@@ -114,7 +114,7 @@ def export_products_in_batches(
"attributes",
"variants",
"collections",
- "images",
+ "media",
"product_type",
"category",
)
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index 08187c7dfa..19cffba54a 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -135,9 +135,9 @@ def prepare_products_relations_data(
for data in relations_data.iterator():
pk = data.get("pk")
collection = data.get("collections__slug")
- image = data.pop("images__image", None)
+ image = data.pop("media__image", None)
- result_data = add_image_uris_to_data(pk, image, "images__image", result_data)
+ result_data = add_image_uris_to_data(pk, image, "media__image", result_data)
result_data = add_collection_info_to_data(pk, collection, result_data)
result_data, data = handle_attribute_data(
@@ -220,10 +220,10 @@ def prepare_variants_relations_data(
for data in relations_data.iterator():
pk = data.get("variants__pk")
- image = data.pop("variants__images__image", None)
+ image = data.pop("variants__media__image", None)
result_data = add_image_uris_to_data(
- pk, image, "variants__images__image", result_data
+ pk, image, "variants__media__image", result_data
)
result_data, data = handle_attribute_data(
pk, data, attribute_ids, result_data, attribute_fields, "variant attribute"
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index cb9ac59cd4..c273e411b6 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -8,6 +8,8 @@ from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils import timezone
from graphene import InputField
+from ....core.utils.validators import get_oembed_data
+from ....product import ProductMediaTypes
from ....product.models import Category, Product, ProductChannelListing
from ...product import types as product_types
from ...tests.utils import get_graphql_content, get_graphql_content_from_response
@@ -279,3 +281,52 @@ def test_requestor_is_superuser_for_anonymous_user():
user = AnonymousUser()
result = requestor_is_superuser(user)
assert result is False
+
+
+ "url, expected_media_type",
+ [
+ (
+ "http://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ ProductMediaTypes.VIDEO,
+ ),
+ (
+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ ProductMediaTypes.VIDEO,
+ ),
+ (
+ "https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=TestingChannel",
+ ProductMediaTypes.VIDEO,
+ ),
+ (
+ "https://vimeo.com/148751763",
+ ProductMediaTypes.VIDEO,
+ ),
+ (
+ "https://www.flickr.com/photos/megane_wakui/31740618232/",
+ ProductMediaTypes.IMAGE,
+ ),
+ ],
+)
+def test_get_oembed_data(url, expected_media_type):
+ oembed_data, media_type = get_oembed_data(url, "media_url")
+
+ assert oembed_data is not {}
+ assert media_type == expected_media_type
+
+
+ "url",
+ [
+ "https://www.streamable.com/8vnouo",
+ "https://www.flickr.com/photos/test/test/",
+ "https://www.youtube.com/embed/v=dQw4w9WgXcQ",
+ "https://vimeo.com/test",
+ "http://onet.pl/",
+ ],
+)
+def test_get_oembed_data_unsupported_media_provider(url):
+ with pytest.raises(
+ ValidationError, match="Unsupported media provider or incorrect URL."
+ ):
+ get_oembed_data(url, "media_url")
diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.py
index ca2c943481..c3c38b4c67 100644
--- a/saleor/graphql/core/tests/test_view.py
+++ b/saleor/graphql/core/tests/test_view.py
@@ -240,7 +240,7 @@ def test_permission_denied_query_graphql_errors_are_logged_in_another_logger(
response = api_client.post_graphql(
"""
mutation {
- productImageDelete(id: "aa") {
+ productMediaDelete(id: "aa") {
errors {
message
}
@@ -261,7 +261,7 @@ def test_validation_errors_query_do_not_get_logged(
response = staff_api_client.post_graphql(
"""
mutation {
- productImageDelete(id: "aa") {
+ productMediaDelete(id: "aa") {
errors {
message
}
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index e5dd829e95..badad64ba0 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -515,7 +515,7 @@ class ProductVariantBulkDelete(ModelBulkDeleteMutation):
models.ProductVariant.objects.filter(id__in=pks).prefetch_related(
"channel_listings",
"attributes__values",
- "variant_images",
+ "variant_media",
)
)
@@ -715,17 +715,17 @@ class ProductTypeBulkDelete(ModelBulkDeleteMutation):
error_type_field = "product_errors"
-class ProductImageBulkDelete(ModelBulkDeleteMutation):
+class ProductMediaBulkDelete(ModelBulkDeleteMutation):
class Arguments:
ids = graphene.List(
graphene.ID,
required=True,
- description="List of product image IDs to delete.",
+ description="List of product media IDs to delete.",
)
class Meta:
- description = "Deletes product images."
- model = models.ProductImage
+ description = "Deletes product media."
+ model = models.ProductMedia
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
diff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.py
index f20074511a..0c3afea470 100644
--- a/saleor/graphql/product/dataloaders/__init__.py
+++ b/saleor/graphql/product/dataloaders/__init__.py
@@ -14,12 +14,14 @@ from .products import (
CollectionsByVariantIdLoader,
ImagesByProductIdLoader,
ImagesByProductVariantIdLoader,
+ MediaByProductIdLoader,
+ MediaByProductVariantIdLoader,
ProductByIdLoader,
ProductByVariantIdLoader,
ProductChannelListingByIdLoader,
ProductChannelListingByProductIdAndChannelSlugLoader,
ProductChannelListingByProductIdLoader,
- ProductImageByIdLoader,
+ ProductMediaByIdLoader,
ProductTypeByIdLoader,
ProductTypeByProductIdLoader,
ProductTypeByVariantIdLoader,
@@ -41,6 +43,8 @@ __all__ = [
"CollectionsByProductIdLoader",
"CollectionsByVariantIdLoader",
"ImagesByProductIdLoader",
+ "ImagesByProductVariantIdLoader",
+ "MediaByProductIdLoader",
"ProductAttributesByProductTypeIdLoader",
"ProductByIdLoader",
"ProductByVariantIdLoader",
@@ -53,8 +57,8 @@ __all__ = [
"ProductVariantByIdLoader",
"ProductVariantChannelListingByIdLoader",
"ProductVariantsByProductIdLoader",
- "ProductImageByIdLoader",
- "ImagesByProductVariantIdLoader",
+ "ProductMediaByIdLoader",
+ "MediaByProductVariantIdLoader",
"SelectedAttributesByProductIdLoader",
"SelectedAttributesByProductVariantIdLoader",
"VariantAttributesByProductTypeIdLoader",
diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.py
index fa04e372f8..27a45d02e0 100644
--- a/saleor/graphql/product/dataloaders/products.py
+++ b/saleor/graphql/product/dataloaders/products.py
@@ -3,6 +3,7 @@ from typing import DefaultDict, Dict, Iterable, List, Optional, Tuple
from django.db.models import F
+from ....product import ProductMediaTypes
from ....product.models import (
Category,
Collection,
@@ -10,11 +11,11 @@ from ....product.models import (
CollectionProduct,
Product,
ProductChannelListing,
- ProductImage,
+ ProductMedia,
ProductType,
ProductVariant,
ProductVariantChannelListing,
- VariantImage,
+ VariantMedia,
)
from ...core.dataloaders import DataLoader
@@ -134,15 +135,28 @@ class ProductTypeByIdLoader(DataLoader):
return [product_types.get(product_type_id) for product_type_id in keys]
+class MediaByProductIdLoader(DataLoader):
+ context_key = "media_by_product"
+
+ def batch_load(self, keys):
+ media = ProductMedia.objects.filter(product_id__in=keys)
+ media_map = defaultdict(list)
+ for media_obj in media:
+ media_map[media_obj.product_id].append(media_obj)
+ return [media_map[product_id] for product_id in keys]
+
+
class ImagesByProductIdLoader(DataLoader):
context_key = "images_by_product"
def batch_load(self, keys):
- images = ProductImage.objects.filter(product_id__in=keys)
- image_map = defaultdict(list)
+ images = ProductMedia.objects.filter(
+ product_id__in=keys, type=ProductMediaTypes.IMAGE
+ )
+ images_map = defaultdict(list)
for image in images:
- image_map[image.product_id].append(image)
- return [image_map[product_id] for product_id in keys]
+ images_map[image.product_id].append(image)
+ return [images_map[product_id] for product_id in keys]
class ProductVariantByIdLoader(DataLoader):
@@ -306,37 +320,71 @@ class VariantsChannelListingByProductIdAndChanneSlugLoader(
]
+class ProductMediaByIdLoader(DataLoader):
+ context_key = "product_media_by_id"
+
+ def batch_load(self, keys):
+ product_media = ProductMedia.objects.in_bulk(keys)
+ return [product_media.get(product_media_id) for product_media_id in keys]
+
+
class ProductImageByIdLoader(DataLoader):
context_key = "product_image_by_id"
def batch_load(self, keys):
- product_images = ProductImage.objects.in_bulk(keys)
- return [product_images.get(product_image_id) for product_image_id in keys]
+ images = ProductMedia.objects.filter(type=ProductMediaTypes.IMAGE).in_bulk(keys)
+ return [images.get(product_image_id) for product_image_id in keys]
+
+
+class MediaByProductVariantIdLoader(DataLoader):
+ context_key = "media_by_product_variant"
+
+ def batch_load(self, keys):
+ variant_media = VariantMedia.objects.filter(variant_id__in=keys).values_list(
+ "variant_id", "media_id"
+ )
+
+ variant_media_pairs = defaultdict(list)
+ for variant_id, media_id in variant_media:
+ variant_media_pairs[variant_id].append(media_id)
+
+ def map_variant_media(variant_media):
+ media_map = {media.id: media for media in variant_media}
+ return [
+ [media_map[media_id] for media_id in variant_media_pairs[variant_id]]
+ for variant_id in keys
+ ]
+
+ return (
+ ProductMediaByIdLoader(self.context)
+ .load_many(set(media_id for variant_id, media_id in variant_media))
+ .then(map_variant_media)
+ )
class ImagesByProductVariantIdLoader(DataLoader):
context_key = "images_by_product_variant"
def batch_load(self, keys):
- variant_images = VariantImage.objects.filter(variant_id__in=keys).values_list(
- "variant_id", "image_id"
- )
+ variant_media = VariantMedia.objects.filter(
+ variant_id__in=keys, media__type=ProductMediaTypes.IMAGE
+ ).values_list("variant_id", "media_id")
- variant_image_pairs = defaultdict(list)
- for variant_id, image_id in variant_images:
- variant_image_pairs[variant_id].append(image_id)
+ variant_media_pairs = defaultdict(list)
+ for variant_id, media_id in variant_media:
+ variant_media_pairs[variant_id].append(media_id)
- def map_variant_images(images):
- images_map = {image.id: image for image in images}
+ def map_variant_media(variant_media):
+ media_map = {media.id: media for media in variant_media}
return [
- [images_map[image_id] for image_id in variant_image_pairs[variant_id]]
+ [media_map[media_id] for media_id in variant_media_pairs[variant_id]]
for variant_id in keys
]
return (
- ProductImageByIdLoader(self.context)
- .load_many(set(image_id for variant_id, image_id in variant_images))
- .then(map_variant_images)
+ ProductMediaByIdLoader(self.context)
+ .load_many(set(media_id for variant_id, media_id in variant_media))
+ .then(map_variant_media)
)
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 549e6a0e03..fbe196f748 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -13,9 +13,10 @@ from ....attribute import models as attribute_models
from ....core.exceptions import PermissionDenied
from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....core.utils.editorjs import clean_editor_js
+from ....core.utils.validators import get_oembed_data
from ....order import OrderStatus
from ....order import models as order_models
-from ....product import models
+from ....product import ProductMediaTypes, models
from ....product.error_codes import CollectionErrorCode, ProductErrorCode
from ....product.tasks import (
update_product_discounted_price_task,
@@ -49,7 +50,7 @@ from ..types import (
Category,
Collection,
Product,
- ProductImage,
+ ProductMedia,
ProductType,
ProductVariant,
)
@@ -66,7 +67,7 @@ class CategoryInput(graphene.InputObjectType):
slug = graphene.String(description="Category slug.")
seo = SeoInput(description="Search engine optimization fields.")
background_image = Upload(description="Background image file.")
- background_image_alt = graphene.String(description="Alt text for an image.")
+ background_image_alt = graphene.String(description="Alt text for a product media.")
class CategoryCreate(ModelMutation):
@@ -471,13 +472,15 @@ class AttributeValueInput(InputObjectType):
class ProductInput(graphene.InputObjectType):
- attributes = graphene.List(AttributeValueInput, description="List of attributes.")
+ attributes = graphene.List(
+ graphene.NonNull(AttributeValueInput), description="List of attributes."
+ )
category = graphene.ID(description="ID of the product's category.", name="category")
charge_taxes = graphene.Boolean(
description="Determine if taxes are being charged for the product."
)
collections = graphene.List(
- graphene.ID,
+ graphene.NonNull(graphene.ID),
description="List of IDs of collections that the product belongs to.",
name="collections",
)
@@ -999,7 +1002,7 @@ class ProductVariantDelete(ModelDeleteMutation):
# Get cached variant with related fields to fully populate webhook payload.
variant = (
models.ProductVariant.objects.prefetch_related(
- "channel_listings", "attributes__values", "variant_images"
+ "channel_listings", "attributes__values", "variant_media"
)
).get(id=instance.id)
@@ -1181,142 +1184,185 @@ class ProductTypeDelete(ModelDeleteMutation):
return response
-class ProductImageCreateInput(graphene.InputObjectType):
- alt = graphene.String(description="Alt text for an image.")
+class ProductMediaCreateInput(graphene.InputObjectType):
+ alt = graphene.String(description="Alt text for a product media.")
image = Upload(
- required=True, description="Represents an image file in a multipart request."
+ required=False, description="Represents an image file in a multipart request."
)
product = graphene.ID(
required=True, description="ID of an product.", name="product"
)
+ media_url = graphene.String(
+ required=False, description="Represents an URL to an external media."
+ )
-class ProductImageCreate(BaseMutation):
+class ProductMediaCreate(BaseMutation):
product = graphene.Field(Product)
- image = graphene.Field(ProductImage)
+ media = graphene.Field(ProductMedia)
class Arguments:
- input = ProductImageCreateInput(
- required=True, description="Fields required to create a product image."
+ input = ProductMediaCreateInput(
+ required=True, description="Fields required to create a product media."
)
class Meta:
description = (
- "Create a product image. This mutation must be sent as a `multipart` "
- "request. More detailed specs of the upload format can be found here: "
+ "Create a media object (image or video URL) associated with product. "
+ "For image, this mutation must be sent as a `multipart` request. "
+ "More detailed specs of the upload format can be found here: "
"https://github.com/jaydenseric/graphql-multipart-request-spec"
)
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
+ @classmethod
+ def validate_input(cls, data):
+ image = data.get("image")
+ media_url = data.get("media_url")
+
+ if not image and not media_url:
+ raise ValidationError(
+ {
+ "input": ValidationError(
+ "Image or external URL is required.",
+ code=ProductErrorCode.REQUIRED,
+ )
+ }
+ )
+ if image and media_url:
+ raise ValidationError(
+ {
+ "input": ValidationError(
+ "Either image or external URL is required.",
+ code=ProductErrorCode.DUPLICATED_INPUT_ITEM,
+ )
+ }
+ )
+
@classmethod
def perform_mutation(cls, _root, info, **data):
data = data.get("input")
+ cls.validate_input(data)
product = cls.get_node_or_error(
info, data["product"], field="product", only_type=Product
)
- image_data = info.context.FILES.get(data["image"])
- validate_image_file(image_data, "image")
+ alt = data.get("alt", "")
+ image = data.get("image")
+ media_url = data.get("media_url")
+ if image:
+ image_data = info.context.FILES.get(image)
+ validate_image_file(image_data, "image")
+ media = product.media.create(
+ image=image_data, alt=alt, type=ProductMediaTypes.IMAGE
+ )
+ create_product_thumbnails.delay(media.pk)
+ else:
+ oembed_data, media_type = get_oembed_data(media_url, "media_url")
+ media = product.media.create(
+ external_url=oembed_data["url"],
+ alt=oembed_data.get("title", alt),
+ type=media_type,
+ oembed_data=oembed_data,
+ )
- image = product.images.create(image=image_data, alt=data.get("alt", ""))
- create_product_thumbnails.delay(image.pk)
product = ChannelContext(node=product, channel_slug=None)
- return ProductImageCreate(product=product, image=image)
+ return ProductMediaCreate(product=product, media=media)
-class ProductImageUpdateInput(graphene.InputObjectType):
- alt = graphene.String(description="Alt text for an image.")
+class ProductMediaUpdateInput(graphene.InputObjectType):
+ alt = graphene.String(description="Alt text for a product media.")
-class ProductImageUpdate(BaseMutation):
+class ProductMediaUpdate(BaseMutation):
product = graphene.Field(Product)
- image = graphene.Field(ProductImage)
+ media = graphene.Field(ProductMedia)
class Arguments:
- id = graphene.ID(required=True, description="ID of a product image to update.")
- input = ProductImageUpdateInput(
- required=True, description="Fields required to update a product image."
+ id = graphene.ID(required=True, description="ID of a product media to update.")
+ input = ProductMediaUpdateInput(
+ required=True, description="Fields required to update a product media."
)
class Meta:
- description = "Updates a product image."
+ description = "Updates a product media."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
@classmethod
def perform_mutation(cls, _root, info, **data):
- image = cls.get_node_or_error(info, data.get("id"), only_type=ProductImage)
- product = image.product
+ media = cls.get_node_or_error(info, data.get("id"), only_type=ProductMedia)
+ product = media.product
alt = data.get("input").get("alt")
if alt is not None:
- image.alt = alt
- image.save(update_fields=["alt"])
+ media.alt = alt
+ media.save(update_fields=["alt"])
product = ChannelContext(node=product, channel_slug=None)
- return ProductImageUpdate(product=product, image=image)
+ return ProductMediaUpdate(product=product, media=media)
-class ProductImageReorder(BaseMutation):
+class ProductMediaReorder(BaseMutation):
product = graphene.Field(Product)
- images = graphene.List(ProductImage)
+ media = graphene.List(graphene.NonNull(ProductMedia))
class Arguments:
product_id = graphene.ID(
required=True,
- description="Id of product that images order will be altered.",
+ description="ID of product that media order will be altered.",
)
- images_ids = graphene.List(
+ media_ids = graphene.List(
graphene.ID,
required=True,
- description="IDs of a product images in the desired order.",
+ description="IDs of a product media in the desired order.",
)
class Meta:
- description = "Changes ordering of the product image."
+ description = "Changes ordering of the product media."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
@classmethod
- def perform_mutation(cls, _root, info, product_id, images_ids):
+ def perform_mutation(cls, _root, info, product_id, media_ids):
product = cls.get_node_or_error(
info, product_id, field="product_id", only_type=Product
)
- if len(images_ids) != product.images.count():
+ if len(media_ids) != product.media.count():
raise ValidationError(
{
"order": ValidationError(
- "Incorrect number of image IDs provided.",
+ "Incorrect number of media IDs provided.",
code=ProductErrorCode.INVALID,
)
}
)
- images = []
- for image_id in images_ids:
- image = cls.get_node_or_error(
- info, image_id, field="order", only_type=ProductImage
+ ordered_media = []
+ for media_id in media_ids:
+ media = cls.get_node_or_error(
+ info, media_id, field="order", only_type=ProductMedia
)
- if image and image.product != product:
+ if media and media.product != product:
raise ValidationError(
{
"order": ValidationError(
- "Image %(image_id)s does not belong to this product.",
+ "Media %(media_id)s does not belong to this product.",
code=ProductErrorCode.NOT_PRODUCTS_IMAGE,
- params={"image_id": image_id},
+ params={"media_id": media_id},
)
}
)
- images.append(image)
+ ordered_media.append(media)
- for order, image in enumerate(images):
- image.sort_order = order
- image.save(update_fields=["sort_order"])
+ for order, media in enumerate(ordered_media):
+ media.sort_order = order
+ media.save(update_fields=["sort_order"])
product = ChannelContext(node=product, channel_slug=None)
- return ProductImageReorder(product=product, images=images)
+ return ProductMediaReorder(product=product, media=ordered_media)
class ProductVariantSetDefault(BaseMutation):
@@ -1439,126 +1485,120 @@ class ProductVariantReorder(BaseMutation):
return ProductVariantReorder(product=product)
-class ProductImageDelete(BaseMutation):
+class ProductMediaDelete(BaseMutation):
product = graphene.Field(Product)
- image = graphene.Field(ProductImage)
+ media = graphene.Field(ProductMedia)
class Arguments:
- id = graphene.ID(required=True, description="ID of a product image to delete.")
+ id = graphene.ID(required=True, description="ID of a product media to delete.")
class Meta:
- description = "Deletes a product image."
+ description = "Deletes a product media."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
@classmethod
def perform_mutation(cls, _root, info, **data):
- image = cls.get_node_or_error(info, data.get("id"), only_type=ProductImage)
- image_id = image.id
- image.delete()
- image.id = image_id
- product = ChannelContext(node=image.product, channel_slug=None)
- return ProductImageDelete(product=product, image=image)
+ media_obj = cls.get_node_or_error(info, data.get("id"), only_type=ProductMedia)
+ media_id = media_obj.id
+ media_obj.delete()
+ media_obj.id = media_id
+ product = ChannelContext(node=media_obj.product, channel_slug=None)
+ return ProductMediaDelete(product=product, media=media_obj)
-class VariantImageAssign(BaseMutation):
+class VariantMediaAssign(BaseMutation):
product_variant = graphene.Field(ProductVariant)
- image = graphene.Field(ProductImage)
+ media = graphene.Field(ProductMedia)
class Arguments:
- image_id = graphene.ID(
- required=True, description="ID of a product image to assign to a variant."
+ media_id = graphene.ID(
+ required=True, description="ID of a product media to assign to a variant."
)
variant_id = graphene.ID(required=True, description="ID of a product variant.")
class Meta:
- description = "Assign an image to a product variant."
+ description = "Assign an media to a product variant."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
@classmethod
@transaction.atomic()
- def perform_mutation(cls, _root, info, image_id, variant_id):
- image = cls.get_node_or_error(
- info, image_id, field="image_id", only_type=ProductImage
+ def perform_mutation(cls, _root, info, media_id, variant_id):
+ media = cls.get_node_or_error(
+ info, media_id, field="media_id", only_type=ProductMedia
)
variant = cls.get_node_or_error(
info, variant_id, field="variant_id", only_type=ProductVariant
)
- if image and variant:
+ if media and variant:
# check if the given image and variant can be matched together
- image_belongs_to_product = variant.product.images.filter(
- pk=image.pk
- ).first()
- if image_belongs_to_product:
- image.variant_images.create(variant=variant)
+ media_belongs_to_product = variant.product.media.filter(pk=media.pk).first()
+ if media_belongs_to_product:
+ media.variant_media.create(variant=variant)
else:
raise ValidationError(
{
- "image_id": ValidationError(
- "This image doesn't belong to that product.",
+ "media_id": ValidationError(
+ "This media doesn't belong to that product.",
code=ProductErrorCode.NOT_PRODUCTS_IMAGE,
)
}
)
variant = ChannelContext(node=variant, channel_slug=None)
-
transaction.on_commit(
lambda: info.context.plugins.product_variant_updated(variant.node)
)
+ return VariantMediaAssign(product_variant=variant, media=media)
- return VariantImageAssign(product_variant=variant, image=image)
-
-class VariantImageUnassign(BaseMutation):
+class VariantMediaUnassign(BaseMutation):
product_variant = graphene.Field(ProductVariant)
- image = graphene.Field(ProductImage)
+ media = graphene.Field(ProductMedia)
class Arguments:
- image_id = graphene.ID(
+ media_id = graphene.ID(
required=True,
- description="ID of a product image to unassign from a variant.",
+ description="ID of a product media to unassign from a variant.",
)
variant_id = graphene.ID(required=True, description="ID of a product variant.")
class Meta:
- description = "Unassign an image from a product variant."
+ description = "Unassign an media from a product variant."
permissions = (ProductPermissions.MANAGE_PRODUCTS,)
error_type_class = ProductError
error_type_field = "product_errors"
@classmethod
@transaction.atomic()
- def perform_mutation(cls, _root, info, image_id, variant_id):
- image = cls.get_node_or_error(
- info, image_id, field="image_id", only_type=ProductImage
+ def perform_mutation(cls, _root, info, media_id, variant_id):
+ media = cls.get_node_or_error(
+ info, media_id, field="image_id", only_type=ProductMedia
)
variant = cls.get_node_or_error(
info, variant_id, field="variant_id", only_type=ProductVariant
)
try:
- variant_image = models.VariantImage.objects.get(
- image=image, variant=variant
+ variant_media = models.VariantMedia.objects.get(
+ media=media, variant=variant
)
- except models.VariantImage.DoesNotExist:
+ except models.VariantMedia.DoesNotExist:
raise ValidationError(
{
- "image_id": ValidationError(
- "Image is not assigned to this variant.",
+ "media_id": ValidationError(
+ "Media is not assigned to this variant.",
code=ProductErrorCode.NOT_PRODUCTS_IMAGE,
)
}
)
else:
- variant_image.delete()
+ variant_media.delete()
variant = ChannelContext(node=variant, channel_slug=None)
-
transaction.on_commit(
lambda: info.context.plugins.product_variant_updated(variant.node)
)
-
- return VariantImageUnassign(product_variant=variant, image=image)
+ return VariantMediaUnassign(product_variant=variant, media=media)
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 0cf87aa3d4..0806eda51a 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -24,7 +24,7 @@ from .bulk_mutations.products import (
CategoryBulkDelete,
CollectionBulkDelete,
ProductBulkDelete,
- ProductImageBulkDelete,
+ ProductMediaBulkDelete,
ProductTypeBulkDelete,
ProductVariantBulkCreate,
ProductVariantBulkDelete,
@@ -70,10 +70,10 @@ from .mutations.products import (
CollectionUpdate,
ProductCreate,
ProductDelete,
- ProductImageCreate,
- ProductImageDelete,
- ProductImageReorder,
- ProductImageUpdate,
+ ProductMediaCreate,
+ ProductMediaDelete,
+ ProductMediaReorder,
+ ProductMediaUpdate,
ProductTypeCreate,
ProductTypeDelete,
ProductTypeUpdate,
@@ -83,8 +83,8 @@ from .mutations.products import (
ProductVariantReorder,
ProductVariantSetDefault,
ProductVariantUpdate,
- VariantImageAssign,
- VariantImageUnassign,
+ VariantMediaAssign,
+ VariantMediaUnassign,
)
from .resolvers import (
resolve_categories,
@@ -408,12 +408,12 @@ class ProductMutations(graphene.ObjectType):
product_channel_listing_update = ProductChannelListingUpdate.Field()
- product_image_create = ProductImageCreate.Field()
+ product_media_create = ProductMediaCreate.Field()
product_variant_reorder = ProductVariantReorder.Field()
- product_image_delete = ProductImageDelete.Field()
- product_image_bulk_delete = ProductImageBulkDelete.Field()
- product_image_reorder = ProductImageReorder.Field()
- product_image_update = ProductImageUpdate.Field()
+ product_media_delete = ProductMediaDelete.Field()
+ product_media_bulk_delete = ProductMediaBulkDelete.Field()
+ product_media_reorder = ProductMediaReorder.Field()
+ product_media_update = ProductMediaUpdate.Field()
product_type_create = ProductTypeCreate.Field()
product_type_delete = ProductTypeDelete.Field()
@@ -443,5 +443,5 @@ class ProductMutations(graphene.ObjectType):
ProductVariantReorderAttributeValues.Field()
)
- variant_image_assign = VariantImageAssign.Field()
- variant_image_unassign = VariantImageUnassign.Field()
+ variant_media_assign = VariantMediaAssign.Field()
+ variant_media_unassign = VariantMediaUnassign.Field()
diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.py
index 520ded6742..e98d20dca0 100644
--- a/saleor/graphql/product/tests/benchmark/test_product.py
+++ b/saleor/graphql/product/tests/benchmark/test_product.py
@@ -65,9 +65,16 @@ def test_product_details(product_with_image, api_client, count_queries, channel_
value: name
}
}
+ media {
+ id
+ url
+ type
+ alt
+ }
images {
id
url
+ alt
}
}
@@ -140,9 +147,11 @@ def test_product_details(product_with_image, api_client, count_queries, channel_
}
}
}
+ media {
+ id
+ }
images {
id
- url
}
variants {
...ProductVariantFields
@@ -155,8 +164,8 @@ def test_product_details(product_with_image, api_client, count_queries, channel_
"""
product = product_with_image
variant = product_with_image.variants.first()
- image = product_with_image.get_first_image()
- image.variant_images.create(variant=variant)
+ media = product_with_image.get_first_image()
+ media.variant_media.create(variant=variant)
variables = {
"id": Node.to_global_id("Product", product.pk),
@@ -191,6 +200,50 @@ def test_retrieve_product_attributes(
get_graphql_content(api_client.post_graphql(query, variables))
[email protected]_queries(autouse=False)
+def test_retrieve_product_images(product_list, api_client, count_queries, channel_USD):
+ query = """
+ query($sortBy: ProductOrder, $channel: String) {
+ products(first: 10, sortBy: $sortBy, channel: $channel) {
+ edges {
+ node {
+ id
+ images {
+ id
+ }
+ }
+ }
+ }
+ }
+ """
+
+ variables = {"channel": channel_USD.slug}
+ get_graphql_content(api_client.post_graphql(query, variables))
+
+
[email protected]_queries(autouse=False)
+def test_retrieve_product_media(product_list, api_client, count_queries, channel_USD):
+ query = """
+ query($sortBy: ProductOrder, $channel: String) {
+ products(first: 10, sortBy: $sortBy, channel: $channel) {
+ edges {
+ node {
+ id
+ media {
+ id
+ }
+ }
+ }
+ }
+ }
+ """
+
+ variables = {"channel": channel_USD.slug}
+ get_graphql_content(api_client.post_graphql(query, variables))
+
+
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_retrieve_channel_listings(
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 78100d38a1..8802442fd2 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -12,7 +12,7 @@ from ....product.models import (
Collection,
Product,
ProductChannelListing,
- ProductImage,
+ ProductMedia,
ProductType,
ProductVariant,
ProductVariantChannelListing,
@@ -307,14 +307,14 @@ def test_delete_products_variants_in_draft_order(
).exists()
-def test_delete_product_images(
+def test_delete_product_media(
staff_api_client, product_with_images, permission_manage_products
):
- images = product_with_images.images.all()
+ media = product_with_images.media.all()
query = """
- mutation productImageBulkDelete($ids: [ID]!) {
- productImageBulkDelete(ids: $ids) {
+ mutation productMediaBulkDelete($ids: [ID]!) {
+ productMediaBulkDelete(ids: $ids) {
count
}
}
@@ -322,7 +322,8 @@ def test_delete_product_images(
variables = {
"ids": [
- graphene.Node.to_global_id("ProductImage", image.id) for image in images
+ graphene.Node.to_global_id("ProductMedia", media_obj.id)
+ for media_obj in media
]
}
response = staff_api_client.post_graphql(
@@ -330,9 +331,9 @@ def test_delete_product_images(
)
content = get_graphql_content(response)
- assert content["data"]["productImageBulkDelete"]["count"] == 2
- assert not ProductImage.objects.filter(
- id__in=[image.id for image in images]
+ assert content["data"]["productMediaBulkDelete"]["count"] == 2
+ assert not ProductMedia.objects.filter(
+ id__in=[media_obj.id for media_obj in media]
).exists()
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 0105be9bfc..f7638077bf 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -21,6 +21,7 @@ from ....core.weight import WeightUnits
from ....order import OrderStatus
from ....order.models import OrderLine
from ....plugins.manager import PluginsManager
+from ....product import ProductMediaTypes
from ....product.error_codes import ProductErrorCode
from ....product.models import (
Category,
@@ -28,7 +29,7 @@ from ....product.models import (
CollectionChannelListing,
Product,
ProductChannelListing,
- ProductImage,
+ ProductMedia,
ProductType,
ProductVariant,
ProductVariantChannelListing,
@@ -1405,7 +1406,7 @@ def test_fetch_product_from_category_query(
url
alt
}
- images {
+ media {
url
}
variants {
@@ -1937,8 +1938,85 @@ def test_query_products_with_filter_ids(
assert [node["node"]["id"] for node in products_data] == product_ids
+def test_query_product_media_by_id(user_api_client, product_with_image, channel_USD):
+ query = """
+ query productMediaById($mediaId: ID!, $productId: ID!, $channel: String) {
+ product(id: $productId, channel: $channel) {
+ mediaById(id: $mediaId) {
+ id
+ url(size: 200)
+ }
+ }
+ }
+ """
+ media = product_with_image.media.first()
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product_with_image.pk),
+ "mediaId": graphene.Node.to_global_id("ProductMedia", media.pk),
+ "channel": channel_USD.slug,
+ }
+
+ response = user_api_client.post_graphql(query, variables)
+
+ content = get_graphql_content(response)
+ assert content["data"]["product"]["mediaById"]["id"]
+ assert content["data"]["product"]["mediaById"]["url"]
+
+
+def test_query_product_media_by_id_missing_id(
+ user_api_client, product_with_image, channel_USD
+):
+ query = """
+ query productMediaById($mediaId: ID!, $productId: ID!, $channel: String) {
+ product(id: $productId, channel: $channel) {
+ mediaById(id: $mediaId) {
+ id
+ url
+ }
+ }
+ }
+ """
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product_with_image.pk),
+ "mediaId": graphene.Node.to_global_id("ProductMedia", 9999),
+ "channel": channel_USD.slug,
+ }
+
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content_from_response(response)
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == "Product media not found."
+ assert content["data"]["product"] is None
+
+
def test_query_product_image_by_id(user_api_client, product_with_image, channel_USD):
- image = product_with_image.images.first()
+ query = """
+ query productMediaById($imageId: ID!, $productId: ID!, $channel: String) {
+ product(id: $productId, channel: $channel) {
+ imageById(id: $imageId) {
+ id
+ url(size: 200)
+ }
+ }
+ }
+ """
+ media = product_with_image.media.first()
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product_with_image.pk),
+ "imageId": graphene.Node.to_global_id("ProductMedia", media.pk),
+ "channel": channel_USD.slug,
+ }
+
+ response = user_api_client.post_graphql(query, variables)
+
+ content = get_graphql_content(response)
+ assert content["data"]["product"]["imageById"]["id"]
+ assert content["data"]["product"]["imageById"]["url"]
+
+
+def test_query_product_image_by_id_missing_id(
+ user_api_client, product_with_image, channel_USD
+):
query = """
query productImageById($imageId: ID!, $productId: ID!, $channel: String) {
product(id: $productId, channel: $channel) {
@@ -1951,13 +2029,16 @@ def test_query_product_image_by_id(user_api_client, product_with_image, channel_
"""
variables = {
"productId": graphene.Node.to_global_id("Product", product_with_image.pk),
- "imageId": graphene.Node.to_global_id("ProductImage", image.pk),
+ "imageId": graphene.Node.to_global_id("ProductMedia", 9999),
"channel": channel_USD.slug,
}
+
response = user_api_client.post_graphql(query, variables)
- data = get_graphql_content(response)
- assert data["data"]["product"]["imageById"]["id"]
- assert data["data"]["product"]["imageById"]["url"]
+
+ content = get_graphql_content_from_response(response)
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == "Product image not found."
+ assert content["data"]["product"]["imageById"] is None
def test_product_with_collections(
@@ -6018,18 +6099,39 @@ def test_product_type_delete_mutation_variants_in_draft_order(
assert OrderLine.objects.filter(pk=order_line_not_in_draft.pk).exists()
-def test_product_image_create_mutation(
- monkeypatch, staff_api_client, product, permission_manage_products, media_root
-):
- query = """
- mutation createProductImage($image: Upload!, $product: ID!) {
- productImageCreate(input: {image: $image, product: $product}) {
- image {
- id
+PRODUCT_MEDIA_CREATE_QUERY = """
+ mutation createProductMedia(
+ $product: ID!,
+ $image: Upload,
+ $mediaUrl: String,
+ $alt: String
+ ) {
+ productMediaCreate(input: {
+ product: $product,
+ mediaUrl: $mediaUrl,
+ alt: $alt,
+ image: $image
+ }) {
+ product {
+ media {
+ url
+ alt
+ type
+ oembedData
+ }
+ }
+ productErrors {
+ code
+ field
}
}
}
"""
+
+
+def test_product_media_create_mutation(
+ monkeypatch, staff_api_client, product, permission_manage_products, media_root
+):
mock_create_thumbnails = Mock(return_value=None)
monkeypatch.setattr(
(
@@ -6042,55 +6144,152 @@ def test_product_image_create_mutation(
image_file, image_name = create_image()
variables = {
"product": graphene.Node.to_global_id("Product", product.id),
+ "alt": "",
"image": image_name,
}
- body = get_multipart_request_body(query, variables, image_file, image_name)
+ body = get_multipart_request_body(
+ PRODUCT_MEDIA_CREATE_QUERY, variables, image_file, image_name
+ )
response = staff_api_client.post_multipart(
body, permissions=[permission_manage_products]
)
get_graphql_content(response)
product.refresh_from_db()
- product_image = product.images.last()
+ product_image = product.media.last()
assert product_image.image.file
# The image creation should have triggered a warm-up
mock_create_thumbnails.assert_called_once_with(product_image.pk)
-def test_product_image_create_mutation_without_file(
+def test_product_media_create_mutation_without_file(
monkeypatch, staff_api_client, product, permission_manage_products, media_root
):
- query = """
- mutation createProductImage($image: Upload!, $product: ID!) {
- productImageCreate(input: {image: $image, product: $product}) {
- productErrors {
- code
- field
- }
- }
- }
- """
variables = {
"product": graphene.Node.to_global_id("Product", product.id),
"image": "image name",
}
- body = get_multipart_request_body(query, variables, file="", file_name="name")
+ body = get_multipart_request_body(
+ PRODUCT_MEDIA_CREATE_QUERY, variables, file="", file_name="name"
+ )
response = staff_api_client.post_multipart(
body, permissions=[permission_manage_products]
)
content = get_graphql_content(response)
- errors = content["data"]["productImageCreate"]["productErrors"]
+
+ errors = content["data"]["productMediaCreate"]["productErrors"]
assert errors[0]["field"] == "image"
assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
-def test_invalid_product_image_create_mutation(
+def test_product_media_create_mutation_with_media_url(
+ monkeypatch, staff_api_client, product, permission_manage_products, media_root
+):
+ variables = {
+ "product": graphene.Node.to_global_id("Product", product.id),
+ "mediaUrl": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
+ "alt": "",
+ }
+ body = get_multipart_request_body(
+ PRODUCT_MEDIA_CREATE_QUERY, variables, file="", file_name="name"
+ )
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+
+ media = content["data"]["productMediaCreate"]["product"]["media"]
+ assert len(media) == 1
+ assert media[0]["url"] == "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
+ assert media[0]["alt"] == "Rick Astley - Never Gonna Give You Up (Video)"
+ assert media[0]["type"] == ProductMediaTypes.VIDEO
+
+ oembed_data = json.loads(media[0]["oembedData"])
+ assert oembed_data["url"] == ("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
+ assert oembed_data["type"] == "video"
+ assert oembed_data["html"] is not None
+ assert oembed_data["thumbnail_url"] == (
+ "https://i.ytimg.com/vi/dQw4w9WgXcQ/hqdefault.jpg"
+ )
+
+
+def test_product_media_create_mutation_without_url_or_image(
+ monkeypatch, staff_api_client, product, permission_manage_products, media_root
+):
+ variables = {
+ "product": graphene.Node.to_global_id("Product", product.id),
+ "alt": "Test Alt Text",
+ }
+ body = get_multipart_request_body(
+ PRODUCT_MEDIA_CREATE_QUERY, variables, file="", file_name="name"
+ )
+
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["productMediaCreate"]["productErrors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "input"
+
+
+def test_product_media_create_mutation_with_both_url_and_image(
+ monkeypatch, staff_api_client, product, permission_manage_products, media_root
+):
+ image_file, image_name = create_image()
+ variables = {
+ "product": graphene.Node.to_global_id("Product", product.id),
+ "mediaUrl": "https://www.youtube.com/watch?v=SomeVideoID&ab_channel=Test",
+ "image": image_name,
+ "alt": "Test Alt Text",
+ }
+ body = get_multipart_request_body(
+ PRODUCT_MEDIA_CREATE_QUERY, variables, image_file, image_name
+ )
+
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["productMediaCreate"]["productErrors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["field"] == "input"
+
+
+def test_product_media_create_mutation_with_unknown_url(
+ monkeypatch, staff_api_client, product, permission_manage_products, media_root
+):
+ variables = {
+ "product": graphene.Node.to_global_id("Product", product.id),
+ "mediaUrl": "https://www.videohosting.com/SomeVideoID",
+ "alt": "Test Alt Text",
+ }
+ body = get_multipart_request_body(
+ PRODUCT_MEDIA_CREATE_QUERY, variables, file="", file_name="name"
+ )
+
+ response = staff_api_client.post_multipart(
+ body, permissions=[permission_manage_products]
+ )
+
+ content = get_graphql_content(response)
+ errors = content["data"]["productMediaCreate"]["productErrors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.UNSUPPORTED_MEDIA_PROVIDER.name
+ assert errors[0]["field"] == "mediaUrl"
+
+
+def test_invalid_product_media_create_mutation(
staff_api_client, product, permission_manage_products
):
query = """
- mutation createProductImage($image: Upload!, $product: ID!) {
- productImageCreate(input: {image: $image, product: $product}) {
- image {
+ mutation createProductMedia($image: Upload!, $product: ID!) {
+ productMediaCreate(input: {image: $image, product: $product}) {
+ media {
id
url
sortOrder
@@ -6108,24 +6307,26 @@ def test_invalid_product_image_create_mutation(
"image": image_name,
}
body = get_multipart_request_body(query, variables, image_file, image_name)
+
response = staff_api_client.post_multipart(
body, permissions=[permission_manage_products]
)
+
content = get_graphql_content(response)
- assert content["data"]["productImageCreate"]["errors"] == [
+ assert content["data"]["productMediaCreate"]["errors"] == [
{"field": "image", "message": "Invalid file type"}
]
product.refresh_from_db()
- assert product.images.count() == 0
+ assert product.media.count() == 0
def test_product_image_update_mutation(
monkeypatch, staff_api_client, product_with_image, permission_manage_products
):
query = """
- mutation updateProductImage($imageId: ID!, $alt: String) {
- productImageUpdate(id: $imageId, input: {alt: $alt}) {
- image {
+ mutation updateProductMedia($mediaId: ID!, $alt: String) {
+ productMediaUpdate(id: $mediaId, input: {alt: $alt}) {
+ media {
alt
}
}
@@ -6141,57 +6342,57 @@ def test_product_image_update_mutation(
mock_create_thumbnails,
)
- image_obj = product_with_image.images.first()
+ media_obj = product_with_image.media.first()
alt = "damage alt"
variables = {
"alt": alt,
- "imageId": graphene.Node.to_global_id("ProductImage", image_obj.id),
+ "mediaId": graphene.Node.to_global_id("ProductMedia", media_obj.id),
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
content = get_graphql_content(response)
- assert content["data"]["productImageUpdate"]["image"]["alt"] == alt
+ assert content["data"]["productMediaUpdate"]["media"]["alt"] == alt
# We did not update the image field,
# the image should not have triggered a warm-up
assert mock_create_thumbnails.call_count == 0
-def test_product_image_delete(
+def test_product_media_delete(
staff_api_client, product_with_image, permission_manage_products
):
product = product_with_image
query = """
- mutation deleteProductImage($id: ID!) {
- productImageDelete(id: $id) {
- image {
+ mutation deleteProductMedia($id: ID!) {
+ productMediaDelete(id: $id) {
+ media {
id
url
}
}
}
"""
- image_obj = product.images.first()
- node_id = graphene.Node.to_global_id("ProductImage", image_obj.id)
+ media_obj = product.media.first()
+ node_id = graphene.Node.to_global_id("ProductMedia", media_obj.id)
variables = {"id": node_id}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
content = get_graphql_content(response)
- data = content["data"]["productImageDelete"]
- assert image_obj.image.url in data["image"]["url"]
- with pytest.raises(image_obj._meta.model.DoesNotExist):
- image_obj.refresh_from_db()
- assert node_id == data["image"]["id"]
+ data = content["data"]["productMediaDelete"]
+ assert media_obj.image.url in data["media"]["url"]
+ with pytest.raises(media_obj._meta.model.DoesNotExist):
+ media_obj.refresh_from_db()
+ assert node_id == data["media"]["id"]
-def test_reorder_images(
+def test_reorder_media(
staff_api_client, product_with_images, permission_manage_products
):
query = """
- mutation reorderImages($product_id: ID!, $images_ids: [ID]!) {
- productImageReorder(productId: $product_id, imagesIds: $images_ids) {
+ mutation reorderMedia($product_id: ID!, $media_ids: [ID]!) {
+ productMediaReorder(productId: $product_id, mediaIds: $media_ids) {
product {
id
}
@@ -6199,14 +6400,14 @@ def test_reorder_images(
}
"""
product = product_with_images
- images = product.images.all()
- image_0 = images[0]
- image_1 = images[1]
- image_0_id = graphene.Node.to_global_id("ProductImage", image_0.id)
- image_1_id = graphene.Node.to_global_id("ProductImage", image_1.id)
+ media = product.media.all()
+ media_0 = media[0]
+ media_1 = media[1]
+ media_0_id = graphene.Node.to_global_id("ProductMedia", media_0.id)
+ media_1_id = graphene.Node.to_global_id("ProductMedia", media_1.id)
product_id = graphene.Node.to_global_id("Product", product.id)
- variables = {"product_id": product_id, "images_ids": [image_1_id, image_0_id]}
+ variables = {"product_id": product_id, "media_ids": [media_1_id, media_0_id]}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
@@ -6214,16 +6415,16 @@ def test_reorder_images(
# Check if order has been changed
product.refresh_from_db()
- reordered_images = product.images.all()
- reordered_image_0 = reordered_images[0]
- reordered_image_1 = reordered_images[1]
- assert image_0.id == reordered_image_1.id
- assert image_1.id == reordered_image_0.id
+ reordered_media = product.media.all()
+ reordered_media_0 = reordered_media[0]
+ reordered_media_1 = reordered_media[1]
+ assert media_0.id == reordered_media_1.id
+ assert media_1.id == reordered_media_0.id
ASSIGN_VARIANT_QUERY = """
- mutation assignVariantImageMutation($variantId: ID!, $imageId: ID!) {
- variantImageAssign(variantId: $variantId, imageId: $imageId) {
+ mutation assignVariantMediaMutation($variantId: ID!, $mediaId: ID!) {
+ variantMediaAssign(variantId: $variantId, mediaId: $mediaId) {
errors {
field
message
@@ -6236,38 +6437,37 @@ ASSIGN_VARIANT_QUERY = """
"""
-def test_assign_variant_image(
+def test_assign_variant_media(
staff_api_client, user_api_client, product_with_image, permission_manage_products
):
query = ASSIGN_VARIANT_QUERY
variant = product_with_image.variants.first()
- image = product_with_image.images.first()
+ media_obj = product_with_image.media.first()
variables = {
"variantId": to_global_id("ProductVariant", variant.pk),
- "imageId": to_global_id("ProductImage", image.pk),
+ "mediaId": to_global_id("ProductMedia", media_obj.pk),
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
get_graphql_content(response)
variant.refresh_from_db()
- assert variant.images.first() == image
+ assert variant.media.first() == media_obj
-def test_assign_variant_image_second_time(
+def test_assign_variant_media_second_time(
staff_api_client, user_api_client, product_with_image, permission_manage_products
):
# given
query = ASSIGN_VARIANT_QUERY
variant = product_with_image.variants.first()
- image = product_with_image.images.first()
-
- image.variant_images.create(variant=variant)
+ media_obj = product_with_image.media.first()
+ media_obj.variant_media.create(variant=variant)
variables = {
"variantId": to_global_id("ProductVariant", variant.pk),
- "imageId": to_global_id("ProductImage", image.pk),
+ "mediaId": to_global_id("ProductMedia", media_obj.pk),
}
# when
@@ -6284,7 +6484,7 @@ def test_assign_variant_image_second_time(
)
-def test_assign_variant_image_from_different_product(
+def test_assign_variant_media_from_different_product(
staff_api_client, user_api_client, product_with_image, permission_manage_products
):
query = ASSIGN_VARIANT_QUERY
@@ -6293,16 +6493,16 @@ def test_assign_variant_image_from_different_product(
product_with_image.slug = "product-with-image"
product_with_image.save()
- image_2 = ProductImage.objects.create(product=product_with_image)
+ media_obj_2 = ProductMedia.objects.create(product=product_with_image)
variables = {
"variantId": to_global_id("ProductVariant", variant.pk),
- "imageId": to_global_id("ProductImage", image_2.pk),
+ "mediaId": to_global_id("ProductMedia", media_obj_2.pk),
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
content = get_graphql_content(response)
- assert content["data"]["variantImageAssign"]["errors"][0]["field"] == "imageId"
+ assert content["data"]["variantMediaAssign"]["errors"][0]["field"] == "mediaId"
# check permissions
response = user_api_client.post_graphql(query, variables)
@@ -6310,8 +6510,8 @@ def test_assign_variant_image_from_different_product(
UNASSIGN_VARIANT_IMAGE_QUERY = """
- mutation unassignVariantImageMutation($variantId: ID!, $imageId: ID!) {
- variantImageUnassign(variantId: $variantId, imageId: $imageId) {
+ mutation unassignVariantMediaMutation($variantId: ID!, $mediaId: ID!) {
+ variantMediaUnassign(variantId: $variantId, mediaId: $mediaId) {
errors {
field
message
@@ -6324,42 +6524,42 @@ UNASSIGN_VARIANT_IMAGE_QUERY = """
"""
-def test_unassign_variant_image(
+def test_unassign_variant_media_image(
staff_api_client, product_with_image, permission_manage_products
):
query = UNASSIGN_VARIANT_IMAGE_QUERY
- image = product_with_image.images.first()
+ media = product_with_image.media.first()
variant = product_with_image.variants.first()
- variant.variant_images.create(image=image)
+ variant.variant_media.create(media=media)
variables = {
"variantId": to_global_id("ProductVariant", variant.pk),
- "imageId": to_global_id("ProductImage", image.pk),
+ "mediaId": to_global_id("ProductMedia", media.pk),
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
get_graphql_content(response)
variant.refresh_from_db()
- assert variant.images.count() == 0
+ assert variant.media.count() == 0
-def test_unassign_not_assigned_variant_image(
+def test_unassign_not_assigned_variant_media_image(
staff_api_client, product_with_image, permission_manage_products
):
query = UNASSIGN_VARIANT_IMAGE_QUERY
variant = product_with_image.variants.first()
- image_2 = ProductImage.objects.create(product=product_with_image)
+ media = ProductMedia.objects.create(product=product_with_image)
variables = {
"variantId": to_global_id("ProductVariant", variant.pk),
- "imageId": to_global_id("ProductImage", image_2.pk),
+ "mediaId": to_global_id("ProductMedia", media.pk),
}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
content = get_graphql_content(response)
- assert content["data"]["variantImageUnassign"]["errors"][0]["field"] == ("imageId")
+ assert content["data"]["variantMediaUnassign"]["errors"][0]["field"] == ("mediaId")
@patch("saleor.product.tasks.update_variants_names.delay")
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 87f5f740c5..3a307d0ac8 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -62,7 +62,7 @@ def test_fetch_variant(
currency
amount
}
- images {
+ media {
id
}
name
diff --git a/saleor/graphql/product/types/__init__.py b/saleor/graphql/product/types/__init__.py
index 59e102e126..a517f650a1 100644
--- a/saleor/graphql/product/types/__init__.py
+++ b/saleor/graphql/product/types/__init__.py
@@ -4,7 +4,7 @@ from .products import (
Category,
Collection,
Product,
- ProductImage,
+ ProductMedia,
ProductType,
ProductVariant,
)
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 9ab596cbeb..7414870521 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -78,6 +78,8 @@ from ..dataloaders import (
CollectionsByProductIdLoader,
ImagesByProductIdLoader,
ImagesByProductVariantIdLoader,
+ MediaByProductIdLoader,
+ MediaByProductVariantIdLoader,
ProductAttributesByProductTypeIdLoader,
ProductByIdLoader,
ProductChannelListingByProductIdAndChannelSlugLoader,
@@ -203,7 +205,13 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
),
)
images = graphene.List(
- lambda: ProductImage, description="List of images for the product variant."
+ lambda: ProductImage,
+ description="List of images for the product variant.",
+ deprecation_reason="Will be removed in Saleor 4.0. Use the `media` instead.",
+ )
+ media = graphene.List(
+ graphene.NonNull(lambda: ProductMedia),
+ description="List of media for the product variant.",
)
translation = TranslationField(
ProductVariantTranslation,
@@ -463,6 +471,10 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
.then(calculate_revenue_with_channel)
)
+ @staticmethod
+ def resolve_media(root: ChannelContext[models.ProductVariant], info, *_args):
+ return MediaByProductVariantIdLoader(info.context).load(root.node.id)
+
@staticmethod
def resolve_images(root: ChannelContext[models.ProductVariant], info, *_args):
return ImagesByProductVariantIdLoader(info.context).load(root.node.id)
@@ -520,16 +532,32 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
graphene.NonNull(ProductChannelListing),
description="List of availability in channels for the product.",
)
+ media_by_id = graphene.Field(
+ graphene.NonNull(lambda: ProductMedia),
+ id=graphene.Argument(graphene.ID, description="ID of a product media."),
+ description="Get a single product media by ID.",
+ )
image_by_id = graphene.Field(
lambda: ProductImage,
id=graphene.Argument(graphene.ID, description="ID of a product image."),
description="Get a single product image by ID.",
+ deprecation_reason=(
+ "Will be removed in Saleor 4.0. Use the `mediaById` field instead."
+ ),
)
variants = graphene.List(
ProductVariant, description="List of variants for the product."
)
+ media = graphene.List(
+ graphene.NonNull(lambda: ProductMedia),
+ description="List of media for the product.",
+ )
images = graphene.List(
- lambda: ProductImage, description="List of images for the product."
+ lambda: ProductImage,
+ description="List of images for the product.",
+ deprecation_reason=(
+ "Will be removed in Saleor 4.0. Use the `media` field instead."
+ ),
)
collections = graphene.List(
lambda: Collection, description="List of collections for the product."
@@ -601,16 +629,23 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
@staticmethod
def resolve_thumbnail(root: ChannelContext[models.Product], info, *, size=255):
- def return_first_thumbnail(images):
- image = images[0] if images else None
- if image:
+ def return_first_thumbnail(product_media):
+ if product_media:
+ image = product_media[0]
+ oembed_data = image.oembed_data
+
+ if oembed_data.get("thumbnail_url"):
+ return Image(
+ alt=oembed_data["title"], url=oembed_data["thumbnail_url"]
+ )
+
url = get_product_image_thumbnail(image, size, method="thumbnail")
alt = image.alt
return Image(alt=alt, url=info.context.build_absolute_uri(url))
return None
return (
- ImagesByProductIdLoader(info.context)
+ MediaByProductIdLoader(info.context)
.load(root.node.id)
.then(return_first_thumbnail)
)
@@ -714,14 +749,26 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
def resolve_attributes(root: ChannelContext[models.Product], info):
return SelectedAttributesByProductIdLoader(info.context).load(root.node.id)
+ @staticmethod
+ def resolve_media_by_id(root: ChannelContext[models.Product], info, id):
+ pk = get_database_id(info, id, ProductMedia)
+ try:
+ return root.node.media.get(pk=pk)
+ except models.ProductMedia.DoesNotExist:
+ raise GraphQLError("Product media not found.")
+
@staticmethod
def resolve_image_by_id(root: ChannelContext[models.Product], info, id):
- pk = get_database_id(info, id, ProductImage)
+ pk = get_database_id(info, id, ProductMedia)
try:
- return root.node.images.get(pk=pk)
- except models.ProductImage.DoesNotExist:
+ return root.node.media.get(pk=pk)
+ except models.ProductMedia.DoesNotExist:
raise GraphQLError("Product image not found.")
+ @staticmethod
+ def resolve_media(root: ChannelContext[models.Product], info, **_kwargs):
+ return MediaByProductIdLoader(info.context).load(root.node.id)
+
@staticmethod
def resolve_images(root: ChannelContext[models.Product], info, **_kwargs):
return ImagesByProductIdLoader(info.context).load(root.node.id)
@@ -1123,21 +1170,24 @@ class Category(CountableDjangoObjectType):
@key(fields="id")
-class ProductImage(CountableDjangoObjectType):
+class ProductMedia(CountableDjangoObjectType):
url = graphene.String(
required=True,
- description="The URL of the image.",
+ description="The URL of the media.",
size=graphene.Int(description="Size of the image."),
)
class Meta:
- description = "Represents a product image."
- only_fields = ["alt", "id", "sort_order"]
+ description = "Represents a product media."
+ fields = ["alt", "id", "sort_order", "type", "oembed_data"]
interfaces = [relay.Node]
- model = models.ProductImage
+ model = models.ProductMedia
@staticmethod
- def resolve_url(root: models.ProductImage, info, *, size=None):
+ def resolve_url(root: models.ProductMedia, info, *, size=None):
+ if root.external_url:
+ return root.external_url
+
if size:
url = get_thumbnail(root.image, size, method="thumbnail")
else:
@@ -1147,3 +1197,37 @@ class ProductImage(CountableDjangoObjectType):
@staticmethod
def __resolve_reference(root, _info, **_kwargs):
return graphene.Node.get_node_from_global_id(_info, root.id)
+
+
+@key(fields="id")
+class ProductImage(graphene.ObjectType):
+ id = graphene.ID(required=True, description="The ID of the image.")
+ alt = graphene.String(description="The alt text of the image.")
+ sort_order = graphene.Int(
+ required=False,
+ description=(
+ "The new relative sorting position of the item (from -inf to +inf). "
+ "1 moves the item one position forward, -1 moves the item one position "
+ "backward, 0 leaves the item unchanged."
+ ),
+ )
+ url = graphene.String(
+ required=True,
+ description="The URL of the image.",
+ size=graphene.Int(description="Size of the image."),
+ )
+
+ class Meta:
+ description = "Represents a product image."
+
+ @staticmethod
+ def resolve_id(root: models.ProductMedia, info):
+ return graphene.Node.to_global_id("ProductMedia", root.id)
+
+ @staticmethod
+ def resolve_url(root: models.ProductMedia, info, *, size=None):
+ if size:
+ url = get_thumbnail(root.image, size, method="thumbnail")
+ else:
+ url = root.image.url
+ return info.context.build_absolute_uri(url)
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 7040053946..c754122668 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -2653,12 +2653,12 @@ type Mutation {
productUpdate(id: ID!, input: ProductInput!): ProductUpdate
productTranslate(id: ID!, input: TranslationInput!, languageCode: LanguageCodeEnum!): ProductTranslate
productChannelListingUpdate(id: ID!, input: ProductChannelListingUpdateInput!): ProductChannelListingUpdate
- productImageCreate(input: ProductImageCreateInput!): ProductImageCreate
+ productMediaCreate(input: ProductMediaCreateInput!): ProductMediaCreate
productVariantReorder(moves: [ReorderInput]!, productId: ID!): ProductVariantReorder
- productImageDelete(id: ID!): ProductImageDelete
- productImageBulkDelete(ids: [ID]!): ProductImageBulkDelete
- productImageReorder(imagesIds: [ID]!, productId: ID!): ProductImageReorder
- productImageUpdate(id: ID!, input: ProductImageUpdateInput!): ProductImageUpdate
+ productMediaDelete(id: ID!): ProductMediaDelete
+ productMediaBulkDelete(ids: [ID]!): ProductMediaBulkDelete
+ productMediaReorder(mediaIds: [ID]!, productId: ID!): ProductMediaReorder
+ productMediaUpdate(id: ID!, input: ProductMediaUpdateInput!): ProductMediaUpdate
productTypeCreate(input: ProductTypeInput!): ProductTypeCreate
productTypeDelete(id: ID!): ProductTypeDelete
productTypeBulkDelete(ids: [ID]!): ProductTypeBulkDelete
@@ -2681,8 +2681,8 @@ type Mutation {
productVariantTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): ProductVariantTranslate
productVariantChannelListingUpdate(id: ID!, input: [ProductVariantChannelListingAddInput!]!): ProductVariantChannelListingUpdate
productVariantReorderAttributeValues(attributeId: ID!, moves: [ReorderInput]!, variantId: ID!): ProductVariantReorderAttributeValues
- variantImageAssign(imageId: ID!, variantId: ID!): VariantImageAssign
- variantImageUnassign(imageId: ID!, variantId: ID!): VariantImageUnassign
+ variantMediaAssign(mediaId: ID!, variantId: ID!): VariantMediaAssign
+ variantMediaUnassign(mediaId: ID!, variantId: ID!): VariantMediaUnassign
paymentCapture(amount: PositiveDecimal, paymentId: ID!): PaymentCapture
paymentRefund(amount: PositiveDecimal, paymentId: ID!): PaymentRefund
paymentVoid(paymentId: ID!): PaymentVoid
@@ -3954,9 +3954,11 @@ type Product implements Node & ObjectWithMetadata {
taxType: TaxType
attributes: [SelectedAttribute!]!
channelListings: [ProductChannelListing!]
- imageById(id: ID): ProductImage
+ mediaById(id: ID): ProductMedia!
+ imageById(id: ID): ProductImage @deprecated(reason: "Will be removed in Saleor 4.0. Use the `mediaById` field instead.")
variants: [ProductVariant]
- images: [ProductImage]
+ media: [ProductMedia!]
+ images: [ProductImage] @deprecated(reason: "Will be removed in Saleor 4.0. Use the `media` field instead.")
collections: [Collection]
translation(languageCode: LanguageCodeEnum!): ProductTranslation
availableForPurchase: Date
@@ -4052,10 +4054,10 @@ type ProductCreate {
}
input ProductCreateInput {
- attributes: [AttributeValueInput]
+ attributes: [AttributeValueInput!]
category: ID
chargeTaxes: Boolean
- collections: [ID]
+ collections: [ID!]
description: JSONString
name: String
slug: String
@@ -4097,6 +4099,7 @@ enum ProductErrorCode {
VARIANT_NO_DIGITAL_CONTENT
CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT
PRODUCT_NOT_ASSIGNED_TO_CHANNEL
+ UNSUPPORTED_MEDIA_PROVIDER
}
enum ProductFieldEnum {
@@ -4131,71 +4134,86 @@ input ProductFilterInput {
channel: String
}
-type ProductImage implements Node {
+type ProductImage {
+ id: ID!
+ alt: String
+ sortOrder: Int
+ url(size: Int): String!
+}
+
+input ProductInput {
+ attributes: [AttributeValueInput!]
+ category: ID
+ chargeTaxes: Boolean
+ collections: [ID!]
+ description: JSONString
+ name: String
+ slug: String
+ taxCode: String
+ seo: SeoInput
+ weight: WeightScalar
+ rating: Float
+}
+
+type ProductMedia implements Node {
id: ID!
sortOrder: Int
alt: String!
+ type: ProductMediaType!
+ oembedData: JSONString!
url(size: Int): String!
}
-type ProductImageBulkDelete {
+type ProductMediaBulkDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
count: Int!
productErrors: [ProductError!]!
}
-type ProductImageCreate {
+type ProductMediaCreate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
product: Product
- image: ProductImage
+ media: ProductMedia
productErrors: [ProductError!]!
}
-input ProductImageCreateInput {
+input ProductMediaCreateInput {
alt: String
- image: Upload!
+ image: Upload
product: ID!
+ mediaUrl: String
}
-type ProductImageDelete {
+type ProductMediaDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
product: Product
- image: ProductImage
+ media: ProductMedia
productErrors: [ProductError!]!
}
-type ProductImageReorder {
+type ProductMediaReorder {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
product: Product
- images: [ProductImage]
+ media: [ProductMedia!]
productErrors: [ProductError!]!
}
-type ProductImageUpdate {
+enum ProductMediaType {
+ IMAGE
+ VIDEO
+}
+
+type ProductMediaUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
product: Product
- image: ProductImage
+ media: ProductMedia
productErrors: [ProductError!]!
}
-input ProductImageUpdateInput {
+input ProductMediaUpdateInput {
alt: String
}
-input ProductInput {
- attributes: [AttributeValueInput]
- category: ID
- chargeTaxes: Boolean
- collections: [ID]
- description: JSONString
- name: String
- slug: String
- taxCode: String
- seo: SeoInput
- weight: WeightScalar
- rating: Float
-}
-
input ProductOrder {
direction: OrderDirection!
channel: String
@@ -4383,7 +4401,8 @@ type ProductVariant implements Node & ObjectWithMetadata {
margin: Int
quantityOrdered: Int
revenue(period: ReportingPeriod): TaxedMoney
- images: [ProductImage]
+ images: [ProductImage] @deprecated(reason: "Will be removed in Saleor 4.0. Use the `media` instead.")
+ media: [ProductMedia!]
translation(languageCode: LanguageCodeEnum!): ProductVariantTranslation
digitalContent: DigitalContent
stocks(address: AddressInput, countryCode: CountryCode): [Stock]
@@ -5545,17 +5564,17 @@ enum VariantAttributeScope {
NOT_VARIANT_SELECTION
}
-type VariantImageAssign {
+type VariantMediaAssign {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
productVariant: ProductVariant
- image: ProductImage
+ media: ProductMedia
productErrors: [ProductError!]!
}
-type VariantImageUnassign {
+type VariantMediaUnassign {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
productVariant: ProductVariant
- image: ProductImage
+ media: ProductMedia
productErrors: [ProductError!]!
}
@@ -5988,7 +6007,7 @@ enum WeightUnitsEnum {
scalar _Any
-union _Entity = Address | User | Group | App | ProductVariant | Product | ProductType | Collection | Category | ProductImage | PageType
+union _Entity = Address | User | Group | App | ProductVariant | Product | ProductType | Collection | Category | ProductMedia | ProductImage | PageType
type _Service {
sdl: String
diff --git a/saleor/order/emails.py b/saleor/order/emails.py
index 0caff4ee7f..5c3b3b89f4 100644
--- a/saleor/order/emails.py
+++ b/saleor/order/emails.py
@@ -44,9 +44,9 @@ def collect_data_for_email(
order_pk: int, template: str, redirect_url: str = ""
) -> dict:
"""Collect the required data for sending emails."""
- order = Order.objects.prefetch_related("lines__variant__product__images").get(
- pk=order_pk
- )
+ order = Order.objects.prefetch_related(
+ "lines__variant__product__media",
+ ).get(pk=order_pk)
recipient_email = order.get_customer_email()
send_kwargs, email_context = get_email_context()
diff --git a/saleor/product/__init__.py b/saleor/product/__init__.py
index e69de29bb2..340776a514 100644
--- a/saleor/product/__init__.py
+++ b/saleor/product/__init__.py
@@ -0,0 +1,8 @@
+class ProductMediaTypes:
+ IMAGE = "IMAGE"
+ VIDEO = "VIDEO"
+
+ CHOICES = [
+ (IMAGE, "An uploaded image or an URL to an image"),
+ (VIDEO, "A URL to an external video"),
+ ]
diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.py
index 527e29ce8a..3e0888d52e 100644
--- a/saleor/product/error_codes.py
+++ b/saleor/product/error_codes.py
@@ -18,6 +18,7 @@ class ProductErrorCode(Enum):
VARIANT_NO_DIGITAL_CONTENT = "variant_no_digital_content"
CANNOT_MANAGE_PRODUCT_WITHOUT_VARIANT = "cannot_manage_product_without_variant"
PRODUCT_NOT_ASSIGNED_TO_CHANNEL = "product_not_assigned_to_channel"
+ UNSUPPORTED_MEDIA_PROVIDER = "unsupported_media_provider"
class CollectionErrorCode(Enum):
diff --git a/saleor/product/migrations/0143_rename_product_images_to_product_media.py b/saleor/product/migrations/0143_rename_product_images_to_product_media.py
new file mode 100644
index 0000000000..d604caa188
--- /dev/null
+++ b/saleor/product/migrations/0143_rename_product_images_to_product_media.py
@@ -0,0 +1,165 @@
+# Generated by Django 3.1.5 on 2021-02-12 13:00
+
+import django.db.models.deletion
+import versatileimagefield.fields
+from django.db import migrations, models
+
+from ...product import ProductMediaTypes
+
+
+def migrate_images_content_to_media(apps, _schema_editor):
+ ProductImage = apps.get_model("product", "ProductImage")
+ ProductMedia = apps.get_model("product", "ProductMedia")
+
+ VariantImage = apps.get_model("product", "VariantImage")
+ VariantMedia = apps.get_model("product", "VariantMedia")
+
+ for image in ProductImage.objects.iterator():
+ product_media, _ = ProductMedia.objects.get_or_create(
+ product=image.product,
+ image=image.image,
+ alt=image.alt,
+ ppoi=image.ppoi,
+ sort_order=image.sort_order,
+ type=ProductMediaTypes.IMAGE,
+ )
+
+ for variant_image in VariantImage.objects.filter(image__pk=image.id):
+ VariantMedia.objects.get_or_create(
+ variant=variant_image.variant, media=product_media
+ )
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0142_auto_20210308_1135"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ProductMedia",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "sort_order",
+ models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ (
+ "image",
+ versatileimagefield.fields.VersatileImageField(
+ blank=True, null=True, upload_to="products"
+ ),
+ ),
+ (
+ "ppoi",
+ versatileimagefield.fields.PPOIField(
+ default="0.5x0.5", editable=False, max_length=20
+ ),
+ ),
+ ("alt", models.CharField(blank=True, max_length=128)),
+ (
+ "type",
+ models.CharField(
+ choices=[
+ ("IMAGE", "An uploaded image or an URL to an image"),
+ ("VIDEO", "A URL to an external video"),
+ ],
+ default="IMAGE",
+ max_length=32,
+ ),
+ ),
+ (
+ "external_url",
+ models.CharField(blank=True, max_length=256, null=True),
+ ),
+ ("oembed_data", models.JSONField(blank=True, default=dict)),
+ (
+ "product",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="media",
+ to="product.product",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("sort_order", "pk"),
+ },
+ ),
+ migrations.CreateModel(
+ name="VariantMedia",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "media",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="variant_media",
+ to="product.productmedia",
+ ),
+ ),
+ ],
+ ),
+ migrations.AddField(
+ model_name="variantmedia",
+ name="variant",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="variant_media",
+ to="product.productvariant",
+ ),
+ ),
+ migrations.RunPython(
+ migrate_images_content_to_media, reverse_code=migrations.RunPython.noop
+ ),
+ migrations.AlterUniqueTogether(
+ name="variantimage",
+ unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="variantimage",
+ name="image",
+ ),
+ migrations.RemoveField(
+ model_name="variantimage",
+ name="variant",
+ ),
+ migrations.RemoveField(
+ model_name="productvariant",
+ name="images",
+ ),
+ migrations.AddField(
+ model_name="productvariant",
+ name="media",
+ field=models.ManyToManyField(
+ through="product.VariantMedia", to="product.ProductMedia"
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="variantmedia",
+ unique_together={("variant", "media")},
+ ),
+ migrations.DeleteModel(
+ name="ProductImage",
+ ),
+ migrations.DeleteModel(
+ name="VariantImage",
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index e4ef7cf8ea..fd35d69124 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -7,6 +7,7 @@ from django.contrib.postgres.aggregates import StringAgg
from django.contrib.postgres.indexes import GinIndex
from django.contrib.postgres.search import SearchVectorField
from django.db import models
+from django.db.models import JSONField # type: ignore
from django.db.models import (
BooleanField,
Case,
@@ -46,6 +47,7 @@ from ..core.weight import WeightUnits, zero_weight
from ..discount import DiscountInfo
from ..discount.utils import calculate_discounted_price
from ..seo.models import SeoModel, SeoModelTranslation
+from . import ProductMediaTypes
if TYPE_CHECKING:
# flake8: noqa
@@ -363,7 +365,8 @@ class Product(SeoModel, ModelWithMetadata):
return json_content_to_raw_text(self.description)
def get_first_image(self):
- images = list(self.images.all())
+ all_media = self.media.all()
+ images = [media for media in all_media if media.type == ProductMediaTypes.IMAGE]
return images[0] if images else None
@staticmethod
@@ -450,7 +453,7 @@ class ProductVariant(SortableModel, ModelWithMetadata):
product = models.ForeignKey(
Product, related_name="variants", on_delete=models.CASCADE
)
- images = models.ManyToManyField("ProductImage", through="VariantImage")
+ media = models.ManyToManyField("ProductMedia", through="VariantMedia")
track_inventory = models.BooleanField(default=True)
weight = MeasurementField(
@@ -505,8 +508,9 @@ class ProductVariant(SortableModel, ModelWithMetadata):
)
return smart_text(product_display)
- def get_first_image(self) -> "ProductImage":
- images = list(self.images.all())
+ def get_first_image(self) -> "ProductMedia":
+ all_media = self.media.all()
+ images = [media for media in all_media if media.type == ProductMediaTypes.IMAGE]
return images[0] if images else self.product.get_first_image()
def get_ordering_queryset(self):
@@ -617,32 +621,39 @@ class DigitalContentUrl(models.Model):
return build_absolute_uri(url)
-class ProductImage(SortableModel):
- product = models.ForeignKey(
- Product, related_name="images", on_delete=models.CASCADE
+class ProductMedia(SortableModel):
+ product = models.ForeignKey(Product, related_name="media", on_delete=models.CASCADE)
+ image = VersatileImageField(
+ upload_to="products", ppoi_field="ppoi", blank=True, null=True
)
- image = VersatileImageField(upload_to="products", ppoi_field="ppoi", blank=False)
ppoi = PPOIField()
alt = models.CharField(max_length=128, blank=True)
+ type = models.CharField(
+ max_length=32,
+ choices=ProductMediaTypes.CHOICES,
+ default=ProductMediaTypes.IMAGE,
+ )
+ external_url = models.CharField(max_length=256, blank=True, null=True)
+ oembed_data = JSONField(blank=True, default=dict)
class Meta:
ordering = ("sort_order", "pk")
app_label = "product"
def get_ordering_queryset(self):
- return self.product.images.all()
+ return self.product.media.all()
-class VariantImage(models.Model):
+class VariantMedia(models.Model):
variant = models.ForeignKey(
- "ProductVariant", related_name="variant_images", on_delete=models.CASCADE
+ "ProductVariant", related_name="variant_media", on_delete=models.CASCADE
)
- image = models.ForeignKey(
- ProductImage, related_name="variant_images", on_delete=models.CASCADE
+ media = models.ForeignKey(
+ ProductMedia, related_name="variant_media", on_delete=models.CASCADE
)
class Meta:
- unique_together = ("variant", "image")
+ unique_together = ("variant", "media")
class CollectionProduct(SortableModel):
diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.py
index 205529ac42..de15ba07b7 100644
--- a/saleor/product/tests/test_product.py
+++ b/saleor/product/tests/test_product.py
@@ -256,12 +256,12 @@ def test_costs_get_margin_for_variant_channel_listing(
@patch("saleor.product.thumbnails.create_thumbnails")
def test_create_product_thumbnails(mock_create_thumbnails, product_with_image):
- product_image = product_with_image.images.first()
+ product_image = product_with_image.media.first()
create_product_thumbnails(product_image.pk)
assert mock_create_thumbnails.call_count == 1
args, kwargs = mock_create_thumbnails.call_args
assert kwargs == {
- "model": models.ProductImage,
+ "model": models.ProductMedia,
"pk": product_image.pk,
"size_set": "products",
}
diff --git a/saleor/product/thumbnails.py b/saleor/product/thumbnails.py
index 8651eed5d8..f8366c84e6 100644
--- a/saleor/product/thumbnails.py
+++ b/saleor/product/thumbnails.py
@@ -1,12 +1,12 @@
from ..celeryconf import app
from ..core.utils import create_thumbnails
-from .models import Category, Collection, ProductImage
+from .models import Category, Collection, ProductMedia
@app.task
def create_product_thumbnails(image_id: str):
- """Take a ProductImage model and create thumbnails for it."""
- create_thumbnails(pk=image_id, model=ProductImage, size_set="products")
+ """Take a ProductMedia model and create thumbnails for it."""
+ create_thumbnails(pk=image_id, model=ProductMedia, size_set="products")
@app.task
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index b18a53bcc1..b15530fce0 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -68,6 +68,7 @@ from ..payment.interface import GatewayConfig, PaymentData
from ..payment.models import Payment
from ..plugins.models import PluginConfiguration
from ..plugins.vatlayer.plugin import VatlayerPlugin
+from ..product import ProductMediaTypes
from ..product.models import (
Category,
CategoryTranslation,
@@ -78,13 +79,13 @@ from ..product.models import (
DigitalContentUrl,
Product,
ProductChannelListing,
- ProductImage,
+ ProductMedia,
ProductTranslation,
ProductType,
ProductVariant,
ProductVariantChannelListing,
ProductVariantTranslation,
- VariantImage,
+ VariantMedia,
)
from ..product.tests.utils import create_image
from ..shipping.models import (
@@ -1332,6 +1333,67 @@ def product_with_variant_with_two_attributes(
return product
+def product_with_variant_with_external_media(
+ color_attribute,
+ size_attribute,
+ category,
+ warehouse,
+ channel_USD,
+):
+ product_type = ProductType.objects.create(
+ name="Type with two variants",
+ slug="two-variants",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.variant_attributes.add(color_attribute)
+ product_type.variant_attributes.add(size_attribute)
+
+ product = Product.objects.create(
+ name="Test product with two variants",
+ slug="test-product-with-two-variant",
+ product_type=product_type,
+ category=category,
+ )
+ media_obj = ProductMedia.objects.create(
+ product=product,
+ external_url="https://www.youtube.com/watch?v=di8_dJ3Clyo",
+ alt="video_1",
+ type=ProductMediaTypes.VIDEO,
+ oembed_data="{}",
+ )
+ product.media.add(media_obj)
+
+ ProductChannelListing.objects.create(
+ product=product,
+ channel=channel_USD,
+ is_published=True,
+ currency=channel_USD.currency_code,
+ visible_in_listings=True,
+ available_for_purchase=datetime.date(1999, 1, 1),
+ )
+
+ variant = ProductVariant.objects.create(product=product, sku="prodVar1")
+ variant.media.add(media_obj)
+ ProductVariantChannelListing.objects.create(
+ variant=variant,
+ channel=channel_USD,
+ price_amount=Decimal(10),
+ cost_price_amount=Decimal(1),
+ currency=channel_USD.currency_code,
+ )
+
+ associate_attribute_values_to_instance(
+ variant, color_attribute, color_attribute.values.first()
+ )
+ associate_attribute_values_to_instance(
+ variant, size_attribute, size_attribute.values.first()
+ )
+
+ return product
+
+
@pytest.fixture
def product_with_variant_with_file_attribute(
color_attribute, file_attribute, category, warehouse, channel_USD
@@ -1872,7 +1934,7 @@ def order_list(customer_user, channel_USD):
@pytest.fixture
def product_with_image(product, image, media_root):
- ProductImage.objects.create(product=product, image=image)
+ ProductMedia.objects.create(product=product, image=image)
return product
@@ -1946,8 +2008,8 @@ def product_with_images(product_type, category, media_root, channel_USD):
file_mock_0.name = "image0.jpg"
file_mock_1 = MagicMock(spec=File, name="FileMock1")
file_mock_1.name = "image1.jpg"
- product.images.create(image=file_mock_0)
- product.images.create(image=file_mock_1)
+ product.media.create(image=file_mock_0)
+ product.media.create(image=file_mock_1)
return product
diff --git a/saleor/tests/runner.py b/saleor/tests/runner.py
index f7c1766112..ca8e13b879 100644
--- a/saleor/tests/runner.py
+++ b/saleor/tests/runner.py
@@ -1,7 +1,7 @@
class PytestTestRunner(object):
"""Runs pytest to discover and run tests."""
- def __init__(self, verbosity=1, failfast=False, keepdb=False, **kwargs):
+ def __init__(self, verbosity=1, failfast=False, keepdb=True, **kwargs):
self.verbosity = verbosity
self.failfast = failfast
self.keepdb = keepdb
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index bf5056e94e..a5bbc5158f 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -18,6 +18,7 @@ from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
from ..order.utils import get_order_country
from ..page.models import Page
from ..payment import ChargeStatus
+from ..product import ProductMediaTypes
from ..product.models import Product
from ..warehouse.models import Warehouse
from .event_types import WebhookEventType
@@ -311,9 +312,16 @@ def generate_product_variant_payload(product_variant: "ProductVariant"):
extra_dict_data={
"attributes": serialize_product_or_variant_attributes(product_variant),
"product_id": product_id,
- "images": [
- {"alt": img.image.alt, "url": build_absolute_uri(img.image.image.url)}
- for img in product_variant.variant_images.all()
+ "media": [
+ {
+ "alt": media_obj.media.alt,
+ "url": (
+ build_absolute_uri(media_obj.media.image.url)
+ if media_obj.media.type == ProductMediaTypes.IMAGE
+ else media_obj.media.external_url
+ ),
+ }
+ for media_obj in product_variant.variant_media.all()
],
},
)
diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.py
index e1fd2aa4d4..f771f3d7c5 100644
--- a/saleor/webhook/tests/test_webhook_payloads.py
+++ b/saleor/webhook/tests/test_webhook_payloads.py
@@ -99,7 +99,7 @@ def test_generate_product_variant_payload(
payload = json.loads(generate_product_variant_payload(variant))[0]
variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
additional_fields = ["channel_listings"]
- extra_dict_data = ["attributes", "product_id", "images"]
+ extra_dict_data = ["attributes", "product_id", "media"]
payload_fields = list(
chain(
["id", "type"], PRODUCT_VARIANT_FIELDS, extra_dict_data, additional_fields
@@ -123,19 +123,53 @@ def test_generate_product_variant_payload(
assert len(payload.keys()) == len(payload_fields)
+def test_generate_product_variant_with_external_media_payload(
+ product_with_variant_with_external_media,
+):
+ variant = product_with_variant_with_external_media.variants.first()
+ payload = json.loads(generate_product_variant_payload(variant))[0]
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ additional_fields = ["channel_listings"]
+ extra_dict_data = ["attributes", "product_id", "media"]
+ payload_fields = list(
+ chain(
+ ["id", "type"], PRODUCT_VARIANT_FIELDS, extra_dict_data, additional_fields
+ )
+ )
+
+ for field in payload_fields:
+ assert payload.get(field) is not None
+
+ assert variant_id is not None
+ assert payload["sku"] == "prodVar1"
+ assert payload["media"] == [
+ {"alt": "video_1", "url": "https://www.youtube.com/watch?v=di8_dJ3Clyo"}
+ ]
+ assert len(payload["attributes"]) == 2
+ assert len(payload["channel_listings"]) == 1
+ assert payload["channel_listings"][0] == {
+ "cost_price_amount": "1.000",
+ "currency": "USD",
+ "id": ANY,
+ "price_amount": "10.000",
+ "type": "ProductVariantChannelListing",
+ }
+ assert len(payload.keys()) == len(payload_fields)
+
+
def test_generate_product_variant_deleted_payload(
product_with_variant_with_two_attributes,
):
variant = product_with_variant_with_two_attributes.variants.prefetch_related(
"channel_listings",
"attributes__values",
- "variant_images",
+ "variant_media",
).first()
ProductVariant.objects.filter(id=variant.id).delete()
payload = json.loads(generate_product_variant_payload(variant))[0]
[_, payload_variant_id] = graphene.Node.from_global_id(payload["id"])
additional_fields = ["channel_listings"]
- extra_dict_data = ["attributes", "product_id", "images"]
+ extra_dict_data = ["attributes", "product_id", "media"]
payload_fields = list(
chain(
["id", "type"], PRODUCT_VARIANT_FIELDS, extra_dict_data, additional_fields