Skip to content

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

Fix tests, clean up code

Pacu2b377a4b77a30
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 31b2960775..a691316780 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -15,7 +15,7 @@ from prices import Money, TaxedMoney
from ...account.models import Address, User
from ...account.utils import store_user_address
-from ...core.utils.text import generate_seo_description
+from ...core.utils.text import strip_html_and_truncate
from ...discount import DiscountValueType, VoucherType
from ...discount.models import Sale, Voucher
from ...menu.models import Menu
@@ -298,7 +298,7 @@ def create_product(**kwargs):
'name': fake.company(),
'price': fake.money(),
'description': '\n\n'.join(description),
- 'seo_description': generate_seo_description(description[0], 300)}
+ 'seo_description': strip_html_and_truncate(description[0], 300)}
defaults.update(kwargs)
return Product.objects.create(**defaults)
diff --git a/saleor/core/utils/text.py b/saleor/core/utils/text.py
index b146881fee..0330a81c89 100644
--- a/saleor/core/utils/text.py
+++ b/saleor/core/utils/text.py
@@ -53,7 +53,7 @@ def strip_html(text: str, **serializer_kwargs: bool):
return text
-def generate_seo_description(html_text: str, max_length: int):
+def strip_html_and_truncate(html_text: str, max_length: int):
"""Strips HTML tags and whitespaces from text,
then trim the description."""
text = strip_html(html_text, strip_whitespace=True)
diff --git a/saleor/dashboard/category/forms.py b/saleor/dashboard/category/forms.py
index 01683fe9ca..88ad23b484 100644
--- a/saleor/dashboard/category/forms.py
+++ b/saleor/dashboard/category/forms.py
@@ -12,17 +12,10 @@ class CategoryForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.parent_pk = kwargs.pop('parent_pk')
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.update({
- 'id': 'seo_description',
- 'data-bind': self['description'].auto_id,
- 'placeholder': placeholder})
+ 'data-bind': self['description'].auto_id})
self.fields['seo_title'].widget.attrs.update({
- 'id': 'seo_title',
- 'data-bind': self['name'].auto_id,
- 'placeholder': self.instance.name})
+ 'data-bind': self['name'].auto_id})
class Meta:
model = Category
diff --git a/saleor/dashboard/collection/forms.py b/saleor/dashboard/collection/forms.py
index d577c55332..8db5b7a425 100644
--- a/saleor/dashboard/collection/forms.py
+++ b/saleor/dashboard/collection/forms.py
@@ -6,8 +6,8 @@ from text_unidecode import unidecode
from ...product.models import Collection, Product
from ..forms import AjaxSelect2MultipleChoiceField
-from ..widgets import CharsLeftWidget
from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS
+from ..widgets import CharsLeftWidget
class CollectionForm(forms.ModelForm):
@@ -39,14 +39,9 @@ class CollectionForm(forms.ModelForm):
if self.instance.pk:
self.fields['products'].set_initial(self.instance.products.all())
self.fields['seo_description'].widget.attrs.update({
- 'id': 'seo_description',
- 'data-bind': '',
- 'placeholder': '',
'min-recommended-length': 130})
self.fields['seo_title'].widget.attrs.update({
- 'id': 'seo_title',
'data-bind': self['name'].auto_id,
- 'placeholder': self.instance.name[:70],
'min-recommended-length': 25})
def save(self, commit=True):
diff --git a/saleor/dashboard/page/forms.py b/saleor/dashboard/page/forms.py
index e52a9b5006..308bcce0db 100644
--- a/saleor/dashboard/page/forms.py
+++ b/saleor/dashboard/page/forms.py
@@ -1,30 +1,20 @@
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
-from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS
+from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS, prepare_seo_description
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.update({
- 'id': 'seo_description',
'data-bind': self['content'].auto_id,
- 'data-materialize': self['content'].html_name,
- 'placeholder': placeholder})
+ 'data-materialize': self['content'].html_name})
self.fields['seo_title'].widget.attrs.update({
- 'id': 'seo_title',
- 'data-bind': self['title'].auto_id,
- 'placeholder': self.instance.title})
+ 'data-bind': self['title'].auto_id})
class Meta:
model = Page
@@ -50,14 +40,8 @@ class PageForm(forms.ModelForm):
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)
+ seo_description = prepare_seo_description(
+ seo_description=self.cleaned_data['seo_description'],
+ html_description=self.data['content'],
+ max_length=self.fields['seo_description'].max_length)
return seo_description
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index 04e2bbe4f8..b6a54b5889 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -9,7 +9,6 @@ from django.utils.text import slugify
from django.utils.translation import pgettext_lazy
from mptt.forms import TreeNodeChoiceField
-from ...core.utils.text import generate_seo_description
from ...product.models import (
AttributeChoiceValue, Category, Collection, Product, ProductAttribute,
ProductImage, ProductType, ProductVariant, Stock, StockLocation,
@@ -18,7 +17,7 @@ from ..forms import OrderedModelMultipleChoiceField, ModelChoiceOrCreationField
from ..widgets import RichTextEditorWidget
from .widgets import ImagePreviewWidget
from . import ProductBulkAction
-from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS
+from ..seo.utils import SEO_HELP_TEXTS, SEO_LABELS, prepare_seo_description
class RichTextField(forms.CharField):
@@ -221,34 +220,17 @@ 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})
+ 'data-materialize': self['description'].html_name})
self.fields['seo_title'].widget.attrs.update({
- 'id': 'seo_title',
- 'data-bind': self['name'].auto_id,
- 'placeholder': self.instance.name})
+ 'data-bind': self['name'].auto_id})
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)
- product_description = self.data['description']
-
- # generate a SEO friendly from HTML description
- seo_description = generate_seo_description(
- product_description, 300)
-
+ seo_description = prepare_seo_description(
+ seo_description=self.cleaned_data['seo_description'],
+ html_description=self.data['description'],
+ max_length=self.fields['seo_description'].max_length)
return seo_description
def save(self, commit=True):
diff --git a/saleor/dashboard/seo/utils.py b/saleor/dashboard/seo/utils.py
new file mode 100644
index 0000000000..b38401a40a
--- /dev/null
+++ b/saleor/dashboard/seo/utils.py
@@ -0,0 +1,36 @@
+from django.utils.translation import pgettext_lazy
+
+from ...core.utils.text import strip_html_and_truncate
+
+SEO_HELP_TEXTS = {
+ 'seo_description': pgettext_lazy(
+ 'Form field help text',
+ (
+ 'If empty, the preview shows what will be autogenerated.')),
+ 'seo_title': pgettext_lazy(
+ 'Form field help text',
+ (
+ 'If empty, the preview shows what will be autogenerated.'))}
+
+SEO_LABELS = {
+ 'seo_description': pgettext_lazy(
+ (
+ 'Field name, Meta Description is page summary '
+ 'used by Search Engines'),
+ 'Meta Description'),
+ 'seo_title': pgettext_lazy(
+ (
+ 'Field name, '
+ 'Title that will be used to describe page in Search Engines'),
+ 'SEO Title')}
+
+
+def prepare_seo_description(seo_description, html_description, max_length):
+ # 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)
+ # generate a SEO friendly from HTML description
+ seo_description = strip_html_and_truncate(
+ html_description, max_length)
+ return seo_description
diff --git a/saleor/product/migrations/0053_product_seo_description.py b/saleor/product/migrations/0053_product_seo_description.py
index 15c29c832a..0c388e3d37 100644
--- a/saleor/product/migrations/0053_product_seo_description.py
+++ b/saleor/product/migrations/0053_product_seo_description.py
@@ -3,7 +3,7 @@ import html
from django.core.validators import MaxLengthValidator
from django.db import migrations, models
-from saleor.core.utils.text import generate_seo_description
+from saleor.core.utils.text import strip_html_and_truncate
def to_seo_friendly(text):
@@ -12,7 +12,7 @@ def to_seo_friendly(text):
text = html.unescape(text)
# cleanup the description and make it seo friendly
- return generate_seo_description(text, 300)
+ return strip_html_and_truncate(text, 300)
def assign_seo_descriptions(apps, schema_editor):
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 1817c9a9bf..e4475cd307 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -3,8 +3,7 @@ from decimal import Decimal
from django.conf import settings
from django.contrib.postgres.fields import HStoreField
-from django.core.validators import (
- MinValueValidator, RegexValidator)
+from django.core.validators import MinValueValidator, RegexValidator
from django.db import models
from django.db.models import F, Max, Q
from django.urls import reverse
diff --git a/saleor/seo/models.py b/saleor/seo/models.py
index 392aa6a8da..8343fbf35f 100644
--- a/saleor/seo/models.py
+++ b/saleor/seo/models.py
@@ -1,5 +1,5 @@
-from django.db import models
from django.core.validators import MaxLengthValidator
+from django.db import models
class SeoModel(models.Model):
diff --git a/saleor/static/dashboard/js/components/google-preview.js b/saleor/static/dashboard/js/components/google-preview.js
index 3fc786bb79..4d05f9b15a 100644
--- a/saleor/static/dashboard/js/components/google-preview.js
+++ b/saleor/static/dashboard/js/components/google-preview.js
@@ -1,10 +1,11 @@
-const $seoTitle = $('#seo_title');
+const $seoTitle = $('#id_seo_title');
const $nameId = $seoTitle.data('bind');
const $name = $(`#${$nameId}`);
-const $seoDescription = $('#seo_description');
+const $seoDescription = $('#id_seo_description');
const $descriptionMaterialize = $seoDescription.data('materialize');
+
let $description = '';
if ($descriptionMaterialize) {
$description = $(`.materialize-textarea[name='${$descriptionMaterialize}']`);
@@ -22,11 +23,21 @@ const $previewErrors = $('#preview-error');
const watchedEvents = 'input propertychange cut paste copy change';
-function updateCharsCount(field) {
- const $fieldId = field.attr('id');
+function setPlaceholderAndPreview(field, seoField, previewField) {
+ const $text = field.text() || field.val();
+ const $placeholderText = truncate($text, seoField);
+ seoField.attr('placeholder', $placeholderText);
+ previewField.text(seoField.val() || $placeholderText);
+}
+
+function updateCharsCount(seoField) {
+ const $fieldId = seoField.attr('id');
const $charCount = $(`span[data-bind=${$fieldId}]`);
- const $fieldLength = field.val().length || field.attr('placeholder').length;
- const $minRecommendedLength = field.attr('min-recommended-length');
+ let $fieldLength = seoField.val().length || seoField.text().length;
+ if (!$fieldLength && seoField.attr('placeholder')) {
+ $fieldLength = seoField.attr('placeholder').length;
+ }
+ const $minRecommendedLength = seoField.attr('min-recommended-length');
const $charCountWrapper = $charCount.parent();
if ($fieldLength < $minRecommendedLength) {
$charCountWrapper.addClass('red-text');
@@ -46,28 +57,31 @@ function checkForErrors() {
$previewErrors.hide();
} else if (!$descriptionText && !$titleText) {
$preview.hide();
- $previewErrors.text(gettext('Please provide title and description to see how this product might appear in search engine results.'));
+ $previewErrors.text(gettext('Please provide SEO Title and Meta Description to see how this product might appear in search engine results.'));
$previewErrors.show();
} else if (!$descriptionText) {
$preview.hide();
- $previewErrors.text(gettext('Please provide description to see how this product might appear in search engine results.'));
+ $previewErrors.text(gettext('Please provide Meta Description to see how this product might appear in search engine results.'));
$previewErrors.show();
} else if (!$titleText) {
$preview.hide();
- $previewErrors.text(gettext('Please provide title to see how this product might appear in search engine results.'));
+ $previewErrors.text(gettext('Please provide SEO Title to see how this product might appear in search engine results.'));
$previewErrors.show();
}
}
function truncate(text, seoField) {
const $fieldMaxLength = seoField.prop('maxLength');
- return text.substring(text, $fieldMaxLength);
+ if (text && text.length > $fieldMaxLength) {
+ return text.substring(text, $fieldMaxLength);
+ }
+ return text;
}
function updatePlaceholderOnInput(field, seoField, previewField) {
field.on(watchedEvents, (e) => {
const $target = $(e.currentTarget);
- const $placeholderText = $target.val();
+ const $placeholderText = $target.val() || $target.text();
seoField.attr('placeholder', truncate($placeholderText, seoField));
const $seoText = seoField.val();
if (!$seoText) {
@@ -93,12 +107,20 @@ function updatePreviewOnInput(seoField, previewField) {
});
}
-checkForErrors();
-updatePlaceholderOnInput($name, $seoTitle, $googleTitlePreview);
-if ($description) {
- updatePlaceholderOnInput($description, $seoDescription, $googleDescriptionPreview);
+if ($seoTitle.length) {
+ if ($name) {
+ setPlaceholderAndPreview($name, $seoTitle, $googleTitlePreview);
+ updatePlaceholderOnInput($name, $seoTitle, $googleTitlePreview);
+ }
+ updatePreviewOnInput($seoTitle, $googleTitlePreview);
+ updateCharsCount($seoTitle);
}
-updatePreviewOnInput($seoTitle, $googleTitlePreview);
-updatePreviewOnInput($seoDescription, $googleDescriptionPreview);
-updateCharsCount($seoTitle);
-updateCharsCount($seoDescription);
+if ($seoDescription.length) {
+ if ($description) {
+ setPlaceholderAndPreview($description, $seoDescription, $googleDescriptionPreview);
+ updatePlaceholderOnInput($description, $seoDescription, $googleDescriptionPreview);
+ }
+ updatePreviewOnInput($seoDescription, $googleDescriptionPreview);
+ updateCharsCount($seoDescription);
+}
+checkForErrors();
diff --git a/saleor/static/dashboard/scss/components/_google-preview.scss b/saleor/static/dashboard/scss/components/_google-preview.scss
index 017619d886..a9d5f66507 100644
--- a/saleor/static/dashboard/scss/components/_google-preview.scss
+++ b/saleor/static/dashboard/scss/components/_google-preview.scss
@@ -1,7 +1,7 @@
.google-preview {
text-align: left;
letter-spacing: initial;
-
+ padding-top: 1rem;
&__container {
margin: 12px;
background-color: #fff;
@@ -12,11 +12,11 @@
text-overflow: ellipsis;
margin-bottom: 2px;
a {
- color: rgb(26, 13, 171);
+ color: #1A0DAB;
cursor: pointer;
font-size: 18px;
line-height: 21px;
- text-decoration: none solid rgb(26, 13, 171);
+ text-decoration: none solid #1A0DAB;
&:hover {
text-decoration: underline;
}
@@ -25,13 +25,13 @@
}
}
&__description {
- color: rgb(84, 84, 84);
+ color: #545454;
font-size: 13px;
line-height: 18px;
overflow-wrap: break-word;
}
&__url {
- color: rgb(0, 102, 33);
+ color: #006621;
font-size: 13px;
line-height: 16px;
white-space: nowrap;
diff --git a/templates/dashboard/includes/_google_preview.html b/templates/dashboard/includes/_google_preview.html
index 9d4a8b6372..445b82e1f3 100644
--- a/templates/dashboard/includes/_google_preview.html
+++ b/templates/dashboard/includes/_google_preview.html
@@ -9,7 +9,7 @@
<div id="preview-error"></div>
<div id="google-preview">
<div class='google-preview__title'>
- <a id="google-preview-title" href='#'>{{ object.seo_title|default:form.seo_title.field.widget.attrs.placeholder }}</a>
+ <a id="google-preview-title" href='#'>{{ object.seo_title|default:"" }}</a>
</div>
<div class='google-preview__url'>
{% if object.pk %}
@@ -18,7 +18,7 @@
{% build_absolute_uri request=request location="/" %}
{% endif %}
</div>
- <div id="google-preview-description" class='google-preview__description'>{{ object.seo_description|default:form.seo_description.field.widget.attrs.placeholder }}</div>
+ <div id="google-preview-description" class='google-preview__description'>{{ object.seo_description|default:"" }}</div>
</div>
</div>
</div>
diff --git a/templates/materializecssform/field.html b/templates/materializecssform/field.html
index bac8d7b657..7049c49df2 100644
--- a/templates/materializecssform/field.html
+++ b/templates/materializecssform/field.html
@@ -344,7 +344,7 @@
{% endif %}
</label>
<span class="chars-left__count">
- <span class="chars-left__count__current" data-bind="{{ field.field.widget.attrs.id }}">
+ <span class="chars-left__count__current" data-bind="{{ field.auto_id }}">
{% blocktrans with current_chars_count=field.value|length max_chars_count=field.field.max_length context "Message showing how many chars were used out of maximum field's length" %}
{{ current_chars_count }}</span> of {{ max_chars_count }} characters used
{% endblocktrans %}
diff --git a/tests/dashboard/test_page.py b/tests/dashboard/test_page.py
index 095e15ed6d..01473115b7 100644
--- a/tests/dashboard/test_page.py
+++ b/tests/dashboard/test_page.py
@@ -54,7 +54,7 @@ def test_page_delete(admin_client, page):
def test_sanitize_page_content(page, default_category):
data = model_to_dict(page)
- data['description'] = (
+ data['content'] = (
'<b>bold</b><p><i>italic</i></p><h2>Header</h2><h3>subheader</h3>'
'<blockquote>quote</blockquote>'
'<p><a href="www.mirumee.com">link</a></p>'
@@ -72,17 +72,17 @@ def test_sanitize_page_content(page, default_category):
'bolditalicHeadersubheaderquotelinkan evil()example')
-def test_set_product_seo_description(unavailable_product):
+def test_set_page_seo_description(page):
seo_description = (
- 'This is a dummy product. '
+ 'This is a dummy page. '
'HTML <b>shouldn\'t be removed</b> since it\'s a simple text field.')
- data = model_to_dict(unavailable_product)
+ data = model_to_dict(page)
data['price'] = 20
- data['description'] = 'a description'
+ data['content'] = 'a description'
data['seo_description'] = seo_description
- form = PageForm(data, instance=unavailable_product)
+ form = PageForm(data, instance=page)
assert form.is_valid()
form.save()
- assert unavailable_product.seo_description == seo_description
+ assert page.seo_description == seo_description