Skip to content

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

Add publish validation in product save and signal for unpublish products after category delete

IKarbowiak5c428bfd2016
diff --git a/saleor/product/models.py b/saleor/product/models.py
index d475d599a5..68ce95548b 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -8,6 +8,8 @@ from django.contrib.postgres.fields import JSONField
from django.core.validators import MinValueValidator
from django.db import models
from django.db.models import Case, Count, F, FilteredRelation, Q, When
+from django.db.models.signals import pre_delete
+from django.dispatch import receiver
from django.urls import reverse
from django.utils.encoding import smart_text
from django.utils.html import strip_tags
@@ -68,6 +70,11 @@ class Category(MPTTModel, ModelWithMetadata, SeoModel):
)
+@receiver(pre_delete, sender=Category)
+def set_category_products_as_unpublished(sender, instance, **kwargs):
+ instance.products.all().update(is_published=False, publication_date=None)
+
+
class CategoryTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)
category = models.ForeignKey(
@@ -319,6 +326,10 @@ class Product(SeoModel, ModelWithMetadata, PublishableModel):
# Make sure the "minimal_variant_price_amount" is set
if self.minimal_variant_price_amount is None:
self.minimal_variant_price_amount = self.price_amount
+
+ # Product can't be published if doesn't have category
+ if not self.category and self.is_published:
+ self.is_published = False
return super().save(force_insert, force_update, using, update_fields)
@property