Skip to content

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

WIP

Pacu2089b9347be3d
diff --git a/saleor/core/views.py b/saleor/core/views.py
index 658109cfe3..27e5748555 100644
--- a/saleor/core/views.py
+++ b/saleor/core/views.py
@@ -8,7 +8,7 @@ from impersonate.views import impersonate as orig_impersonate
from ..account.models import User
from ..dashboard.views import staff_member_required
from ..product.utils import products_for_homepage, products_with_availability
-from ..schema.webpage import get_webpage_schema
+from ..seo.schema.webpage import get_webpage_schema
def home(request):
diff --git a/saleor/dashboard/category/forms.py b/saleor/dashboard/category/forms.py
index a26b830540..4e6850333c 100644
--- a/saleor/dashboard/category/forms.py
+++ b/saleor/dashboard/category/forms.py
@@ -10,7 +10,18 @@ from ...product.models import Category
class CategoryForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.parent_pk = kwargs.pop('parent_pk')
- super(CategoryForm, self).__init__(*args, **kwargs)
+ super().__init__(*args, **kwargs)
+ field_maxlength = self.fields['seo_description'].max_length
+ # Placeholder should be no longer than fields maximum size
+ placeholder = self.instance.description[:field_maxlength]
+ self.fields['seo_description'].widget.attrs = {
+ 'id': 'seo_description',
+ 'data-bind': self['description'].auto_id,
+ 'placeholder': placeholder}
+ self.fields['seo_title'].widget.attrs = {
+ 'id': 'seo_title',
+ 'data-bind': self['name'].auto_id,
+ 'placeholder': self.instance.name}
class Meta:
model = Category
diff --git a/saleor/dashboard/collection/forms.py b/saleor/dashboard/collection/forms.py
index 6e45229801..b03e557252 100644
--- a/saleor/dashboard/collection/forms.py
+++ b/saleor/dashboard/collection/forms.py
@@ -31,6 +31,14 @@ class CollectionForm(forms.ModelForm):
super().__init__(*args, **kwargs)
if self.instance.pk:
self.fields['products'].set_initial(self.instance.products.all())
+ self.fields['seo_description'].widget.attrs = {
+ 'id': 'seo_description',
+ 'data-bind': '',
+ 'placeholder': ''}
+ self.fields['seo_title'].widget.attrs = {
+ 'id': 'seo_title',
+ 'data-bind': self['name'].auto_id,
+ 'placeholder': self.instance.name}
def save(self, commit=True):
self.instance.slug = slugify(unidecode(self.instance.name))
diff --git a/saleor/dashboard/page/forms.py b/saleor/dashboard/page/forms.py
index b7bb5d15b9..8f0f4500fe 100644
--- a/saleor/dashboard/page/forms.py
+++ b/saleor/dashboard/page/forms.py
@@ -1,12 +1,30 @@
from django import forms
from django.utils.translation import pgettext_lazy
+from ...core.utils.text import generate_seo_description
from ...page.models import Page
from ..product.forms import RichTextField
class PageForm(forms.ModelForm):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ # Placeholder should be no longer than fields maximum size
+ field_maxlength = self.fields['seo_description'].max_length
+ # Page's content contains htm tags which should be stripped
+ placeholder = generate_seo_description(
+ self.instance.content, field_maxlength)
+ self.fields['seo_description'].widget.attrs = {
+ 'id': 'seo_description',
+ 'data-bind': self['content'].auto_id,
+ 'data-materialize': self['content'].html_name,
+ 'placeholder': placeholder}
+ self.fields['seo_title'].widget.attrs = {
+ 'id': 'seo_title',
+ 'data-bind': self['title'].auto_id,
+ 'placeholder': self.instance.title}
+
class Meta:
model = Page
exclude = []
@@ -27,3 +45,16 @@ class PageForm(forms.ModelForm):
slug = self.cleaned_data.get('slug')
slug = slug.lower()
return slug
+
+ def clean_seo_description(self):
+ seo_description = self.cleaned_data['seo_description']
+
+ # if there is no SEO friendly description set,
+ # generate it from the HTML description
+ if not seo_description:
+ # get the non-safe description (has non escaped HTML tags in it)
+ description = self.data['description']
+
+ # generate a SEO friendly from HTML description
+ seo_description = generate_seo_description(description, 300)
+ return seo_description
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index c2cf2dbf2d..f35a20d9cf 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -218,6 +218,20 @@ class ProductForm(forms.ModelForm, AttributesMixin):
self.prepare_fields_for_attributes()
self.fields['collections'].initial = Collection.objects.filter(
products__name=self.instance)
+ # Placeholder should be no longer than fields maximum size
+ field_maxlength = self.fields['seo_description'].max_length
+ # Product's description contains htm tags which should be stripped
+ placeholder = generate_seo_description(
+ self.instance.description, field_maxlength)
+ self.fields['seo_description'].widget.attrs.update({
+ 'id': 'seo_description',
+ 'data-bind': self['description'].auto_id,
+ 'data-materialize': self['description'].html_name,
+ 'placeholder': placeholder})
+ self.fields['seo_title'].widget.attrs.update({
+ 'id': 'seo_title',
+ 'data-bind': self['name'].auto_id,
+ 'placeholder': self.instance.name})
def clean_seo_description(self):
seo_description = self.cleaned_data['seo_description']
diff --git a/saleor/order/emails.py b/saleor/order/emails.py
index 9268885124..025c2f1d4f 100644
--- a/saleor/order/emails.py
+++ b/saleor/order/emails.py
@@ -5,7 +5,7 @@ from django.urls import reverse
from templated_email import send_templated_mail
from ..core.utils import build_absolute_uri
-from ..schema.email import get_order_confirmation_markup
+from ..seo.schema.email import get_order_confirmation_markup
from .models import Fulfillment, Order
CONFIRM_ORDER_TEMPLATE = 'source/order/confirm_order'
diff --git a/saleor/page/models.py b/saleor/page/models.py
index 4e2ce42ab3..212f4356da 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -4,9 +4,9 @@ from django.db import models
from django.db.models import Q
from django.urls import reverse
from django.utils.translation import pgettext_lazy
-from django.core.validators import MaxLengthValidator
from ..core.utils import build_absolute_uri
+from ..seo.models import SeoModel
class PageQuerySet(models.QuerySet):
@@ -17,19 +17,13 @@ class PageQuerySet(models.QuerySet):
Q(available_on__lte=today) | Q(available_on__isnull=True))
-class Page(models.Model):
+class Page(SeoModel):
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_visible = models.BooleanField(default=False)
available_on = models.DateField(blank=True, null=True)
- seo_title = models.CharField(
- max_length=70, blank=True, null=True,
- validators=[MaxLengthValidator(70)])
- seo_description = models.CharField(
- max_length=300, blank=True, null=True,
- validators=[MaxLengthValidator(300)])
objects = PageQuerySet.as_manager()
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 2a70703ae5..1817c9a9bf 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -4,7 +4,7 @@ from decimal import Decimal
from django.conf import settings
from django.contrib.postgres.fields import HStoreField
from django.core.validators import (
- MaxLengthValidator, MinValueValidator, RegexValidator)
+ MinValueValidator, RegexValidator)
from django.db import models
from django.db.models import F, Max, Q
from django.urls import reverse
@@ -20,19 +20,14 @@ from versatileimagefield.fields import PPOIField, VersatileImageField
from ..core.exceptions import InsufficientStock
from ..discount.utils import calculate_discounted_price
+from ..seo.models import SeoModel
from .utils import get_attributes_display_map
-class Category(MPTTModel):
+class Category(MPTTModel, SeoModel):
name = models.CharField(max_length=128)
slug = models.SlugField(max_length=128)
description = models.TextField(blank=True)
- seo_title = models.CharField(
- max_length=70, blank=True, null=True,
- validators=[MaxLengthValidator(70)])
- seo_description = models.CharField(
- max_length=300, blank=True, null=True,
- validators=[MaxLengthValidator(300)])
parent = models.ForeignKey(
'self', null=True, blank=True, related_name='children',
on_delete=models.CASCADE)
@@ -96,17 +91,11 @@ class ProductQuerySet(models.QuerySet):
Q(is_published=True))
-class Product(models.Model):
+class Product(SeoModel):
product_type = models.ForeignKey(
ProductType, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
description = models.TextField()
- seo_title = models.CharField(
- max_length=70, blank=True, null=True,
- validators=[MaxLengthValidator(70)])
- seo_description = models.CharField(
- max_length=300, blank=True, null=True,
- validators=[MaxLengthValidator(300)])
category = models.ForeignKey(
Category, related_name='products', on_delete=models.CASCADE)
price = MoneyField(
@@ -397,19 +386,13 @@ class VariantImage(models.Model):
ProductImage, related_name='variant_images', on_delete=models.CASCADE)
-class Collection(models.Model):
+class Collection(SeoModel):
name = models.CharField(max_length=128, unique=True)
slug = models.SlugField(max_length=128)
products = models.ManyToManyField(
Product, blank=True, related_name='collections')
background_image = VersatileImageField(
upload_to='collection-backgrounds', blank=True, null=True)
- seo_title = models.CharField(
- max_length=70, blank=True, null=True,
- validators=[MaxLengthValidator(70)])
- seo_description = models.CharField(
- max_length=300, blank=True, null=True,
- validators=[MaxLengthValidator(300)])
class Meta:
ordering = ['pk']
diff --git a/saleor/product/utils.py b/saleor/product/utils.py
index 405fec9716..8abe578027 100644
--- a/saleor/product/utils.py
+++ b/saleor/product/utils.py
@@ -13,7 +13,7 @@ from ..cart.utils import get_cart_from_request, get_or_create_cart_from_request
from ..core.utils import (
ZERO_TAXED_MONEY, get_paginator_items, to_local_currency)
from ..core.utils.filters import get_now_sorted_by
-from ..schema.product import variant_json_ld
+from ..seo.schema.product import variant_json_ld
from .forms import ProductForm
diff --git a/saleor/product/views.py b/saleor/product/views.py
index 3c957efddb..709eeacc01 100644
--- a/saleor/product/views.py
+++ b/saleor/product/views.py
@@ -8,7 +8,7 @@ from django.urls import reverse
from ..cart.utils import set_cart_cookie
from ..core.utils import serialize_decimal
-from ..schema.product import product_json_ld
+from ..seo.schema.product import product_json_ld
from .filters import ProductCategoryFilter, ProductCollectionFilter
from .models import Category, Collection
from .utils import (
diff --git a/saleor/schema/__init__.py b/saleor/seo/__init__.py
similarity index 100%
rename from saleor/schema/__init__.py
rename to saleor/seo/__init__.py
diff --git a/saleor/seo/models.py b/saleor/seo/models.py
new file mode 100644
index 0000000000..392aa6a8da
--- /dev/null
+++ b/saleor/seo/models.py
@@ -0,0 +1,14 @@
+from django.db import models
+from django.core.validators import MaxLengthValidator
+
+
+class SeoModel(models.Model):
+ seo_title = models.CharField(
+ max_length=70, blank=True, null=True,
+ validators=[MaxLengthValidator(70)])
+ seo_description = models.CharField(
+ max_length=300, blank=True, null=True,
+ validators=[MaxLengthValidator(300)])
+
+ class Meta:
+ abstract = True
diff --git a/saleor/seo/schema/__init__.py b/saleor/seo/schema/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/schema/email.py b/saleor/seo/schema/email.py
similarity index 97%
rename from saleor/schema/email.py
rename to saleor/seo/schema/email.py
index 8871d9e266..f8e3099158 100644
--- a/saleor/schema/email.py
+++ b/saleor/seo/schema/email.py
@@ -3,7 +3,7 @@ import json
from django.contrib.sites.models import Site
from django.core.serializers.json import DjangoJSONEncoder
-from ..core.utils import build_absolute_uri
+from ...core.utils import build_absolute_uri
def get_organization():
diff --git a/saleor/schema/product.py b/saleor/seo/schema/product.py
similarity index 100%
rename from saleor/schema/product.py
rename to saleor/seo/schema/product.py
diff --git a/saleor/schema/webpage.py b/saleor/seo/schema/webpage.py
similarity index 94%
rename from saleor/schema/webpage.py
rename to saleor/seo/schema/webpage.py
index 24bd97003e..d62b1b6b2f 100644
--- a/saleor/schema/webpage.py
+++ b/saleor/seo/schema/webpage.py
@@ -4,7 +4,7 @@ from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
-from ..core.utils import build_absolute_uri
+from ...core.utils import build_absolute_uri
def get_webpage_schema(request):
diff --git a/saleor/settings.py b/saleor/settings.py
index 8c05d60a6a..e9e5e5ef5e 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -189,7 +189,7 @@ INSTALLED_APPS = [
'saleor.menu',
'saleor.order.OrderAppConfig',
'saleor.dashboard',
- 'saleor.schema',
+ 'saleor.seo',
'saleor.shipping',
'saleor.search',
'saleor.site',
diff --git a/saleor/static/dashboard/js/components/google-preview.js b/saleor/static/dashboard/js/components/google-preview.js
index 1bf75338f3..dafe80e0d9 100644
--- a/saleor/static/dashboard/js/components/google-preview.js
+++ b/saleor/static/dashboard/js/components/google-preview.js
@@ -1,17 +1,91 @@
-const $seoTitle = $('#id_seo_title');
-const $seoDescription = $('#id_seo_description');
-
-$seoTitle.on('input propertychange', function (e) {
- const $target = $(e.currentTarget);
- const $currentText = $target.val();
- const $googlePreview = $('#google-preview-title');
- $googlePreview.text($currentText);
-});
-
-$seoDescription.on('input propertychange', function (e) {
- console.log('DUPA');
- const $target = $(e.currentTarget);
- const $currentText = $target.val();
- const $googlePreview = $('#google-preview-description');
- $googlePreview.text($currentText);
-});
+const $seoTitle = $('#seo_title');
+
+const $nameId = $seoTitle.data('bind');
+const $name = $(`#${$nameId}`);
+
+const $seoDescription = $('#seo_description');
+const $descriptionMaterialize = $seoDescription.data('materialize');
+if ($descriptionMaterialize) {
+ var $description = $(`.materialize-textarea[name='${$descriptionMaterialize}']`);
+} else {
+ const $descriptionId = $seoDescription.data('bind');
+ var $description = $(`#${$descriptionId}`);
+}
+
+const $googleTitlePreview = $('#google-preview-title');
+const $googleDescriptionPreview = $('#google-preview-description');
+const $preview = $('.preview');
+const $previewErrors = $('#preview-error');
+
+const watchedEvents = 'input propertychange cut paste copy change delete';
+
+function checkForErrors() {
+ const $descriptionText = $googleDescriptionPreview.text() || $googleDescriptionPreview.val();
+ const $titleText = $googleTitlePreview.text();
+ if ($descriptionText && $titleText) {
+ $preview.show();
+ $previewErrors.hide();
+ } else if (!$descriptionText && !$titleText) {
+ $preview.hide();
+ $previewErrors.text(gettext('title and description missing'));
+ $previewErrors.show();
+
+ // title and descriptions missing
+ } else if (!$descriptionText) {
+ $preview.hide();
+ $previewErrors.show();
+ $previewErrors.text(gettext('description missing'));
+
+ // description missing
+ } else if (!$titleText) {
+ // title missing
+ $preview.hide();
+ $previewErrors.show();
+ $previewErrors.text(gettext('title missing'));
+ }
+}
+
+function truncate(text, seoField) {
+ const $fieldMaxLength = seoField.prop('maxLength');
+ if ($fieldMaxLength === -1) {
+ // console.log('Field maxlength is not defined');
+ return text;
+ }
+ return text.substring(text, $fieldMaxLength);
+}
+
+function updatePlaceholderOnInput(field, seoField, previewField) {
+ field.on(watchedEvents, (e) => {
+ const $target = $(e.currentTarget);
+ const $placeholderText = $target.val();
+ console.log($placeholderText);
+ seoField.attr('placeholder', truncate($placeholderText, seoField));
+ const $seoText = seoField.val();
+ console.log($seoText);
+ if (!$seoText) {
+ previewField.text(truncate($placeholderText, seoField));
+ } else {
+ previewField.text(truncate($seoText, seoField));
+ }
+ checkForErrors();
+ });
+}
+
+function updatePreviewOnInput(seoField, previewField) {
+ seoField.on(watchedEvents, (e) => {
+ const $target = $(e.currentTarget);
+ const $currentText = $target.val();
+ if ($currentText) {
+ previewField.text(truncate($currentText, seoField));
+ } else {
+ const $placeholderValue = seoField.attr('placeholder');
+ previewField.text(truncate($placeholderValue, seoField));
+ }
+ checkForErrors();
+ });
+}
+checkForErrors();
+updatePlaceholderOnInput($name, $seoTitle, $googleTitlePreview);
+updatePlaceholderOnInput($description, $seoDescription, $googleDescriptionPreview);
+updatePreviewOnInput($seoTitle, $googleTitlePreview);
+updatePreviewOnInput($seoDescription, $googleDescriptionPreview);
diff --git a/saleor/static/dashboard/scss/components/_google-preview.scss b/saleor/static/dashboard/scss/components/_google-preview.scss
index 7e3e055c94..d722fd3723 100644
--- a/saleor/static/dashboard/scss/components/_google-preview.scss
+++ b/saleor/static/dashboard/scss/components/_google-preview.scss
@@ -1,43 +1,42 @@
.google-preview {
- font-family: arial, sans-serif;
text-align: left;
+ letter-spacing: initial;
.container {
- padding: 12px;
- border: 2px solid #ccc;
margin: 12px;
background-color: #fff;
max-width: 600px;
.title {
- overflow: hidden;
+ display: block;
text-overflow: ellipsis;
+ margin-bottom: 2px;
a {
color: rgb(26, 13, 171);
cursor: pointer;
font-size: 18px;
- line-height: 21.6px;
+ line-height: 21px;
text-decoration: none solid rgb(26, 13, 171);
- zoom: 1;
&:hover {
text-decoration: underline;
}
word-wrap: break-word;
+ overflow-wrap: break-word;
}
}
.description {
color: rgb(84, 84, 84);
font-size: 13px;
- line-height: 18.2px;
- word-wrap: break-word;
- zoom: 1;
+ line-height: 18px;
+ overflow-wrap: break-word;
}
.url {
color: rgb(0, 102, 33);
font-size: 13px;
line-height: 16px;
white-space: nowrap;
- height: 16px;
+ margin-bottom: 2px;
+ overflow: hidden;
+ text-overflow: ellipsis;
}
-
}
}
diff --git a/templates/dashboard/category/form.html b/templates/dashboard/category/form.html
index 672c03ef08..56947ce25f 100644
--- a/templates/dashboard/category/form.html
+++ b/templates/dashboard/category/form.html
@@ -98,6 +98,9 @@
<div class="row">
{{ form.description|materializecss }}
</div>
+ <div class="row">
+ {% include "dashboard/includes/_google_preview.html" with object=category form=form %}
+ </div>
</div>
</div>
<div class="row">
diff --git a/templates/dashboard/collection/detail.html b/templates/dashboard/collection/detail.html
index 206a705704..a97672dabc 100644
--- a/templates/dashboard/collection/detail.html
+++ b/templates/dashboard/collection/detail.html
@@ -58,6 +58,9 @@
<div class="row">
{{ form.background_image|materializecss }}
</div>
+ <div class="row">
+ {% include "dashboard/includes/_google_preview.html" with object=collection form=form %}
+ </div>
</div>
<div class="card-action right-align">
<a href="{% url 'dashboard:collection-list' %}" class="btn btn-flat">
diff --git a/templates/dashboard/includes/_google_preview.html b/templates/dashboard/includes/_google_preview.html
index ea84fe0821..6d05d025eb 100644
--- a/templates/dashboard/includes/_google_preview.html
+++ b/templates/dashboard/includes/_google_preview.html
@@ -1,17 +1,25 @@
{% load build_absolute_uri from urls %}
{% load materializecss %}
+{% load i18n %}
<div class='google-preview'>
<div class='container'>
- <div class='title'>
- <a id="google-preview-title" href='#'>Example title</a>
+ <p class="flow-text">Search engine listing preview</p>
+ <br>
+ <div id="preview-error">
+ {% trans "Please provide title and description to see how this product might appear in search engine results." %}
+ </div>
+ <div class="preview">
+ <div class='title'>
+ <a id="google-preview-title" href='#'>{{ object.seo_title|default:form.seo_title.field.widget.attrs.placeholder }}</a>
+ </div>
+ {% if object.pk %}
+ <div class='url'>{% build_absolute_uri request=request location=object.get_absolute_url %}</div>
+ {% else %}
+ <div class='url'>{% build_absolute_uri request=request location="/" %}</div>
+ {% endif %}
+ <div id="google-preview-description" class='description'>{{ object.seo_description|default:form.seo_description.field.widget.attrs.placeholder }}</div>
</div>
- {% if object.pk %}
- <div class='url'>{% build_absolute_uri request=request location=object.get_absolute_url %}</div>
- {% else %}
- <div class='url'>{% build_absolute_uri request=request location="/" %}</div>
- {% endif %}
- <div id="google-preview-description" class='description'>{{ object.seo_description|default:_("Here is an example of what a snippet looks like in Google's Search Engine Results Page. ") }}</div>
</div>
</div>
{{ form.seo_title|materializecss }}
diff --git a/templates/dashboard/page/form.html b/templates/dashboard/page/form.html
index 287d97b82c..79ce3512c1 100644
--- a/templates/dashboard/page/form.html
+++ b/templates/dashboard/page/form.html
@@ -62,6 +62,7 @@
<div class="col s12 l8">
{{ form.title|materializecss }}
{{ form.content|materializecss }}
+ {% include "dashboard/includes/_google_preview.html" with object=page form=form %}
</div>
<div class="col s12 l4">
{{ form.slug|materializecss }}
diff --git a/tests/test_schema.py b/tests/test_seo_schema.py
similarity index 97%
rename from tests/test_schema.py
rename to tests/test_seo_schema.py
index b06de37bf1..eac9b817b6 100644
--- a/tests/test_schema.py
+++ b/tests/test_seo_schema.py
@@ -2,7 +2,7 @@ import json
import pytest
-from saleor.schema.email import (
+from saleor.seo.schema.email import (
get_order_confirmation_markup, get_organization, get_product_data)