Skip to content

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

Made possible to set the SEO friendly description. Which also fixes the issue with the meta description being a ugly escaped HTML text. The SEO friendly description defaults to the product description trimmed to 155 chars with a suffix of '[...]'.

NyanKiyoshia4b432ad4ee2
diff --git a/saleor/core/utils/text.py b/saleor/core/utils/text.py
new file mode 100644
index 0000000000..6fa80a3906
--- /dev/null
+++ b/saleor/core/utils/text.py
@@ -0,0 +1,74 @@
+import bleach
+from html5lib.serializer import HTMLSerializer
+
+
+def trim_text(text: str, max_length: int, suffix: str=''):
+ """Trims a given text in accordance to parameters.
+ If text length is greater than allowed, it trims it and add a given suffix to the text.
+ Note that the text + suffix is equal to the max length.
+
+ Example:
+ max length = 16
+ prefix = '[...]' (5 chars)
+ text = 'Hello World, everyone!' (22 chars)
+
+ => text = 'Hello World[...]'
+
+ :param text:
+ :type text: str
+ :param max_length:
+ :type max_length: int
+ :param suffix:
+ :type suffix: str
+
+ :rtype: str
+ """
+ if len(text) > max_length:
+ new_length = max_length - len(suffix)
+ text = '%s%s' % (text[:new_length], suffix)
+ return text
+
+
+def get_cleaner(**serializer_kwargs: bool):
+ """
+ :param serializer_kwargs:
+ options:
+ - alphabetical_attributes
+ - escape_lt_in_attrs
+ - escape_rcdata
+ - inject_meta_charset
+ - minimize_boolean_attributes
+ - omit_optional_tags
+ - quote_attr_values
+ - quote_char
+ - resolve_entities
+ - sanitize
+ - space_before_trailing_solidus
+ - strip_whitespace
+ - use_best_quote_char
+ - use_trailing_solidus
+ :type serializer_kwargs: Dict[str, bool]
+
+ :rtype: bleach.Cleaner
+ """
+ cleaner = bleach.Cleaner([], strip=True)
+ for k, v in serializer_kwargs.items():
+ if k not in HTMLSerializer.options:
+ raise ValueError('Parameter %s is not a valid option for HTMLSerializer' % k)
+ setattr(cleaner.serializer, k, v)
+ return cleaner
+
+
+def strip_html(text: str, **serializer_kwargs: bool):
+ """Removes (strips) HTML tags from text.
+ Can also take additional parameters to be passed to the serializer (see `get_cleaner`).
+
+ :param text:
+ :type text: str
+ :param serializer_kwargs:
+ :type serializer_kwargs: Dict[str, bool]
+ :rtype: str
+ """
+ cleaner = get_cleaner(**serializer_kwargs)
+ text = cleaner.clean(text)
+ return text
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index 95e220530e..8daa5ad69e 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -8,6 +8,7 @@ from django.utils.encoding import smart_text
from django.utils.text import slugify
from django.utils.translation import pgettext_lazy
+from saleor.core.utils.text import strip_html, trim_text
from . import ProductBulkAction
from ...product.models import (
AttributeChoiceValue, Collection, Product, ProductAttribute, ProductImage,
@@ -141,6 +142,8 @@ class ProductForm(forms.ModelForm):
labels = {
'name': pgettext_lazy('Item name', 'Name'),
'description': pgettext_lazy('Description', 'Description'),
+ 'seo_description': pgettext_lazy(
+ 'A SEO friendly description', 'SEO Friendly Description'),
'category': pgettext_lazy('Category', 'Category'),
'price': pgettext_lazy('Currency amount', 'Price'),
'available_on': pgettext_lazy(
@@ -167,6 +170,26 @@ class ProductForm(forms.ModelForm):
self.fields["collections"].initial = Collection.objects.filter(
products__name=self.instance)
+ @classmethod
+ def generate_seo_description(cls, html_text):
+ """Strips HTML tags and whitespaces from text, then trim the description."""
+ text = strip_html(html_text, strip_whitespace=True)
+ text = trim_text(text, settings.GENERATED_SEO_MAX_LENGTH, settings.GENERATED_SEO_SUFFIX)
+ return text
+
+ 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 = self.generate_seo_description(product_description)
+
+ return seo_description
+
def prepare_fields_for_attributes(self):
for attribute in self.product_attributes:
field_defaults = {
diff --git a/saleor/product/migrations/0053_product_seo_description.py b/saleor/product/migrations/0053_product_seo_description.py
new file mode 100644
index 0000000000..ddadd27d60
--- /dev/null
+++ b/saleor/product/migrations/0053_product_seo_description.py
@@ -0,0 +1,40 @@
+# Generated by Django 2.0.2 on 2018-03-11 18:54
+import html
+
+from django.db import migrations, models
+
+from saleor.dashboard.product.forms import ProductForm
+
+
+def to_seo_friendly(text):
+ # saleor descriptions are stored as escaped HTML,
+ # we need to decode them before processing them
+ text = html.unescape(text)
+
+ # cleanup the description and make it seo friendly
+ return ProductForm.generate_seo_description(text)
+
+
+def assign_seo_descriptions(apps, schema_editor):
+ Product = apps.get_model('product', 'Product')
+ for product in Product.objects.all():
+ if product.seo_description is None:
+ product.seo_description = to_seo_friendly(product.description)
+ product.save()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('product', '0052_slug_field_length'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name='product',
+ name='seo_description',
+ field=models.CharField(blank=True, null=True, max_length=255),
+ preserve_default=False,
+ ),
+ migrations.RunPython(assign_seo_descriptions)
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index ac639ed348..249a606780 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -92,6 +92,7 @@ class Product(models.Model):
ProductType, related_name='products', on_delete=models.CASCADE)
name = models.CharField(max_length=128)
description = models.TextField()
+ seo_description = models.CharField(max_length=255, blank=True, null=True)
category = models.ForeignKey(
Category, related_name='products', on_delete=models.CASCADE)
price = MoneyField(
diff --git a/saleor/settings.py b/saleor/settings.py
index 4d528b563e..20d7dbd4d2 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -419,3 +419,6 @@ ALLOWED_ATTRIBUTES = {
'a': ['href', 'title'],
'img': ['src']}
ALLOWED_STYLES = ['text-align']
+
+GENERATED_SEO_MAX_LENGTH = 155
+GENERATED_SEO_SUFFIX = '[...]'
diff --git a/templates/dashboard/product/form.html b/templates/dashboard/product/form.html
index 0a5f005754..d42f4c4c93 100644
--- a/templates/dashboard/product/form.html
+++ b/templates/dashboard/product/form.html
@@ -72,6 +72,9 @@
<div class="row">
{{ product_form.name|materializecss }}
</div>
+ <div class="row">
+ {{ product_form.seo_description|materializecss }}
+ </div>
{% for attribute_field in product_form.iter_attribute_fields %}
<div class="row">
{{ attribute_field|materializecss:"input-field s12" }}
diff --git a/templates/product/details.html b/templates/product/details.html
index d2946e3925..724d2567af 100644
--- a/templates/product/details.html
+++ b/templates/product/details.html
@@ -12,11 +12,11 @@
{% block title %}{{ product }} — {{ block.super }}{% endblock %}
-{% block meta_description %}{{ product.description }}{% endblock %}
+{% block meta_description %}{{ product.seo_description }}{% endblock %}
{% block meta_tags %}
<meta property="og:title" content="{{ product }}">
- <meta property="og:description" content="{{ product.description }}">
+ <meta property="og:description" content="{{ product.seo_description }}">
{% build_absolute_uri request=request location=product.get_absolute_url as product_url %}
<meta property="og:url" content="{{ product_url }}">
diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.py
index 0e122d99eb..9f9937c025 100644
--- a/tests/dashboard/test_product.py
+++ b/tests/dashboard/test_product.py
@@ -697,3 +697,21 @@ def test_sanitize_product_description(product_type, default_category):
'<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>'
'<p>an &lt;script&gt;evil()&lt;/script&gt;example</p>')
+
+ assert product.seo_description == 'bolditalicHeadersubheaderquotelinkan evil()example'
+
+
+def test_set_product_seo_description(unavailable_product):
+ seo_description = (
+ 'This is a dummy product. '
+ 'HTML <b>shouldn\'t be removed</b> since it\'s a simple text field.')
+ data = model_to_dict(unavailable_product)
+ data['price'] = 20
+ data['description'] = 'a description'
+ data['seo_description'] = seo_description
+
+ form = ProductForm(data, instance=unavailable_product)
+
+ assert form.is_valid()
+ form.save()
+ assert unavailable_product.seo_description == seo_description
diff --git a/tests/test_core.py b/tests/test_core.py
index 62c90df4ae..a4a3724cf0 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -8,6 +8,7 @@ from saleor.account.models import Address, User
from saleor.core.utils import (
Country, create_superuser, format_money, get_country_by_ip,
get_currency_for_country, random_data)
+from saleor.core.utils.text import trim_text, strip_html, get_cleaner
from saleor.discount.models import Sale, Voucher
from saleor.order.models import Order
from saleor.product.models import Product
@@ -160,3 +161,21 @@ def test_manifest(client, site_settings):
assert content['name'] == site_settings.site.name
assert content['short_name'] == site_settings.site.name
assert content['description'] == site_settings.description
+
+
+def test_utils_trim_text():
+ text = trim_text('Hello World, everyone!', 16, '[...]')
+ assert text == 'Hello World[...]'
+
+
+def test_utils_get_cleaner_invalid_parameters():
+ with pytest.raises(ValueError):
+ get_cleaner(bad=True)
+
+
+def test_utils_strip_html():
+ base_text = ('<p>Hello</p>'
+ '\n\n'
+ '\t<b>World</b>')
+ text = strip_html(base_text, strip_whitespace=True)
+ assert text == 'Hello World'