Skip to content

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

Modify models to use is_visible, implement PublishableModel

Michał Jelonek8e2d058f29fe
diff --git a/saleor/core/models.py b/saleor/core/models.py
index fc61fd1883..9dd558331d 100644
--- a/saleor/core/models.py
+++ b/saleor/core/models.py
@@ -1,5 +1,7 @@
+import datetime
+
from django.db import models
-from django.db.models import F, Max
+from django.db.models import F, Max, Q
class SortableModel(models.Model):
@@ -24,3 +26,37 @@ class SortableModel(models.Model):
qs.filter(sort_order__gt=self.sort_order).update(
sort_order=F('sort_order') - 1)
super().delete(*args, **kwargs)
+
+
+class PublishedQuerySet(models.QuerySet):
+
+ def published(self):
+ today = datetime.date.today()
+ return self.filter(
+ Q(publication_date__lte=today) | Q(publication_date__isnull=True),
+ is_published=True)
+
+ @staticmethod
+ def user_has_access_to_all(user):
+ return user.is_active and user.has_perm('product.manage_products')
+
+ def visible_to_user(self, user):
+ if self.user_has_access_to_all(user):
+ return self.all()
+ return self.published()
+
+
+class PublishableModel(models.Model):
+ publication_date = models.DateField(blank=True, null=True)
+ is_published = models.BooleanField(default=True)
+
+ objects = PublishedQuerySet.as_manager()
+
+ class Meta:
+ abstract = True
+
+ @property
+ def is_visible(self):
+ return self.is_published and (
+ self.publication_date is None
+ or self.publication_date < datetime.date.today())
diff --git a/saleor/core/sitemaps.py b/saleor/core/sitemaps.py
index 2880434285..d14c12d89e 100644
--- a/saleor/core/sitemaps.py
+++ b/saleor/core/sitemaps.py
@@ -26,14 +26,14 @@ class CategorySitemap(I18nSitemap):
class CollectionSitemap(I18nSitemap):
def items(self):
- collections = Collection.objects.available().order_by('id')
+ collections = Collection.objects.published().order_by('id')
return collections.only('id', 'name', 'slug')
class PageSitemap(I18nSitemap):
def items(self):
- posts = Page.objects.available()
+ posts = Page.objects.published()
return posts.only('id', 'title', 'slug')
diff --git a/saleor/core/templatetags/status.py b/saleor/core/templatetags/status.py
index 2a0b904489..85b95d2146 100644
--- a/saleor/core/templatetags/status.py
+++ b/saleor/core/templatetags/status.py
@@ -59,8 +59,8 @@ def render_variant_availability_status(variant):
@register.inclusion_tag('dashboard/includes/_page_availability.html')
def render_page_availability(page):
- ctx = {'is_available': page.is_available, 'page': page}
- if page.is_available:
+ ctx = {'is_visible': page.is_visible, 'page': page}
+ if page.is_visible:
label_cls = LABEL_SUCCESS
ctx.update({'label_cls': label_cls})
return ctx
@@ -68,10 +68,10 @@ def render_page_availability(page):
@register.inclusion_tag('dashboard/includes/_collection_availability.html')
def render_collection_availability(collection):
- if collection.is_available:
+ if collection.is_visible:
label_cls = LABEL_SUCCESS
else:
label_cls = LABEL_DANGER
- return {'is_available': collection.is_available,
+ return {'is_visible': collection.is_visible,
'collection': collection,
'label_cls': label_cls}
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index a5578b24d1..ebc49894bd 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -539,7 +539,7 @@ class AddVariantToOrderForm(forms.Form):
variant = AjaxSelect2ChoiceField(
queryset=ProductVariant.objects.filter(
- product__in=Product.objects.available()),
+ product__in=Product.objects.published()),
fetch_data_url=reverse_lazy('dashboard:ajax-available-variants'),
label=pgettext_lazy(
'Order form: subform to add variant to order form: variant field',
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 8eaf63071c..068c8f59ef 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -206,7 +206,7 @@ def ajax_products_list(request):
queryset = (
Product.objects.all()
if request.user.has_perm('product.manage_products')
- else Product.objects.available())
+ else Product.objects.published())
search_query = request.GET.get('q', '')
if search_query:
queryset = queryset.filter(Q(name__icontains=search_query))
@@ -405,7 +405,7 @@ def ajax_available_variants_list(request):
Response format is that of a Select2 JS widget.
"""
- available_products = Product.objects.available().prefetch_related(
+ available_products = Product.objects.published().prefetch_related(
'category',
'product_type__product_attributes')
queryset = ProductVariant.objects.filter(
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index e7c6cd3006..30a6ee5037 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -481,7 +481,7 @@ class Category(CountableDjangoObjectType):
# Otherwise we want to include products from child categories which
# requires performing additional logic.
tree = self.get_descendants(include_self=True)
- qs = models.Product.objects.available()
+ qs = models.Product.objects.published()
qs = qs.filter(category__in=tree)
return gql_optimizer.query(qs, info)
diff --git a/saleor/page/models.py b/saleor/page/models.py
index 9a069de193..ac3c421162 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -1,12 +1,10 @@
-import datetime
-
from django.db import models
from django.urls import reverse
from django.utils.translation import pgettext_lazy
+from ..core.models import PublishableModel, PublishedQuerySet
from ..core.utils import build_absolute_uri
from ..core.utils.translations import TranslationProxy
-from ..product.models import PublishedQuerySet
from ..seo.models import SeoModel, SeoModelTranslation
@@ -17,13 +15,11 @@ class PagePublishedQuerySet(PublishedQuerySet):
return user.is_active and user.has_perm('page.manage_pages')
-class Page(SeoModel):
+class Page(SeoModel, PublishableModel):
slug = models.SlugField(unique=True, max_length=100)
title = models.CharField(max_length=200)
content = models.TextField()
created = models.DateTimeField(auto_now_add=True)
- is_published = models.BooleanField(default=False)
- publication_date = models.DateField(blank=True, null=True)
objects = PagePublishedQuerySet.as_manager()
translated = TranslationProxy()
@@ -43,12 +39,6 @@ class Page(SeoModel):
def get_full_url(self):
return build_absolute_uri(self.get_absolute_url())
- @property
- def is_available(self):
- today = datetime.date.today()
- return self.is_published and (
- self.publication_date is None or self.publication_date <= today)
-
class PageTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)
diff --git a/saleor/page/utils.py b/saleor/page/utils.py
index f9f4b2cb16..14bd6c97af 100644
--- a/saleor/page/utils.py
+++ b/saleor/page/utils.py
@@ -5,4 +5,4 @@ def pages_visible_to_user(user):
qs = Page.objects.prefetch_related('translations')
if user.is_authenticated and user.is_active and user.is_staff:
return qs
- return qs.available()
+ return qs.published()
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 99203edb35..bd5c44fd3e 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -1,11 +1,9 @@
-import datetime
from decimal import Decimal
from django.conf import settings
from django.contrib.postgres.fields import HStoreField
from django.core.validators import MinValueValidator
from django.db import models
-from django.db.models import Q
from django.urls import reverse
from django.utils.encoding import smart_text
from django.utils.text import slugify
@@ -22,7 +20,7 @@ from versatileimagefield.fields import PPOIField, VersatileImageField
from ..core import TaxRateType
from ..core.exceptions import InsufficientStock
-from ..core.models import SortableModel
+from ..core.models import PublishableModel, SortableModel
from ..core.utils.taxes import DEFAULT_TAX_RATE_NAME, apply_tax_to_price
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
@@ -30,24 +28,6 @@ from ..discount.utils import calculate_discounted_price
from ..seo.models import SeoModel, SeoModelTranslation
-class PublishedQuerySet(models.QuerySet):
-
- def available(self):
- today = datetime.date.today()
- return self.filter(
- Q(publication_date__lte=today) | Q(publication_date__isnull=True),
- is_published=True)
-
- @staticmethod
- def user_has_access_to_all(user):
- return user.is_active and user.has_perm('product.manage_products')
-
- def visible_to_user(self, user):
- if self.user_has_access_to_all(user):
- return self.all()
- return self.available()
-
-
class Category(MPTTModel, SeoModel):
name = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
@@ -114,7 +94,7 @@ class ProductType(models.Model):
class_.__module__, class_.__name__, self.pk, self.name)
-class Product(SeoModel):
+class Product(SeoModel, PublishableModel):
product_type = models.ForeignKey(
ProductType, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
@@ -125,8 +105,6 @@ class Product(SeoModel):
currency=settings.DEFAULT_CURRENCY,
max_digits=settings.DEFAULT_MAX_DIGITS,
decimal_places=settings.DEFAULT_DECIMAL_PLACES)
- publication_date = models.DateField(blank=True, null=True)
- is_published = models.BooleanField(default=True)
attributes = HStoreField(default=dict, blank=True)
updated_at = models.DateTimeField(auto_now=True, null=True)
charge_taxes = models.BooleanField(default=True)
@@ -137,7 +115,6 @@ class Product(SeoModel):
measurement=Weight, unit_choices=WeightUnits.CHOICES,
blank=True, null=True)
- objects = PublishedQuerySet.as_manager()
translated = TranslationProxy()
class Meta:
@@ -172,12 +149,6 @@ class Product(SeoModel):
def is_in_stock(self):
return any(variant.is_in_stock() for variant in self)
- @property
- def is_available(self):
- return self.is_published and (
- self.publication_date is None
- or self.publication_date < datetime.date.today())
-
def get_first_image(self):
images = list(self.images.all())
return images[0] if images else None
@@ -438,7 +409,7 @@ class VariantImage(models.Model):
ProductImage, related_name='variant_images', on_delete=models.CASCADE)
-class Collection(SeoModel):
+class Collection(SeoModel, PublishableModel):
name = models.CharField(max_length=128, unique=True)
slug = models.SlugField(max_length=128)
products = models.ManyToManyField(
@@ -446,11 +417,8 @@ class Collection(SeoModel):
background_image = VersatileImageField(
upload_to='collection-backgrounds', blank=True, null=True)
background_image_alt = models.CharField(max_length=128, blank=True)
- is_published = models.BooleanField(default=False)
description = models.TextField(blank=True)
- publication_date = models.DateField(blank=True, null=True)
- objects = PublishedQuerySet.as_manager()
translated = TranslationProxy()
class Meta:
@@ -464,12 +432,6 @@ class Collection(SeoModel):
'product:collection',
kwargs={'pk': self.id, 'slug': self.slug})
- @property
- def is_available(self):
- return self.is_published and (
- self.publication_date is None
- or self.publication_date <= datetime.date.today())
-
class CollectionTranslation(SeoModelTranslation):
language_code = models.CharField(max_length=10)
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index e09d6d4885..b9e1d2fd11 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -17,7 +17,7 @@ def products_visible_to_user(user):
from ..models import Product
if user.is_authenticated and user.is_active and user.is_staff:
return Product.objects.all()
- return Product.objects.available()
+ return Product.objects.published()
def products_with_details(user):
@@ -138,7 +138,7 @@ def collections_visible_to_user(user):
from ..models import Collection
if user.is_authenticated and user.is_active and user.is_staff:
return Collection.objects.all()
- return Collection.objects.available()
+ return Collection.objects.published()
def calculate_revenue_for_variant(variant, start_date):
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index 913733f6d7..0aef3122e9 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -16,7 +16,7 @@ def products_with_availability(products, discounts, taxes, local_currency):
def get_product_availability_status(product):
- is_available = product.is_available
+ is_visible = product.is_visible
are_all_variants_in_stock = all(
variant.is_in_stock() for variant in product.variants.all())
is_in_stock = any(
@@ -34,7 +34,7 @@ def get_product_availability_status(product):
return ProductAvailabilityStatus.OUT_OF_STOCK
if not are_all_variants_in_stock:
return ProductAvailabilityStatus.LOW_STOCK
- if not is_available and product.publication_date is not None:
+ if not is_visible and product.publication_date is not None:
return ProductAvailabilityStatus.NOT_YET_AVAILABLE
return ProductAvailabilityStatus.READY_FOR_PURCHASE
@@ -70,9 +70,9 @@ def get_availability(product, discounts=None, taxes=None, local_currency=None):
price_range_local = None
discount_local_currency = None
- is_available = product.is_in_stock() and product.is_available
+ is_available = product.is_in_stock() and product.is_visible
is_on_sale = (
- product.is_available and discount is not None and
+ product.is_visible and discount is not None and
undiscounted.start != price_range.start)
return ProductAvailability(
diff --git a/saleor/seo/schema/product.py b/saleor/seo/schema/product.py
index 444c8bc4e5..cc93a5021e 100644
--- a/saleor/seo/schema/product.py
+++ b/saleor/seo/schema/product.py
@@ -32,7 +32,7 @@ def product_json_ld(product, attributes=None):
for variant in product.variants.all():
price = variant.get_price()
in_stock = True
- if not product.is_available or not variant.is_in_stock():
+ if not product.is_visible or not variant.is_in_stock():
in_stock = False
variant_data = variant_json_ld(price, variant, in_stock)
data['offers'].append(variant_data)
diff --git a/templates/collection/index.html b/templates/collection/index.html
index c27a407175..dfb22e16e1 100644
--- a/templates/collection/index.html
+++ b/templates/collection/index.html
@@ -10,7 +10,7 @@
{% endblock %}
{% block collection_published_warning %}
- {% if not object.is_available %}
+ {% if not object.is_visible %}
<div class="alert alert-warning" role="alert">
{% if object.publication_date %}
{% blocktrans trimmed with date=object.publication_date|date context "Unpublished collection details text" %}
diff --git a/templates/dashboard/includes/_collection_availability.html b/templates/dashboard/includes/_collection_availability.html
index d008576092..49b0290fbf 100644
--- a/templates/dashboard/includes/_collection_availability.html
+++ b/templates/dashboard/includes/_collection_availability.html
@@ -1,7 +1,7 @@
{% load i18n %}
<div class="label label-{{ label_cls }}">
- {% if is_available %}
+ {% if is_visible %}
{% trans "Published" context "Collection availability status" %}
{% elif collection.publication_date is not None %}
<div class="label">
diff --git a/templates/dashboard/includes/_page_availability.html b/templates/dashboard/includes/_page_availability.html
index 8cbe445638..42082aa68b 100644
--- a/templates/dashboard/includes/_page_availability.html
+++ b/templates/dashboard/includes/_page_availability.html
@@ -1,6 +1,6 @@
{% load i18n %}
-{% if is_available %}
+{% if is_visible %}
<div class="label label-{{ label_cls }}">
{% trans "Published" context "Page availability status" %}
</div>
diff --git a/tests/conftest.py b/tests/conftest.py
index c68a9a8fe4..5ffe6922ec 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -648,7 +648,7 @@ def collection(db):
@pytest.fixture
def collection_with_image(db, image):
collection = Collection.objects.create(
- name='Collection', slug='collection', is_published=True,
+ name='Collection', slug='collection',
description='Test description', background_image=image)
return collection
@@ -656,7 +656,7 @@ def collection_with_image(db, image):
@pytest.fixture
def draft_collection(db):
collection = Collection.objects.create(
- name='Draft collection', slug='draft-collection')
+ name='Draft collection', slug='draft-collection', is_published=False)
return collection
diff --git a/tests/dashboard/test_menu.py b/tests/dashboard/test_menu.py
index 5f396a27dd..cd62c2cc0d 100644
--- a/tests/dashboard/test_menu.py
+++ b/tests/dashboard/test_menu.py
@@ -394,8 +394,8 @@ def test_menu_item_status(menu, category, collection, page):
item = MenuItem.objects.create(
name='Name', menu=menu, page=page)
- assert not item.is_public()
- page.is_published = True
+ assert item.is_public()
+ page.is_published = False
page.save()
item.refresh_from_db()
- assert item.is_public()
+ assert not item.is_public()
diff --git a/tests/test_collection.py b/tests/test_collection.py
index 5680f7f4ad..74a0bb1b0f 100644
--- a/tests/test_collection.py
+++ b/tests/test_collection.py
@@ -34,7 +34,7 @@ def test_collection_not_exists(client):
def test_collection_not_yet_published_returns_404(
- admin_client, client, draft_collection):
+ admin_client, client, draft_collection):
url_kwargs = {'pk': draft_collection.pk, 'slug': draft_collection.slug}
url = reverse('product:collection', kwargs=url_kwargs)
response = client.get(url)
diff --git a/tests/test_page.py b/tests/test_page.py
index ca89b58dea..f4075b69c7 100644
--- a/tests/test_page.py
+++ b/tests/test_page.py
@@ -1,4 +1,6 @@
def test_draft_page_details(client, admin_client, page):
+ page.is_published = False
+ page.save()
page_url = page.get_absolute_url()
response = client.get(page_url)
assert response.status_code == 404
@@ -7,8 +9,6 @@ def test_draft_page_details(client, admin_client, page):
def test_public_page_details(client, admin_client, page):
- page.is_published = True
- page.save()
page_url = page.get_absolute_url()
response = client.get(page_url)
assert response.status_code == 200
diff --git a/tests/test_product_availability.py b/tests/test_product_availability.py
index 34155c444f..ac966a6cc9 100644
--- a/tests/test_product_availability.py
+++ b/tests/test_product_availability.py
@@ -92,7 +92,7 @@ def test_availability(product, monkeypatch, settings, taxes):
def test_available_products_only_published(product_list):
- available_products = models.Product.objects.available()
+ available_products = models.Product.objects.published()
assert available_products.count() == 2
assert all([product.is_published for product in available_products])
@@ -102,6 +102,6 @@ def test_available_products_only_available(product_list):
date_tomorrow = datetime.date.today() + datetime.timedelta(days=1)
product.publication_date = date_tomorrow
product.save()
- available_products = models.Product.objects.available()
+ available_products = models.Product.objects.published()
assert available_products.count() == 1
- assert all([product.is_available for product in available_products])
+ assert all([product.is_visible for product in available_products])
diff --git a/tests/test_templatetags.py b/tests/test_templatetags.py
index d15e81dfa1..3eaea869c9 100644
--- a/tests/test_templatetags.py
+++ b/tests/test_templatetags.py
@@ -35,10 +35,10 @@ def test_menu(menu_with_items):
def test_render_page_availability(page):
page_ctx = render_page_availability(page)
- assert page_ctx == {'page': page, 'is_available': False}
+ assert page_ctx == {
+ 'page': page, 'is_visible': True, 'label_cls': LABEL_SUCCESS}
- page.is_published = True
+ page.is_published = False
page.save()
page_ctx = render_page_availability(page)
- assert page_ctx == {
- 'page': page, 'is_available': True, 'label_cls': LABEL_SUCCESS}
+ assert page_ctx == {'page': page, 'is_visible': False}